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 |
|---|---|---|---|---|---|---|---|---|---|---|
acorg/dark-matter | dark/diamond/hsp.py | _debugPrint | def _debugPrint(hsp, queryLen, localDict, msg=''):
"""
Print debugging information showing the local variables used during
a call to normalizeHSP and the hsp and then raise an C{AssertionError}.
@param hsp: The HSP C{dict} passed to normalizeHSP.
@param queryLen: the length of the query sequence.
@param localDict: A C{dict} of local variables (as produced by locals()).
@param msg: A C{str} message to raise C{AssertionError} with.
@raise AssertionError: unconditionally.
"""
print('normalizeHSP error:', file=sys.stderr)
print(' queryLen: %d' % queryLen, file=sys.stderr)
print(' Original HSP:', file=sys.stderr)
for attr in ['bits', 'btop', 'expect', 'frame', 'query_end', 'query_start',
'sbjct', 'query', 'sbjct_end', 'sbjct_start']:
print(' %s: %r' % (attr, hsp[attr]), file=sys.stderr)
print(' Local variables:', file=sys.stderr)
for var in sorted(localDict):
if var != 'hsp':
print(' %s: %s' % (var, localDict[var]), file=sys.stderr)
raise AssertionError(msg) | python | def _debugPrint(hsp, queryLen, localDict, msg=''):
"""
Print debugging information showing the local variables used during
a call to normalizeHSP and the hsp and then raise an C{AssertionError}.
@param hsp: The HSP C{dict} passed to normalizeHSP.
@param queryLen: the length of the query sequence.
@param localDict: A C{dict} of local variables (as produced by locals()).
@param msg: A C{str} message to raise C{AssertionError} with.
@raise AssertionError: unconditionally.
"""
print('normalizeHSP error:', file=sys.stderr)
print(' queryLen: %d' % queryLen, file=sys.stderr)
print(' Original HSP:', file=sys.stderr)
for attr in ['bits', 'btop', 'expect', 'frame', 'query_end', 'query_start',
'sbjct', 'query', 'sbjct_end', 'sbjct_start']:
print(' %s: %r' % (attr, hsp[attr]), file=sys.stderr)
print(' Local variables:', file=sys.stderr)
for var in sorted(localDict):
if var != 'hsp':
print(' %s: %s' % (var, localDict[var]), file=sys.stderr)
raise AssertionError(msg) | [
"def",
"_debugPrint",
"(",
"hsp",
",",
"queryLen",
",",
"localDict",
",",
"msg",
"=",
"''",
")",
":",
"print",
"(",
"'normalizeHSP error:'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"' queryLen: %d'",
"%",
"queryLen",
",",
"file",
"=",... | Print debugging information showing the local variables used during
a call to normalizeHSP and the hsp and then raise an C{AssertionError}.
@param hsp: The HSP C{dict} passed to normalizeHSP.
@param queryLen: the length of the query sequence.
@param localDict: A C{dict} of local variables (as produced by locals()).
@param msg: A C{str} message to raise C{AssertionError} with.
@raise AssertionError: unconditionally. | [
"Print",
"debugging",
"information",
"showing",
"the",
"local",
"variables",
"used",
"during",
"a",
"call",
"to",
"normalizeHSP",
"and",
"the",
"hsp",
"and",
"then",
"raise",
"an",
"C",
"{",
"AssertionError",
"}",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/hsp.py#L7-L31 |
acorg/dark-matter | dark/diamond/hsp.py | _sanityCheck | def _sanityCheck(subjectStart, subjectEnd, queryStart, queryEnd,
queryStartInSubject, queryEndInSubject, hsp, queryLen,
subjectGaps, queryGaps, localDict):
"""
Perform some sanity checks on an HSP. Call _debugPrint on any error.
@param subjectStart: The 0-based C{int} start offset of the match in the
subject.
@param subjectEnd: The 0-based C{int} end offset of the match in the
subject.
@param queryStart: The 0-based C{int} start offset of the match in the
query.
@param queryEnd: The 0-based C{int} end offset of the match in the query.
@param queryStartInSubject: The 0-based C{int} offset of where the query
starts in the subject.
@param queryEndInSubject: The 0-based C{int} offset of where the query
ends in the subject.
@param hsp: The HSP C{dict} passed to normalizeHSP.
@param queryLen: the C{int} length of the query sequence.
@param subjectGaps: the C{int} number of gaps in the subject.
@param queryGaps: the C{int} number of gaps in the query.
@param localDict: A C{dict} of local variables from our caller (as
produced by locals()).
"""
# Subject indices must always be ascending.
if subjectStart >= subjectEnd:
_debugPrint(hsp, queryLen, localDict, 'subjectStart >= subjectEnd')
subjectMatchLength = subjectEnd - subjectStart
queryMatchLength = queryEnd - queryStart
# Sanity check that the length of the matches in the subject and query
# are identical, taking into account gaps in both.
subjectMatchLengthWithGaps = subjectMatchLength + subjectGaps
queryMatchLengthWithGaps = queryMatchLength + queryGaps
if subjectMatchLengthWithGaps != queryMatchLengthWithGaps:
_debugPrint(hsp, queryLen, localDict,
'Including gaps, subject match length (%d) != Query match '
'length (%d)' % (subjectMatchLengthWithGaps,
queryMatchLengthWithGaps))
if queryStartInSubject > subjectStart:
_debugPrint(hsp, queryLen, localDict,
'queryStartInSubject (%d) > subjectStart (%d)' %
(queryStartInSubject, subjectStart))
if queryEndInSubject < subjectEnd:
_debugPrint(hsp, queryLen, localDict,
'queryEndInSubject (%d) < subjectEnd (%d)' %
(queryEndInSubject, subjectEnd)) | python | def _sanityCheck(subjectStart, subjectEnd, queryStart, queryEnd,
queryStartInSubject, queryEndInSubject, hsp, queryLen,
subjectGaps, queryGaps, localDict):
"""
Perform some sanity checks on an HSP. Call _debugPrint on any error.
@param subjectStart: The 0-based C{int} start offset of the match in the
subject.
@param subjectEnd: The 0-based C{int} end offset of the match in the
subject.
@param queryStart: The 0-based C{int} start offset of the match in the
query.
@param queryEnd: The 0-based C{int} end offset of the match in the query.
@param queryStartInSubject: The 0-based C{int} offset of where the query
starts in the subject.
@param queryEndInSubject: The 0-based C{int} offset of where the query
ends in the subject.
@param hsp: The HSP C{dict} passed to normalizeHSP.
@param queryLen: the C{int} length of the query sequence.
@param subjectGaps: the C{int} number of gaps in the subject.
@param queryGaps: the C{int} number of gaps in the query.
@param localDict: A C{dict} of local variables from our caller (as
produced by locals()).
"""
# Subject indices must always be ascending.
if subjectStart >= subjectEnd:
_debugPrint(hsp, queryLen, localDict, 'subjectStart >= subjectEnd')
subjectMatchLength = subjectEnd - subjectStart
queryMatchLength = queryEnd - queryStart
# Sanity check that the length of the matches in the subject and query
# are identical, taking into account gaps in both.
subjectMatchLengthWithGaps = subjectMatchLength + subjectGaps
queryMatchLengthWithGaps = queryMatchLength + queryGaps
if subjectMatchLengthWithGaps != queryMatchLengthWithGaps:
_debugPrint(hsp, queryLen, localDict,
'Including gaps, subject match length (%d) != Query match '
'length (%d)' % (subjectMatchLengthWithGaps,
queryMatchLengthWithGaps))
if queryStartInSubject > subjectStart:
_debugPrint(hsp, queryLen, localDict,
'queryStartInSubject (%d) > subjectStart (%d)' %
(queryStartInSubject, subjectStart))
if queryEndInSubject < subjectEnd:
_debugPrint(hsp, queryLen, localDict,
'queryEndInSubject (%d) < subjectEnd (%d)' %
(queryEndInSubject, subjectEnd)) | [
"def",
"_sanityCheck",
"(",
"subjectStart",
",",
"subjectEnd",
",",
"queryStart",
",",
"queryEnd",
",",
"queryStartInSubject",
",",
"queryEndInSubject",
",",
"hsp",
",",
"queryLen",
",",
"subjectGaps",
",",
"queryGaps",
",",
"localDict",
")",
":",
"# Subject indic... | Perform some sanity checks on an HSP. Call _debugPrint on any error.
@param subjectStart: The 0-based C{int} start offset of the match in the
subject.
@param subjectEnd: The 0-based C{int} end offset of the match in the
subject.
@param queryStart: The 0-based C{int} start offset of the match in the
query.
@param queryEnd: The 0-based C{int} end offset of the match in the query.
@param queryStartInSubject: The 0-based C{int} offset of where the query
starts in the subject.
@param queryEndInSubject: The 0-based C{int} offset of where the query
ends in the subject.
@param hsp: The HSP C{dict} passed to normalizeHSP.
@param queryLen: the C{int} length of the query sequence.
@param subjectGaps: the C{int} number of gaps in the subject.
@param queryGaps: the C{int} number of gaps in the query.
@param localDict: A C{dict} of local variables from our caller (as
produced by locals()). | [
"Perform",
"some",
"sanity",
"checks",
"on",
"an",
"HSP",
".",
"Call",
"_debugPrint",
"on",
"any",
"error",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/hsp.py#L34-L82 |
acorg/dark-matter | dark/diamond/hsp.py | normalizeHSP | def normalizeHSP(hsp, queryLen, diamondTask):
"""
Examine an HSP and return information about where the query and subject
match begins and ends. Return a dict with keys that allow the query to
be displayed against the subject. The returned readStartInSubject and
readEndInSubject indices are offsets into the subject. I.e., they
indicate where in the subject the query falls.
In the returned object, all indices are suitable for Python string
slicing etc. We must be careful to convert from the 1-based offsets
found in DIAMOND output properly.
hsp['frame'] is a value from {-3, -2, -1, 1, 2, 3}. The sign indicates
negative or positive sense (i.e., the direction of reading through the
query to get the alignment). The frame value is the nucleotide match offset
modulo 3, plus one (i.e., it tells us which of the 3 possible query reading
frames was used in the match).
NOTE: the returned readStartInSubject value may be negative. We consider
the subject sequence to start at offset 0. So if the query string has
sufficient additional nucleotides before the start of the alignment
match, it may protrude to the left of the subject. Similarly, the returned
readEndInSubject can be greater than the subjectEnd.
@param hsp: an HSP in the form of a C{dict}, built from a DIAMOND record.
All passed offsets are 1-based.
@param queryLen: the length of the query sequence.
@param diamondTask: The C{str} command-line matching algorithm that was
run (either 'blastx' or 'blastp').
@return: A C{dict} with C{str} keys and C{int} offset values. Keys are
readStart
readEnd
readStartInSubject
readEndInSubject
subjectStart
subjectEnd
The returned offset values are all zero-based.
"""
queryGaps, subjectGaps = countGaps(hsp['btop'])
# Make some variables using Python's standard string indexing (start
# offset included, end offset not). No calculations in this function
# are done with the original 1-based HSP variables.
queryStart = hsp['query_start'] - 1
queryEnd = hsp['query_end']
subjectStart = hsp['sbjct_start'] - 1
subjectEnd = hsp['sbjct_end']
queryReversed = hsp['frame'] < 0
# Query offsets must be ascending, unless we're looking at blastx output
# and the query was reversed for the match.
if queryStart >= queryEnd:
if diamondTask == 'blastx' and queryReversed:
# Compute new query start and end indices, based on their
# distance from the end of the string.
#
# Above we took one off the start index, so we need to undo
# that (because the start is actually the end). We didn't take
# one off the end index, and need to do that now (because the
# end is actually the start).
queryStart = queryLen - (queryStart + 1)
queryEnd = queryLen - (queryEnd - 1)
else:
_debugPrint(hsp, queryLen, locals(), 'queryStart >= queryEnd')
if diamondTask == 'blastx':
# In DIAMOND blastx output, subject offsets are based on protein
# sequence length but queries (and the reported offsets) are
# nucleotide. Convert the query offsets to protein because we will
# plot against the subject (protein).
#
# Convert queryLen and the query nucleotide start and end offsets
# to be valid for the query after translation to AAs. When
# translating, DIAMOND may ignore some nucleotides at the start
# and/or the end of the original DNA query. At the start this is
# due to the frame in use, and at the end it is due to always using
# three nucleotides at a time to form codons.
#
# So, for example, a query of 6 nucleotides that is translated in
# frame 2 (i.e., the translation starts from the second nucleotide)
# will have length 1 as an AA sequence. The first nucleotide is
# ignored due to the frame and the last two due to there not being
# enough final nucleotides to make another codon.
#
# In the following, the subtraction accounts for the first form of
# loss and the integer division for the second.
initiallyIgnored = abs(hsp['frame']) - 1
queryLen = (queryLen - initiallyIgnored) // 3
queryStart = (queryStart - initiallyIgnored) // 3
queryEnd = (queryEnd - initiallyIgnored) // 3
# unmatchedQueryLeft is the number of query bases that will extend
# to the left of the start of the subject in our plots.
unmatchedQueryLeft = queryStart
# Set the query offsets into the subject.
queryStartInSubject = subjectStart - unmatchedQueryLeft
queryEndInSubject = queryStartInSubject + queryLen + queryGaps
_sanityCheck(subjectStart, subjectEnd, queryStart, queryEnd,
queryStartInSubject, queryEndInSubject, hsp, queryLen,
subjectGaps, queryGaps, locals())
return {
'readStart': queryStart,
'readEnd': queryEnd,
'readStartInSubject': queryStartInSubject,
'readEndInSubject': queryEndInSubject,
'subjectStart': subjectStart,
'subjectEnd': subjectEnd,
} | python | def normalizeHSP(hsp, queryLen, diamondTask):
"""
Examine an HSP and return information about where the query and subject
match begins and ends. Return a dict with keys that allow the query to
be displayed against the subject. The returned readStartInSubject and
readEndInSubject indices are offsets into the subject. I.e., they
indicate where in the subject the query falls.
In the returned object, all indices are suitable for Python string
slicing etc. We must be careful to convert from the 1-based offsets
found in DIAMOND output properly.
hsp['frame'] is a value from {-3, -2, -1, 1, 2, 3}. The sign indicates
negative or positive sense (i.e., the direction of reading through the
query to get the alignment). The frame value is the nucleotide match offset
modulo 3, plus one (i.e., it tells us which of the 3 possible query reading
frames was used in the match).
NOTE: the returned readStartInSubject value may be negative. We consider
the subject sequence to start at offset 0. So if the query string has
sufficient additional nucleotides before the start of the alignment
match, it may protrude to the left of the subject. Similarly, the returned
readEndInSubject can be greater than the subjectEnd.
@param hsp: an HSP in the form of a C{dict}, built from a DIAMOND record.
All passed offsets are 1-based.
@param queryLen: the length of the query sequence.
@param diamondTask: The C{str} command-line matching algorithm that was
run (either 'blastx' or 'blastp').
@return: A C{dict} with C{str} keys and C{int} offset values. Keys are
readStart
readEnd
readStartInSubject
readEndInSubject
subjectStart
subjectEnd
The returned offset values are all zero-based.
"""
queryGaps, subjectGaps = countGaps(hsp['btop'])
# Make some variables using Python's standard string indexing (start
# offset included, end offset not). No calculations in this function
# are done with the original 1-based HSP variables.
queryStart = hsp['query_start'] - 1
queryEnd = hsp['query_end']
subjectStart = hsp['sbjct_start'] - 1
subjectEnd = hsp['sbjct_end']
queryReversed = hsp['frame'] < 0
# Query offsets must be ascending, unless we're looking at blastx output
# and the query was reversed for the match.
if queryStart >= queryEnd:
if diamondTask == 'blastx' and queryReversed:
# Compute new query start and end indices, based on their
# distance from the end of the string.
#
# Above we took one off the start index, so we need to undo
# that (because the start is actually the end). We didn't take
# one off the end index, and need to do that now (because the
# end is actually the start).
queryStart = queryLen - (queryStart + 1)
queryEnd = queryLen - (queryEnd - 1)
else:
_debugPrint(hsp, queryLen, locals(), 'queryStart >= queryEnd')
if diamondTask == 'blastx':
# In DIAMOND blastx output, subject offsets are based on protein
# sequence length but queries (and the reported offsets) are
# nucleotide. Convert the query offsets to protein because we will
# plot against the subject (protein).
#
# Convert queryLen and the query nucleotide start and end offsets
# to be valid for the query after translation to AAs. When
# translating, DIAMOND may ignore some nucleotides at the start
# and/or the end of the original DNA query. At the start this is
# due to the frame in use, and at the end it is due to always using
# three nucleotides at a time to form codons.
#
# So, for example, a query of 6 nucleotides that is translated in
# frame 2 (i.e., the translation starts from the second nucleotide)
# will have length 1 as an AA sequence. The first nucleotide is
# ignored due to the frame and the last two due to there not being
# enough final nucleotides to make another codon.
#
# In the following, the subtraction accounts for the first form of
# loss and the integer division for the second.
initiallyIgnored = abs(hsp['frame']) - 1
queryLen = (queryLen - initiallyIgnored) // 3
queryStart = (queryStart - initiallyIgnored) // 3
queryEnd = (queryEnd - initiallyIgnored) // 3
# unmatchedQueryLeft is the number of query bases that will extend
# to the left of the start of the subject in our plots.
unmatchedQueryLeft = queryStart
# Set the query offsets into the subject.
queryStartInSubject = subjectStart - unmatchedQueryLeft
queryEndInSubject = queryStartInSubject + queryLen + queryGaps
_sanityCheck(subjectStart, subjectEnd, queryStart, queryEnd,
queryStartInSubject, queryEndInSubject, hsp, queryLen,
subjectGaps, queryGaps, locals())
return {
'readStart': queryStart,
'readEnd': queryEnd,
'readStartInSubject': queryStartInSubject,
'readEndInSubject': queryEndInSubject,
'subjectStart': subjectStart,
'subjectEnd': subjectEnd,
} | [
"def",
"normalizeHSP",
"(",
"hsp",
",",
"queryLen",
",",
"diamondTask",
")",
":",
"queryGaps",
",",
"subjectGaps",
"=",
"countGaps",
"(",
"hsp",
"[",
"'btop'",
"]",
")",
"# Make some variables using Python's standard string indexing (start",
"# offset included, end offset... | Examine an HSP and return information about where the query and subject
match begins and ends. Return a dict with keys that allow the query to
be displayed against the subject. The returned readStartInSubject and
readEndInSubject indices are offsets into the subject. I.e., they
indicate where in the subject the query falls.
In the returned object, all indices are suitable for Python string
slicing etc. We must be careful to convert from the 1-based offsets
found in DIAMOND output properly.
hsp['frame'] is a value from {-3, -2, -1, 1, 2, 3}. The sign indicates
negative or positive sense (i.e., the direction of reading through the
query to get the alignment). The frame value is the nucleotide match offset
modulo 3, plus one (i.e., it tells us which of the 3 possible query reading
frames was used in the match).
NOTE: the returned readStartInSubject value may be negative. We consider
the subject sequence to start at offset 0. So if the query string has
sufficient additional nucleotides before the start of the alignment
match, it may protrude to the left of the subject. Similarly, the returned
readEndInSubject can be greater than the subjectEnd.
@param hsp: an HSP in the form of a C{dict}, built from a DIAMOND record.
All passed offsets are 1-based.
@param queryLen: the length of the query sequence.
@param diamondTask: The C{str} command-line matching algorithm that was
run (either 'blastx' or 'blastp').
@return: A C{dict} with C{str} keys and C{int} offset values. Keys are
readStart
readEnd
readStartInSubject
readEndInSubject
subjectStart
subjectEnd
The returned offset values are all zero-based. | [
"Examine",
"an",
"HSP",
"and",
"return",
"information",
"about",
"where",
"the",
"query",
"and",
"subject",
"match",
"begins",
"and",
"ends",
".",
"Return",
"a",
"dict",
"with",
"keys",
"that",
"allow",
"the",
"query",
"to",
"be",
"displayed",
"against",
"... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/hsp.py#L85-L197 |
flo-compbio/genometools | genometools/gcloud/service_account.py | get_storage_credentials | def get_storage_credentials(key, read_only=False):
"""Authenticates a service account for reading and/or writing on a bucket.
This uses the `google.oauth2.service_account` module to obtain "scoped
credentials". These can be used with the `google.storage` module.
TODO: docstring"""
if read_only:
scopes = ['https://www.googleapis.com/auth/devstorage.read_only']
else:
scopes = ['https://www.googleapis.com/auth/devstorage.read_write']
credentials = service_account.Credentials.from_service_account_info(key)
scoped_credentials = credentials.with_scopes(scopes)
return scoped_credentials | python | def get_storage_credentials(key, read_only=False):
"""Authenticates a service account for reading and/or writing on a bucket.
This uses the `google.oauth2.service_account` module to obtain "scoped
credentials". These can be used with the `google.storage` module.
TODO: docstring"""
if read_only:
scopes = ['https://www.googleapis.com/auth/devstorage.read_only']
else:
scopes = ['https://www.googleapis.com/auth/devstorage.read_write']
credentials = service_account.Credentials.from_service_account_info(key)
scoped_credentials = credentials.with_scopes(scopes)
return scoped_credentials | [
"def",
"get_storage_credentials",
"(",
"key",
",",
"read_only",
"=",
"False",
")",
":",
"if",
"read_only",
":",
"scopes",
"=",
"[",
"'https://www.googleapis.com/auth/devstorage.read_only'",
"]",
"else",
":",
"scopes",
"=",
"[",
"'https://www.googleapis.com/auth/devstora... | Authenticates a service account for reading and/or writing on a bucket.
This uses the `google.oauth2.service_account` module to obtain "scoped
credentials". These can be used with the `google.storage` module.
TODO: docstring | [
"Authenticates",
"a",
"service",
"account",
"for",
"reading",
"and",
"/",
"or",
"writing",
"on",
"a",
"bucket",
".",
"This",
"uses",
"the",
"google",
".",
"oauth2",
".",
"service_account",
"module",
"to",
"obtain",
"scoped",
"credentials",
".",
"These",
"can... | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/service_account.py#L9-L25 |
flo-compbio/genometools | genometools/gcloud/service_account.py | get_compute_credentials | def get_compute_credentials(key):
"""Authenticates a service account for the compute engine.
This uses the `oauth2client.service_account` module. Since the `google`
Python package does not support the compute engine (yet?), we need to make
direct HTTP requests. For that we need authentication tokens. Obtaining
these based on the credentials provided by the `google.auth2` module is
much more cumbersome than using the `oauth2client` module.
See:
- https://cloud.google.com/iap/docs/authentication-howto
- https://developers.google.com/identity/protocols/OAuth2ServiceAccount
TODO: docstring"""
scopes = ['https://www.googleapis.com/auth/compute']
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
key, scopes=scopes)
return credentials | python | def get_compute_credentials(key):
"""Authenticates a service account for the compute engine.
This uses the `oauth2client.service_account` module. Since the `google`
Python package does not support the compute engine (yet?), we need to make
direct HTTP requests. For that we need authentication tokens. Obtaining
these based on the credentials provided by the `google.auth2` module is
much more cumbersome than using the `oauth2client` module.
See:
- https://cloud.google.com/iap/docs/authentication-howto
- https://developers.google.com/identity/protocols/OAuth2ServiceAccount
TODO: docstring"""
scopes = ['https://www.googleapis.com/auth/compute']
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
key, scopes=scopes)
return credentials | [
"def",
"get_compute_credentials",
"(",
"key",
")",
":",
"scopes",
"=",
"[",
"'https://www.googleapis.com/auth/compute'",
"]",
"credentials",
"=",
"ServiceAccountCredentials",
".",
"from_json_keyfile_dict",
"(",
"key",
",",
"scopes",
"=",
"scopes",
")",
"return",
"cred... | Authenticates a service account for the compute engine.
This uses the `oauth2client.service_account` module. Since the `google`
Python package does not support the compute engine (yet?), we need to make
direct HTTP requests. For that we need authentication tokens. Obtaining
these based on the credentials provided by the `google.auth2` module is
much more cumbersome than using the `oauth2client` module.
See:
- https://cloud.google.com/iap/docs/authentication-howto
- https://developers.google.com/identity/protocols/OAuth2ServiceAccount
TODO: docstring | [
"Authenticates",
"a",
"service",
"account",
"for",
"the",
"compute",
"engine",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/service_account.py#L28-L47 |
flo-compbio/genometools | genometools/expression/gene_table.py | ExpGeneTable.hash | def hash(self):
"""Generate a hash value."""
h = hash_pandas_object(self, index=True)
return hashlib.md5(h.values.tobytes()).hexdigest() | python | def hash(self):
"""Generate a hash value."""
h = hash_pandas_object(self, index=True)
return hashlib.md5(h.values.tobytes()).hexdigest() | [
"def",
"hash",
"(",
"self",
")",
":",
"h",
"=",
"hash_pandas_object",
"(",
"self",
",",
"index",
"=",
"True",
")",
"return",
"hashlib",
".",
"md5",
"(",
"h",
".",
"values",
".",
"tobytes",
"(",
")",
")",
".",
"hexdigest",
"(",
")"
] | Generate a hash value. | [
"Generate",
"a",
"hash",
"value",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/gene_table.py#L86-L89 |
flo-compbio/genometools | genometools/expression/gene_table.py | ExpGeneTable.genes | def genes(self):
"""Return a list of all genes."""
return [ExpGene.from_series(g)
for i, g in self.reset_index().iterrows()] | python | def genes(self):
"""Return a list of all genes."""
return [ExpGene.from_series(g)
for i, g in self.reset_index().iterrows()] | [
"def",
"genes",
"(",
"self",
")",
":",
"return",
"[",
"ExpGene",
".",
"from_series",
"(",
"g",
")",
"for",
"i",
",",
"g",
"in",
"self",
".",
"reset_index",
"(",
")",
".",
"iterrows",
"(",
")",
"]"
] | Return a list of all genes. | [
"Return",
"a",
"list",
"of",
"all",
"genes",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/gene_table.py#L97-L100 |
flo-compbio/genometools | genometools/expression/gene_table.py | ExpGeneTable.read_tsv | def read_tsv(cls, file_or_buffer: str):
"""Read genes from tab-delimited text file."""
df = pd.read_csv(file_or_buffer, sep='\t', index_col=0)
df = df.where(pd.notnull(df), None)
# Note: df.where(..., None) changes all column types to `object`.
return cls(df) | python | def read_tsv(cls, file_or_buffer: str):
"""Read genes from tab-delimited text file."""
df = pd.read_csv(file_or_buffer, sep='\t', index_col=0)
df = df.where(pd.notnull(df), None)
# Note: df.where(..., None) changes all column types to `object`.
return cls(df) | [
"def",
"read_tsv",
"(",
"cls",
",",
"file_or_buffer",
":",
"str",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"file_or_buffer",
",",
"sep",
"=",
"'\\t'",
",",
"index_col",
"=",
"0",
")",
"df",
"=",
"df",
".",
"where",
"(",
"pd",
".",
"notnull"... | Read genes from tab-delimited text file. | [
"Read",
"genes",
"from",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/gene_table.py#L113-L118 |
flo-compbio/genometools | genometools/expression/gene_table.py | ExpGeneTable.from_genes | def from_genes(cls, genes: List[ExpGene]):
"""Initialize instance using a list of `ExpGene` objects."""
data = [g.to_dict() for g in genes]
index = [d.pop('ensembl_id') for d in data]
table = cls(data, index=index)
return table | python | def from_genes(cls, genes: List[ExpGene]):
"""Initialize instance using a list of `ExpGene` objects."""
data = [g.to_dict() for g in genes]
index = [d.pop('ensembl_id') for d in data]
table = cls(data, index=index)
return table | [
"def",
"from_genes",
"(",
"cls",
",",
"genes",
":",
"List",
"[",
"ExpGene",
"]",
")",
":",
"data",
"=",
"[",
"g",
".",
"to_dict",
"(",
")",
"for",
"g",
"in",
"genes",
"]",
"index",
"=",
"[",
"d",
".",
"pop",
"(",
"'ensembl_id'",
")",
"for",
"d"... | Initialize instance using a list of `ExpGene` objects. | [
"Initialize",
"instance",
"using",
"a",
"list",
"of",
"ExpGene",
"objects",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/gene_table.py#L121-L126 |
flo-compbio/genometools | genometools/expression/gene_table.py | ExpGeneTable.from_gene_ids | def from_gene_ids(cls, gene_ids: List[str]):
"""Initialize instance from gene IDs."""
genes = [ExpGene(id_) for id_ in gene_ids]
return cls.from_genes(genes) | python | def from_gene_ids(cls, gene_ids: List[str]):
"""Initialize instance from gene IDs."""
genes = [ExpGene(id_) for id_ in gene_ids]
return cls.from_genes(genes) | [
"def",
"from_gene_ids",
"(",
"cls",
",",
"gene_ids",
":",
"List",
"[",
"str",
"]",
")",
":",
"genes",
"=",
"[",
"ExpGene",
"(",
"id_",
")",
"for",
"id_",
"in",
"gene_ids",
"]",
"return",
"cls",
".",
"from_genes",
"(",
"genes",
")"
] | Initialize instance from gene IDs. | [
"Initialize",
"instance",
"from",
"gene",
"IDs",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/gene_table.py#L129-L132 |
flo-compbio/genometools | genometools/expression/gene_table.py | ExpGeneTable.from_gene_ids_and_names | def from_gene_ids_and_names(cls, gene_names: Dict[str, str]):
"""Initialize instance from gene IDs and names."""
genes = [ExpGene(id_, name=name) for id_, name in gene_names.items()]
return cls.from_genes(genes) | python | def from_gene_ids_and_names(cls, gene_names: Dict[str, str]):
"""Initialize instance from gene IDs and names."""
genes = [ExpGene(id_, name=name) for id_, name in gene_names.items()]
return cls.from_genes(genes) | [
"def",
"from_gene_ids_and_names",
"(",
"cls",
",",
"gene_names",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
":",
"genes",
"=",
"[",
"ExpGene",
"(",
"id_",
",",
"name",
"=",
"name",
")",
"for",
"id_",
",",
"name",
"in",
"gene_names",
".",
"items",... | Initialize instance from gene IDs and names. | [
"Initialize",
"instance",
"from",
"gene",
"IDs",
"and",
"names",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/gene_table.py#L135-L138 |
flo-compbio/genometools | genometools/expression/gene_table.py | ExpGeneTable.find_gene | def find_gene(self, name: str):
"""Find gene(s) by name."""
result = [ExpGene.from_series(s)
for i, s in self.loc[self['name'] == name].iterrows()]
return result | python | def find_gene(self, name: str):
"""Find gene(s) by name."""
result = [ExpGene.from_series(s)
for i, s in self.loc[self['name'] == name].iterrows()]
return result | [
"def",
"find_gene",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"result",
"=",
"[",
"ExpGene",
".",
"from_series",
"(",
"s",
")",
"for",
"i",
",",
"s",
"in",
"self",
".",
"loc",
"[",
"self",
"[",
"'name'",
"]",
"==",
"name",
"]",
".",
"iter... | Find gene(s) by name. | [
"Find",
"gene",
"(",
"s",
")",
"by",
"name",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/gene_table.py#L149-L153 |
flo-compbio/genometools | genometools/expression/visualize/corr_heatmap.py | SampleCorrelationHeatmap.get_figure | def get_figure(self, **kwargs):
"""Get a plotly figure of the heatmap."""
emin = kwargs.pop('emin', -1.0)
emax = kwargs.pop('emax', 1.0)
width = kwargs.pop('width', 800)
height = kwargs.pop('height', 600)
margin_left = kwargs.pop('margin_left', 100)
margin_bottom = kwargs.pop('margin_bottom', 60)
margin_top = kwargs.pop('margin_top', 30)
margin_right = kwargs.pop('margin_right', 0)
colorbar_size = kwargs.pop('colorbar_size', 0.4)
xaxis_label = kwargs.pop('xaxis_label', None)
yaxis_label = kwargs.pop('yaxis_label', None)
xticks_angle = kwargs.pop('xaxis_angle', 30)
font = kwargs.pop('font', '"Droid Serif", "Open Serif", serif')
font_size = kwargs.pop('font_size', 12)
title = kwargs.pop('title', None)
title_font_size = kwargs.pop('title_font_size', None)
annotation_font_size = kwargs.pop('annotation_font_size', None)
show_sample_labels = kwargs.pop('show_sample_labels', 'x')
if show_sample_labels not in ['none', 'x', 'y', 'both']:
raise ValueError('"show_sample_labels" must be "none", "x", "y", '
'or "both".')
padding_top = kwargs.pop('padding_top', 0.1)
padding_right = kwargs.pop('padding_top', 0.1)
xaxis_nticks = kwargs.pop('xaxis_nticks', None)
#yaxis_nticks = kwargs.pop('yaxis_nticks', None)
if title_font_size is None:
title_font_size = font_size
if annotation_font_size is None:
annotation_font_size = font_size
colorbar_label = self.colorbar_label or 'Pearson Correlation'
### set up heatmap
colorbar = go.ColorBar(
lenmode='fraction',
len=colorbar_size,
title=colorbar_label,
titlefont = dict(
size=title_font_size,
),
titleside='right',
xpad=0,
ypad=0,
outlinewidth=0, # no border
thickness=20, # in pixels
# outlinecolor = '#000000',
)
def fix_plotly_label_bug(labels):
"""
This fixes a bug whereby plotly treats labels that look
like numbers (integers or floats) as numeric instead of
categorical, even when they are passed as strings. The fix consists
of appending an underscore to any label that looks like a number.
"""
assert isinstance(labels, Iterable)
fixed_labels = []
for l in labels:
try:
float(l)
except ValueError:
fixed_labels.append(str(l))
else:
fixed_labels.append(str(l) + '_')
return fixed_labels
x = fix_plotly_label_bug(self.corr_matrix.samples)
y = x
data = [
go.Heatmap(
z=self.corr_matrix.X,
x=x,
y=y,
zmin=emin,
zmax=emax,
colorscale=self.colorscale,
colorbar=colorbar,
hoverinfo='x+y+z',
**kwargs
),
]
xshowticklabels = False
yshowticklabels = False
### set up layout
if show_sample_labels == 'x':
xshowticklabels = True
elif show_sample_labels == 'y':
yshowticklabels = True
elif show_sample_labels == 'both':
xshowticklabels = True
yshowticklabels = True
xticks = 'outside'
yticks = 'outside'
if xaxis_label is None:
if self.corr_matrix.samples.name is not None:
xaxis_label = self.corr_matrix.samples.name
else:
xaxis_label = 'Samples'
xaxis_label = xaxis_label + ' (n = %d)' % self.corr_matrix.n
if yaxis_label is None:
yaxis_label = xaxis_label
layout = go.Layout(
width=width,
height=height,
title=title,
titlefont=go.Font(
size=title_font_size
),
font=go.Font(
size=font_size,
family=font
),
xaxis=go.XAxis(
title=xaxis_label,
titlefont=dict(size=title_font_size),
showticklabels=xshowticklabels,
ticks=xticks,
nticks=xaxis_nticks,
tickangle=xticks_angle,
#range=[-0.5, self.corr_matrix.n-0.5],
showline=True,
zeroline=False,
showgrid=False,
),
yaxis=go.YAxis(
title=yaxis_label,
titlefont=dict(size=title_font_size),
showticklabels=yshowticklabels,
ticks=xticks,
nticks=xaxis_nticks,
autorange='reversed',
showline=True,
zeroline=False,
showgrid=False,
),
margin=go.Margin(
l=margin_left,
t=margin_top,
b=margin_bottom,
r=margin_right,
pad=0
),
)
### add annotations
# we need separate, but overlaying, axes to place the annotations
layout['xaxis2'] = go.XAxis(
overlaying='x',
showline=False,
tickfont=dict(size=0),
autorange=False,
#range=[-0.5, self.corr_matrix.n-0.5],
range=[-0.5, self.corr_matrix.n-0.5],
ticks='',
showticklabels=False,
zeroline=False,
showgrid=False,
)
layout['yaxis2'] = go.YAxis(
overlaying='y',
showline=False,
tickfont=dict(size=0),
autorange=False,
range=[self.corr_matrix.n-0.5, -0.5],
ticks='',
showticklabels=False,
zeroline=False,
showgrid=False,
)
# generate coordinates and labels for the block annotations
k = len(self.block_annotations)
block_coords = np.zeros((k, 2), dtype=np.float64)
block_labels = []
for i, ann in enumerate(self.block_annotations):
block_coords[i, :] = [ann.start_index-0.5, ann.end_index+0.5]
block_labels.append(ann.label)
# this produces the squares for the block annotations
for i in range(k):
mn = block_coords[i, 0]
mx = block_coords[i, 1]
data.append(
go.Scatter(
x=[mn, mx, mx, mn, mn],
y=[mn, mn, mx, mx, mn],
mode='lines',
hoverinfo='none',
showlegend=False,
line=dict(color='black'),
xaxis='x2',
yaxis='y2',
)
)
# - this produces the square labels for the block annotations
# - we use plotly annotations, so that the labels are not limited
# by the plotting area
for i in range(k):
mn = block_coords[i, 0]
mx = block_coords[i, 1]
layout.annotations.append(
dict(
x=mx,
y=(mn+mx)/2.0,
text=block_labels[i],
xref='x2',
yref='y2',
showarrow=False,
#ax=20,
#ay=-20,
xanchor='left',
yanchor='middle',
font=dict(
color='black',
size=annotation_font_size,
family='serif bold',
),
bgcolor='white',
opacity=0.7,
#textanchor='top right'
)
)
fig = go.Figure(
data=data,
layout=layout
)
return fig | python | def get_figure(self, **kwargs):
"""Get a plotly figure of the heatmap."""
emin = kwargs.pop('emin', -1.0)
emax = kwargs.pop('emax', 1.0)
width = kwargs.pop('width', 800)
height = kwargs.pop('height', 600)
margin_left = kwargs.pop('margin_left', 100)
margin_bottom = kwargs.pop('margin_bottom', 60)
margin_top = kwargs.pop('margin_top', 30)
margin_right = kwargs.pop('margin_right', 0)
colorbar_size = kwargs.pop('colorbar_size', 0.4)
xaxis_label = kwargs.pop('xaxis_label', None)
yaxis_label = kwargs.pop('yaxis_label', None)
xticks_angle = kwargs.pop('xaxis_angle', 30)
font = kwargs.pop('font', '"Droid Serif", "Open Serif", serif')
font_size = kwargs.pop('font_size', 12)
title = kwargs.pop('title', None)
title_font_size = kwargs.pop('title_font_size', None)
annotation_font_size = kwargs.pop('annotation_font_size', None)
show_sample_labels = kwargs.pop('show_sample_labels', 'x')
if show_sample_labels not in ['none', 'x', 'y', 'both']:
raise ValueError('"show_sample_labels" must be "none", "x", "y", '
'or "both".')
padding_top = kwargs.pop('padding_top', 0.1)
padding_right = kwargs.pop('padding_top', 0.1)
xaxis_nticks = kwargs.pop('xaxis_nticks', None)
#yaxis_nticks = kwargs.pop('yaxis_nticks', None)
if title_font_size is None:
title_font_size = font_size
if annotation_font_size is None:
annotation_font_size = font_size
colorbar_label = self.colorbar_label or 'Pearson Correlation'
### set up heatmap
colorbar = go.ColorBar(
lenmode='fraction',
len=colorbar_size,
title=colorbar_label,
titlefont = dict(
size=title_font_size,
),
titleside='right',
xpad=0,
ypad=0,
outlinewidth=0, # no border
thickness=20, # in pixels
# outlinecolor = '#000000',
)
def fix_plotly_label_bug(labels):
"""
This fixes a bug whereby plotly treats labels that look
like numbers (integers or floats) as numeric instead of
categorical, even when they are passed as strings. The fix consists
of appending an underscore to any label that looks like a number.
"""
assert isinstance(labels, Iterable)
fixed_labels = []
for l in labels:
try:
float(l)
except ValueError:
fixed_labels.append(str(l))
else:
fixed_labels.append(str(l) + '_')
return fixed_labels
x = fix_plotly_label_bug(self.corr_matrix.samples)
y = x
data = [
go.Heatmap(
z=self.corr_matrix.X,
x=x,
y=y,
zmin=emin,
zmax=emax,
colorscale=self.colorscale,
colorbar=colorbar,
hoverinfo='x+y+z',
**kwargs
),
]
xshowticklabels = False
yshowticklabels = False
### set up layout
if show_sample_labels == 'x':
xshowticklabels = True
elif show_sample_labels == 'y':
yshowticklabels = True
elif show_sample_labels == 'both':
xshowticklabels = True
yshowticklabels = True
xticks = 'outside'
yticks = 'outside'
if xaxis_label is None:
if self.corr_matrix.samples.name is not None:
xaxis_label = self.corr_matrix.samples.name
else:
xaxis_label = 'Samples'
xaxis_label = xaxis_label + ' (n = %d)' % self.corr_matrix.n
if yaxis_label is None:
yaxis_label = xaxis_label
layout = go.Layout(
width=width,
height=height,
title=title,
titlefont=go.Font(
size=title_font_size
),
font=go.Font(
size=font_size,
family=font
),
xaxis=go.XAxis(
title=xaxis_label,
titlefont=dict(size=title_font_size),
showticklabels=xshowticklabels,
ticks=xticks,
nticks=xaxis_nticks,
tickangle=xticks_angle,
#range=[-0.5, self.corr_matrix.n-0.5],
showline=True,
zeroline=False,
showgrid=False,
),
yaxis=go.YAxis(
title=yaxis_label,
titlefont=dict(size=title_font_size),
showticklabels=yshowticklabels,
ticks=xticks,
nticks=xaxis_nticks,
autorange='reversed',
showline=True,
zeroline=False,
showgrid=False,
),
margin=go.Margin(
l=margin_left,
t=margin_top,
b=margin_bottom,
r=margin_right,
pad=0
),
)
### add annotations
# we need separate, but overlaying, axes to place the annotations
layout['xaxis2'] = go.XAxis(
overlaying='x',
showline=False,
tickfont=dict(size=0),
autorange=False,
#range=[-0.5, self.corr_matrix.n-0.5],
range=[-0.5, self.corr_matrix.n-0.5],
ticks='',
showticklabels=False,
zeroline=False,
showgrid=False,
)
layout['yaxis2'] = go.YAxis(
overlaying='y',
showline=False,
tickfont=dict(size=0),
autorange=False,
range=[self.corr_matrix.n-0.5, -0.5],
ticks='',
showticklabels=False,
zeroline=False,
showgrid=False,
)
# generate coordinates and labels for the block annotations
k = len(self.block_annotations)
block_coords = np.zeros((k, 2), dtype=np.float64)
block_labels = []
for i, ann in enumerate(self.block_annotations):
block_coords[i, :] = [ann.start_index-0.5, ann.end_index+0.5]
block_labels.append(ann.label)
# this produces the squares for the block annotations
for i in range(k):
mn = block_coords[i, 0]
mx = block_coords[i, 1]
data.append(
go.Scatter(
x=[mn, mx, mx, mn, mn],
y=[mn, mn, mx, mx, mn],
mode='lines',
hoverinfo='none',
showlegend=False,
line=dict(color='black'),
xaxis='x2',
yaxis='y2',
)
)
# - this produces the square labels for the block annotations
# - we use plotly annotations, so that the labels are not limited
# by the plotting area
for i in range(k):
mn = block_coords[i, 0]
mx = block_coords[i, 1]
layout.annotations.append(
dict(
x=mx,
y=(mn+mx)/2.0,
text=block_labels[i],
xref='x2',
yref='y2',
showarrow=False,
#ax=20,
#ay=-20,
xanchor='left',
yanchor='middle',
font=dict(
color='black',
size=annotation_font_size,
family='serif bold',
),
bgcolor='white',
opacity=0.7,
#textanchor='top right'
)
)
fig = go.Figure(
data=data,
layout=layout
)
return fig | [
"def",
"get_figure",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"emin",
"=",
"kwargs",
".",
"pop",
"(",
"'emin'",
",",
"-",
"1.0",
")",
"emax",
"=",
"kwargs",
".",
"pop",
"(",
"'emax'",
",",
"1.0",
")",
"width",
"=",
"kwargs",
".",
"pop",
... | Get a plotly figure of the heatmap. | [
"Get",
"a",
"plotly",
"figure",
"of",
"the",
"heatmap",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/visualize/corr_heatmap.py#L79-L328 |
ownport/scrapy-dblite | dblite/__init__.py | copy | def copy(src, trg, transform=None):
''' copy items with optional fields transformation
'''
source = open(src[0], src[1])
target = open(trg[0], trg[1], autocommit=1000)
for item in source.get():
item = dict(item)
if '_id' in item:
del item['_id']
if transform:
item = transform(item)
target.put(trg[0](item))
source.close()
target.commit()
target.close() | python | def copy(src, trg, transform=None):
''' copy items with optional fields transformation
'''
source = open(src[0], src[1])
target = open(trg[0], trg[1], autocommit=1000)
for item in source.get():
item = dict(item)
if '_id' in item:
del item['_id']
if transform:
item = transform(item)
target.put(trg[0](item))
source.close()
target.commit()
target.close() | [
"def",
"copy",
"(",
"src",
",",
"trg",
",",
"transform",
"=",
"None",
")",
":",
"source",
"=",
"open",
"(",
"src",
"[",
"0",
"]",
",",
"src",
"[",
"1",
"]",
")",
"target",
"=",
"open",
"(",
"trg",
"[",
"0",
"]",
",",
"trg",
"[",
"1",
"]",
... | copy items with optional fields transformation | [
"copy",
"items",
"with",
"optional",
"fields",
"transformation"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L34-L51 |
ownport/scrapy-dblite | dblite/__init__.py | _regexp | def _regexp(expr, item):
''' REGEXP function for Sqlite
'''
reg = re.compile(expr)
return reg.search(item) is not None | python | def _regexp(expr, item):
''' REGEXP function for Sqlite
'''
reg = re.compile(expr)
return reg.search(item) is not None | [
"def",
"_regexp",
"(",
"expr",
",",
"item",
")",
":",
"reg",
"=",
"re",
".",
"compile",
"(",
"expr",
")",
"return",
"reg",
".",
"search",
"(",
"item",
")",
"is",
"not",
"None"
] | REGEXP function for Sqlite | [
"REGEXP",
"function",
"for",
"Sqlite"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L54-L58 |
ownport/scrapy-dblite | dblite/__init__.py | Storage._dict_factory | def _dict_factory(cursor, row):
''' factory for sqlite3 to return results as dict
'''
d = {}
for idx, col in enumerate(cursor.description):
if col[0] == 'rowid':
d['_id'] = row[idx]
else:
d[col[0]] = row[idx]
return d | python | def _dict_factory(cursor, row):
''' factory for sqlite3 to return results as dict
'''
d = {}
for idx, col in enumerate(cursor.description):
if col[0] == 'rowid':
d['_id'] = row[idx]
else:
d[col[0]] = row[idx]
return d | [
"def",
"_dict_factory",
"(",
"cursor",
",",
"row",
")",
":",
"d",
"=",
"{",
"}",
"for",
"idx",
",",
"col",
"in",
"enumerate",
"(",
"cursor",
".",
"description",
")",
":",
"if",
"col",
"[",
"0",
"]",
"==",
"'rowid'",
":",
"d",
"[",
"'_id'",
"]",
... | factory for sqlite3 to return results as dict | [
"factory",
"for",
"sqlite3",
"to",
"return",
"results",
"as",
"dict"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L121-L130 |
ownport/scrapy-dblite | dblite/__init__.py | Storage.parse_uri | def parse_uri(uri):
''' parse URI
'''
if not uri or uri.find('://') <= 0:
raise RuntimeError('Incorrect URI definition: {}'.format(uri))
backend, rest_uri = uri.split('://')
if backend not in SUPPORTED_BACKENDS:
raise RuntimeError('Unknown backend: {}'.format(backend))
database, table = rest_uri.rsplit(':',1)
return database, table | python | def parse_uri(uri):
''' parse URI
'''
if not uri or uri.find('://') <= 0:
raise RuntimeError('Incorrect URI definition: {}'.format(uri))
backend, rest_uri = uri.split('://')
if backend not in SUPPORTED_BACKENDS:
raise RuntimeError('Unknown backend: {}'.format(backend))
database, table = rest_uri.rsplit(':',1)
return database, table | [
"def",
"parse_uri",
"(",
"uri",
")",
":",
"if",
"not",
"uri",
"or",
"uri",
".",
"find",
"(",
"'://'",
")",
"<=",
"0",
":",
"raise",
"RuntimeError",
"(",
"'Incorrect URI definition: {}'",
".",
"format",
"(",
"uri",
")",
")",
"backend",
",",
"rest_uri",
... | parse URI | [
"parse",
"URI"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L133-L143 |
ownport/scrapy-dblite | dblite/__init__.py | Storage.fieldnames | def fieldnames(self):
''' return fieldnames
'''
if not self._fields:
if self._item_class is not None:
for m in inspect.getmembers(self._item_class):
if m[0] == 'fields' and isinstance(m[1], dict):
self._fields = m[1]
if not self._fields:
raise RuntimeError('Unknown item type, no fields: %s' % self._item_class)
else:
raise RuntimeError('Item class is not defined, %s' % self._item_class)
return self._fields.keys() | python | def fieldnames(self):
''' return fieldnames
'''
if not self._fields:
if self._item_class is not None:
for m in inspect.getmembers(self._item_class):
if m[0] == 'fields' and isinstance(m[1], dict):
self._fields = m[1]
if not self._fields:
raise RuntimeError('Unknown item type, no fields: %s' % self._item_class)
else:
raise RuntimeError('Item class is not defined, %s' % self._item_class)
return self._fields.keys() | [
"def",
"fieldnames",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_fields",
":",
"if",
"self",
".",
"_item_class",
"is",
"not",
"None",
":",
"for",
"m",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
".",
"_item_class",
")",
":",
"if",
"m",
... | return fieldnames | [
"return",
"fieldnames"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L146-L158 |
ownport/scrapy-dblite | dblite/__init__.py | Storage._create_table | def _create_table(self, table_name):
''' create sqlite's table for storing simple dictionaries
'''
if self.fieldnames:
sql_fields = []
for field in self._fields:
if field != '_id':
if 'dblite' in self._fields[field]:
sql_fields.append(' '.join([field, self._fields[field]['dblite']]))
else:
sql_fields.append(field)
sql_fields = ','.join(sql_fields)
SQL = 'CREATE TABLE IF NOT EXISTS %s (%s);' % (table_name, sql_fields)
try:
self._cursor.execute(SQL)
except sqlite3.OperationalError, err:
raise RuntimeError('Create table error, %s, SQL: %s' % (err, SQL)) | python | def _create_table(self, table_name):
''' create sqlite's table for storing simple dictionaries
'''
if self.fieldnames:
sql_fields = []
for field in self._fields:
if field != '_id':
if 'dblite' in self._fields[field]:
sql_fields.append(' '.join([field, self._fields[field]['dblite']]))
else:
sql_fields.append(field)
sql_fields = ','.join(sql_fields)
SQL = 'CREATE TABLE IF NOT EXISTS %s (%s);' % (table_name, sql_fields)
try:
self._cursor.execute(SQL)
except sqlite3.OperationalError, err:
raise RuntimeError('Create table error, %s, SQL: %s' % (err, SQL)) | [
"def",
"_create_table",
"(",
"self",
",",
"table_name",
")",
":",
"if",
"self",
".",
"fieldnames",
":",
"sql_fields",
"=",
"[",
"]",
"for",
"field",
"in",
"self",
".",
"_fields",
":",
"if",
"field",
"!=",
"'_id'",
":",
"if",
"'dblite'",
"in",
"self",
... | create sqlite's table for storing simple dictionaries | [
"create",
"sqlite",
"s",
"table",
"for",
"storing",
"simple",
"dictionaries"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L160-L176 |
ownport/scrapy-dblite | dblite/__init__.py | Storage._make_item | def _make_item(self, item):
''' make Item class
'''
for field in self._item_class.fields:
if (field in item) and ('dblite_serializer' in self._item_class.fields[field]):
serializer = self._item_class.fields[field]['dblite_serializer']
item[field] = serializer.loads(item[field])
return self._item_class(item) | python | def _make_item(self, item):
''' make Item class
'''
for field in self._item_class.fields:
if (field in item) and ('dblite_serializer' in self._item_class.fields[field]):
serializer = self._item_class.fields[field]['dblite_serializer']
item[field] = serializer.loads(item[field])
return self._item_class(item) | [
"def",
"_make_item",
"(",
"self",
",",
"item",
")",
":",
"for",
"field",
"in",
"self",
".",
"_item_class",
".",
"fields",
":",
"if",
"(",
"field",
"in",
"item",
")",
"and",
"(",
"'dblite_serializer'",
"in",
"self",
".",
"_item_class",
".",
"fields",
"[... | make Item class | [
"make",
"Item",
"class"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L178-L185 |
ownport/scrapy-dblite | dblite/__init__.py | Storage.get | def get(self, criteria=None, offset=None, limit=None):
''' returns items selected by criteria
If the criteria is not defined, get() returns all items.
'''
if criteria is None and limit is None:
return self._get_all()
elif limit is not None and limit == 1:
return self.get_one(criteria)
else:
return self._get_with_criteria(criteria, offset=offset, limit=limit) | python | def get(self, criteria=None, offset=None, limit=None):
''' returns items selected by criteria
If the criteria is not defined, get() returns all items.
'''
if criteria is None and limit is None:
return self._get_all()
elif limit is not None and limit == 1:
return self.get_one(criteria)
else:
return self._get_with_criteria(criteria, offset=offset, limit=limit) | [
"def",
"get",
"(",
"self",
",",
"criteria",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"criteria",
"is",
"None",
"and",
"limit",
"is",
"None",
":",
"return",
"self",
".",
"_get_all",
"(",
")",
"elif",
"limit... | returns items selected by criteria
If the criteria is not defined, get() returns all items. | [
"returns",
"items",
"selected",
"by",
"criteria"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L187-L197 |
ownport/scrapy-dblite | dblite/__init__.py | Storage._get_all | def _get_all(self):
''' return all items
'''
rowid = 0
while True:
SQL_SELECT_MANY = 'SELECT rowid, * FROM %s WHERE rowid > ? LIMIT ?;' % self._table
self._cursor.execute(SQL_SELECT_MANY, (rowid, ITEMS_PER_REQUEST))
items = self._cursor.fetchall()
if len(items) == 0:
break
for item in items:
rowid = item['_id']
yield self._make_item(item) | python | def _get_all(self):
''' return all items
'''
rowid = 0
while True:
SQL_SELECT_MANY = 'SELECT rowid, * FROM %s WHERE rowid > ? LIMIT ?;' % self._table
self._cursor.execute(SQL_SELECT_MANY, (rowid, ITEMS_PER_REQUEST))
items = self._cursor.fetchall()
if len(items) == 0:
break
for item in items:
rowid = item['_id']
yield self._make_item(item) | [
"def",
"_get_all",
"(",
"self",
")",
":",
"rowid",
"=",
"0",
"while",
"True",
":",
"SQL_SELECT_MANY",
"=",
"'SELECT rowid, * FROM %s WHERE rowid > ? LIMIT ?;'",
"%",
"self",
".",
"_table",
"self",
".",
"_cursor",
".",
"execute",
"(",
"SQL_SELECT_MANY",
",",
"(",... | return all items | [
"return",
"all",
"items"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L199-L211 |
ownport/scrapy-dblite | dblite/__init__.py | Storage._get_with_criteria | def _get_with_criteria(self, criteria, offset=None, limit=None):
''' returns items selected by criteria
'''
SQL = SQLBuilder(self._table, criteria).select(offset=offset, limit=limit)
self._cursor.execute(SQL)
for item in self._cursor.fetchall():
yield self._make_item(item) | python | def _get_with_criteria(self, criteria, offset=None, limit=None):
''' returns items selected by criteria
'''
SQL = SQLBuilder(self._table, criteria).select(offset=offset, limit=limit)
self._cursor.execute(SQL)
for item in self._cursor.fetchall():
yield self._make_item(item) | [
"def",
"_get_with_criteria",
"(",
"self",
",",
"criteria",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"SQL",
"=",
"SQLBuilder",
"(",
"self",
".",
"_table",
",",
"criteria",
")",
".",
"select",
"(",
"offset",
"=",
"offset",
",",
... | returns items selected by criteria | [
"returns",
"items",
"selected",
"by",
"criteria"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L213-L219 |
ownport/scrapy-dblite | dblite/__init__.py | Storage.get_one | def get_one(self, criteria):
''' return one item
'''
try:
items = [item for item in self._get_with_criteria(criteria, limit=1)]
return items[0]
except:
return None | python | def get_one(self, criteria):
''' return one item
'''
try:
items = [item for item in self._get_with_criteria(criteria, limit=1)]
return items[0]
except:
return None | [
"def",
"get_one",
"(",
"self",
",",
"criteria",
")",
":",
"try",
":",
"items",
"=",
"[",
"item",
"for",
"item",
"in",
"self",
".",
"_get_with_criteria",
"(",
"criteria",
",",
"limit",
"=",
"1",
")",
"]",
"return",
"items",
"[",
"0",
"]",
"except",
... | return one item | [
"return",
"one",
"item"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L221-L228 |
ownport/scrapy-dblite | dblite/__init__.py | Storage._do_autocommit | def _do_autocommit(self):
''' perform autocommit
'''
# commit()
self._commit_counter += 1
# autocommit as boolean
if isinstance(self._autocommit, bool) and self._autocommit:
self.commit()
self._commit_counter = 0
# autocommit as counter
elif isinstance(self._autocommit, int) and self._autocommit > 0:
if (self._commit_counter % self._autocommit) == 0:
self.commit()
self._commit_counter = 0 | python | def _do_autocommit(self):
''' perform autocommit
'''
# commit()
self._commit_counter += 1
# autocommit as boolean
if isinstance(self._autocommit, bool) and self._autocommit:
self.commit()
self._commit_counter = 0
# autocommit as counter
elif isinstance(self._autocommit, int) and self._autocommit > 0:
if (self._commit_counter % self._autocommit) == 0:
self.commit()
self._commit_counter = 0 | [
"def",
"_do_autocommit",
"(",
"self",
")",
":",
"# commit()",
"self",
".",
"_commit_counter",
"+=",
"1",
"# autocommit as boolean",
"if",
"isinstance",
"(",
"self",
".",
"_autocommit",
",",
"bool",
")",
"and",
"self",
".",
"_autocommit",
":",
"self",
".",
"c... | perform autocommit | [
"perform",
"autocommit"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L230-L244 |
ownport/scrapy-dblite | dblite/__init__.py | Storage.put | def put(self, item):
''' store item in sqlite database
'''
if isinstance(item, self._item_class):
self._put_one(item)
elif isinstance(item, (list, tuple)):
self._put_many(item)
else:
raise RuntimeError('Unknown item(s) type, %s' % type(item)) | python | def put(self, item):
''' store item in sqlite database
'''
if isinstance(item, self._item_class):
self._put_one(item)
elif isinstance(item, (list, tuple)):
self._put_many(item)
else:
raise RuntimeError('Unknown item(s) type, %s' % type(item)) | [
"def",
"put",
"(",
"self",
",",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"self",
".",
"_item_class",
")",
":",
"self",
".",
"_put_one",
"(",
"item",
")",
"elif",
"isinstance",
"(",
"item",
",",
"(",
"list",
",",
"tuple",
")",
")",
... | store item in sqlite database | [
"store",
"item",
"in",
"sqlite",
"database"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L246-L254 |
ownport/scrapy-dblite | dblite/__init__.py | Storage._put_one | def _put_one(self, item):
''' store one item in database
'''
# prepare values
values = []
for k, v in item.items():
if k == '_id':
continue
if 'dblite_serializer' in item.fields[k]:
serializer = item.fields[k]['dblite_serializer']
v = serializer.dumps(v)
if v is not None:
v = sqlite3.Binary(buffer(v))
values.append(v)
# check if Item is new => update it
if '_id' in item:
fieldnames = ','.join(['%s=?' % f for f in item if f != '_id'])
values.append(item['_id'])
SQL = 'UPDATE %s SET %s WHERE rowid=?;' % (self._table, fieldnames)
# new Item
else:
fieldnames = ','.join([f for f in item if f != '_id'])
fieldnames_template = ','.join(['?' for f in item if f != '_id'])
SQL = 'INSERT INTO %s (%s) VALUES (%s);' % (self._table, fieldnames, fieldnames_template)
try:
self._cursor.execute(SQL, values)
except sqlite3.OperationalError, err:
raise RuntimeError('Item put() error, %s, SQL: %s, values: %s' % (err, SQL, values) )
except sqlite3.IntegrityError:
raise DuplicateItem('Duplicate item, %s' % item)
self._do_autocommit() | python | def _put_one(self, item):
''' store one item in database
'''
# prepare values
values = []
for k, v in item.items():
if k == '_id':
continue
if 'dblite_serializer' in item.fields[k]:
serializer = item.fields[k]['dblite_serializer']
v = serializer.dumps(v)
if v is not None:
v = sqlite3.Binary(buffer(v))
values.append(v)
# check if Item is new => update it
if '_id' in item:
fieldnames = ','.join(['%s=?' % f for f in item if f != '_id'])
values.append(item['_id'])
SQL = 'UPDATE %s SET %s WHERE rowid=?;' % (self._table, fieldnames)
# new Item
else:
fieldnames = ','.join([f for f in item if f != '_id'])
fieldnames_template = ','.join(['?' for f in item if f != '_id'])
SQL = 'INSERT INTO %s (%s) VALUES (%s);' % (self._table, fieldnames, fieldnames_template)
try:
self._cursor.execute(SQL, values)
except sqlite3.OperationalError, err:
raise RuntimeError('Item put() error, %s, SQL: %s, values: %s' % (err, SQL, values) )
except sqlite3.IntegrityError:
raise DuplicateItem('Duplicate item, %s' % item)
self._do_autocommit() | [
"def",
"_put_one",
"(",
"self",
",",
"item",
")",
":",
"# prepare values",
"values",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"item",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'_id'",
":",
"continue",
"if",
"'dblite_serializer'",
"in",
"item",... | store one item in database | [
"store",
"one",
"item",
"in",
"database"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L256-L288 |
ownport/scrapy-dblite | dblite/__init__.py | Storage._put_many | def _put_many(self, items):
''' store items in sqlite database
'''
for item in items:
if not isinstance(item, self._item_class):
raise RuntimeError('Items mismatch for %s and %s' % (self._item_class, type(item)))
self._put_one(item) | python | def _put_many(self, items):
''' store items in sqlite database
'''
for item in items:
if not isinstance(item, self._item_class):
raise RuntimeError('Items mismatch for %s and %s' % (self._item_class, type(item)))
self._put_one(item) | [
"def",
"_put_many",
"(",
"self",
",",
"items",
")",
":",
"for",
"item",
"in",
"items",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"self",
".",
"_item_class",
")",
":",
"raise",
"RuntimeError",
"(",
"'Items mismatch for %s and %s'",
"%",
"(",
"self",... | store items in sqlite database | [
"store",
"items",
"in",
"sqlite",
"database"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L290-L296 |
ownport/scrapy-dblite | dblite/__init__.py | Storage.sql | def sql(self, sql, params=()):
''' execute sql request and return items
'''
def _items(items):
for item in items:
yield self._item_class(item)
sql = sql.strip()
try:
self._cursor.execute(sql, params)
except sqlite3.OperationalError, err:
raise SQLError('%s, SQL: %s, params: %s' % (err, sql, params) )
except sqlite3.IntegrityError:
raise DuplicateItem('Duplicate item, %s' % item)
if sql.upper().startswith('SELECT'):
return _items(self._cursor.fetchall())
else:
return None | python | def sql(self, sql, params=()):
''' execute sql request and return items
'''
def _items(items):
for item in items:
yield self._item_class(item)
sql = sql.strip()
try:
self._cursor.execute(sql, params)
except sqlite3.OperationalError, err:
raise SQLError('%s, SQL: %s, params: %s' % (err, sql, params) )
except sqlite3.IntegrityError:
raise DuplicateItem('Duplicate item, %s' % item)
if sql.upper().startswith('SELECT'):
return _items(self._cursor.fetchall())
else:
return None | [
"def",
"sql",
"(",
"self",
",",
"sql",
",",
"params",
"=",
"(",
")",
")",
":",
"def",
"_items",
"(",
"items",
")",
":",
"for",
"item",
"in",
"items",
":",
"yield",
"self",
".",
"_item_class",
"(",
"item",
")",
"sql",
"=",
"sql",
".",
"strip",
"... | execute sql request and return items | [
"execute",
"sql",
"request",
"and",
"return",
"items"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L298-L316 |
ownport/scrapy-dblite | dblite/__init__.py | Storage.delete | def delete(self, criteria=None, _all=False):
''' delete dictionary(ies) in sqlite database
_all = True - delete all items
'''
if isinstance(criteria, self._item_class):
criteria = {'_id': criteria['_id']}
if criteria is None and not _all:
raise RuntimeError('Criteria is not defined')
SQL = SQLBuilder(self._table, criteria).delete()
self._cursor.execute(SQL) | python | def delete(self, criteria=None, _all=False):
''' delete dictionary(ies) in sqlite database
_all = True - delete all items
'''
if isinstance(criteria, self._item_class):
criteria = {'_id': criteria['_id']}
if criteria is None and not _all:
raise RuntimeError('Criteria is not defined')
SQL = SQLBuilder(self._table, criteria).delete()
self._cursor.execute(SQL) | [
"def",
"delete",
"(",
"self",
",",
"criteria",
"=",
"None",
",",
"_all",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"criteria",
",",
"self",
".",
"_item_class",
")",
":",
"criteria",
"=",
"{",
"'_id'",
":",
"criteria",
"[",
"'_id'",
"]",
"}",
... | delete dictionary(ies) in sqlite database
_all = True - delete all items | [
"delete",
"dictionary",
"(",
"ies",
")",
"in",
"sqlite",
"database"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/__init__.py#L318-L330 |
invenia/Arbiter | arbiter/async.py | run_tasks | def run_tasks(tasks, max_workers=None, use_processes=False):
"""
Run an iterable of tasks.
tasks: The iterable of tasks
max_workers: (optional, None) The maximum number of workers to use.
As of Python 3.5, if None is passed to the thread executor will
default to 5 * the number of processors and the process executor
will default to the number of processors. If you are running an
older version, consider this a non-optional value.
use_processes: (optional, False) use a process pool instead of a
thread pool.
"""
futures = set()
if use_processes:
get_executor = concurrent.futures.ProcessPoolExecutor
else:
get_executor = concurrent.futures.ThreadPoolExecutor
with get_executor(max_workers) as executor:
def execute(function, name):
"""
Submit a task to the pool
"""
future = executor.submit(function)
future.name = name
futures.add(future)
def wait():
"""
Wait for at least one task to complete
"""
results = []
waited = concurrent.futures.wait(
futures, return_when=concurrent.futures.FIRST_COMPLETED
)
for future in waited.done:
exc = future.exception()
if exc is None:
results.append(
TaskResult(
future.name,
True,
None,
future.result()
)
)
else:
results.append(TaskResult(future.name, False, exc, None))
futures.remove(future)
return results
return task_loop(tasks, execute, wait) | python | def run_tasks(tasks, max_workers=None, use_processes=False):
"""
Run an iterable of tasks.
tasks: The iterable of tasks
max_workers: (optional, None) The maximum number of workers to use.
As of Python 3.5, if None is passed to the thread executor will
default to 5 * the number of processors and the process executor
will default to the number of processors. If you are running an
older version, consider this a non-optional value.
use_processes: (optional, False) use a process pool instead of a
thread pool.
"""
futures = set()
if use_processes:
get_executor = concurrent.futures.ProcessPoolExecutor
else:
get_executor = concurrent.futures.ThreadPoolExecutor
with get_executor(max_workers) as executor:
def execute(function, name):
"""
Submit a task to the pool
"""
future = executor.submit(function)
future.name = name
futures.add(future)
def wait():
"""
Wait for at least one task to complete
"""
results = []
waited = concurrent.futures.wait(
futures, return_when=concurrent.futures.FIRST_COMPLETED
)
for future in waited.done:
exc = future.exception()
if exc is None:
results.append(
TaskResult(
future.name,
True,
None,
future.result()
)
)
else:
results.append(TaskResult(future.name, False, exc, None))
futures.remove(future)
return results
return task_loop(tasks, execute, wait) | [
"def",
"run_tasks",
"(",
"tasks",
",",
"max_workers",
"=",
"None",
",",
"use_processes",
"=",
"False",
")",
":",
"futures",
"=",
"set",
"(",
")",
"if",
"use_processes",
":",
"get_executor",
"=",
"concurrent",
".",
"futures",
".",
"ProcessPoolExecutor",
"else... | Run an iterable of tasks.
tasks: The iterable of tasks
max_workers: (optional, None) The maximum number of workers to use.
As of Python 3.5, if None is passed to the thread executor will
default to 5 * the number of processors and the process executor
will default to the number of processors. If you are running an
older version, consider this a non-optional value.
use_processes: (optional, False) use a process pool instead of a
thread pool. | [
"Run",
"an",
"iterable",
"of",
"tasks",
"."
] | train | https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/async.py#L12-L70 |
flo-compbio/genometools | genometools/gcloud/operations.py | wait_for_zone_op | def wait_for_zone_op(access_token, project, zone, name, interval=1.0):
"""Wait until a zone operation is finished.
TODO: docstring"""
assert isinstance(interval, (int, float))
assert interval >= 0.1
status = 'RUNNING'
progress = 0
LOGGER.info('Waiting for zone operation "%s" to finish...', name)
while status != 'DONE':
# print('\rRunning! Progress: %d %%' % progress, end='')
r = requests.get('https://www.googleapis.com/compute/v1/'
'projects/%s/zones/%s/operations/%s?access_token=%s'
% (project, zone, name, access_token.access_token))
r.raise_for_status()
# print(r.status_code)
#result = json.loads(r.content.decode('utf-8'))
result = r.json()
status = result['status']
progress = result['progress']
time.sleep(interval)
LOGGER.info('Zone operation "%s" done!', name) | python | def wait_for_zone_op(access_token, project, zone, name, interval=1.0):
"""Wait until a zone operation is finished.
TODO: docstring"""
assert isinstance(interval, (int, float))
assert interval >= 0.1
status = 'RUNNING'
progress = 0
LOGGER.info('Waiting for zone operation "%s" to finish...', name)
while status != 'DONE':
# print('\rRunning! Progress: %d %%' % progress, end='')
r = requests.get('https://www.googleapis.com/compute/v1/'
'projects/%s/zones/%s/operations/%s?access_token=%s'
% (project, zone, name, access_token.access_token))
r.raise_for_status()
# print(r.status_code)
#result = json.loads(r.content.decode('utf-8'))
result = r.json()
status = result['status']
progress = result['progress']
time.sleep(interval)
LOGGER.info('Zone operation "%s" done!', name) | [
"def",
"wait_for_zone_op",
"(",
"access_token",
",",
"project",
",",
"zone",
",",
"name",
",",
"interval",
"=",
"1.0",
")",
":",
"assert",
"isinstance",
"(",
"interval",
",",
"(",
"int",
",",
"float",
")",
")",
"assert",
"interval",
">=",
"0.1",
"status"... | Wait until a zone operation is finished.
TODO: docstring | [
"Wait",
"until",
"a",
"zone",
"operation",
"is",
"finished",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/operations.py#L12-L41 |
acorg/dark-matter | dark/local_align.py | LocalAlignment._initialise | def _initialise(self):
"""
Initialises table with dictionary.
"""
d = {'score': 0, 'pointer': None, 'ins': 0, 'del': 0}
cols = len(self.seq1Seq) + 1
rows = len(self.seq2Seq) + 1
# Note that this puts a ref to the same dict (d) into each cell of
# the table. Hopefully that is what was intended. Eyeballing the
# code below that uses the table it looks like table entries are
# entirely replaced, so this seems ok. Terry.
table = [[d for _ in range(cols)] for _ in range(rows)]
return table | python | def _initialise(self):
"""
Initialises table with dictionary.
"""
d = {'score': 0, 'pointer': None, 'ins': 0, 'del': 0}
cols = len(self.seq1Seq) + 1
rows = len(self.seq2Seq) + 1
# Note that this puts a ref to the same dict (d) into each cell of
# the table. Hopefully that is what was intended. Eyeballing the
# code below that uses the table it looks like table entries are
# entirely replaced, so this seems ok. Terry.
table = [[d for _ in range(cols)] for _ in range(rows)]
return table | [
"def",
"_initialise",
"(",
"self",
")",
":",
"d",
"=",
"{",
"'score'",
":",
"0",
",",
"'pointer'",
":",
"None",
",",
"'ins'",
":",
"0",
",",
"'del'",
":",
"0",
"}",
"cols",
"=",
"len",
"(",
"self",
".",
"seq1Seq",
")",
"+",
"1",
"rows",
"=",
... | Initialises table with dictionary. | [
"Initialises",
"table",
"with",
"dictionary",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/local_align.py#L57-L69 |
acorg/dark-matter | dark/local_align.py | LocalAlignment._fillAndTraceback | def _fillAndTraceback(self, table):
"""
Perform Local Alignment according to Smith-Waterman Algorithm.
Fills the table and then traces back from the highest score.
NB left = deletion and up = insertion wrt seq1
"""
# Fill
max_score = 0
max_row = 0
max_col = 0
for row in range(1, len(self.seq2Seq) + 1):
for col in range(1, len(self.seq1Seq) + 1):
# Calculate match score
letter1 = self.seq1Seq[col - 1]
letter2 = self.seq2Seq[row - 1]
if letter1 == letter2:
diagonal_score = (table[row - 1][col - 1]['score'] +
self.match)
else:
diagonal_score = (table[row - 1][col - 1]['score'] +
self.mismatch)
ins_run = table[row - 1][col]['ins']
del_run = table[row][col - 1]['del']
# Calculate gap scores ensuring extension is not > 0
if table[row - 1][col]['ins'] <= 0:
ins_score = table[row - 1][col]['score'] + self.gapOpen
else:
if self.gapExtend + ins_run * self.gapExtendDecay <= 0.0:
ins_score = (table[row - 1][col]['score'] +
self.gapExtend +
ins_run * self.gapExtendDecay)
else:
ins_score = table[row - 1][col]['score']
if table[row - 1][col]['del'] <= 0:
del_score = table[row][col - 1]['score'] + self.gapOpen
else:
if self.gapExtend + del_run * self.gapExtendDecay <= 0.0:
del_score = (table[row][col - 1]['score'] +
self.gapExtend +
del_run * self.gapExtendDecay)
else:
del_score = table[row][col - 1]['score']
# Choose best score
if diagonal_score <= 0 and ins_score <= 0 and del_score <= 0:
table[row][col] = {'score': 0, 'pointer': None, 'ins': 0,
'del': 0}
else:
if diagonal_score >= ins_score:
if diagonal_score >= del_score: # diag lef/up
diagonal = {'score': diagonal_score,
'pointer': 'diagonal', 'ins': 0,
'del': 0}
table[row][col] = diagonal
else: # lef diag/up
deletion = {'score': del_score, 'pointer': 'del',
'ins': 0, 'del': del_run + 1}
table[row][col] = deletion
else: # up diag
if ins_score >= del_score: # up diag/lef
insertion = {'score': ins_score, 'pointer': 'ins',
'ins': ins_run + 1, 'del': 0}
table[row][col] = insertion
else: # lef up diag
deletion = {'score': del_score, 'pointer': 'del',
'ins': 0, 'del': del_run + 1}
table[row][col] = deletion
# Set max score - is this the best way of getting max score
# considering how the for loop iterates through the matrix?
if table[row][col]['score'] >= max_score:
max_row = row
max_col = col
max_score = table[row][col]['score']
# Traceback
indexes = {'max_row': max_row, 'max_col': max_col}
align1 = ''
align2 = ''
align = ''
current_row = max_row
current_col = max_col
while True:
arrow = table[current_row][current_col]['pointer']
if arrow is None:
min_row = current_row + 1
min_col = current_col + 1
break
elif arrow == 'diagonal':
align1 += self.seq1Seq[current_col - 1]
align2 += self.seq2Seq[current_row - 1]
if self.seq1Seq[current_col - 1] == self.seq2Seq[
current_row - 1]:
align += '|'
else:
align += ' '
current_row -= 1
current_col -= 1
elif arrow == 'del':
align1 += self.seq1Seq[current_col - 1]
align2 += '-'
align += ' '
current_col -= 1
elif arrow == 'ins':
align1 += '-'
align2 += self.seq2Seq[current_row - 1]
align += ' '
current_row -= 1
else:
raise ValueError('Invalid pointer: %s' % arrow)
indexes['min_row'] = min_row
indexes['min_col'] = min_col
align1 = align1[::-1]
align2 = align2[::-1]
align = align[::-1]
if len(align1) != len(align2):
raise ValueError(
'Lengths of locally aligned sequences differ (%d != %d).' % (
len(align1), len(align2)))
return ([align1, align, align2], indexes) | python | def _fillAndTraceback(self, table):
"""
Perform Local Alignment according to Smith-Waterman Algorithm.
Fills the table and then traces back from the highest score.
NB left = deletion and up = insertion wrt seq1
"""
# Fill
max_score = 0
max_row = 0
max_col = 0
for row in range(1, len(self.seq2Seq) + 1):
for col in range(1, len(self.seq1Seq) + 1):
# Calculate match score
letter1 = self.seq1Seq[col - 1]
letter2 = self.seq2Seq[row - 1]
if letter1 == letter2:
diagonal_score = (table[row - 1][col - 1]['score'] +
self.match)
else:
diagonal_score = (table[row - 1][col - 1]['score'] +
self.mismatch)
ins_run = table[row - 1][col]['ins']
del_run = table[row][col - 1]['del']
# Calculate gap scores ensuring extension is not > 0
if table[row - 1][col]['ins'] <= 0:
ins_score = table[row - 1][col]['score'] + self.gapOpen
else:
if self.gapExtend + ins_run * self.gapExtendDecay <= 0.0:
ins_score = (table[row - 1][col]['score'] +
self.gapExtend +
ins_run * self.gapExtendDecay)
else:
ins_score = table[row - 1][col]['score']
if table[row - 1][col]['del'] <= 0:
del_score = table[row][col - 1]['score'] + self.gapOpen
else:
if self.gapExtend + del_run * self.gapExtendDecay <= 0.0:
del_score = (table[row][col - 1]['score'] +
self.gapExtend +
del_run * self.gapExtendDecay)
else:
del_score = table[row][col - 1]['score']
# Choose best score
if diagonal_score <= 0 and ins_score <= 0 and del_score <= 0:
table[row][col] = {'score': 0, 'pointer': None, 'ins': 0,
'del': 0}
else:
if diagonal_score >= ins_score:
if diagonal_score >= del_score: # diag lef/up
diagonal = {'score': diagonal_score,
'pointer': 'diagonal', 'ins': 0,
'del': 0}
table[row][col] = diagonal
else: # lef diag/up
deletion = {'score': del_score, 'pointer': 'del',
'ins': 0, 'del': del_run + 1}
table[row][col] = deletion
else: # up diag
if ins_score >= del_score: # up diag/lef
insertion = {'score': ins_score, 'pointer': 'ins',
'ins': ins_run + 1, 'del': 0}
table[row][col] = insertion
else: # lef up diag
deletion = {'score': del_score, 'pointer': 'del',
'ins': 0, 'del': del_run + 1}
table[row][col] = deletion
# Set max score - is this the best way of getting max score
# considering how the for loop iterates through the matrix?
if table[row][col]['score'] >= max_score:
max_row = row
max_col = col
max_score = table[row][col]['score']
# Traceback
indexes = {'max_row': max_row, 'max_col': max_col}
align1 = ''
align2 = ''
align = ''
current_row = max_row
current_col = max_col
while True:
arrow = table[current_row][current_col]['pointer']
if arrow is None:
min_row = current_row + 1
min_col = current_col + 1
break
elif arrow == 'diagonal':
align1 += self.seq1Seq[current_col - 1]
align2 += self.seq2Seq[current_row - 1]
if self.seq1Seq[current_col - 1] == self.seq2Seq[
current_row - 1]:
align += '|'
else:
align += ' '
current_row -= 1
current_col -= 1
elif arrow == 'del':
align1 += self.seq1Seq[current_col - 1]
align2 += '-'
align += ' '
current_col -= 1
elif arrow == 'ins':
align1 += '-'
align2 += self.seq2Seq[current_row - 1]
align += ' '
current_row -= 1
else:
raise ValueError('Invalid pointer: %s' % arrow)
indexes['min_row'] = min_row
indexes['min_col'] = min_col
align1 = align1[::-1]
align2 = align2[::-1]
align = align[::-1]
if len(align1) != len(align2):
raise ValueError(
'Lengths of locally aligned sequences differ (%d != %d).' % (
len(align1), len(align2)))
return ([align1, align, align2], indexes) | [
"def",
"_fillAndTraceback",
"(",
"self",
",",
"table",
")",
":",
"# Fill",
"max_score",
"=",
"0",
"max_row",
"=",
"0",
"max_col",
"=",
"0",
"for",
"row",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"seq2Seq",
")",
"+",
"1",
")",
":",
"... | Perform Local Alignment according to Smith-Waterman Algorithm.
Fills the table and then traces back from the highest score.
NB left = deletion and up = insertion wrt seq1 | [
"Perform",
"Local",
"Alignment",
"according",
"to",
"Smith",
"-",
"Waterman",
"Algorithm",
".",
"Fills",
"the",
"table",
"and",
"then",
"traces",
"back",
"from",
"the",
"highest",
"score",
".",
"NB",
"left",
"=",
"deletion",
"and",
"up",
"=",
"insertion",
... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/local_align.py#L71-L199 |
acorg/dark-matter | dark/local_align.py | LocalAlignment._cigarString | def _cigarString(self, output):
"""
Return a cigar string of aligned sequences.
@param output: a C{tup} of strings (align1, align, align2)
@return: a C{str} containing the cigar string. Eg with input:
'GGCCCGCA' and 'GG-CTGCA', return 2=1D1=1X3=
"""
cigar = []
count = 0
align1 = output[0]
align2 = output[2]
for nt1, nt2 in zip(align1, align2):
if nt1 == nt2:
cigar.append('=')
elif nt1 == '-':
cigar.append('I')
elif nt2 == '-':
cigar.append('D')
else:
cigar.append('X')
# Initially create a list of characters,
# eg ['=', '=', 'D', '=', 'X', '=', '=', '=']
cigar.append('*')
# Append an arbitrary character to ensure parsing below functions
cigarString = ''
previousCharacter = ''
count = 0
first = True
for character in cigar:
if first:
previousCharacter = character
count += 1
first = False
else:
if character == previousCharacter:
count += 1
else:
cigarString += (str(count) + str(previousCharacter))
count = 1
previousCharacter = character
return cigarString | python | def _cigarString(self, output):
"""
Return a cigar string of aligned sequences.
@param output: a C{tup} of strings (align1, align, align2)
@return: a C{str} containing the cigar string. Eg with input:
'GGCCCGCA' and 'GG-CTGCA', return 2=1D1=1X3=
"""
cigar = []
count = 0
align1 = output[0]
align2 = output[2]
for nt1, nt2 in zip(align1, align2):
if nt1 == nt2:
cigar.append('=')
elif nt1 == '-':
cigar.append('I')
elif nt2 == '-':
cigar.append('D')
else:
cigar.append('X')
# Initially create a list of characters,
# eg ['=', '=', 'D', '=', 'X', '=', '=', '=']
cigar.append('*')
# Append an arbitrary character to ensure parsing below functions
cigarString = ''
previousCharacter = ''
count = 0
first = True
for character in cigar:
if first:
previousCharacter = character
count += 1
first = False
else:
if character == previousCharacter:
count += 1
else:
cigarString += (str(count) + str(previousCharacter))
count = 1
previousCharacter = character
return cigarString | [
"def",
"_cigarString",
"(",
"self",
",",
"output",
")",
":",
"cigar",
"=",
"[",
"]",
"count",
"=",
"0",
"align1",
"=",
"output",
"[",
"0",
"]",
"align2",
"=",
"output",
"[",
"2",
"]",
"for",
"nt1",
",",
"nt2",
"in",
"zip",
"(",
"align1",
",",
"... | Return a cigar string of aligned sequences.
@param output: a C{tup} of strings (align1, align, align2)
@return: a C{str} containing the cigar string. Eg with input:
'GGCCCGCA' and 'GG-CTGCA', return 2=1D1=1X3= | [
"Return",
"a",
"cigar",
"string",
"of",
"aligned",
"sequences",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/local_align.py#L201-L242 |
acorg/dark-matter | dark/local_align.py | LocalAlignment._alignmentToStr | def _alignmentToStr(self, result):
"""
Make a textual representation of an alignment result.
@param result: A C{dict}, as returned by C{self.createAlignment}.
@return: A C{str} desription of a result. For every three lines the
first and third contain the input sequences, possibly padded
with '-'. The second contains '|' where the two sequences match,
and ' ' where not.
Format of the output is as follows:
Cigar: (Cigar string)
Evalue:
Bitscore:
Id1 Match start: (int) Match end: (int)
Id2 Match start: (int) Match end: (int)
Id1: 1 (seq) 50
[lines to show matches]
Id2: 1 (seq) 50
"""
if result is None:
return ('\nNo alignment between %s and %s\n' % (
self.seq1ID, self.seq2ID))
else:
header = (
'\nCigar string of aligned region: %s\n'
'%s Match start: %d Match end: %d\n'
'%s Match start: %d Match end: %d\n' %
(result['cigar'],
self.seq1ID, result['sequence1Start'], result['sequence1End'],
self.seq2ID, result['sequence2Start'], result['sequence2End'])
)
text = '\n'.join(result['text'])
return header + text | python | def _alignmentToStr(self, result):
"""
Make a textual representation of an alignment result.
@param result: A C{dict}, as returned by C{self.createAlignment}.
@return: A C{str} desription of a result. For every three lines the
first and third contain the input sequences, possibly padded
with '-'. The second contains '|' where the two sequences match,
and ' ' where not.
Format of the output is as follows:
Cigar: (Cigar string)
Evalue:
Bitscore:
Id1 Match start: (int) Match end: (int)
Id2 Match start: (int) Match end: (int)
Id1: 1 (seq) 50
[lines to show matches]
Id2: 1 (seq) 50
"""
if result is None:
return ('\nNo alignment between %s and %s\n' % (
self.seq1ID, self.seq2ID))
else:
header = (
'\nCigar string of aligned region: %s\n'
'%s Match start: %d Match end: %d\n'
'%s Match start: %d Match end: %d\n' %
(result['cigar'],
self.seq1ID, result['sequence1Start'], result['sequence1End'],
self.seq2ID, result['sequence2Start'], result['sequence2End'])
)
text = '\n'.join(result['text'])
return header + text | [
"def",
"_alignmentToStr",
"(",
"self",
",",
"result",
")",
":",
"if",
"result",
"is",
"None",
":",
"return",
"(",
"'\\nNo alignment between %s and %s\\n'",
"%",
"(",
"self",
".",
"seq1ID",
",",
"self",
".",
"seq2ID",
")",
")",
"else",
":",
"header",
"=",
... | Make a textual representation of an alignment result.
@param result: A C{dict}, as returned by C{self.createAlignment}.
@return: A C{str} desription of a result. For every three lines the
first and third contain the input sequences, possibly padded
with '-'. The second contains '|' where the two sequences match,
and ' ' where not.
Format of the output is as follows:
Cigar: (Cigar string)
Evalue:
Bitscore:
Id1 Match start: (int) Match end: (int)
Id2 Match start: (int) Match end: (int)
Id1: 1 (seq) 50
[lines to show matches]
Id2: 1 (seq) 50 | [
"Make",
"a",
"textual",
"representation",
"of",
"an",
"alignment",
"result",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/local_align.py#L293-L326 |
acorg/dark-matter | dark/local_align.py | LocalAlignment.createAlignment | def createAlignment(self, resultFormat=dict):
"""
Run the alignment algorithm.
@param resultFormat: Either C{dict} or C{str}, giving the desired
result format.
@return: If C{resultFormat} is C{dict}, a C{dict} containing
information about the match (or C{None}) if there is no match.
If C{resultFormat} is C{str}, a C{str} containing a readable
version of the match info (see _alignmentToStr above for the exact
format).
"""
table = self._initialise()
alignment = self._fillAndTraceback(table)
output = alignment[0]
if output[0] == '' or output[2] == '':
result = None
else:
indexes = alignment[1]
result = {
'cigar': self._cigarString(output),
'sequence1Start': indexes['min_col'],
'sequence1End': indexes['max_col'],
'sequence2Start': indexes['min_row'],
'sequence2End': indexes['max_row'],
'text': self._formatAlignment(output, indexes),
}
return self._alignmentToStr(result) if resultFormat is str else result | python | def createAlignment(self, resultFormat=dict):
"""
Run the alignment algorithm.
@param resultFormat: Either C{dict} or C{str}, giving the desired
result format.
@return: If C{resultFormat} is C{dict}, a C{dict} containing
information about the match (or C{None}) if there is no match.
If C{resultFormat} is C{str}, a C{str} containing a readable
version of the match info (see _alignmentToStr above for the exact
format).
"""
table = self._initialise()
alignment = self._fillAndTraceback(table)
output = alignment[0]
if output[0] == '' or output[2] == '':
result = None
else:
indexes = alignment[1]
result = {
'cigar': self._cigarString(output),
'sequence1Start': indexes['min_col'],
'sequence1End': indexes['max_col'],
'sequence2Start': indexes['min_row'],
'sequence2End': indexes['max_row'],
'text': self._formatAlignment(output, indexes),
}
return self._alignmentToStr(result) if resultFormat is str else result | [
"def",
"createAlignment",
"(",
"self",
",",
"resultFormat",
"=",
"dict",
")",
":",
"table",
"=",
"self",
".",
"_initialise",
"(",
")",
"alignment",
"=",
"self",
".",
"_fillAndTraceback",
"(",
"table",
")",
"output",
"=",
"alignment",
"[",
"0",
"]",
"if",... | Run the alignment algorithm.
@param resultFormat: Either C{dict} or C{str}, giving the desired
result format.
@return: If C{resultFormat} is C{dict}, a C{dict} containing
information about the match (or C{None}) if there is no match.
If C{resultFormat} is C{str}, a C{str} containing a readable
version of the match info (see _alignmentToStr above for the exact
format). | [
"Run",
"the",
"alignment",
"algorithm",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/local_align.py#L328-L356 |
ownport/scrapy-dblite | dblite/query.py | SQLBuilder.select | def select(self, fields=['rowid', '*'], offset=None, limit=None):
''' return SELECT SQL
'''
# base SQL
SQL = 'SELECT %s FROM %s' % (','.join(fields), self._table)
# selectors
if self._selectors:
SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip()
# modifiers
if self._modifiers:
SQL = ' '.join([SQL, self._modifiers])
# limit
if limit is not None and isinstance(limit, int):
SQL = ' '.join((SQL, 'LIMIT %s' % limit))
# offset
if (limit is not None) and (offset is not None) and isinstance(offset, int):
SQL = ' '.join((SQL, 'OFFSET %s' % offset))
return ''.join((SQL, ';')) | python | def select(self, fields=['rowid', '*'], offset=None, limit=None):
''' return SELECT SQL
'''
# base SQL
SQL = 'SELECT %s FROM %s' % (','.join(fields), self._table)
# selectors
if self._selectors:
SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip()
# modifiers
if self._modifiers:
SQL = ' '.join([SQL, self._modifiers])
# limit
if limit is not None and isinstance(limit, int):
SQL = ' '.join((SQL, 'LIMIT %s' % limit))
# offset
if (limit is not None) and (offset is not None) and isinstance(offset, int):
SQL = ' '.join((SQL, 'OFFSET %s' % offset))
return ''.join((SQL, ';')) | [
"def",
"select",
"(",
"self",
",",
"fields",
"=",
"[",
"'rowid'",
",",
"'*'",
"]",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"# base SQL",
"SQL",
"=",
"'SELECT %s FROM %s'",
"%",
"(",
"','",
".",
"join",
"(",
"fields",
")",
"... | return SELECT SQL | [
"return",
"SELECT",
"SQL"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/query.py#L37-L59 |
ownport/scrapy-dblite | dblite/query.py | SQLBuilder.delete | def delete(self):
''' return DELETE SQL
'''
SQL = 'DELETE FROM %s' % self._table
if self._selectors:
SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip()
return SQL | python | def delete(self):
''' return DELETE SQL
'''
SQL = 'DELETE FROM %s' % self._table
if self._selectors:
SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip()
return SQL | [
"def",
"delete",
"(",
"self",
")",
":",
"SQL",
"=",
"'DELETE FROM %s'",
"%",
"self",
".",
"_table",
"if",
"self",
".",
"_selectors",
":",
"SQL",
"=",
"' '",
".",
"join",
"(",
"[",
"SQL",
",",
"'WHERE'",
",",
"self",
".",
"_selectors",
"]",
")",
"."... | return DELETE SQL | [
"return",
"DELETE",
"SQL"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/query.py#L61-L68 |
ownport/scrapy-dblite | dblite/query.py | SQLBuilder._parse | def _parse(self, params):
''' parse parameters and return SQL
'''
if not isinstance(params, dict):
return None, None
if len(params) == 0:
return None, None
selectors = list()
modifiers = list()
for k in params.keys():
if k in LOGICAL_OPERATORS:
selectors.append(self._logical(k, params[k]))
elif k in QUERY_MODIFIERS:
modifiers.append(self._modifier(k, params[k]))
else:
if k == '_id':
selectors.append("rowid%s" % (self._value_wrapper(params[k])))
else:
selectors.append("%s%s" % (k, self._value_wrapper(params[k])))
_selectors = ' AND '.join(selectors).strip()
_modifiers = ' '.join(modifiers).strip()
return _selectors, _modifiers | python | def _parse(self, params):
''' parse parameters and return SQL
'''
if not isinstance(params, dict):
return None, None
if len(params) == 0:
return None, None
selectors = list()
modifiers = list()
for k in params.keys():
if k in LOGICAL_OPERATORS:
selectors.append(self._logical(k, params[k]))
elif k in QUERY_MODIFIERS:
modifiers.append(self._modifier(k, params[k]))
else:
if k == '_id':
selectors.append("rowid%s" % (self._value_wrapper(params[k])))
else:
selectors.append("%s%s" % (k, self._value_wrapper(params[k])))
_selectors = ' AND '.join(selectors).strip()
_modifiers = ' '.join(modifiers).strip()
return _selectors, _modifiers | [
"def",
"_parse",
"(",
"self",
",",
"params",
")",
":",
"if",
"not",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"return",
"None",
",",
"None",
"if",
"len",
"(",
"params",
")",
"==",
"0",
":",
"return",
"None",
",",
"None",
"selectors",
"=",... | parse parameters and return SQL | [
"parse",
"parameters",
"and",
"return",
"SQL"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/query.py#L70-L98 |
ownport/scrapy-dblite | dblite/query.py | SQLBuilder._logical | def _logical(self, operator, params):
'''
$and: joins query clauses with a logical AND returns all items
that match the conditions of both clauses
$or: joins query clauses with a logical OR returns all items
that match the conditions of either clause.
'''
result = list()
if isinstance(params, dict):
for k,v in params.items():
selectors, modifiers = self._parse(dict([(k, v),]))
result.append("(%s)" % selectors)
elif isinstance(params, (list, tuple)):
for v in params:
selectors, modifiers = self._parse(v)
result.append("(%s)" % selectors)
else:
raise RuntimeError('Unknow parameter type, %s:%s' % (type(params), params))
if operator == '$and':
return ' AND '.join(result)
elif operator == '$or':
return ' OR '.join(result)
else:
raise RuntimeError('Unknown operator, %s' % operator) | python | def _logical(self, operator, params):
'''
$and: joins query clauses with a logical AND returns all items
that match the conditions of both clauses
$or: joins query clauses with a logical OR returns all items
that match the conditions of either clause.
'''
result = list()
if isinstance(params, dict):
for k,v in params.items():
selectors, modifiers = self._parse(dict([(k, v),]))
result.append("(%s)" % selectors)
elif isinstance(params, (list, tuple)):
for v in params:
selectors, modifiers = self._parse(v)
result.append("(%s)" % selectors)
else:
raise RuntimeError('Unknow parameter type, %s:%s' % (type(params), params))
if operator == '$and':
return ' AND '.join(result)
elif operator == '$or':
return ' OR '.join(result)
else:
raise RuntimeError('Unknown operator, %s' % operator) | [
"def",
"_logical",
"(",
"self",
",",
"operator",
",",
"params",
")",
":",
"result",
"=",
"list",
"(",
")",
"if",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
":",
"selectors",
"... | $and: joins query clauses with a logical AND returns all items
that match the conditions of both clauses
$or: joins query clauses with a logical OR returns all items
that match the conditions of either clause. | [
"$and",
":",
"joins",
"query",
"clauses",
"with",
"a",
"logical",
"AND",
"returns",
"all",
"items",
"that",
"match",
"the",
"conditions",
"of",
"both",
"clauses",
"$or",
":",
"joins",
"query",
"clauses",
"with",
"a",
"logical",
"OR",
"returns",
"all",
"ite... | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/query.py#L100-L125 |
ownport/scrapy-dblite | dblite/query.py | SQLBuilder._modifier | def _modifier(self, operator, params):
'''
$orderby: sorts the results of a query in ascending (1) or descending (-1) order.
'''
if operator == '$orderby':
order_types = {-1: 'DESC', 1: 'ASC'}
if not isinstance(params, dict):
raise RuntimeError('Incorrect parameter type, %s' % params)
return 'ORDER BY %s' % ','.join(["%s %s" % (p, order_types[params[p]]) for p in params])
else:
raise RuntimeError('Unknown operator, %s' % operator) | python | def _modifier(self, operator, params):
'''
$orderby: sorts the results of a query in ascending (1) or descending (-1) order.
'''
if operator == '$orderby':
order_types = {-1: 'DESC', 1: 'ASC'}
if not isinstance(params, dict):
raise RuntimeError('Incorrect parameter type, %s' % params)
return 'ORDER BY %s' % ','.join(["%s %s" % (p, order_types[params[p]]) for p in params])
else:
raise RuntimeError('Unknown operator, %s' % operator) | [
"def",
"_modifier",
"(",
"self",
",",
"operator",
",",
"params",
")",
":",
"if",
"operator",
"==",
"'$orderby'",
":",
"order_types",
"=",
"{",
"-",
"1",
":",
"'DESC'",
",",
"1",
":",
"'ASC'",
"}",
"if",
"not",
"isinstance",
"(",
"params",
",",
"dict"... | $orderby: sorts the results of a query in ascending (1) or descending (-1) order. | [
"$orderby",
":",
"sorts",
"the",
"results",
"of",
"a",
"query",
"in",
"ascending",
"(",
"1",
")",
"or",
"descending",
"(",
"-",
"1",
")",
"order",
"."
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/query.py#L127-L138 |
ownport/scrapy-dblite | dblite/query.py | SQLBuilder._value_wrapper | def _value_wrapper(self, value):
''' wrapper for values
'''
if isinstance(value, (int, float,)):
return '=%s' % value
elif isinstance(value, (str, unicode)):
value = value.strip()
# LIKE
if RE_LIKE.match(value):
return ' LIKE %s' % repr(RE_LIKE.match(value).group('RE_LIKE'))
# REGEXP
elif RE_REGEXP.match(value):
return ' REGEXP %s' % repr(RE_REGEXP.search(value).group('RE_REGEXP'))
else:
return '=%s' % repr(value)
elif value is None:
return ' ISNULL' | python | def _value_wrapper(self, value):
''' wrapper for values
'''
if isinstance(value, (int, float,)):
return '=%s' % value
elif isinstance(value, (str, unicode)):
value = value.strip()
# LIKE
if RE_LIKE.match(value):
return ' LIKE %s' % repr(RE_LIKE.match(value).group('RE_LIKE'))
# REGEXP
elif RE_REGEXP.match(value):
return ' REGEXP %s' % repr(RE_REGEXP.search(value).group('RE_REGEXP'))
else:
return '=%s' % repr(value)
elif value is None:
return ' ISNULL' | [
"def",
"_value_wrapper",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
",",
")",
")",
":",
"return",
"'=%s'",
"%",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"unicode",
... | wrapper for values | [
"wrapper",
"for",
"values"
] | train | https://github.com/ownport/scrapy-dblite/blob/6de5021caa31d439478d9808738b046d1db699c9/dblite/query.py#L140-L156 |
openfisca/openfisca-web-api | openfisca_web_api/urls.py | make_router | def make_router(*routings):
"""Return a WSGI application that dispatches requests to controllers """
routes = []
for routing in routings:
methods, regex, app = routing[:3]
if isinstance(methods, basestring):
methods = (methods,)
vars = routing[3] if len(routing) >= 4 else {}
routes.append((methods, re.compile(unicode(regex)), app, vars))
def router(environ, start_response):
"""Dispatch request to controllers."""
req = webob.Request(environ)
split_path_info = req.path_info.split('/')
if split_path_info[0]:
# When path_info doesn't start with a "/" this is an error or a attack => Reject request.
# An example of an URL with such a invalid path_info: http://127.0.0.1http%3A//127.0.0.1%3A80/result?...
ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
return wsgihelpers.respond_json(ctx,
dict(
apiVersion = 1,
error = dict(
code = 400, # Bad Request
message = ctx._(u"Invalid path: {0}").format(req.path_info),
),
),
headers = headers,
)(environ, start_response)
for methods, regex, app, vars in routes:
match = regex.match(req.path_info)
if match is not None:
if methods is not None and req.method not in methods:
ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
return wsgihelpers.respond_json(ctx,
dict(
apiVersion = 1,
error = dict(
code = 405,
message = ctx._(u"You cannot use HTTP {} to access this URL. Use one of {}.").format(
req.method, methods),
),
),
headers = headers,
)(environ, start_response)
if getattr(req, 'urlvars', None) is None:
req.urlvars = {}
req.urlvars.update(match.groupdict())
req.urlvars.update(vars)
req.script_name += req.path_info[:match.end()]
req.path_info = req.path_info[match.end():]
return app(req.environ, start_response)
ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
return wsgihelpers.respond_json(ctx,
dict(
apiVersion = 1,
error = dict(
code = 404, # Not Found
message = ctx._(u"Path not found: {0}").format(req.path_info),
),
),
headers = headers,
)(environ, start_response)
return router | python | def make_router(*routings):
"""Return a WSGI application that dispatches requests to controllers """
routes = []
for routing in routings:
methods, regex, app = routing[:3]
if isinstance(methods, basestring):
methods = (methods,)
vars = routing[3] if len(routing) >= 4 else {}
routes.append((methods, re.compile(unicode(regex)), app, vars))
def router(environ, start_response):
"""Dispatch request to controllers."""
req = webob.Request(environ)
split_path_info = req.path_info.split('/')
if split_path_info[0]:
# When path_info doesn't start with a "/" this is an error or a attack => Reject request.
# An example of an URL with such a invalid path_info: http://127.0.0.1http%3A//127.0.0.1%3A80/result?...
ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
return wsgihelpers.respond_json(ctx,
dict(
apiVersion = 1,
error = dict(
code = 400, # Bad Request
message = ctx._(u"Invalid path: {0}").format(req.path_info),
),
),
headers = headers,
)(environ, start_response)
for methods, regex, app, vars in routes:
match = regex.match(req.path_info)
if match is not None:
if methods is not None and req.method not in methods:
ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
return wsgihelpers.respond_json(ctx,
dict(
apiVersion = 1,
error = dict(
code = 405,
message = ctx._(u"You cannot use HTTP {} to access this URL. Use one of {}.").format(
req.method, methods),
),
),
headers = headers,
)(environ, start_response)
if getattr(req, 'urlvars', None) is None:
req.urlvars = {}
req.urlvars.update(match.groupdict())
req.urlvars.update(vars)
req.script_name += req.path_info[:match.end()]
req.path_info = req.path_info[match.end():]
return app(req.environ, start_response)
ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
return wsgihelpers.respond_json(ctx,
dict(
apiVersion = 1,
error = dict(
code = 404, # Not Found
message = ctx._(u"Path not found: {0}").format(req.path_info),
),
),
headers = headers,
)(environ, start_response)
return router | [
"def",
"make_router",
"(",
"*",
"routings",
")",
":",
"routes",
"=",
"[",
"]",
"for",
"routing",
"in",
"routings",
":",
"methods",
",",
"regex",
",",
"app",
"=",
"routing",
"[",
":",
"3",
"]",
"if",
"isinstance",
"(",
"methods",
",",
"basestring",
")... | Return a WSGI application that dispatches requests to controllers | [
"Return",
"a",
"WSGI",
"application",
"that",
"dispatches",
"requests",
"to",
"controllers"
] | train | https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/urls.py#L63-L129 |
cemerick/nrepl-python-client | nrepl/__init__.py | connect | def connect(uri):
"""
Connects to an nREPL endpoint identified by the given URL/URI. Valid
examples include:
nrepl://192.168.0.12:7889
telnet://localhost:5000
http://your-app-name.heroku.com/repl
This fn delegates to another looked up in that dispatches on the scheme of
the URI provided (which can be a string or java.net.URI). By default, only
`nrepl` (corresponding to using the default bencode transport) is
supported. Alternative implementations may add support for other schemes,
such as http/https, JMX, various message queues, etc.
"""
#
uri = uri if isinstance(uri, ParseResult) else urlparse(uri)
if not uri.scheme:
raise ValueError("uri has no scheme: " + uri)
f = _connect_fns.get(uri.scheme.lower(), None)
if not f:
err = "No connect function registered for scheme `%s`" % uri.scheme
raise Exception(err)
return f(uri) | python | def connect(uri):
"""
Connects to an nREPL endpoint identified by the given URL/URI. Valid
examples include:
nrepl://192.168.0.12:7889
telnet://localhost:5000
http://your-app-name.heroku.com/repl
This fn delegates to another looked up in that dispatches on the scheme of
the URI provided (which can be a string or java.net.URI). By default, only
`nrepl` (corresponding to using the default bencode transport) is
supported. Alternative implementations may add support for other schemes,
such as http/https, JMX, various message queues, etc.
"""
#
uri = uri if isinstance(uri, ParseResult) else urlparse(uri)
if not uri.scheme:
raise ValueError("uri has no scheme: " + uri)
f = _connect_fns.get(uri.scheme.lower(), None)
if not f:
err = "No connect function registered for scheme `%s`" % uri.scheme
raise Exception(err)
return f(uri) | [
"def",
"connect",
"(",
"uri",
")",
":",
"#",
"uri",
"=",
"uri",
"if",
"isinstance",
"(",
"uri",
",",
"ParseResult",
")",
"else",
"urlparse",
"(",
"uri",
")",
"if",
"not",
"uri",
".",
"scheme",
":",
"raise",
"ValueError",
"(",
"\"uri has no scheme: \"",
... | Connects to an nREPL endpoint identified by the given URL/URI. Valid
examples include:
nrepl://192.168.0.12:7889
telnet://localhost:5000
http://your-app-name.heroku.com/repl
This fn delegates to another looked up in that dispatches on the scheme of
the URI provided (which can be a string or java.net.URI). By default, only
`nrepl` (corresponding to using the default bencode transport) is
supported. Alternative implementations may add support for other schemes,
such as http/https, JMX, various message queues, etc. | [
"Connects",
"to",
"an",
"nREPL",
"endpoint",
"identified",
"by",
"the",
"given",
"URL",
"/",
"URI",
".",
"Valid",
"examples",
"include",
":"
] | train | https://github.com/cemerick/nrepl-python-client/blob/7f0fa7bad73e52e2359b49bc5b719bc19590edf9/nrepl/__init__.py#L106-L129 |
cemerick/nrepl-python-client | nrepl/__init__.py | WatchableConnection.watch | def watch(self, key, criteria, callback):
"""
Registers a new watch under [key] (which can be used with `unwatch()`
to remove the watch) that filters messages using [criteria] (may be a
predicate or a 'criteria dict' [see the README for more info there]).
Matching messages are passed to [callback], which must accept three
arguments: the matched incoming message, this instance of
`WatchableConnection`, and the key under which the watch was
registered.
"""
if hasattr(criteria, '__call__'):
pred = criteria
else:
pred = lambda incoming: _match_criteria(criteria, incoming)
with self._watches_lock:
self._watches[key] = (pred, callback) | python | def watch(self, key, criteria, callback):
"""
Registers a new watch under [key] (which can be used with `unwatch()`
to remove the watch) that filters messages using [criteria] (may be a
predicate or a 'criteria dict' [see the README for more info there]).
Matching messages are passed to [callback], which must accept three
arguments: the matched incoming message, this instance of
`WatchableConnection`, and the key under which the watch was
registered.
"""
if hasattr(criteria, '__call__'):
pred = criteria
else:
pred = lambda incoming: _match_criteria(criteria, incoming)
with self._watches_lock:
self._watches[key] = (pred, callback) | [
"def",
"watch",
"(",
"self",
",",
"key",
",",
"criteria",
",",
"callback",
")",
":",
"if",
"hasattr",
"(",
"criteria",
",",
"'__call__'",
")",
":",
"pred",
"=",
"criteria",
"else",
":",
"pred",
"=",
"lambda",
"incoming",
":",
"_match_criteria",
"(",
"c... | Registers a new watch under [key] (which can be used with `unwatch()`
to remove the watch) that filters messages using [criteria] (may be a
predicate or a 'criteria dict' [see the README for more info there]).
Matching messages are passed to [callback], which must accept three
arguments: the matched incoming message, this instance of
`WatchableConnection`, and the key under which the watch was
registered. | [
"Registers",
"a",
"new",
"watch",
"under",
"[",
"key",
"]",
"(",
"which",
"can",
"be",
"used",
"with",
"unwatch",
"()",
"to",
"remove",
"the",
"watch",
")",
"that",
"filters",
"messages",
"using",
"[",
"criteria",
"]",
"(",
"may",
"be",
"a",
"predicate... | train | https://github.com/cemerick/nrepl-python-client/blob/7f0fa7bad73e52e2359b49bc5b719bc19590edf9/nrepl/__init__.py#L85-L100 |
nkavaldj/myhdl_lib | myhdl_lib/fifo_async.py | fifo_async | def fifo_async(wrst, rrst, wclk, rclk, wfull, we, wdata, rempty, re, rdata, depth=None, width=None):
''' Asynchronous FIFO
Implements the design described in:
Clifford E. Cummings, "Simulation and Synthesis Techniques for Asynchronous FIFO Design," SNUG 2002 (Synopsys
Users Group Conference, San Jose, CA, 2002) User Papers, March 2002, Section TB2, 2nd paper. Also available at
www.sunburst-design.com/papers
Write side interface:
wrst - reset
wclk - clock
wfull - full flag, immediate set on 'write', delayed clear on 'read' due to clock domain synchronization
we - write enable
wdata - write data
Read side interface
rrst - reset
cclk - clock
rempty - empty flag, immediate set on 'read', delayed clear on 'write' due to clock domain synchronization
re - read enable
rdata - read data
Parameters
depth - fifo depth. If not set, default 4 is used. Must be >=4. Must be power of 2
width - data width. If not set, data with equals len(wdata). Can be [0,1,2,3...)
It is possible to instantiate a fifo with data width 0 (no data) if width=0 or width=None and wdata=None
'''
if (width == None):
width = 0
if wdata is not None:
width = len(wdata)
if (depth == None):
depth = 4
assert depth >= 4, "Fifo_async parameter 'depth' must be >= 4 , detected depth={}".format(depth)
assert (depth & (depth-1)) == 0, "Fifo_async parameter 'depth' must be 2**n, detected depth={}".format(depth)
full_flg = Signal(bool(1))
empty_flg = Signal(bool(1))
full_val = Signal(bool(1))
empty_val = Signal(bool(1))
we_safe = Signal(bool(0))
re_safe = Signal(bool(0))
rd_ptr = Signal(intbv(0, min=0, max=depth))
wr_ptr = Signal(intbv(0, min=0, max=depth))
WIDTH = len(rd_ptr)
rd_ptr_bin = Signal(intbv(0)[WIDTH+1:])
rd_ptr_bin_new = Signal(intbv(0)[WIDTH+1:])
rd_ptr_gray = Signal(intbv(0)[WIDTH+1:])
rd_ptr_gray_new = Signal(intbv(0)[WIDTH+1:])
rd_ptr_gray_sync1 = Signal(intbv(0)[WIDTH+1:])
rd_ptr_gray_sync2 = Signal(intbv(0)[WIDTH+1:])
wr_ptr_bin = Signal(intbv(0)[WIDTH+1:])
wr_ptr_bin_new = Signal(intbv(0)[WIDTH+1:])
wr_ptr_gray = Signal(intbv(0)[WIDTH+1:])
wr_ptr_gray_new = Signal(intbv(0)[WIDTH+1:])
wr_ptr_gray_sync1 = Signal(intbv(0)[WIDTH+1:])
wr_ptr_gray_sync2 = Signal(intbv(0)[WIDTH+1:])
@always_comb
def safe_read_write():
wfull.next = full_flg
rempty.next = empty_flg
we_safe.next = we and not full_flg
re_safe.next = re and not empty_flg
@always(wclk.posedge)
def sync_r2w():
''' Read-domain to write-domain synchronizer '''
if (wrst):
rd_ptr_gray_sync1.next = 0
rd_ptr_gray_sync2.next = 0
else:
rd_ptr_gray_sync1.next = rd_ptr_gray
rd_ptr_gray_sync2.next = rd_ptr_gray_sync1
@always(rclk.posedge)
def sync_w2r():
''' Write-domain to read-domain synchronizer '''
if (rrst):
wr_ptr_gray_sync1.next = 0
wr_ptr_gray_sync2.next = 0
else:
wr_ptr_gray_sync1.next = wr_ptr_gray
wr_ptr_gray_sync2.next = wr_ptr_gray_sync1
@always_comb
def bin_comb():
wr_ptr_bin_new.next = wr_ptr_bin
rd_ptr_bin_new.next = rd_ptr_bin
if (we_safe):
wr_ptr_bin_new.next = (wr_ptr_bin + 1) % wr_ptr_bin.max
if (re_safe):
rd_ptr_bin_new.next = (rd_ptr_bin + 1) % rd_ptr_bin.max
@always_comb
def gray_comb():
wr_ptr_gray_new.next = (wr_ptr_bin_new >> 1) ^ wr_ptr_bin_new
rd_ptr_gray_new.next = (rd_ptr_bin_new >> 1) ^ rd_ptr_bin_new
@always_comb
def full_empty_comb():
empty_val.next = (rd_ptr_gray_new == wr_ptr_gray_sync2)
full_val.next = (wr_ptr_gray_new[WIDTH] != rd_ptr_gray_sync2[WIDTH]) and \
(wr_ptr_gray_new[WIDTH-1] != rd_ptr_gray_sync2[WIDTH-1]) and \
(wr_ptr_gray_new[WIDTH-1:] == rd_ptr_gray_sync2[WIDTH-1:])
@always(wclk.posedge)
def wptr_proc():
if (wrst):
wr_ptr_bin.next = 0
wr_ptr_gray.next = 0
full_flg.next = 0
else:
wr_ptr_bin.next = wr_ptr_bin_new
wr_ptr_gray.next = wr_ptr_gray_new
full_flg.next = full_val
@always(rclk.posedge)
def rptr_proc():
if (rrst):
rd_ptr_bin.next = 0
rd_ptr_gray.next = 0
empty_flg.next = 1
else:
rd_ptr_bin.next = rd_ptr_bin_new
rd_ptr_gray.next = rd_ptr_gray_new
empty_flg.next = empty_val
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 = wclk,
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_bin[WIDTH:]
mem_addrr.next = rd_ptr_bin[WIDTH:]
mem_di.next = wdata
rdata.next = mem_do
return instances() | python | def fifo_async(wrst, rrst, wclk, rclk, wfull, we, wdata, rempty, re, rdata, depth=None, width=None):
''' Asynchronous FIFO
Implements the design described in:
Clifford E. Cummings, "Simulation and Synthesis Techniques for Asynchronous FIFO Design," SNUG 2002 (Synopsys
Users Group Conference, San Jose, CA, 2002) User Papers, March 2002, Section TB2, 2nd paper. Also available at
www.sunburst-design.com/papers
Write side interface:
wrst - reset
wclk - clock
wfull - full flag, immediate set on 'write', delayed clear on 'read' due to clock domain synchronization
we - write enable
wdata - write data
Read side interface
rrst - reset
cclk - clock
rempty - empty flag, immediate set on 'read', delayed clear on 'write' due to clock domain synchronization
re - read enable
rdata - read data
Parameters
depth - fifo depth. If not set, default 4 is used. Must be >=4. Must be power of 2
width - data width. If not set, data with equals len(wdata). Can be [0,1,2,3...)
It is possible to instantiate a fifo with data width 0 (no data) if width=0 or width=None and wdata=None
'''
if (width == None):
width = 0
if wdata is not None:
width = len(wdata)
if (depth == None):
depth = 4
assert depth >= 4, "Fifo_async parameter 'depth' must be >= 4 , detected depth={}".format(depth)
assert (depth & (depth-1)) == 0, "Fifo_async parameter 'depth' must be 2**n, detected depth={}".format(depth)
full_flg = Signal(bool(1))
empty_flg = Signal(bool(1))
full_val = Signal(bool(1))
empty_val = Signal(bool(1))
we_safe = Signal(bool(0))
re_safe = Signal(bool(0))
rd_ptr = Signal(intbv(0, min=0, max=depth))
wr_ptr = Signal(intbv(0, min=0, max=depth))
WIDTH = len(rd_ptr)
rd_ptr_bin = Signal(intbv(0)[WIDTH+1:])
rd_ptr_bin_new = Signal(intbv(0)[WIDTH+1:])
rd_ptr_gray = Signal(intbv(0)[WIDTH+1:])
rd_ptr_gray_new = Signal(intbv(0)[WIDTH+1:])
rd_ptr_gray_sync1 = Signal(intbv(0)[WIDTH+1:])
rd_ptr_gray_sync2 = Signal(intbv(0)[WIDTH+1:])
wr_ptr_bin = Signal(intbv(0)[WIDTH+1:])
wr_ptr_bin_new = Signal(intbv(0)[WIDTH+1:])
wr_ptr_gray = Signal(intbv(0)[WIDTH+1:])
wr_ptr_gray_new = Signal(intbv(0)[WIDTH+1:])
wr_ptr_gray_sync1 = Signal(intbv(0)[WIDTH+1:])
wr_ptr_gray_sync2 = Signal(intbv(0)[WIDTH+1:])
@always_comb
def safe_read_write():
wfull.next = full_flg
rempty.next = empty_flg
we_safe.next = we and not full_flg
re_safe.next = re and not empty_flg
@always(wclk.posedge)
def sync_r2w():
''' Read-domain to write-domain synchronizer '''
if (wrst):
rd_ptr_gray_sync1.next = 0
rd_ptr_gray_sync2.next = 0
else:
rd_ptr_gray_sync1.next = rd_ptr_gray
rd_ptr_gray_sync2.next = rd_ptr_gray_sync1
@always(rclk.posedge)
def sync_w2r():
''' Write-domain to read-domain synchronizer '''
if (rrst):
wr_ptr_gray_sync1.next = 0
wr_ptr_gray_sync2.next = 0
else:
wr_ptr_gray_sync1.next = wr_ptr_gray
wr_ptr_gray_sync2.next = wr_ptr_gray_sync1
@always_comb
def bin_comb():
wr_ptr_bin_new.next = wr_ptr_bin
rd_ptr_bin_new.next = rd_ptr_bin
if (we_safe):
wr_ptr_bin_new.next = (wr_ptr_bin + 1) % wr_ptr_bin.max
if (re_safe):
rd_ptr_bin_new.next = (rd_ptr_bin + 1) % rd_ptr_bin.max
@always_comb
def gray_comb():
wr_ptr_gray_new.next = (wr_ptr_bin_new >> 1) ^ wr_ptr_bin_new
rd_ptr_gray_new.next = (rd_ptr_bin_new >> 1) ^ rd_ptr_bin_new
@always_comb
def full_empty_comb():
empty_val.next = (rd_ptr_gray_new == wr_ptr_gray_sync2)
full_val.next = (wr_ptr_gray_new[WIDTH] != rd_ptr_gray_sync2[WIDTH]) and \
(wr_ptr_gray_new[WIDTH-1] != rd_ptr_gray_sync2[WIDTH-1]) and \
(wr_ptr_gray_new[WIDTH-1:] == rd_ptr_gray_sync2[WIDTH-1:])
@always(wclk.posedge)
def wptr_proc():
if (wrst):
wr_ptr_bin.next = 0
wr_ptr_gray.next = 0
full_flg.next = 0
else:
wr_ptr_bin.next = wr_ptr_bin_new
wr_ptr_gray.next = wr_ptr_gray_new
full_flg.next = full_val
@always(rclk.posedge)
def rptr_proc():
if (rrst):
rd_ptr_bin.next = 0
rd_ptr_gray.next = 0
empty_flg.next = 1
else:
rd_ptr_bin.next = rd_ptr_bin_new
rd_ptr_gray.next = rd_ptr_gray_new
empty_flg.next = empty_val
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 = wclk,
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_bin[WIDTH:]
mem_addrr.next = rd_ptr_bin[WIDTH:]
mem_di.next = wdata
rdata.next = mem_do
return instances() | [
"def",
"fifo_async",
"(",
"wrst",
",",
"rrst",
",",
"wclk",
",",
"rclk",
",",
"wfull",
",",
"we",
",",
"wdata",
",",
"rempty",
",",
"re",
",",
"rdata",
",",
"depth",
"=",
"None",
",",
"width",
"=",
"None",
")",
":",
"if",
"(",
"width",
"==",
"N... | Asynchronous FIFO
Implements the design described in:
Clifford E. Cummings, "Simulation and Synthesis Techniques for Asynchronous FIFO Design," SNUG 2002 (Synopsys
Users Group Conference, San Jose, CA, 2002) User Papers, March 2002, Section TB2, 2nd paper. Also available at
www.sunburst-design.com/papers
Write side interface:
wrst - reset
wclk - clock
wfull - full flag, immediate set on 'write', delayed clear on 'read' due to clock domain synchronization
we - write enable
wdata - write data
Read side interface
rrst - reset
cclk - clock
rempty - empty flag, immediate set on 'read', delayed clear on 'write' due to clock domain synchronization
re - read enable
rdata - read data
Parameters
depth - fifo depth. If not set, default 4 is used. Must be >=4. Must be power of 2
width - data width. If not set, data with equals len(wdata). Can be [0,1,2,3...)
It is possible to instantiate a fifo with data width 0 (no data) if width=0 or width=None and wdata=None | [
"Asynchronous",
"FIFO"
] | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/fifo_async.py#L5-L166 |
openfisca/openfisca-web-api | openfisca_web_api/wsgihelpers.py | respond_json | def respond_json(ctx, data, code = None, headers = [], json_dumps_default = None, jsonp = None):
"""Return a JSON response.
This function is optimized for JSON following
`Google JSON Style Guide <http://google-styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml>`_, but will handle
any JSON except for HTTP errors.
"""
if isinstance(data, collections.Mapping):
# Remove null properties as recommended by Google JSON Style Guide.
data = type(data)(
(name, value)
for name, value in data.iteritems()
if value is not None
)
error = data.get('error')
if isinstance(error, collections.Mapping):
error = data['error'] = type(error)(
(name, value)
for name, value in error.iteritems()
if value is not None
)
else:
error = None
if jsonp:
content_type = 'application/javascript; charset=utf-8'
else:
content_type = 'application/json; charset=utf-8'
if error:
code = code or error['code']
assert isinstance(code, int)
response = webob.exc.status_map[code](headers = headers)
response.content_type = content_type
if code == 204: # No content
return response
if error.get('code') is None:
error['code'] = code
if error.get('message') is None:
title = errors_title.get(code)
title = ctx._(title) if title is not None else response.status
error['message'] = title
else:
response = ctx.req.response
response.content_type = content_type
if code is not None:
response.status = code
response.headers.update(headers)
# try:
# text = json.dumps(data, encoding = 'utf-8', ensure_ascii = False, indent = 2)
# except UnicodeDecodeError:
# text = json.dumps(data, ensure_ascii = True, indent = 2)
if json_dumps_default is None:
text = json.dumps(data)
else:
text = json.dumps(data, default = json_dumps_default)
text = unicode(text)
if jsonp:
text = u'{0}({1})'.format(jsonp, text)
response.text = text
return response | python | def respond_json(ctx, data, code = None, headers = [], json_dumps_default = None, jsonp = None):
"""Return a JSON response.
This function is optimized for JSON following
`Google JSON Style Guide <http://google-styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml>`_, but will handle
any JSON except for HTTP errors.
"""
if isinstance(data, collections.Mapping):
# Remove null properties as recommended by Google JSON Style Guide.
data = type(data)(
(name, value)
for name, value in data.iteritems()
if value is not None
)
error = data.get('error')
if isinstance(error, collections.Mapping):
error = data['error'] = type(error)(
(name, value)
for name, value in error.iteritems()
if value is not None
)
else:
error = None
if jsonp:
content_type = 'application/javascript; charset=utf-8'
else:
content_type = 'application/json; charset=utf-8'
if error:
code = code or error['code']
assert isinstance(code, int)
response = webob.exc.status_map[code](headers = headers)
response.content_type = content_type
if code == 204: # No content
return response
if error.get('code') is None:
error['code'] = code
if error.get('message') is None:
title = errors_title.get(code)
title = ctx._(title) if title is not None else response.status
error['message'] = title
else:
response = ctx.req.response
response.content_type = content_type
if code is not None:
response.status = code
response.headers.update(headers)
# try:
# text = json.dumps(data, encoding = 'utf-8', ensure_ascii = False, indent = 2)
# except UnicodeDecodeError:
# text = json.dumps(data, ensure_ascii = True, indent = 2)
if json_dumps_default is None:
text = json.dumps(data)
else:
text = json.dumps(data, default = json_dumps_default)
text = unicode(text)
if jsonp:
text = u'{0}({1})'.format(jsonp, text)
response.text = text
return response | [
"def",
"respond_json",
"(",
"ctx",
",",
"data",
",",
"code",
"=",
"None",
",",
"headers",
"=",
"[",
"]",
",",
"json_dumps_default",
"=",
"None",
",",
"jsonp",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"collections",
".",
"Mapping",
... | Return a JSON response.
This function is optimized for JSON following
`Google JSON Style Guide <http://google-styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml>`_, but will handle
any JSON except for HTTP errors. | [
"Return",
"a",
"JSON",
"response",
"."
] | train | https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/wsgihelpers.py#L69-L128 |
kyegupov/py-unrar2 | UnRAR2/unix.py | call_unrar | def call_unrar(params):
"""Calls rar/unrar command line executable, returns stdout pipe"""
global rar_executable_cached
if rar_executable_cached is None:
for command in ('unrar', 'rar'):
try:
subprocess.Popen([command], stdout=subprocess.PIPE)
rar_executable_cached = command
break
except OSError:
pass
if rar_executable_cached is None:
raise UnpackerNotInstalled("No suitable RAR unpacker installed")
assert type(params) == list, "params must be list"
args = [rar_executable_cached] + params
try:
gc.disable() # See http://bugs.python.org/issue1336
return subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
finally:
gc.enable() | python | def call_unrar(params):
"""Calls rar/unrar command line executable, returns stdout pipe"""
global rar_executable_cached
if rar_executable_cached is None:
for command in ('unrar', 'rar'):
try:
subprocess.Popen([command], stdout=subprocess.PIPE)
rar_executable_cached = command
break
except OSError:
pass
if rar_executable_cached is None:
raise UnpackerNotInstalled("No suitable RAR unpacker installed")
assert type(params) == list, "params must be list"
args = [rar_executable_cached] + params
try:
gc.disable() # See http://bugs.python.org/issue1336
return subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
finally:
gc.enable() | [
"def",
"call_unrar",
"(",
"params",
")",
":",
"global",
"rar_executable_cached",
"if",
"rar_executable_cached",
"is",
"None",
":",
"for",
"command",
"in",
"(",
"'unrar'",
",",
"'rar'",
")",
":",
"try",
":",
"subprocess",
".",
"Popen",
"(",
"[",
"command",
... | Calls rar/unrar command line executable, returns stdout pipe | [
"Calls",
"rar",
"/",
"unrar",
"command",
"line",
"executable",
"returns",
"stdout",
"pipe"
] | train | https://github.com/kyegupov/py-unrar2/blob/186a4c1feb9ef3d96a2331f8fb3ebf88036e15e5/UnRAR2/unix.py#L57-L78 |
biocommons/bioutils | src/bioutils/assemblies.py | get_assembly_names | def get_assembly_names():
"""return list of available assemblies
>>> assy_names = get_assembly_names()
>>> 'GRCh37.p13' in assy_names
True
"""
return [
n.replace(".json.gz", "")
for n in pkg_resources.resource_listdir(__name__, _assy_dir)
if n.endswith(".json.gz")
] | python | def get_assembly_names():
"""return list of available assemblies
>>> assy_names = get_assembly_names()
>>> 'GRCh37.p13' in assy_names
True
"""
return [
n.replace(".json.gz", "")
for n in pkg_resources.resource_listdir(__name__, _assy_dir)
if n.endswith(".json.gz")
] | [
"def",
"get_assembly_names",
"(",
")",
":",
"return",
"[",
"n",
".",
"replace",
"(",
"\".json.gz\"",
",",
"\"\"",
")",
"for",
"n",
"in",
"pkg_resources",
".",
"resource_listdir",
"(",
"__name__",
",",
"_assy_dir",
")",
"if",
"n",
".",
"endswith",
"(",
"\... | return list of available assemblies
>>> assy_names = get_assembly_names()
>>> 'GRCh37.p13' in assy_names
True | [
"return",
"list",
"of",
"available",
"assemblies",
">>>",
"assy_names",
"=",
"get_assembly_names",
"()"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/assemblies.py#L34-L48 |
biocommons/bioutils | src/bioutils/assemblies.py | get_assembly | def get_assembly(name):
"""read a single assembly by name, returning a dictionary of assembly data
>>> assy = get_assembly('GRCh37.p13')
>>> assy['name']
'GRCh37.p13'
>>> assy['description']
'Genome Reference Consortium Human Build 37 patch release 13 (GRCh37.p13)'
>>> assy['refseq_ac']
'GCF_000001405.25'
>>> assy['genbank_ac']
'GCA_000001405.14'
>>> len(assy['sequences'])
297
>>> import pprint
>>> pprint.pprint(assy['sequences'][0])
{'aliases': ['chr1'],
'assembly_unit': 'Primary Assembly',
'genbank_ac': 'CM000663.1',
'length': 249250621,
'name': '1',
'refseq_ac': 'NC_000001.10',
'relationship': '=',
'sequence_role': 'assembled-molecule'}
"""
fn = pkg_resources.resource_filename(
__name__, _assy_path_fmt.format(name=name))
return json.load(gzip.open(fn, mode="rt", encoding="utf-8")) | python | def get_assembly(name):
"""read a single assembly by name, returning a dictionary of assembly data
>>> assy = get_assembly('GRCh37.p13')
>>> assy['name']
'GRCh37.p13'
>>> assy['description']
'Genome Reference Consortium Human Build 37 patch release 13 (GRCh37.p13)'
>>> assy['refseq_ac']
'GCF_000001405.25'
>>> assy['genbank_ac']
'GCA_000001405.14'
>>> len(assy['sequences'])
297
>>> import pprint
>>> pprint.pprint(assy['sequences'][0])
{'aliases': ['chr1'],
'assembly_unit': 'Primary Assembly',
'genbank_ac': 'CM000663.1',
'length': 249250621,
'name': '1',
'refseq_ac': 'NC_000001.10',
'relationship': '=',
'sequence_role': 'assembled-molecule'}
"""
fn = pkg_resources.resource_filename(
__name__, _assy_path_fmt.format(name=name))
return json.load(gzip.open(fn, mode="rt", encoding="utf-8")) | [
"def",
"get_assembly",
"(",
"name",
")",
":",
"fn",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"__name__",
",",
"_assy_path_fmt",
".",
"format",
"(",
"name",
"=",
"name",
")",
")",
"return",
"json",
".",
"load",
"(",
"gzip",
".",
"open",
"(",
... | read a single assembly by name, returning a dictionary of assembly data
>>> assy = get_assembly('GRCh37.p13')
>>> assy['name']
'GRCh37.p13'
>>> assy['description']
'Genome Reference Consortium Human Build 37 patch release 13 (GRCh37.p13)'
>>> assy['refseq_ac']
'GCF_000001405.25'
>>> assy['genbank_ac']
'GCA_000001405.14'
>>> len(assy['sequences'])
297
>>> import pprint
>>> pprint.pprint(assy['sequences'][0])
{'aliases': ['chr1'],
'assembly_unit': 'Primary Assembly',
'genbank_ac': 'CM000663.1',
'length': 249250621,
'name': '1',
'refseq_ac': 'NC_000001.10',
'relationship': '=',
'sequence_role': 'assembled-molecule'} | [
"read",
"a",
"single",
"assembly",
"by",
"name",
"returning",
"a",
"dictionary",
"of",
"assembly",
"data"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/assemblies.py#L51-L85 |
biocommons/bioutils | src/bioutils/assemblies.py | get_assemblies | def get_assemblies(names=[]):
"""read specified assemblies, or all if none specified, returning a
dictionary of assembly-name: assembly. See get_assembly()
function for the structure of assembly data.
>>> assemblies = get_assemblies(names=['GRCh37.p13'])
>>> assy = assemblies['GRCh37.p13']
>>> assemblies = get_assemblies()
>>> 'GRCh38.p2' in assemblies
True
"""
if names == []:
names = get_assembly_names()
return {a['name']: a for a in (get_assembly(n) for n in names)} | python | def get_assemblies(names=[]):
"""read specified assemblies, or all if none specified, returning a
dictionary of assembly-name: assembly. See get_assembly()
function for the structure of assembly data.
>>> assemblies = get_assemblies(names=['GRCh37.p13'])
>>> assy = assemblies['GRCh37.p13']
>>> assemblies = get_assemblies()
>>> 'GRCh38.p2' in assemblies
True
"""
if names == []:
names = get_assembly_names()
return {a['name']: a for a in (get_assembly(n) for n in names)} | [
"def",
"get_assemblies",
"(",
"names",
"=",
"[",
"]",
")",
":",
"if",
"names",
"==",
"[",
"]",
":",
"names",
"=",
"get_assembly_names",
"(",
")",
"return",
"{",
"a",
"[",
"'name'",
"]",
":",
"a",
"for",
"a",
"in",
"(",
"get_assembly",
"(",
"n",
"... | read specified assemblies, or all if none specified, returning a
dictionary of assembly-name: assembly. See get_assembly()
function for the structure of assembly data.
>>> assemblies = get_assemblies(names=['GRCh37.p13'])
>>> assy = assemblies['GRCh37.p13']
>>> assemblies = get_assemblies()
>>> 'GRCh38.p2' in assemblies
True | [
"read",
"specified",
"assemblies",
"or",
"all",
"if",
"none",
"specified",
"returning",
"a",
"dictionary",
"of",
"assembly",
"-",
"name",
":",
"assembly",
".",
"See",
"get_assembly",
"()",
"function",
"for",
"the",
"structure",
"of",
"assembly",
"data",
"."
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/assemblies.py#L88-L104 |
biocommons/bioutils | src/bioutils/assemblies.py | make_name_ac_map | def make_name_ac_map(assy_name, primary_only=False):
"""make map from sequence name to accession for given assembly name
>>> grch38p5_name_ac_map = make_name_ac_map('GRCh38.p5')
>>> grch38p5_name_ac_map['1']
'NC_000001.11'
"""
return {
s['name']: s['refseq_ac']
for s in get_assembly(assy_name)['sequences']
if (not primary_only or _is_primary(s))
} | python | def make_name_ac_map(assy_name, primary_only=False):
"""make map from sequence name to accession for given assembly name
>>> grch38p5_name_ac_map = make_name_ac_map('GRCh38.p5')
>>> grch38p5_name_ac_map['1']
'NC_000001.11'
"""
return {
s['name']: s['refseq_ac']
for s in get_assembly(assy_name)['sequences']
if (not primary_only or _is_primary(s))
} | [
"def",
"make_name_ac_map",
"(",
"assy_name",
",",
"primary_only",
"=",
"False",
")",
":",
"return",
"{",
"s",
"[",
"'name'",
"]",
":",
"s",
"[",
"'refseq_ac'",
"]",
"for",
"s",
"in",
"get_assembly",
"(",
"assy_name",
")",
"[",
"'sequences'",
"]",
"if",
... | make map from sequence name to accession for given assembly name
>>> grch38p5_name_ac_map = make_name_ac_map('GRCh38.p5')
>>> grch38p5_name_ac_map['1']
'NC_000001.11' | [
"make",
"map",
"from",
"sequence",
"name",
"to",
"accession",
"for",
"given",
"assembly",
"name"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/assemblies.py#L107-L119 |
biocommons/bioutils | src/bioutils/assemblies.py | make_ac_name_map | def make_ac_name_map(assy_name, primary_only=False):
"""make map from accession (str) to sequence name (str) for given assembly name
>>> grch38p5_ac_name_map = make_ac_name_map('GRCh38.p5')
>>> grch38p5_ac_name_map['NC_000001.11']
'1'
"""
return {
s['refseq_ac']: s['name']
for s in get_assembly(assy_name)['sequences']
if (not primary_only or _is_primary(s))
} | python | def make_ac_name_map(assy_name, primary_only=False):
"""make map from accession (str) to sequence name (str) for given assembly name
>>> grch38p5_ac_name_map = make_ac_name_map('GRCh38.p5')
>>> grch38p5_ac_name_map['NC_000001.11']
'1'
"""
return {
s['refseq_ac']: s['name']
for s in get_assembly(assy_name)['sequences']
if (not primary_only or _is_primary(s))
} | [
"def",
"make_ac_name_map",
"(",
"assy_name",
",",
"primary_only",
"=",
"False",
")",
":",
"return",
"{",
"s",
"[",
"'refseq_ac'",
"]",
":",
"s",
"[",
"'name'",
"]",
"for",
"s",
"in",
"get_assembly",
"(",
"assy_name",
")",
"[",
"'sequences'",
"]",
"if",
... | make map from accession (str) to sequence name (str) for given assembly name
>>> grch38p5_ac_name_map = make_ac_name_map('GRCh38.p5')
>>> grch38p5_ac_name_map['NC_000001.11']
'1' | [
"make",
"map",
"from",
"accession",
"(",
"str",
")",
"to",
"sequence",
"name",
"(",
"str",
")",
"for",
"given",
"assembly",
"name"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/assemblies.py#L122-L135 |
flo-compbio/genometools | genometools/ensembl/cli/extract_protein_coding_exon_annotations.py | main | def main(args=None):
"""Extract all exon annotations of protein-coding genes."""
if args is None:
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
field_name = args.field_name
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 = re.compile(ensembl.SPECIES_CHROMPAT[species])
else:
chrom_pat = re.compile(chrom_pat)
logger.info('Regular expression used for filtering chromosome names: "%s"',
chrom_pat.pattern)
chromosomes = set()
excluded_chromosomes = set()
i = 0
exons = 0
logger.info('Parsing data...')
if input_file == '-':
input_file = None
with misc.smart_open_read(input_file, mode = 'rb', try_gzip = True) as fh, \
misc.smart_open_write(output_file) as ofh:
#if i >= 500000: break
reader = csv.reader(fh, dialect = 'excel-tab')
writer = csv.writer(ofh, dialect = 'excel-tab', lineterminator = os.linesep,
quoting = csv.QUOTE_NONE , quotechar = '|')
for l in reader:
i += 1
#if i % int(1e5) == 0:
# print '\r%d...' %(i), ; sys.stdout.flush() # report progress
if len(l) > 1 and l[2] == field_name:
attr = parse_attributes(l[8])
type_ = attr['gene_biotype']
if type_ in ['protein_coding','polymorphic_pseudogene']:
# test whether chromosome is valid
chrom = l[0]
m = chrom_pat.match(chrom)
if m is None:
excluded_chromosomes.add(chrom)
continue
chromosomes.add(chrom)
writer.writerow(l)
exons += 1
logger.info('Done! (Parsed %d lines.)', i)
logger.info('')
logger.info('Gene chromosomes (%d):', len(chromosomes))
logger.info('\t' + ', '.join(sorted(chromosomes)))
logger.info('')
logger.info('Excluded chromosomes (%d):', len(excluded_chromosomes))
logger.info('\t' + ', '.join(sorted(excluded_chromosomes)))
logger.info('')
logger.info('Total no. of exons: %d' %(exons))
return 0 | python | def main(args=None):
"""Extract all exon annotations of protein-coding genes."""
if args is None:
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
field_name = args.field_name
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 = re.compile(ensembl.SPECIES_CHROMPAT[species])
else:
chrom_pat = re.compile(chrom_pat)
logger.info('Regular expression used for filtering chromosome names: "%s"',
chrom_pat.pattern)
chromosomes = set()
excluded_chromosomes = set()
i = 0
exons = 0
logger.info('Parsing data...')
if input_file == '-':
input_file = None
with misc.smart_open_read(input_file, mode = 'rb', try_gzip = True) as fh, \
misc.smart_open_write(output_file) as ofh:
#if i >= 500000: break
reader = csv.reader(fh, dialect = 'excel-tab')
writer = csv.writer(ofh, dialect = 'excel-tab', lineterminator = os.linesep,
quoting = csv.QUOTE_NONE , quotechar = '|')
for l in reader:
i += 1
#if i % int(1e5) == 0:
# print '\r%d...' %(i), ; sys.stdout.flush() # report progress
if len(l) > 1 and l[2] == field_name:
attr = parse_attributes(l[8])
type_ = attr['gene_biotype']
if type_ in ['protein_coding','polymorphic_pseudogene']:
# test whether chromosome is valid
chrom = l[0]
m = chrom_pat.match(chrom)
if m is None:
excluded_chromosomes.add(chrom)
continue
chromosomes.add(chrom)
writer.writerow(l)
exons += 1
logger.info('Done! (Parsed %d lines.)', i)
logger.info('')
logger.info('Gene chromosomes (%d):', len(chromosomes))
logger.info('\t' + ', '.join(sorted(chromosomes)))
logger.info('')
logger.info('Excluded chromosomes (%d):', len(excluded_chromosomes))
logger.info('\t' + ', '.join(sorted(excluded_chromosomes)))
logger.info('')
logger.info('Total no. of exons: %d' %(exons))
return 0 | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"parser",
"=",
"get_argument_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"input_file",
"=",
"args",
".",
"annotation_file",
"output_file",
"=",... | Extract all exon annotations of protein-coding genes. | [
"Extract",
"all",
"exon",
"annotations",
"of",
"protein",
"-",
"coding",
"genes",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ensembl/cli/extract_protein_coding_exon_annotations.py#L53-L131 |
acorg/dark-matter | dark/titles.py | titleCounts | def titleCounts(readsAlignments):
"""
Count the number of times each title in a readsAlignments instance is
matched. This is useful for rapidly discovering what titles were matched
and with what frequency.
@param readsAlignments: A L{dark.alignments.ReadsAlignments} instance.
@return: A C{dict} whose keys are titles and whose values are the integer
counts of the number of reads that matched that title.
"""
titles = defaultdict(int)
for readAlignments in readsAlignments:
for alignment in readAlignments:
titles[alignment.subjectTitle] += 1
return titles | python | def titleCounts(readsAlignments):
"""
Count the number of times each title in a readsAlignments instance is
matched. This is useful for rapidly discovering what titles were matched
and with what frequency.
@param readsAlignments: A L{dark.alignments.ReadsAlignments} instance.
@return: A C{dict} whose keys are titles and whose values are the integer
counts of the number of reads that matched that title.
"""
titles = defaultdict(int)
for readAlignments in readsAlignments:
for alignment in readAlignments:
titles[alignment.subjectTitle] += 1
return titles | [
"def",
"titleCounts",
"(",
"readsAlignments",
")",
":",
"titles",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"readAlignments",
"in",
"readsAlignments",
":",
"for",
"alignment",
"in",
"readAlignments",
":",
"titles",
"[",
"alignment",
".",
"subjectTitle",
"]",
... | Count the number of times each title in a readsAlignments instance is
matched. This is useful for rapidly discovering what titles were matched
and with what frequency.
@param readsAlignments: A L{dark.alignments.ReadsAlignments} instance.
@return: A C{dict} whose keys are titles and whose values are the integer
counts of the number of reads that matched that title. | [
"Count",
"the",
"number",
"of",
"times",
"each",
"title",
"in",
"a",
"readsAlignments",
"instance",
"is",
"matched",
".",
"This",
"is",
"useful",
"for",
"rapidly",
"discovering",
"what",
"titles",
"were",
"matched",
"and",
"with",
"what",
"frequency",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L8-L23 |
acorg/dark-matter | dark/titles.py | TitleAlignment.toDict | def toDict(self):
"""
Get information about a title alignment as a dictionary.
@return: A C{dict} representation of the title aligment.
"""
return {
'hsps': [hsp.toDict() for hsp in self.hsps],
'read': self.read.toDict(),
} | python | def toDict(self):
"""
Get information about a title alignment as a dictionary.
@return: A C{dict} representation of the title aligment.
"""
return {
'hsps': [hsp.toDict() for hsp in self.hsps],
'read': self.read.toDict(),
} | [
"def",
"toDict",
"(",
"self",
")",
":",
"return",
"{",
"'hsps'",
":",
"[",
"hsp",
".",
"toDict",
"(",
")",
"for",
"hsp",
"in",
"self",
".",
"hsps",
"]",
",",
"'read'",
":",
"self",
".",
"read",
".",
"toDict",
"(",
")",
",",
"}"
] | Get information about a title alignment as a dictionary.
@return: A C{dict} representation of the title aligment. | [
"Get",
"information",
"about",
"a",
"title",
"alignment",
"as",
"a",
"dictionary",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L38-L47 |
acorg/dark-matter | dark/titles.py | TitleAlignments.hasScoreBetterThan | def hasScoreBetterThan(self, score):
"""
Is there an HSP with a score better than a given value?
@return: A C{bool}, C{True} if there is at least one HSP in the
alignments for this title with a score better than C{score}.
"""
# Note: Do not assume that HSPs in an alignment are sorted in
# decreasing order (as they are in BLAST output). If we could
# assume that, we could just check the first HSP in each alignment.
for hsp in self.hsps():
if hsp.betterThan(score):
return True
return False | python | def hasScoreBetterThan(self, score):
"""
Is there an HSP with a score better than a given value?
@return: A C{bool}, C{True} if there is at least one HSP in the
alignments for this title with a score better than C{score}.
"""
# Note: Do not assume that HSPs in an alignment are sorted in
# decreasing order (as they are in BLAST output). If we could
# assume that, we could just check the first HSP in each alignment.
for hsp in self.hsps():
if hsp.betterThan(score):
return True
return False | [
"def",
"hasScoreBetterThan",
"(",
"self",
",",
"score",
")",
":",
"# Note: Do not assume that HSPs in an alignment are sorted in",
"# decreasing order (as they are in BLAST output). If we could",
"# assume that, we could just check the first HSP in each alignment.",
"for",
"hsp",
"in",
"... | Is there an HSP with a score better than a given value?
@return: A C{bool}, C{True} if there is at least one HSP in the
alignments for this title with a score better than C{score}. | [
"Is",
"there",
"an",
"HSP",
"with",
"a",
"score",
"better",
"than",
"a",
"given",
"value?"
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L133-L146 |
acorg/dark-matter | dark/titles.py | TitleAlignments.coverage | def coverage(self):
"""
Get the fraction of this title sequence that is matched by its reads.
@return: The C{float} fraction of the title sequence matched by its
reads.
"""
intervals = ReadIntervals(self.subjectLength)
for hsp in self.hsps():
intervals.add(hsp.subjectStart, hsp.subjectEnd)
return intervals.coverage() | python | def coverage(self):
"""
Get the fraction of this title sequence that is matched by its reads.
@return: The C{float} fraction of the title sequence matched by its
reads.
"""
intervals = ReadIntervals(self.subjectLength)
for hsp in self.hsps():
intervals.add(hsp.subjectStart, hsp.subjectEnd)
return intervals.coverage() | [
"def",
"coverage",
"(",
"self",
")",
":",
"intervals",
"=",
"ReadIntervals",
"(",
"self",
".",
"subjectLength",
")",
"for",
"hsp",
"in",
"self",
".",
"hsps",
"(",
")",
":",
"intervals",
".",
"add",
"(",
"hsp",
".",
"subjectStart",
",",
"hsp",
".",
"s... | Get the fraction of this title sequence that is matched by its reads.
@return: The C{float} fraction of the title sequence matched by its
reads. | [
"Get",
"the",
"fraction",
"of",
"this",
"title",
"sequence",
"that",
"is",
"matched",
"by",
"its",
"reads",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L159-L169 |
acorg/dark-matter | dark/titles.py | TitleAlignments.coverageInfo | def coverageInfo(self):
"""
Return information about the bases found at each location in our title
sequence.
@return: A C{dict} whose keys are C{int} subject offsets and whose
values are unsorted lists of (score, base) 2-tuples, giving all the
bases from reads that matched the subject at subject location,
along with the bit score of the matching read.
"""
result = defaultdict(list)
for titleAlignment in self:
for hsp in titleAlignment.hsps:
score = hsp.score.score
for (subjectOffset, base, _) in titleAlignment.read.walkHSP(
hsp, includeWhiskers=False):
result[subjectOffset].append((score, base))
return result | python | def coverageInfo(self):
"""
Return information about the bases found at each location in our title
sequence.
@return: A C{dict} whose keys are C{int} subject offsets and whose
values are unsorted lists of (score, base) 2-tuples, giving all the
bases from reads that matched the subject at subject location,
along with the bit score of the matching read.
"""
result = defaultdict(list)
for titleAlignment in self:
for hsp in titleAlignment.hsps:
score = hsp.score.score
for (subjectOffset, base, _) in titleAlignment.read.walkHSP(
hsp, includeWhiskers=False):
result[subjectOffset].append((score, base))
return result | [
"def",
"coverageInfo",
"(",
"self",
")",
":",
"result",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"titleAlignment",
"in",
"self",
":",
"for",
"hsp",
"in",
"titleAlignment",
".",
"hsps",
":",
"score",
"=",
"hsp",
".",
"score",
".",
"score",
"for",
"(... | Return information about the bases found at each location in our title
sequence.
@return: A C{dict} whose keys are C{int} subject offsets and whose
values are unsorted lists of (score, base) 2-tuples, giving all the
bases from reads that matched the subject at subject location,
along with the bit score of the matching read. | [
"Return",
"information",
"about",
"the",
"bases",
"found",
"at",
"each",
"location",
"in",
"our",
"title",
"sequence",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L181-L200 |
acorg/dark-matter | dark/titles.py | TitleAlignments.residueCounts | def residueCounts(self, convertCaseTo='upper'):
"""
Count residue frequencies at all sequence locations matched by reads.
@param convertCaseTo: A C{str}, 'upper', 'lower', or 'none'.
If 'none', case will not be converted (both the upper and lower
case string of a residue will be present in the result if they are
present in the read - usually due to low complexity masking).
@return: A C{dict} whose keys are C{int} offsets into the title
sequence and whose values are C{Counters} with the residue as keys
and the count of that residue at that location as values.
"""
if convertCaseTo == 'none':
def convert(x):
return x
elif convertCaseTo == 'lower':
convert = str.lower
elif convertCaseTo == 'upper':
convert = str.upper
else:
raise ValueError(
"convertCaseTo must be one of 'none', 'lower', or 'upper'")
counts = defaultdict(Counter)
for titleAlignment in self:
read = titleAlignment.read
for hsp in titleAlignment.hsps:
for (subjectOffset, residue, inMatch) in read.walkHSP(hsp):
counts[subjectOffset][convert(residue)] += 1
return counts | python | def residueCounts(self, convertCaseTo='upper'):
"""
Count residue frequencies at all sequence locations matched by reads.
@param convertCaseTo: A C{str}, 'upper', 'lower', or 'none'.
If 'none', case will not be converted (both the upper and lower
case string of a residue will be present in the result if they are
present in the read - usually due to low complexity masking).
@return: A C{dict} whose keys are C{int} offsets into the title
sequence and whose values are C{Counters} with the residue as keys
and the count of that residue at that location as values.
"""
if convertCaseTo == 'none':
def convert(x):
return x
elif convertCaseTo == 'lower':
convert = str.lower
elif convertCaseTo == 'upper':
convert = str.upper
else:
raise ValueError(
"convertCaseTo must be one of 'none', 'lower', or 'upper'")
counts = defaultdict(Counter)
for titleAlignment in self:
read = titleAlignment.read
for hsp in titleAlignment.hsps:
for (subjectOffset, residue, inMatch) in read.walkHSP(hsp):
counts[subjectOffset][convert(residue)] += 1
return counts | [
"def",
"residueCounts",
"(",
"self",
",",
"convertCaseTo",
"=",
"'upper'",
")",
":",
"if",
"convertCaseTo",
"==",
"'none'",
":",
"def",
"convert",
"(",
"x",
")",
":",
"return",
"x",
"elif",
"convertCaseTo",
"==",
"'lower'",
":",
"convert",
"=",
"str",
".... | Count residue frequencies at all sequence locations matched by reads.
@param convertCaseTo: A C{str}, 'upper', 'lower', or 'none'.
If 'none', case will not be converted (both the upper and lower
case string of a residue will be present in the result if they are
present in the read - usually due to low complexity masking).
@return: A C{dict} whose keys are C{int} offsets into the title
sequence and whose values are C{Counters} with the residue as keys
and the count of that residue at that location as values. | [
"Count",
"residue",
"frequencies",
"at",
"all",
"sequence",
"locations",
"matched",
"by",
"reads",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L202-L233 |
acorg/dark-matter | dark/titles.py | TitleAlignments.summary | def summary(self):
"""
Summarize the alignments for this subject.
@return: A C{dict} with C{str} keys:
bestScore: The C{float} best score of the matching reads.
coverage: The C{float} fraction of the subject genome that is
matched by at least one read.
hspCount: The C{int} number of hsps that match the subject.
medianScore: The C{float} median score of the matching reads.
readCount: The C{int} number of reads that match the subject.
subjectLength: The C{int} length of the subject.
subjectTitle: The C{str} title of the subject.
"""
return {
'bestScore': self.bestHsp().score.score,
'coverage': self.coverage(),
'hspCount': self.hspCount(),
'medianScore': self.medianScore(),
'readCount': self.readCount(),
'subjectLength': self.subjectLength,
'subjectTitle': self.subjectTitle,
} | python | def summary(self):
"""
Summarize the alignments for this subject.
@return: A C{dict} with C{str} keys:
bestScore: The C{float} best score of the matching reads.
coverage: The C{float} fraction of the subject genome that is
matched by at least one read.
hspCount: The C{int} number of hsps that match the subject.
medianScore: The C{float} median score of the matching reads.
readCount: The C{int} number of reads that match the subject.
subjectLength: The C{int} length of the subject.
subjectTitle: The C{str} title of the subject.
"""
return {
'bestScore': self.bestHsp().score.score,
'coverage': self.coverage(),
'hspCount': self.hspCount(),
'medianScore': self.medianScore(),
'readCount': self.readCount(),
'subjectLength': self.subjectLength,
'subjectTitle': self.subjectTitle,
} | [
"def",
"summary",
"(",
"self",
")",
":",
"return",
"{",
"'bestScore'",
":",
"self",
".",
"bestHsp",
"(",
")",
".",
"score",
".",
"score",
",",
"'coverage'",
":",
"self",
".",
"coverage",
"(",
")",
",",
"'hspCount'",
":",
"self",
".",
"hspCount",
"(",... | Summarize the alignments for this subject.
@return: A C{dict} with C{str} keys:
bestScore: The C{float} best score of the matching reads.
coverage: The C{float} fraction of the subject genome that is
matched by at least one read.
hspCount: The C{int} number of hsps that match the subject.
medianScore: The C{float} median score of the matching reads.
readCount: The C{int} number of reads that match the subject.
subjectLength: The C{int} length of the subject.
subjectTitle: The C{str} title of the subject. | [
"Summarize",
"the",
"alignments",
"for",
"this",
"subject",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L235-L257 |
acorg/dark-matter | dark/titles.py | TitleAlignments.toDict | def toDict(self):
"""
Get information about the title's alignments as a dictionary.
@return: A C{dict} representation of the title's aligments.
"""
return {
'titleAlignments': [titleAlignment.toDict()
for titleAlignment in self],
'subjectTitle': self.subjectTitle,
'subjectLength': self.subjectLength,
} | python | def toDict(self):
"""
Get information about the title's alignments as a dictionary.
@return: A C{dict} representation of the title's aligments.
"""
return {
'titleAlignments': [titleAlignment.toDict()
for titleAlignment in self],
'subjectTitle': self.subjectTitle,
'subjectLength': self.subjectLength,
} | [
"def",
"toDict",
"(",
"self",
")",
":",
"return",
"{",
"'titleAlignments'",
":",
"[",
"titleAlignment",
".",
"toDict",
"(",
")",
"for",
"titleAlignment",
"in",
"self",
"]",
",",
"'subjectTitle'",
":",
"self",
".",
"subjectTitle",
",",
"'subjectLength'",
":",... | Get information about the title's alignments as a dictionary.
@return: A C{dict} representation of the title's aligments. | [
"Get",
"information",
"about",
"the",
"title",
"s",
"alignments",
"as",
"a",
"dictionary",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L259-L270 |
acorg/dark-matter | dark/titles.py | TitlesAlignments.addTitle | def addTitle(self, title, titleAlignments):
"""
Add a new title to self.
@param title: A C{str} title.
@param titleAlignments: An instance of L{TitleAlignments}.
@raises KeyError: If the title is already present.
"""
if title in self:
raise KeyError('Title %r already present in TitlesAlignments '
'instance.' % title)
else:
self[title] = titleAlignments | python | def addTitle(self, title, titleAlignments):
"""
Add a new title to self.
@param title: A C{str} title.
@param titleAlignments: An instance of L{TitleAlignments}.
@raises KeyError: If the title is already present.
"""
if title in self:
raise KeyError('Title %r already present in TitlesAlignments '
'instance.' % title)
else:
self[title] = titleAlignments | [
"def",
"addTitle",
"(",
"self",
",",
"title",
",",
"titleAlignments",
")",
":",
"if",
"title",
"in",
"self",
":",
"raise",
"KeyError",
"(",
"'Title %r already present in TitlesAlignments '",
"'instance.'",
"%",
"title",
")",
"else",
":",
"self",
"[",
"title",
... | Add a new title to self.
@param title: A C{str} title.
@param titleAlignments: An instance of L{TitleAlignments}.
@raises KeyError: If the title is already present. | [
"Add",
"a",
"new",
"title",
"to",
"self",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L307-L319 |
acorg/dark-matter | dark/titles.py | TitlesAlignments.filter | def filter(self, minMatchingReads=None, minMedianScore=None,
withScoreBetterThan=None, minNewReads=None, minCoverage=None,
maxTitles=None, sortOn='maxScore'):
"""
Filter the titles in self to create another TitlesAlignments.
@param minMatchingReads: titles that are matched by fewer reads
are unacceptable.
@param minMedianScore: sequences that are matched with a median
bit score that is less are unacceptable.
@param withScoreBetterThan: if the best score for a title is not
as good as this value, the title is not acceptable.
@param minNewReads: The C{float} fraction of its reads by which a new
title's read set must differ from the read sets of all previously
seen titles in order for this title to be considered acceptably
different (and therefore interesting).
@param minCoverage: The C{float} minimum fraction of the title sequence
that must be matched by at least one read.
@param maxTitles: A non-negative C{int} maximum number of titles to
keep. If more titles than this are present, titles will be sorted
(according to C{sortOn}) and only the best will be retained.
@param sortOn: A C{str} attribute to sort on, used only if C{maxTitles}
is not C{None}. See the C{sortTitles} method below for the legal
values.
@raise: C{ValueError} if C{maxTitles} is less than zero or the value of
C{sortOn} is unknown.
@return: A new L{TitlesAlignments} instance containing only the
matching titles.
"""
# Use a ReadSetFilter only if we're checking that read sets are
# sufficiently new.
if minNewReads is None:
readSetFilter = None
else:
if self.readSetFilter is None:
self.readSetFilter = ReadSetFilter(minNewReads)
readSetFilter = self.readSetFilter
result = TitlesAlignments(
self.readsAlignments, self.scoreClass, self.readSetFilter,
importReadsAlignmentsTitles=False)
if maxTitles is not None and len(self) > maxTitles:
if maxTitles < 0:
raise ValueError('maxTitles (%r) cannot be negative.' %
maxTitles)
else:
# There are too many titles. Make a sorted list of them so
# we loop through them (below) in the desired order and can
# break when/if we've reached the maximum. We can't just
# take the first maxTitles titles from the sorted list now,
# as some of those titles might later be discarded by the
# filter and then we'd return a result with fewer titles
# than we should.
titles = self.sortTitles(sortOn)
else:
titles = self.keys()
for title in titles:
# Test max titles up front, as it may be zero.
if maxTitles is not None and len(result) == maxTitles:
break
titleAlignments = self[title]
if (minMatchingReads is not None and
titleAlignments.readCount() < minMatchingReads):
continue
# To compare the median score with another score, we must
# convert both values to instances of the score class used in
# this data set so they can be compared without us needing to
# know if numerically greater scores are considered better or
# not.
if (minMedianScore is not None and
self.scoreClass(titleAlignments.medianScore()) <
self.scoreClass(minMedianScore)):
continue
if (withScoreBetterThan is not None and not
titleAlignments.hasScoreBetterThan(withScoreBetterThan)):
continue
if (minCoverage is not None and
titleAlignments.coverage() < minCoverage):
continue
if (readSetFilter and not
readSetFilter.accept(title, titleAlignments)):
continue
result.addTitle(title, titleAlignments)
return result | python | def filter(self, minMatchingReads=None, minMedianScore=None,
withScoreBetterThan=None, minNewReads=None, minCoverage=None,
maxTitles=None, sortOn='maxScore'):
"""
Filter the titles in self to create another TitlesAlignments.
@param minMatchingReads: titles that are matched by fewer reads
are unacceptable.
@param minMedianScore: sequences that are matched with a median
bit score that is less are unacceptable.
@param withScoreBetterThan: if the best score for a title is not
as good as this value, the title is not acceptable.
@param minNewReads: The C{float} fraction of its reads by which a new
title's read set must differ from the read sets of all previously
seen titles in order for this title to be considered acceptably
different (and therefore interesting).
@param minCoverage: The C{float} minimum fraction of the title sequence
that must be matched by at least one read.
@param maxTitles: A non-negative C{int} maximum number of titles to
keep. If more titles than this are present, titles will be sorted
(according to C{sortOn}) and only the best will be retained.
@param sortOn: A C{str} attribute to sort on, used only if C{maxTitles}
is not C{None}. See the C{sortTitles} method below for the legal
values.
@raise: C{ValueError} if C{maxTitles} is less than zero or the value of
C{sortOn} is unknown.
@return: A new L{TitlesAlignments} instance containing only the
matching titles.
"""
# Use a ReadSetFilter only if we're checking that read sets are
# sufficiently new.
if minNewReads is None:
readSetFilter = None
else:
if self.readSetFilter is None:
self.readSetFilter = ReadSetFilter(minNewReads)
readSetFilter = self.readSetFilter
result = TitlesAlignments(
self.readsAlignments, self.scoreClass, self.readSetFilter,
importReadsAlignmentsTitles=False)
if maxTitles is not None and len(self) > maxTitles:
if maxTitles < 0:
raise ValueError('maxTitles (%r) cannot be negative.' %
maxTitles)
else:
# There are too many titles. Make a sorted list of them so
# we loop through them (below) in the desired order and can
# break when/if we've reached the maximum. We can't just
# take the first maxTitles titles from the sorted list now,
# as some of those titles might later be discarded by the
# filter and then we'd return a result with fewer titles
# than we should.
titles = self.sortTitles(sortOn)
else:
titles = self.keys()
for title in titles:
# Test max titles up front, as it may be zero.
if maxTitles is not None and len(result) == maxTitles:
break
titleAlignments = self[title]
if (minMatchingReads is not None and
titleAlignments.readCount() < minMatchingReads):
continue
# To compare the median score with another score, we must
# convert both values to instances of the score class used in
# this data set so they can be compared without us needing to
# know if numerically greater scores are considered better or
# not.
if (minMedianScore is not None and
self.scoreClass(titleAlignments.medianScore()) <
self.scoreClass(minMedianScore)):
continue
if (withScoreBetterThan is not None and not
titleAlignments.hasScoreBetterThan(withScoreBetterThan)):
continue
if (minCoverage is not None and
titleAlignments.coverage() < minCoverage):
continue
if (readSetFilter and not
readSetFilter.accept(title, titleAlignments)):
continue
result.addTitle(title, titleAlignments)
return result | [
"def",
"filter",
"(",
"self",
",",
"minMatchingReads",
"=",
"None",
",",
"minMedianScore",
"=",
"None",
",",
"withScoreBetterThan",
"=",
"None",
",",
"minNewReads",
"=",
"None",
",",
"minCoverage",
"=",
"None",
",",
"maxTitles",
"=",
"None",
",",
"sortOn",
... | Filter the titles in self to create another TitlesAlignments.
@param minMatchingReads: titles that are matched by fewer reads
are unacceptable.
@param minMedianScore: sequences that are matched with a median
bit score that is less are unacceptable.
@param withScoreBetterThan: if the best score for a title is not
as good as this value, the title is not acceptable.
@param minNewReads: The C{float} fraction of its reads by which a new
title's read set must differ from the read sets of all previously
seen titles in order for this title to be considered acceptably
different (and therefore interesting).
@param minCoverage: The C{float} minimum fraction of the title sequence
that must be matched by at least one read.
@param maxTitles: A non-negative C{int} maximum number of titles to
keep. If more titles than this are present, titles will be sorted
(according to C{sortOn}) and only the best will be retained.
@param sortOn: A C{str} attribute to sort on, used only if C{maxTitles}
is not C{None}. See the C{sortTitles} method below for the legal
values.
@raise: C{ValueError} if C{maxTitles} is less than zero or the value of
C{sortOn} is unknown.
@return: A new L{TitlesAlignments} instance containing only the
matching titles. | [
"Filter",
"the",
"titles",
"in",
"self",
"to",
"create",
"another",
"TitlesAlignments",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L321-L413 |
acorg/dark-matter | dark/titles.py | TitlesAlignments.hsps | def hsps(self):
"""
Get all HSPs for all the alignments for all titles.
@return: A generator yielding L{dark.hsp.HSP} instances.
"""
return (hsp for titleAlignments in self.values()
for alignment in titleAlignments for hsp in alignment.hsps) | python | def hsps(self):
"""
Get all HSPs for all the alignments for all titles.
@return: A generator yielding L{dark.hsp.HSP} instances.
"""
return (hsp for titleAlignments in self.values()
for alignment in titleAlignments for hsp in alignment.hsps) | [
"def",
"hsps",
"(",
"self",
")",
":",
"return",
"(",
"hsp",
"for",
"titleAlignments",
"in",
"self",
".",
"values",
"(",
")",
"for",
"alignment",
"in",
"titleAlignments",
"for",
"hsp",
"in",
"alignment",
".",
"hsps",
")"
] | Get all HSPs for all the alignments for all titles.
@return: A generator yielding L{dark.hsp.HSP} instances. | [
"Get",
"all",
"HSPs",
"for",
"all",
"the",
"alignments",
"for",
"all",
"titles",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L415-L422 |
acorg/dark-matter | dark/titles.py | TitlesAlignments.sortTitles | def sortTitles(self, by):
"""
Sort titles by a given attribute and then by title.
@param by: A C{str}, one of 'length', 'maxScore', 'medianScore',
'readCount', or 'title'.
@raise ValueError: If an unknown C{by} value is given.
@return: A sorted C{list} of titles.
"""
# First sort titles by the secondary key, which is always the title.
titles = sorted(iter(self))
# Then sort on the primary key (if any).
if by == 'length':
return sorted(
titles, reverse=True,
key=lambda title: self[title].subjectLength)
if by == 'maxScore':
return sorted(
titles, reverse=True, key=lambda title: self[title].bestHsp())
if by == 'medianScore':
return sorted(
titles, reverse=True,
key=lambda title: self.scoreClass(self[title].medianScore()))
if by == 'readCount':
return sorted(
titles, reverse=True,
key=lambda title: self[title].readCount())
if by == 'title':
return titles
raise ValueError('Sort attribute must be one of "length", "maxScore", '
'"medianScore", "readCount", "title".') | python | def sortTitles(self, by):
"""
Sort titles by a given attribute and then by title.
@param by: A C{str}, one of 'length', 'maxScore', 'medianScore',
'readCount', or 'title'.
@raise ValueError: If an unknown C{by} value is given.
@return: A sorted C{list} of titles.
"""
# First sort titles by the secondary key, which is always the title.
titles = sorted(iter(self))
# Then sort on the primary key (if any).
if by == 'length':
return sorted(
titles, reverse=True,
key=lambda title: self[title].subjectLength)
if by == 'maxScore':
return sorted(
titles, reverse=True, key=lambda title: self[title].bestHsp())
if by == 'medianScore':
return sorted(
titles, reverse=True,
key=lambda title: self.scoreClass(self[title].medianScore()))
if by == 'readCount':
return sorted(
titles, reverse=True,
key=lambda title: self[title].readCount())
if by == 'title':
return titles
raise ValueError('Sort attribute must be one of "length", "maxScore", '
'"medianScore", "readCount", "title".') | [
"def",
"sortTitles",
"(",
"self",
",",
"by",
")",
":",
"# First sort titles by the secondary key, which is always the title.",
"titles",
"=",
"sorted",
"(",
"iter",
"(",
"self",
")",
")",
"# Then sort on the primary key (if any).",
"if",
"by",
"==",
"'length'",
":",
"... | Sort titles by a given attribute and then by title.
@param by: A C{str}, one of 'length', 'maxScore', 'medianScore',
'readCount', or 'title'.
@raise ValueError: If an unknown C{by} value is given.
@return: A sorted C{list} of titles. | [
"Sort",
"titles",
"by",
"a",
"given",
"attribute",
"and",
"then",
"by",
"title",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L424-L456 |
acorg/dark-matter | dark/titles.py | TitlesAlignments.summary | def summary(self, sortOn=None):
"""
Summarize all the alignments for this title.
@param sortOn: A C{str} attribute to sort titles on. One of 'length',
'maxScore', 'medianScore', 'readCount', or 'title'.
@raise ValueError: If an unknown C{sortOn} value is given.
@return: A generator that yields C{dict} instances as produced by
C{TitleAlignments} (see class earlier in this file), sorted by
C{sortOn}.
"""
titles = self if sortOn is None else self.sortTitles(sortOn)
for title in titles:
yield self[title].summary() | python | def summary(self, sortOn=None):
"""
Summarize all the alignments for this title.
@param sortOn: A C{str} attribute to sort titles on. One of 'length',
'maxScore', 'medianScore', 'readCount', or 'title'.
@raise ValueError: If an unknown C{sortOn} value is given.
@return: A generator that yields C{dict} instances as produced by
C{TitleAlignments} (see class earlier in this file), sorted by
C{sortOn}.
"""
titles = self if sortOn is None else self.sortTitles(sortOn)
for title in titles:
yield self[title].summary() | [
"def",
"summary",
"(",
"self",
",",
"sortOn",
"=",
"None",
")",
":",
"titles",
"=",
"self",
"if",
"sortOn",
"is",
"None",
"else",
"self",
".",
"sortTitles",
"(",
"sortOn",
")",
"for",
"title",
"in",
"titles",
":",
"yield",
"self",
"[",
"title",
"]",
... | Summarize all the alignments for this title.
@param sortOn: A C{str} attribute to sort titles on. One of 'length',
'maxScore', 'medianScore', 'readCount', or 'title'.
@raise ValueError: If an unknown C{sortOn} value is given.
@return: A generator that yields C{dict} instances as produced by
C{TitleAlignments} (see class earlier in this file), sorted by
C{sortOn}. | [
"Summarize",
"all",
"the",
"alignments",
"for",
"this",
"title",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L458-L472 |
acorg/dark-matter | dark/titles.py | TitlesAlignments.tabSeparatedSummary | def tabSeparatedSummary(self, sortOn=None):
"""
Summarize all the alignments for this title as multi-line string with
TAB-separated values on each line.
@param sortOn: A C{str} attribute to sort titles on. One of 'length',
'maxScore', 'medianScore', 'readCount', or 'title'.
@raise ValueError: If an unknown C{sortOn} value is given.
@return: A newline-separated C{str}, each line with a summary of a
title. Each summary line is TAB-separated.
"""
# The order of the fields returned here is somewhat arbitrary. The
# subject titles are last because they are so variable in length.
# Putting them last makes it more likely that the initial columns in
# printed output will be easier to read down.
#
# Note that post-processing scripts will be relying on the field
# ordering here. So you can't just add fields. It's probably safe
# to add them at the end, but be careful / think.
#
# A TAB-separated file can easily be read by awk using e.g.,
# awk 'BEGIN {FS = "\t"} ...'
result = []
for titleSummary in self.summary(sortOn):
result.append('\t'.join([
'%(coverage)f',
'%(medianScore)f',
'%(bestScore)f',
'%(readCount)d',
'%(hspCount)d',
'%(subjectLength)d',
'%(subjectTitle)s',
]) % titleSummary)
return '\n'.join(result) | python | def tabSeparatedSummary(self, sortOn=None):
"""
Summarize all the alignments for this title as multi-line string with
TAB-separated values on each line.
@param sortOn: A C{str} attribute to sort titles on. One of 'length',
'maxScore', 'medianScore', 'readCount', or 'title'.
@raise ValueError: If an unknown C{sortOn} value is given.
@return: A newline-separated C{str}, each line with a summary of a
title. Each summary line is TAB-separated.
"""
# The order of the fields returned here is somewhat arbitrary. The
# subject titles are last because they are so variable in length.
# Putting them last makes it more likely that the initial columns in
# printed output will be easier to read down.
#
# Note that post-processing scripts will be relying on the field
# ordering here. So you can't just add fields. It's probably safe
# to add them at the end, but be careful / think.
#
# A TAB-separated file can easily be read by awk using e.g.,
# awk 'BEGIN {FS = "\t"} ...'
result = []
for titleSummary in self.summary(sortOn):
result.append('\t'.join([
'%(coverage)f',
'%(medianScore)f',
'%(bestScore)f',
'%(readCount)d',
'%(hspCount)d',
'%(subjectLength)d',
'%(subjectTitle)s',
]) % titleSummary)
return '\n'.join(result) | [
"def",
"tabSeparatedSummary",
"(",
"self",
",",
"sortOn",
"=",
"None",
")",
":",
"# The order of the fields returned here is somewhat arbitrary. The",
"# subject titles are last because they are so variable in length.",
"# Putting them last makes it more likely that the initial columns in",
... | Summarize all the alignments for this title as multi-line string with
TAB-separated values on each line.
@param sortOn: A C{str} attribute to sort titles on. One of 'length',
'maxScore', 'medianScore', 'readCount', or 'title'.
@raise ValueError: If an unknown C{sortOn} value is given.
@return: A newline-separated C{str}, each line with a summary of a
title. Each summary line is TAB-separated. | [
"Summarize",
"all",
"the",
"alignments",
"for",
"this",
"title",
"as",
"multi",
"-",
"line",
"string",
"with",
"TAB",
"-",
"separated",
"values",
"on",
"each",
"line",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L474-L508 |
acorg/dark-matter | dark/titles.py | TitlesAlignments.toDict | def toDict(self):
"""
Get information about the titles alignments as a dictionary.
@return: A C{dict} representation of the titles aligments.
"""
return {
'scoreClass': self.scoreClass.__name__,
'titles': dict((title, titleAlignments.toDict())
for title, titleAlignments in self.items()),
} | python | def toDict(self):
"""
Get information about the titles alignments as a dictionary.
@return: A C{dict} representation of the titles aligments.
"""
return {
'scoreClass': self.scoreClass.__name__,
'titles': dict((title, titleAlignments.toDict())
for title, titleAlignments in self.items()),
} | [
"def",
"toDict",
"(",
"self",
")",
":",
"return",
"{",
"'scoreClass'",
":",
"self",
".",
"scoreClass",
".",
"__name__",
",",
"'titles'",
":",
"dict",
"(",
"(",
"title",
",",
"titleAlignments",
".",
"toDict",
"(",
")",
")",
"for",
"title",
",",
"titleAl... | Get information about the titles alignments as a dictionary.
@return: A C{dict} representation of the titles aligments. | [
"Get",
"information",
"about",
"the",
"titles",
"alignments",
"as",
"a",
"dictionary",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L510-L520 |
acorg/dark-matter | dark/filter.py | addFASTAFilteringCommandLineOptions | def addFASTAFilteringCommandLineOptions(parser):
"""
Add standard FASTA filtering command-line options to an argparse parser.
These are options that can be used to select or omit entire FASTA records,
NOT options that change them (for that see
addFASTAEditingCommandLineOptions).
@param parser: An C{argparse.ArgumentParser} instance.
"""
parser.add_argument(
'--minLength', type=int,
help='The minimum sequence length')
parser.add_argument(
'--maxLength', type=int,
help='The maximum sequence length')
parser.add_argument(
'--whitelist', action='append',
help='Sequence titles (ids) that should be whitelisted')
parser.add_argument(
'--blacklist', action='append',
help='Sequence titles (ids) that should be blacklisted')
parser.add_argument(
'--whitelistFile',
help=('The name of a file that contains sequence titles (ids) that '
'should be whitelisted, one per line'))
parser.add_argument(
'--blacklistFile',
help=('The name of a file that contains sequence titles (ids) that '
'should be blacklisted, one per line'))
parser.add_argument(
'--titleRegex', help='A regex that sequence titles (ids) must match.')
parser.add_argument(
'--negativeTitleRegex',
help='A regex that sequence titles (ids) must not match.')
# A mutually exclusive group for --keepSequences and --removeSequences.
group = parser.add_mutually_exclusive_group()
group.add_argument(
'--keepSequences',
help=('Specify (1-based) ranges of sequence numbers that should be '
'kept. E.g., --keepSequences 1-3,5 will output just the 1st, '
'2nd, 3rd, and 5th sequences. All others will be omitted.'))
group.add_argument(
'--removeSequences',
help=('Specify (1-based) ranges of sequence numbers that should be '
'removed. E.g., --removeSequences 1-3,5 will output all but the '
'1st, 2nd, 3rd, and 5th sequences. All others will be ouput.'))
parser.add_argument(
'--head', type=int, metavar='N',
help='Only the first N sequences will be printed.')
parser.add_argument(
'--removeDuplicates', action='store_true', default=False,
help=('Duplicate reads will be removed, based only on '
'sequence identity. The first occurrence is kept.'))
parser.add_argument(
'--removeDuplicatesById', action='store_true', default=False,
help=('Duplicate reads will be removed, based only on '
'read id. The first occurrence is kept.'))
# See the docstring for dark.reads.Reads.filter for more detail on
# randomSubset.
parser.add_argument(
'--randomSubset', type=int,
help=('An integer giving the number of sequences that should be kept. '
'These will be selected at random.'))
# See the docstring for dark.reads.Reads.filter for more detail on
# trueLength.
parser.add_argument(
'--trueLength', type=int,
help=('The number of reads in the FASTA input. Only to be used with '
'randomSubset'))
parser.add_argument(
'--sampleFraction', type=float,
help=('A [0.0, 1.0] C{float} indicating a fraction of the reads that '
'should be allowed to pass through the filter. The sample size '
'will only be approximately the product of the sample fraction '
'and the number of reads. The sample is taken at random.'))
parser.add_argument(
'--sequenceNumbersFile',
help=('A file of (1-based) sequence numbers to retain. Numbers must '
'be one per line.')) | python | def addFASTAFilteringCommandLineOptions(parser):
"""
Add standard FASTA filtering command-line options to an argparse parser.
These are options that can be used to select or omit entire FASTA records,
NOT options that change them (for that see
addFASTAEditingCommandLineOptions).
@param parser: An C{argparse.ArgumentParser} instance.
"""
parser.add_argument(
'--minLength', type=int,
help='The minimum sequence length')
parser.add_argument(
'--maxLength', type=int,
help='The maximum sequence length')
parser.add_argument(
'--whitelist', action='append',
help='Sequence titles (ids) that should be whitelisted')
parser.add_argument(
'--blacklist', action='append',
help='Sequence titles (ids) that should be blacklisted')
parser.add_argument(
'--whitelistFile',
help=('The name of a file that contains sequence titles (ids) that '
'should be whitelisted, one per line'))
parser.add_argument(
'--blacklistFile',
help=('The name of a file that contains sequence titles (ids) that '
'should be blacklisted, one per line'))
parser.add_argument(
'--titleRegex', help='A regex that sequence titles (ids) must match.')
parser.add_argument(
'--negativeTitleRegex',
help='A regex that sequence titles (ids) must not match.')
# A mutually exclusive group for --keepSequences and --removeSequences.
group = parser.add_mutually_exclusive_group()
group.add_argument(
'--keepSequences',
help=('Specify (1-based) ranges of sequence numbers that should be '
'kept. E.g., --keepSequences 1-3,5 will output just the 1st, '
'2nd, 3rd, and 5th sequences. All others will be omitted.'))
group.add_argument(
'--removeSequences',
help=('Specify (1-based) ranges of sequence numbers that should be '
'removed. E.g., --removeSequences 1-3,5 will output all but the '
'1st, 2nd, 3rd, and 5th sequences. All others will be ouput.'))
parser.add_argument(
'--head', type=int, metavar='N',
help='Only the first N sequences will be printed.')
parser.add_argument(
'--removeDuplicates', action='store_true', default=False,
help=('Duplicate reads will be removed, based only on '
'sequence identity. The first occurrence is kept.'))
parser.add_argument(
'--removeDuplicatesById', action='store_true', default=False,
help=('Duplicate reads will be removed, based only on '
'read id. The first occurrence is kept.'))
# See the docstring for dark.reads.Reads.filter for more detail on
# randomSubset.
parser.add_argument(
'--randomSubset', type=int,
help=('An integer giving the number of sequences that should be kept. '
'These will be selected at random.'))
# See the docstring for dark.reads.Reads.filter for more detail on
# trueLength.
parser.add_argument(
'--trueLength', type=int,
help=('The number of reads in the FASTA input. Only to be used with '
'randomSubset'))
parser.add_argument(
'--sampleFraction', type=float,
help=('A [0.0, 1.0] C{float} indicating a fraction of the reads that '
'should be allowed to pass through the filter. The sample size '
'will only be approximately the product of the sample fraction '
'and the number of reads. The sample is taken at random.'))
parser.add_argument(
'--sequenceNumbersFile',
help=('A file of (1-based) sequence numbers to retain. Numbers must '
'be one per line.')) | [
"def",
"addFASTAFilteringCommandLineOptions",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'--minLength'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'The minimum sequence length'",
")",
"parser",
".",
"add_argument",
"(",
"'--maxLength'",
",",
"... | Add standard FASTA filtering command-line options to an argparse parser.
These are options that can be used to select or omit entire FASTA records,
NOT options that change them (for that see
addFASTAEditingCommandLineOptions).
@param parser: An C{argparse.ArgumentParser} instance. | [
"Add",
"standard",
"FASTA",
"filtering",
"command",
"-",
"line",
"options",
"to",
"an",
"argparse",
"parser",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/filter.py#L172-L268 |
acorg/dark-matter | dark/filter.py | parseFASTAFilteringCommandLineOptions | def parseFASTAFilteringCommandLineOptions(args, reads):
"""
Examine parsed FASTA filtering command-line options and return filtered
reads.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@param reads: A C{Reads} instance to filter.
@return: The filtered C{Reads} instance.
"""
keepSequences = (
parseRangeString(args.keepSequences, convertToZeroBased=True)
if args.keepSequences else None)
removeSequences = (
parseRangeString(args.removeSequences, convertToZeroBased=True)
if args.removeSequences else None)
return reads.filter(
minLength=args.minLength, maxLength=args.maxLength,
whitelist=set(args.whitelist) if args.whitelist else None,
blacklist=set(args.blacklist) if args.blacklist else None,
whitelistFile=args.whitelistFile, blacklistFile=args.blacklistFile,
titleRegex=args.titleRegex,
negativeTitleRegex=args.negativeTitleRegex,
keepSequences=keepSequences, removeSequences=removeSequences,
head=args.head, removeDuplicates=args.removeDuplicates,
removeDuplicatesById=args.removeDuplicatesById,
randomSubset=args.randomSubset, trueLength=args.trueLength,
sampleFraction=args.sampleFraction,
sequenceNumbersFile=args.sequenceNumbersFile) | python | def parseFASTAFilteringCommandLineOptions(args, reads):
"""
Examine parsed FASTA filtering command-line options and return filtered
reads.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@param reads: A C{Reads} instance to filter.
@return: The filtered C{Reads} instance.
"""
keepSequences = (
parseRangeString(args.keepSequences, convertToZeroBased=True)
if args.keepSequences else None)
removeSequences = (
parseRangeString(args.removeSequences, convertToZeroBased=True)
if args.removeSequences else None)
return reads.filter(
minLength=args.minLength, maxLength=args.maxLength,
whitelist=set(args.whitelist) if args.whitelist else None,
blacklist=set(args.blacklist) if args.blacklist else None,
whitelistFile=args.whitelistFile, blacklistFile=args.blacklistFile,
titleRegex=args.titleRegex,
negativeTitleRegex=args.negativeTitleRegex,
keepSequences=keepSequences, removeSequences=removeSequences,
head=args.head, removeDuplicates=args.removeDuplicates,
removeDuplicatesById=args.removeDuplicatesById,
randomSubset=args.randomSubset, trueLength=args.trueLength,
sampleFraction=args.sampleFraction,
sequenceNumbersFile=args.sequenceNumbersFile) | [
"def",
"parseFASTAFilteringCommandLineOptions",
"(",
"args",
",",
"reads",
")",
":",
"keepSequences",
"=",
"(",
"parseRangeString",
"(",
"args",
".",
"keepSequences",
",",
"convertToZeroBased",
"=",
"True",
")",
"if",
"args",
".",
"keepSequences",
"else",
"None",
... | Examine parsed FASTA filtering command-line options and return filtered
reads.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@param reads: A C{Reads} instance to filter.
@return: The filtered C{Reads} instance. | [
"Examine",
"parsed",
"FASTA",
"filtering",
"command",
"-",
"line",
"options",
"and",
"return",
"filtered",
"reads",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/filter.py#L271-L301 |
acorg/dark-matter | dark/filter.py | addFASTAEditingCommandLineOptions | def addFASTAEditingCommandLineOptions(parser):
"""
Add standard FASTA editing command-line options to an argparse parser.
These are options that can be used to alter FASTA records, NOT options
that simply select or reject those things (for those see
addFASTAFilteringCommandLineOptions).
@param parser: An C{argparse.ArgumentParser} instance.
"""
# A mutually exclusive group for --keepSites, --keepSitesFile,
# --removeSites, and --removeSitesFile.
group = parser.add_mutually_exclusive_group()
# In the 4 options below, the 'indices' alternate names are kept for
# backwards compatibility.
group.add_argument(
'--keepSites', '--keepIndices',
help=('Specify 1-based sequence sites to keep. All other sites will '
'be removed. The sites must be given in the form e.g., '
'24,100-200,260. Note that the requested sites will be taken '
'from the input sequences in order, not in the order given by '
'--keepSites. I.e., --keepSites 5,8-10 will get you the same '
'result as --keepSites 8-10,5.'))
group.add_argument(
'--keepSitesFile', '--keepIndicesFile',
help=('Specify a file containing 1-based sites to keep. All other '
'sequence sites will be removed. Lines in the file must be '
'given in the form e.g., 24,100-200,260. See --keepSites for '
'more detail.'))
group.add_argument(
'--removeSites', '--removeIndices',
help=('Specify 1-based sites to remove. All other sequence sites will '
'be kept. The sites must be given in the form e.g., '
'24,100-200,260. See --keepSites for more detail.'))
group.add_argument(
'--removeSitesFile', '--removeIndicesFile',
help=('Specify a file containing 1-based sites to remove. All other '
'sequence sites will be kept. Lines in the file must be given '
'in the form e.g., 24,100-200,260. See --keepSites for more '
'detail.'))
parser.add_argument(
'--removeGaps', action='store_true', default=False,
help="If True, gap ('-') characters in sequences will be removed.")
parser.add_argument(
'--truncateTitlesAfter',
help=('A string that sequence titles (ids) will be truncated beyond. '
'If the truncated version of a title has already been seen, '
'that title will be skipped.'))
parser.add_argument(
'--removeDescriptions', action='store_true', default=False,
help=('Read id descriptions will be removed. The '
'description is the part of a sequence id after the '
'first whitespace (if any).'))
parser.add_argument(
'--idLambda', metavar='LAMBDA-FUNCTION',
help=('A one-argument function taking and returning a read id. '
'E.g., --idLambda "lambda id: id.split(\'_\')[0]" or '
'--idLambda "lambda id: id[:10]". If the function returns None, '
'the read will be filtered out.'))
parser.add_argument(
'--readLambda', metavar='LAMBDA-FUNCTION',
help=('A one-argument function taking and returning a read. '
'E.g., --readLambda "lambda r: Read(r.id.split(\'_\')[0], '
'r.sequence.strip(\'-\')". Make sure to also modify the quality '
'string if you change the length of a FASTQ sequence. If the '
'function returns None, the read will be filtered out. The '
'function will be passed to eval with the dark.reads classes '
'Read, DNARead, AARead, etc. all in scope.'))
parser.add_argument(
'--reverse', action='store_true', default=False,
help=('Reverse the sequences. Note that this is NOT reverse '
'complementing.'))
parser.add_argument(
'--reverseComplement', action='store_true', default=False,
help='Reverse complement the sequences.') | python | def addFASTAEditingCommandLineOptions(parser):
"""
Add standard FASTA editing command-line options to an argparse parser.
These are options that can be used to alter FASTA records, NOT options
that simply select or reject those things (for those see
addFASTAFilteringCommandLineOptions).
@param parser: An C{argparse.ArgumentParser} instance.
"""
# A mutually exclusive group for --keepSites, --keepSitesFile,
# --removeSites, and --removeSitesFile.
group = parser.add_mutually_exclusive_group()
# In the 4 options below, the 'indices' alternate names are kept for
# backwards compatibility.
group.add_argument(
'--keepSites', '--keepIndices',
help=('Specify 1-based sequence sites to keep. All other sites will '
'be removed. The sites must be given in the form e.g., '
'24,100-200,260. Note that the requested sites will be taken '
'from the input sequences in order, not in the order given by '
'--keepSites. I.e., --keepSites 5,8-10 will get you the same '
'result as --keepSites 8-10,5.'))
group.add_argument(
'--keepSitesFile', '--keepIndicesFile',
help=('Specify a file containing 1-based sites to keep. All other '
'sequence sites will be removed. Lines in the file must be '
'given in the form e.g., 24,100-200,260. See --keepSites for '
'more detail.'))
group.add_argument(
'--removeSites', '--removeIndices',
help=('Specify 1-based sites to remove. All other sequence sites will '
'be kept. The sites must be given in the form e.g., '
'24,100-200,260. See --keepSites for more detail.'))
group.add_argument(
'--removeSitesFile', '--removeIndicesFile',
help=('Specify a file containing 1-based sites to remove. All other '
'sequence sites will be kept. Lines in the file must be given '
'in the form e.g., 24,100-200,260. See --keepSites for more '
'detail.'))
parser.add_argument(
'--removeGaps', action='store_true', default=False,
help="If True, gap ('-') characters in sequences will be removed.")
parser.add_argument(
'--truncateTitlesAfter',
help=('A string that sequence titles (ids) will be truncated beyond. '
'If the truncated version of a title has already been seen, '
'that title will be skipped.'))
parser.add_argument(
'--removeDescriptions', action='store_true', default=False,
help=('Read id descriptions will be removed. The '
'description is the part of a sequence id after the '
'first whitespace (if any).'))
parser.add_argument(
'--idLambda', metavar='LAMBDA-FUNCTION',
help=('A one-argument function taking and returning a read id. '
'E.g., --idLambda "lambda id: id.split(\'_\')[0]" or '
'--idLambda "lambda id: id[:10]". If the function returns None, '
'the read will be filtered out.'))
parser.add_argument(
'--readLambda', metavar='LAMBDA-FUNCTION',
help=('A one-argument function taking and returning a read. '
'E.g., --readLambda "lambda r: Read(r.id.split(\'_\')[0], '
'r.sequence.strip(\'-\')". Make sure to also modify the quality '
'string if you change the length of a FASTQ sequence. If the '
'function returns None, the read will be filtered out. The '
'function will be passed to eval with the dark.reads classes '
'Read, DNARead, AARead, etc. all in scope.'))
parser.add_argument(
'--reverse', action='store_true', default=False,
help=('Reverse the sequences. Note that this is NOT reverse '
'complementing.'))
parser.add_argument(
'--reverseComplement', action='store_true', default=False,
help='Reverse complement the sequences.') | [
"def",
"addFASTAEditingCommandLineOptions",
"(",
"parser",
")",
":",
"# A mutually exclusive group for --keepSites, --keepSitesFile,",
"# --removeSites, and --removeSitesFile.",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"# In the 4 options below, the 'indic... | Add standard FASTA editing command-line options to an argparse parser.
These are options that can be used to alter FASTA records, NOT options
that simply select or reject those things (for those see
addFASTAFilteringCommandLineOptions).
@param parser: An C{argparse.ArgumentParser} instance. | [
"Add",
"standard",
"FASTA",
"editing",
"command",
"-",
"line",
"options",
"to",
"an",
"argparse",
"parser",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/filter.py#L304-L389 |
acorg/dark-matter | dark/filter.py | parseFASTAEditingCommandLineOptions | def parseFASTAEditingCommandLineOptions(args, reads):
"""
Examine parsed FASTA editing command-line options and return information
about kept sites and sequences.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@param reads: A C{Reads} instance to filter.
@return: The filtered C{Reads} instance.
"""
removeGaps = args.removeGaps
removeDescriptions = args.removeDescriptions
truncateTitlesAfter = args.truncateTitlesAfter
keepSites = (
parseRangeString(args.keepSites, convertToZeroBased=True)
if args.keepSites else None)
if args.keepSitesFile:
keepSites = keepSites or set()
with open(args.keepSitesFile) as fp:
for lineNumber, line in enumerate(fp):
try:
keepSites.update(
parseRangeString(line, convertToZeroBased=True))
except ValueError as e:
raise ValueError(
'Keep sites file %r line %d could not be parsed: '
'%s' % (args.keepSitesFile, lineNumber, e))
removeSites = (
parseRangeString(args.removeSites, convertToZeroBased=True)
if args.removeSites else None)
if args.removeSitesFile:
removeSites = removeSites or set()
with open(args.removeSitesFile) as fp:
for lineNumber, line in enumerate(fp):
try:
removeSites.update(
parseRangeString(line, convertToZeroBased=True))
except ValueError as e:
raise ValueError(
'Remove sites file %r line %d parse error: %s'
% (args.removeSitesFile, lineNumber, e))
return reads.filter(
removeGaps=removeGaps,
truncateTitlesAfter=truncateTitlesAfter,
removeDescriptions=removeDescriptions,
idLambda=args.idLambda, readLambda=args.readLambda,
keepSites=keepSites, removeSites=removeSites,
reverse=args.reverse, reverseComplement=args.reverseComplement) | python | def parseFASTAEditingCommandLineOptions(args, reads):
"""
Examine parsed FASTA editing command-line options and return information
about kept sites and sequences.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@param reads: A C{Reads} instance to filter.
@return: The filtered C{Reads} instance.
"""
removeGaps = args.removeGaps
removeDescriptions = args.removeDescriptions
truncateTitlesAfter = args.truncateTitlesAfter
keepSites = (
parseRangeString(args.keepSites, convertToZeroBased=True)
if args.keepSites else None)
if args.keepSitesFile:
keepSites = keepSites or set()
with open(args.keepSitesFile) as fp:
for lineNumber, line in enumerate(fp):
try:
keepSites.update(
parseRangeString(line, convertToZeroBased=True))
except ValueError as e:
raise ValueError(
'Keep sites file %r line %d could not be parsed: '
'%s' % (args.keepSitesFile, lineNumber, e))
removeSites = (
parseRangeString(args.removeSites, convertToZeroBased=True)
if args.removeSites else None)
if args.removeSitesFile:
removeSites = removeSites or set()
with open(args.removeSitesFile) as fp:
for lineNumber, line in enumerate(fp):
try:
removeSites.update(
parseRangeString(line, convertToZeroBased=True))
except ValueError as e:
raise ValueError(
'Remove sites file %r line %d parse error: %s'
% (args.removeSitesFile, lineNumber, e))
return reads.filter(
removeGaps=removeGaps,
truncateTitlesAfter=truncateTitlesAfter,
removeDescriptions=removeDescriptions,
idLambda=args.idLambda, readLambda=args.readLambda,
keepSites=keepSites, removeSites=removeSites,
reverse=args.reverse, reverseComplement=args.reverseComplement) | [
"def",
"parseFASTAEditingCommandLineOptions",
"(",
"args",
",",
"reads",
")",
":",
"removeGaps",
"=",
"args",
".",
"removeGaps",
"removeDescriptions",
"=",
"args",
".",
"removeDescriptions",
"truncateTitlesAfter",
"=",
"args",
".",
"truncateTitlesAfter",
"keepSites",
... | Examine parsed FASTA editing command-line options and return information
about kept sites and sequences.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@param reads: A C{Reads} instance to filter.
@return: The filtered C{Reads} instance. | [
"Examine",
"parsed",
"FASTA",
"editing",
"command",
"-",
"line",
"options",
"and",
"return",
"information",
"about",
"kept",
"sites",
"and",
"sequences",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/filter.py#L392-L443 |
acorg/dark-matter | dark/filter.py | TitleFilter.accept | def accept(self, title):
"""
Return a value (see below) to indicate if a title is acceptable (and,
if so, in what way).
@param title: A C{str} sequence title.
@return: An C{int} to indicate an acceptable title or not. This will be
C{self.REJECT} if the title is unacceptable.
C{self.WHITELIST_ACCEPT} if the title is whitelisted.
C{self.DEFAULT_ACCEPT} if the title is acceptable by default.
These three values are needed so our caller can distinguish between
the two reasons for acceptance.
"""
if self._whitelist and title in self._whitelist:
return self.WHITELIST_ACCEPT
if self._blacklist and title in self._blacklist:
return self.REJECT
# If we have a positive regex but we don't match it, reject.
if self._positiveRegex and self._positiveRegex.search(title) is None:
return self.REJECT
# If we have a negative regex and we do match it, reject.
if (self._negativeRegex and
self._negativeRegex.search(title) is not None):
return self.REJECT
if self._truncated is not None:
truncated = simplifyTitle(title, self._truncateAfter)
if truncated in self._truncated:
# We've already seen this (truncated) title. Reject unless
# this is the original title that we truncated to make this
# entry. That title must continue to be accepted.
if self._truncated[truncated] == title:
return self.DEFAULT_ACCEPT
else:
return self.REJECT
else:
self._truncated[truncated] = title
return self.DEFAULT_ACCEPT | python | def accept(self, title):
"""
Return a value (see below) to indicate if a title is acceptable (and,
if so, in what way).
@param title: A C{str} sequence title.
@return: An C{int} to indicate an acceptable title or not. This will be
C{self.REJECT} if the title is unacceptable.
C{self.WHITELIST_ACCEPT} if the title is whitelisted.
C{self.DEFAULT_ACCEPT} if the title is acceptable by default.
These three values are needed so our caller can distinguish between
the two reasons for acceptance.
"""
if self._whitelist and title in self._whitelist:
return self.WHITELIST_ACCEPT
if self._blacklist and title in self._blacklist:
return self.REJECT
# If we have a positive regex but we don't match it, reject.
if self._positiveRegex and self._positiveRegex.search(title) is None:
return self.REJECT
# If we have a negative regex and we do match it, reject.
if (self._negativeRegex and
self._negativeRegex.search(title) is not None):
return self.REJECT
if self._truncated is not None:
truncated = simplifyTitle(title, self._truncateAfter)
if truncated in self._truncated:
# We've already seen this (truncated) title. Reject unless
# this is the original title that we truncated to make this
# entry. That title must continue to be accepted.
if self._truncated[truncated] == title:
return self.DEFAULT_ACCEPT
else:
return self.REJECT
else:
self._truncated[truncated] = title
return self.DEFAULT_ACCEPT | [
"def",
"accept",
"(",
"self",
",",
"title",
")",
":",
"if",
"self",
".",
"_whitelist",
"and",
"title",
"in",
"self",
".",
"_whitelist",
":",
"return",
"self",
".",
"WHITELIST_ACCEPT",
"if",
"self",
".",
"_blacklist",
"and",
"title",
"in",
"self",
".",
... | Return a value (see below) to indicate if a title is acceptable (and,
if so, in what way).
@param title: A C{str} sequence title.
@return: An C{int} to indicate an acceptable title or not. This will be
C{self.REJECT} if the title is unacceptable.
C{self.WHITELIST_ACCEPT} if the title is whitelisted.
C{self.DEFAULT_ACCEPT} if the title is acceptable by default.
These three values are needed so our caller can distinguish between
the two reasons for acceptance. | [
"Return",
"a",
"value",
"(",
"see",
"below",
")",
"to",
"indicate",
"if",
"a",
"title",
"is",
"acceptable",
"(",
"and",
"if",
"so",
"in",
"what",
"way",
")",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/filter.py#L67-L110 |
acorg/dark-matter | dark/filter.py | ReadSetFilter.accept | def accept(self, title, titleAlignments):
"""
Return C{True} if the read id set in C{titleAlignments} is sufficiently
different from all previously seen read sets.
@param title: A C{str} sequence title.
@param titleAlignments: An instance of L{TitleAlignment}.
@return: A C{bool} indicating whether a title has an acceptably novel
read set or not.
"""
# Sanity check: titles can only be passed once.
assert title not in self._titles, (
'Title %r seen multiple times.' % title)
readIds = titleAlignments.readIds()
newReadsRequired = ceil(self._minNew * len(readIds))
for readSet, invalidatedTitles in self._titles.values():
if len(readIds - readSet) < newReadsRequired:
# Add this title to the set of titles invalidated by this
# previously seen read set.
invalidatedTitles.append(title)
return False
# Remember the new read set and an empty list of invalidated titles.
self._titles[title] = (readIds, [])
return True | python | def accept(self, title, titleAlignments):
"""
Return C{True} if the read id set in C{titleAlignments} is sufficiently
different from all previously seen read sets.
@param title: A C{str} sequence title.
@param titleAlignments: An instance of L{TitleAlignment}.
@return: A C{bool} indicating whether a title has an acceptably novel
read set or not.
"""
# Sanity check: titles can only be passed once.
assert title not in self._titles, (
'Title %r seen multiple times.' % title)
readIds = titleAlignments.readIds()
newReadsRequired = ceil(self._minNew * len(readIds))
for readSet, invalidatedTitles in self._titles.values():
if len(readIds - readSet) < newReadsRequired:
# Add this title to the set of titles invalidated by this
# previously seen read set.
invalidatedTitles.append(title)
return False
# Remember the new read set and an empty list of invalidated titles.
self._titles[title] = (readIds, [])
return True | [
"def",
"accept",
"(",
"self",
",",
"title",
",",
"titleAlignments",
")",
":",
"# Sanity check: titles can only be passed once.",
"assert",
"title",
"not",
"in",
"self",
".",
"_titles",
",",
"(",
"'Title %r seen multiple times.'",
"%",
"title",
")",
"readIds",
"=",
... | Return C{True} if the read id set in C{titleAlignments} is sufficiently
different from all previously seen read sets.
@param title: A C{str} sequence title.
@param titleAlignments: An instance of L{TitleAlignment}.
@return: A C{bool} indicating whether a title has an acceptably novel
read set or not. | [
"Return",
"C",
"{",
"True",
"}",
"if",
"the",
"read",
"id",
"set",
"in",
"C",
"{",
"titleAlignments",
"}",
"is",
"sufficiently",
"different",
"from",
"all",
"previously",
"seen",
"read",
"sets",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/filter.py#L129-L157 |
acorg/dark-matter | dark/blast/conversion.py | XMLRecordsReader._convertBlastRecordToDict | def _convertBlastRecordToDict(self, record):
"""
Pull (only) the fields we use out of the record and return them as a
dict. Although we take the title from each alignment description, we
save space in the JSON output by storing it in the alignment dict (not
in a separated 'description' dict). When we undo this conversion (in
JSONRecordsReader._convertDictToBlastRecord) we'll pull the title out
of the alignment dict and put it into the right place in the BLAST
record.
@param record: An instance of C{Bio.Blast.Record.Blast}. The attributes
on this don't seem to be documented. You'll need to look at the
BioPython source to see everything it contains.
@return: A C{dict} with 'alignments' and 'query' keys.
"""
alignments = []
for alignment in record.alignments:
hsps = []
for hsp in alignment.hsps:
hsps.append({
'bits': hsp.bits,
'expect': hsp.expect,
'frame': hsp.frame,
'identicalCount': hsp.identities,
'positiveCount': hsp.positives,
'query': hsp.query,
'query_start': hsp.query_start,
'query_end': hsp.query_end,
'sbjct': hsp.sbjct,
'sbjct_start': hsp.sbjct_start,
'sbjct_end': hsp.sbjct_end,
})
alignments.append({
'hsps': hsps,
'length': alignment.length,
'title': alignment.title,
})
return {
'alignments': alignments,
'query': record.query,
} | python | def _convertBlastRecordToDict(self, record):
"""
Pull (only) the fields we use out of the record and return them as a
dict. Although we take the title from each alignment description, we
save space in the JSON output by storing it in the alignment dict (not
in a separated 'description' dict). When we undo this conversion (in
JSONRecordsReader._convertDictToBlastRecord) we'll pull the title out
of the alignment dict and put it into the right place in the BLAST
record.
@param record: An instance of C{Bio.Blast.Record.Blast}. The attributes
on this don't seem to be documented. You'll need to look at the
BioPython source to see everything it contains.
@return: A C{dict} with 'alignments' and 'query' keys.
"""
alignments = []
for alignment in record.alignments:
hsps = []
for hsp in alignment.hsps:
hsps.append({
'bits': hsp.bits,
'expect': hsp.expect,
'frame': hsp.frame,
'identicalCount': hsp.identities,
'positiveCount': hsp.positives,
'query': hsp.query,
'query_start': hsp.query_start,
'query_end': hsp.query_end,
'sbjct': hsp.sbjct,
'sbjct_start': hsp.sbjct_start,
'sbjct_end': hsp.sbjct_end,
})
alignments.append({
'hsps': hsps,
'length': alignment.length,
'title': alignment.title,
})
return {
'alignments': alignments,
'query': record.query,
} | [
"def",
"_convertBlastRecordToDict",
"(",
"self",
",",
"record",
")",
":",
"alignments",
"=",
"[",
"]",
"for",
"alignment",
"in",
"record",
".",
"alignments",
":",
"hsps",
"=",
"[",
"]",
"for",
"hsp",
"in",
"alignment",
".",
"hsps",
":",
"hsps",
".",
"a... | Pull (only) the fields we use out of the record and return them as a
dict. Although we take the title from each alignment description, we
save space in the JSON output by storing it in the alignment dict (not
in a separated 'description' dict). When we undo this conversion (in
JSONRecordsReader._convertDictToBlastRecord) we'll pull the title out
of the alignment dict and put it into the right place in the BLAST
record.
@param record: An instance of C{Bio.Blast.Record.Blast}. The attributes
on this don't seem to be documented. You'll need to look at the
BioPython source to see everything it contains.
@return: A C{dict} with 'alignments' and 'query' keys. | [
"Pull",
"(",
"only",
")",
"the",
"fields",
"we",
"use",
"out",
"of",
"the",
"record",
"and",
"return",
"them",
"as",
"a",
"dict",
".",
"Although",
"we",
"take",
"the",
"title",
"from",
"each",
"alignment",
"description",
"we",
"save",
"space",
"in",
"t... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/conversion.py#L31-L73 |
acorg/dark-matter | dark/blast/conversion.py | XMLRecordsReader._convertBlastParamsToDict | def _convertBlastParamsToDict(self, record):
"""
Pull the global BLAST parameters out of a BLAST record and return
them as a C{dict}.
Some of these attributes are useless (not filled in), but we record
them all just in case we one day need them or they start to be used or
they disappear etc. Any of those changes might alert us that something
has changed in BLAST XML output or in BioPython.
@param record: An instance of C{Bio.Blast.Record.Blast}. The attributes
on this don't seem to be documented. You'll need to look at the
BioPython source to see everything it contains.
@return: A C{dict}, as described above.
"""
result = {}
for attr in (
# From Bio.Blast.Record.Header
'application',
'version',
'date',
'reference',
'query',
'query_letters',
'database',
'database_sequences',
'database_letters',
# From Bio.Blast.Record.DatabaseReport
'database_name',
'posted_date',
'num_letters_in_database',
'num_sequences_in_database',
'ka_params',
'gapped',
'ka_params_gap',
# From Bio.Blast.Record.Parameters
'matrix',
'gap_penalties',
'sc_match',
'sc_mismatch',
'num_hits',
'num_sequences',
'num_good_extends',
'num_seqs_better_e',
'hsps_no_gap',
'hsps_prelim_gapped',
'hsps_prelim_gapped_attemped',
'hsps_gapped',
'query_id',
'query_length',
'database_length',
'effective_hsp_length',
'effective_query_length',
'effective_database_length',
'effective_search_space',
'effective_search_space_used',
'frameshift',
'threshold',
'window_size',
'dropoff_1st_pass',
'gap_x_dropoff',
'gap_x_dropoff_final',
'gap_trigger',
'blast_cutoff'):
result[attr] = getattr(record, attr)
return result | python | def _convertBlastParamsToDict(self, record):
"""
Pull the global BLAST parameters out of a BLAST record and return
them as a C{dict}.
Some of these attributes are useless (not filled in), but we record
them all just in case we one day need them or they start to be used or
they disappear etc. Any of those changes might alert us that something
has changed in BLAST XML output or in BioPython.
@param record: An instance of C{Bio.Blast.Record.Blast}. The attributes
on this don't seem to be documented. You'll need to look at the
BioPython source to see everything it contains.
@return: A C{dict}, as described above.
"""
result = {}
for attr in (
# From Bio.Blast.Record.Header
'application',
'version',
'date',
'reference',
'query',
'query_letters',
'database',
'database_sequences',
'database_letters',
# From Bio.Blast.Record.DatabaseReport
'database_name',
'posted_date',
'num_letters_in_database',
'num_sequences_in_database',
'ka_params',
'gapped',
'ka_params_gap',
# From Bio.Blast.Record.Parameters
'matrix',
'gap_penalties',
'sc_match',
'sc_mismatch',
'num_hits',
'num_sequences',
'num_good_extends',
'num_seqs_better_e',
'hsps_no_gap',
'hsps_prelim_gapped',
'hsps_prelim_gapped_attemped',
'hsps_gapped',
'query_id',
'query_length',
'database_length',
'effective_hsp_length',
'effective_query_length',
'effective_database_length',
'effective_search_space',
'effective_search_space_used',
'frameshift',
'threshold',
'window_size',
'dropoff_1st_pass',
'gap_x_dropoff',
'gap_x_dropoff_final',
'gap_trigger',
'blast_cutoff'):
result[attr] = getattr(record, attr)
return result | [
"def",
"_convertBlastParamsToDict",
"(",
"self",
",",
"record",
")",
":",
"result",
"=",
"{",
"}",
"for",
"attr",
"in",
"(",
"# From Bio.Blast.Record.Header",
"'application'",
",",
"'version'",
",",
"'date'",
",",
"'reference'",
",",
"'query'",
",",
"'query_lett... | Pull the global BLAST parameters out of a BLAST record and return
them as a C{dict}.
Some of these attributes are useless (not filled in), but we record
them all just in case we one day need them or they start to be used or
they disappear etc. Any of those changes might alert us that something
has changed in BLAST XML output or in BioPython.
@param record: An instance of C{Bio.Blast.Record.Blast}. The attributes
on this don't seem to be documented. You'll need to look at the
BioPython source to see everything it contains.
@return: A C{dict}, as described above. | [
"Pull",
"the",
"global",
"BLAST",
"parameters",
"out",
"of",
"a",
"BLAST",
"record",
"and",
"return",
"them",
"as",
"a",
"C",
"{",
"dict",
"}",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/conversion.py#L75-L140 |
acorg/dark-matter | dark/blast/conversion.py | XMLRecordsReader.records | def records(self):
"""
Yield BLAST records, as read by the BioPython NCBIXML.parse
method. Set self.params from data in the first record.
"""
first = True
with as_handle(self._filename) as fp:
for record in NCBIXML.parse(fp):
if first:
self.params = self._convertBlastParamsToDict(record)
first = False
yield record | python | def records(self):
"""
Yield BLAST records, as read by the BioPython NCBIXML.parse
method. Set self.params from data in the first record.
"""
first = True
with as_handle(self._filename) as fp:
for record in NCBIXML.parse(fp):
if first:
self.params = self._convertBlastParamsToDict(record)
first = False
yield record | [
"def",
"records",
"(",
"self",
")",
":",
"first",
"=",
"True",
"with",
"as_handle",
"(",
"self",
".",
"_filename",
")",
"as",
"fp",
":",
"for",
"record",
"in",
"NCBIXML",
".",
"parse",
"(",
"fp",
")",
":",
"if",
"first",
":",
"self",
".",
"params",... | Yield BLAST records, as read by the BioPython NCBIXML.parse
method. Set self.params from data in the first record. | [
"Yield",
"BLAST",
"records",
"as",
"read",
"by",
"the",
"BioPython",
"NCBIXML",
".",
"parse",
"method",
".",
"Set",
"self",
".",
"params",
"from",
"data",
"in",
"the",
"first",
"record",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/conversion.py#L142-L153 |
acorg/dark-matter | dark/blast/conversion.py | XMLRecordsReader.saveAsJSON | def saveAsJSON(self, fp):
"""
Write the records out as JSON. The first JSON object saved contains
the BLAST parameters.
@param fp: A C{str} file pointer to write to.
"""
first = True
for record in self.records():
if first:
print(dumps(self.params, separators=(',', ':')), file=fp)
first = False
print(dumps(self._convertBlastRecordToDict(record),
separators=(',', ':')), file=fp) | python | def saveAsJSON(self, fp):
"""
Write the records out as JSON. The first JSON object saved contains
the BLAST parameters.
@param fp: A C{str} file pointer to write to.
"""
first = True
for record in self.records():
if first:
print(dumps(self.params, separators=(',', ':')), file=fp)
first = False
print(dumps(self._convertBlastRecordToDict(record),
separators=(',', ':')), file=fp) | [
"def",
"saveAsJSON",
"(",
"self",
",",
"fp",
")",
":",
"first",
"=",
"True",
"for",
"record",
"in",
"self",
".",
"records",
"(",
")",
":",
"if",
"first",
":",
"print",
"(",
"dumps",
"(",
"self",
".",
"params",
",",
"separators",
"=",
"(",
"','",
... | Write the records out as JSON. The first JSON object saved contains
the BLAST parameters.
@param fp: A C{str} file pointer to write to. | [
"Write",
"the",
"records",
"out",
"as",
"JSON",
".",
"The",
"first",
"JSON",
"object",
"saved",
"contains",
"the",
"BLAST",
"parameters",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/conversion.py#L155-L168 |
acorg/dark-matter | dark/blast/conversion.py | JSONRecordsReader._open | def _open(self, filename):
"""
Open the input file. Set self._fp to point to it. Read the first
line of parameters.
@param filename: A C{str} filename containing JSON BLAST records.
@raise ValueError: if the first line of the file isn't valid JSON,
if the input file is empty, or if the JSON does not contain an
'application' key.
"""
if filename.endswith('.bz2'):
if six.PY3:
self._fp = bz2.open(filename, mode='rt', encoding='UTF-8')
else:
self._fp = bz2.BZ2File(filename)
else:
self._fp = open(filename)
line = self._fp.readline()
if not line:
raise ValueError('JSON file %r was empty.' % self._filename)
try:
self.params = loads(line[:-1])
except ValueError as e:
raise ValueError(
'Could not convert first line of %r to JSON (%s). '
'Line is %r.' % (self._filename, e, line[:-1]))
else:
if 'application' not in self.params:
raise ValueError(
'%r appears to be an old JSON file with no BLAST global '
'parameters. Please re-run convert-blast-xml-to-json.py '
'to convert it to the newest format.' % self._filename) | python | def _open(self, filename):
"""
Open the input file. Set self._fp to point to it. Read the first
line of parameters.
@param filename: A C{str} filename containing JSON BLAST records.
@raise ValueError: if the first line of the file isn't valid JSON,
if the input file is empty, or if the JSON does not contain an
'application' key.
"""
if filename.endswith('.bz2'):
if six.PY3:
self._fp = bz2.open(filename, mode='rt', encoding='UTF-8')
else:
self._fp = bz2.BZ2File(filename)
else:
self._fp = open(filename)
line = self._fp.readline()
if not line:
raise ValueError('JSON file %r was empty.' % self._filename)
try:
self.params = loads(line[:-1])
except ValueError as e:
raise ValueError(
'Could not convert first line of %r to JSON (%s). '
'Line is %r.' % (self._filename, e, line[:-1]))
else:
if 'application' not in self.params:
raise ValueError(
'%r appears to be an old JSON file with no BLAST global '
'parameters. Please re-run convert-blast-xml-to-json.py '
'to convert it to the newest format.' % self._filename) | [
"def",
"_open",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.bz2'",
")",
":",
"if",
"six",
".",
"PY3",
":",
"self",
".",
"_fp",
"=",
"bz2",
".",
"open",
"(",
"filename",
",",
"mode",
"=",
"'rt'",
",",
"encodi... | Open the input file. Set self._fp to point to it. Read the first
line of parameters.
@param filename: A C{str} filename containing JSON BLAST records.
@raise ValueError: if the first line of the file isn't valid JSON,
if the input file is empty, or if the JSON does not contain an
'application' key. | [
"Open",
"the",
"input",
"file",
".",
"Set",
"self",
".",
"_fp",
"to",
"point",
"to",
"it",
".",
"Read",
"the",
"first",
"line",
"of",
"parameters",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/conversion.py#L196-L229 |
acorg/dark-matter | dark/blast/conversion.py | JSONRecordsReader._dictToAlignments | def _dictToAlignments(self, blastDict, read):
"""
Take a dict (made by XMLRecordsReader._convertBlastRecordToDict)
and convert it to a list of alignments.
@param blastDict: A C{dict}, from convertBlastRecordToDict.
@param read: A C{Read} instance, containing the read that BLAST used
to create this record.
@raise ValueError: If the query id in the BLAST dictionary does not
match the id of the read.
@return: A C{list} of L{dark.alignment.Alignment} instances.
"""
if (blastDict['query'] != read.id and
blastDict['query'].split()[0] != read.id):
raise ValueError(
'The reads you have provided do not match the BLAST output: '
'BLAST record query id (%s) does not match the id of the '
'supposedly corresponding read (%s).' %
(blastDict['query'], read.id))
alignments = []
getScore = itemgetter('bits' if self._hspClass is HSP else 'expect')
for blastAlignment in blastDict['alignments']:
alignment = Alignment(blastAlignment['length'],
blastAlignment['title'])
alignments.append(alignment)
for blastHsp in blastAlignment['hsps']:
score = getScore(blastHsp)
normalized = normalizeHSP(blastHsp, len(read),
self.application)
hsp = self._hspClass(
score,
readStart=normalized['readStart'],
readEnd=normalized['readEnd'],
readStartInSubject=normalized['readStartInSubject'],
readEndInSubject=normalized['readEndInSubject'],
readFrame=blastHsp['frame'][0],
subjectStart=normalized['subjectStart'],
subjectEnd=normalized['subjectEnd'],
subjectFrame=blastHsp['frame'][1],
readMatchedSequence=blastHsp['query'],
subjectMatchedSequence=blastHsp['sbjct'],
# Use blastHsp.get on identicalCount and positiveCount
# because they were added in version 2.0.3 and will not
# be present in any of our JSON output generated before
# that. Those values will be None for those JSON files,
# but that's much better than no longer being able to
# read all that data.
identicalCount=blastHsp.get('identicalCount'),
positiveCount=blastHsp.get('positiveCount'))
alignment.addHsp(hsp)
return alignments | python | def _dictToAlignments(self, blastDict, read):
"""
Take a dict (made by XMLRecordsReader._convertBlastRecordToDict)
and convert it to a list of alignments.
@param blastDict: A C{dict}, from convertBlastRecordToDict.
@param read: A C{Read} instance, containing the read that BLAST used
to create this record.
@raise ValueError: If the query id in the BLAST dictionary does not
match the id of the read.
@return: A C{list} of L{dark.alignment.Alignment} instances.
"""
if (blastDict['query'] != read.id and
blastDict['query'].split()[0] != read.id):
raise ValueError(
'The reads you have provided do not match the BLAST output: '
'BLAST record query id (%s) does not match the id of the '
'supposedly corresponding read (%s).' %
(blastDict['query'], read.id))
alignments = []
getScore = itemgetter('bits' if self._hspClass is HSP else 'expect')
for blastAlignment in blastDict['alignments']:
alignment = Alignment(blastAlignment['length'],
blastAlignment['title'])
alignments.append(alignment)
for blastHsp in blastAlignment['hsps']:
score = getScore(blastHsp)
normalized = normalizeHSP(blastHsp, len(read),
self.application)
hsp = self._hspClass(
score,
readStart=normalized['readStart'],
readEnd=normalized['readEnd'],
readStartInSubject=normalized['readStartInSubject'],
readEndInSubject=normalized['readEndInSubject'],
readFrame=blastHsp['frame'][0],
subjectStart=normalized['subjectStart'],
subjectEnd=normalized['subjectEnd'],
subjectFrame=blastHsp['frame'][1],
readMatchedSequence=blastHsp['query'],
subjectMatchedSequence=blastHsp['sbjct'],
# Use blastHsp.get on identicalCount and positiveCount
# because they were added in version 2.0.3 and will not
# be present in any of our JSON output generated before
# that. Those values will be None for those JSON files,
# but that's much better than no longer being able to
# read all that data.
identicalCount=blastHsp.get('identicalCount'),
positiveCount=blastHsp.get('positiveCount'))
alignment.addHsp(hsp)
return alignments | [
"def",
"_dictToAlignments",
"(",
"self",
",",
"blastDict",
",",
"read",
")",
":",
"if",
"(",
"blastDict",
"[",
"'query'",
"]",
"!=",
"read",
".",
"id",
"and",
"blastDict",
"[",
"'query'",
"]",
".",
"split",
"(",
")",
"[",
"0",
"]",
"!=",
"read",
".... | Take a dict (made by XMLRecordsReader._convertBlastRecordToDict)
and convert it to a list of alignments.
@param blastDict: A C{dict}, from convertBlastRecordToDict.
@param read: A C{Read} instance, containing the read that BLAST used
to create this record.
@raise ValueError: If the query id in the BLAST dictionary does not
match the id of the read.
@return: A C{list} of L{dark.alignment.Alignment} instances. | [
"Take",
"a",
"dict",
"(",
"made",
"by",
"XMLRecordsReader",
".",
"_convertBlastRecordToDict",
")",
"and",
"convert",
"it",
"to",
"a",
"list",
"of",
"alignments",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/conversion.py#L231-L285 |
acorg/dark-matter | dark/blast/conversion.py | JSONRecordsReader.readAlignments | def readAlignments(self, reads):
"""
Read lines of JSON from self._filename, convert them to read alignments
and yield them.
@param reads: An iterable of L{Read} instances, corresponding to the
reads that were given to BLAST.
@raise ValueError: If any of the lines in the file cannot be converted
to JSON.
@return: A generator that yields C{dark.alignments.ReadAlignments}
instances.
"""
if self._fp is None:
self._open(self._filename)
reads = iter(reads)
try:
for lineNumber, line in enumerate(self._fp, start=2):
try:
record = loads(line[:-1])
except ValueError as e:
raise ValueError(
'Could not convert line %d of %r to JSON (%s). '
'Line is %r.' %
(lineNumber, self._filename, e, line[:-1]))
else:
try:
read = next(reads)
except StopIteration:
raise ValueError(
'Read generator failed to yield read number %d '
'during parsing of BLAST file %r.' %
(lineNumber - 1, self._filename))
else:
alignments = self._dictToAlignments(record, read)
yield ReadAlignments(read, alignments)
finally:
self._fp.close()
self._fp = None | python | def readAlignments(self, reads):
"""
Read lines of JSON from self._filename, convert them to read alignments
and yield them.
@param reads: An iterable of L{Read} instances, corresponding to the
reads that were given to BLAST.
@raise ValueError: If any of the lines in the file cannot be converted
to JSON.
@return: A generator that yields C{dark.alignments.ReadAlignments}
instances.
"""
if self._fp is None:
self._open(self._filename)
reads = iter(reads)
try:
for lineNumber, line in enumerate(self._fp, start=2):
try:
record = loads(line[:-1])
except ValueError as e:
raise ValueError(
'Could not convert line %d of %r to JSON (%s). '
'Line is %r.' %
(lineNumber, self._filename, e, line[:-1]))
else:
try:
read = next(reads)
except StopIteration:
raise ValueError(
'Read generator failed to yield read number %d '
'during parsing of BLAST file %r.' %
(lineNumber - 1, self._filename))
else:
alignments = self._dictToAlignments(record, read)
yield ReadAlignments(read, alignments)
finally:
self._fp.close()
self._fp = None | [
"def",
"readAlignments",
"(",
"self",
",",
"reads",
")",
":",
"if",
"self",
".",
"_fp",
"is",
"None",
":",
"self",
".",
"_open",
"(",
"self",
".",
"_filename",
")",
"reads",
"=",
"iter",
"(",
"reads",
")",
"try",
":",
"for",
"lineNumber",
",",
"lin... | Read lines of JSON from self._filename, convert them to read alignments
and yield them.
@param reads: An iterable of L{Read} instances, corresponding to the
reads that were given to BLAST.
@raise ValueError: If any of the lines in the file cannot be converted
to JSON.
@return: A generator that yields C{dark.alignments.ReadAlignments}
instances. | [
"Read",
"lines",
"of",
"JSON",
"from",
"self",
".",
"_filename",
"convert",
"them",
"to",
"read",
"alignments",
"and",
"yield",
"them",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/conversion.py#L287-L326 |
acorg/dark-matter | dark/reads.py | _makeComplementTable | def _makeComplementTable(complementData):
"""
Make a sequence complement table.
@param complementData: A C{dict} whose keys and values are strings of
length one. A key, value pair indicates a substitution that should
be performed during complementation.
@return: A 256 character string that can be used as a translation table
by the C{translate} method of a Python string.
"""
table = list(range(256))
for _from, to in complementData.items():
table[ord(_from[0].lower())] = ord(to[0].lower())
table[ord(_from[0].upper())] = ord(to[0].upper())
return ''.join(map(chr, table)) | python | def _makeComplementTable(complementData):
"""
Make a sequence complement table.
@param complementData: A C{dict} whose keys and values are strings of
length one. A key, value pair indicates a substitution that should
be performed during complementation.
@return: A 256 character string that can be used as a translation table
by the C{translate} method of a Python string.
"""
table = list(range(256))
for _from, to in complementData.items():
table[ord(_from[0].lower())] = ord(to[0].lower())
table[ord(_from[0].upper())] = ord(to[0].upper())
return ''.join(map(chr, table)) | [
"def",
"_makeComplementTable",
"(",
"complementData",
")",
":",
"table",
"=",
"list",
"(",
"range",
"(",
"256",
")",
")",
"for",
"_from",
",",
"to",
"in",
"complementData",
".",
"items",
"(",
")",
":",
"table",
"[",
"ord",
"(",
"_from",
"[",
"0",
"]"... | Make a sequence complement table.
@param complementData: A C{dict} whose keys and values are strings of
length one. A key, value pair indicates a substitution that should
be performed during complementation.
@return: A 256 character string that can be used as a translation table
by the C{translate} method of a Python string. | [
"Make",
"a",
"sequence",
"complement",
"table",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L18-L32 |
acorg/dark-matter | dark/reads.py | addFASTACommandLineOptions | def addFASTACommandLineOptions(parser):
"""
Add standard command-line options to an argparse parser.
@param parser: An C{argparse.ArgumentParser} instance.
"""
parser.add_argument(
'--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
help=('The name of the FASTA input file. Standard input will be read '
'if no file name is given.'))
parser.add_argument(
'--readClass', default='DNARead', choices=readClassNameToClass,
metavar='CLASSNAME',
help=('If specified, give the type of the reads in the input. '
'Possible choices: %s.' % ', '.join(readClassNameToClass)))
# A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
group = parser.add_mutually_exclusive_group()
group.add_argument(
'--fasta', default=False, action='store_true',
help=('If specified, input will be treated as FASTA. This is the '
'default.'))
group.add_argument(
'--fastq', default=False, action='store_true',
help='If specified, input will be treated as FASTQ.')
group.add_argument(
'--fasta-ss', dest='fasta_ss', default=False, action='store_true',
help=('If specified, input will be treated as PDB FASTA '
'(i.e., regular FASTA with each sequence followed by its '
'structure).')) | python | def addFASTACommandLineOptions(parser):
"""
Add standard command-line options to an argparse parser.
@param parser: An C{argparse.ArgumentParser} instance.
"""
parser.add_argument(
'--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
help=('The name of the FASTA input file. Standard input will be read '
'if no file name is given.'))
parser.add_argument(
'--readClass', default='DNARead', choices=readClassNameToClass,
metavar='CLASSNAME',
help=('If specified, give the type of the reads in the input. '
'Possible choices: %s.' % ', '.join(readClassNameToClass)))
# A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
group = parser.add_mutually_exclusive_group()
group.add_argument(
'--fasta', default=False, action='store_true',
help=('If specified, input will be treated as FASTA. This is the '
'default.'))
group.add_argument(
'--fastq', default=False, action='store_true',
help='If specified, input will be treated as FASTQ.')
group.add_argument(
'--fasta-ss', dest='fasta_ss', default=False, action='store_true',
help=('If specified, input will be treated as PDB FASTA '
'(i.e., regular FASTA with each sequence followed by its '
'structure).')) | [
"def",
"addFASTACommandLineOptions",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'--fastaFile'",
",",
"type",
"=",
"open",
",",
"default",
"=",
"sys",
".",
"stdin",
",",
"metavar",
"=",
"'FILENAME'",
",",
"help",
"=",
"(",
"'The name of the... | Add standard command-line options to an argparse parser.
@param parser: An C{argparse.ArgumentParser} instance. | [
"Add",
"standard",
"command",
"-",
"line",
"options",
"to",
"an",
"argparse",
"parser",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L1476-L1510 |
acorg/dark-matter | dark/reads.py | parseFASTACommandLineOptions | def parseFASTACommandLineOptions(args):
"""
Examine parsed command-line options and return a Reads instance.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@return: A C{Reads} subclass instance, depending on the type of FASTA file
given.
"""
# Set default FASTA type.
if not (args.fasta or args.fastq or args.fasta_ss):
args.fasta = True
readClass = readClassNameToClass[args.readClass]
if args.fasta:
from dark.fasta import FastaReads
return FastaReads(args.fastaFile, readClass=readClass)
elif args.fastq:
from dark.fastq import FastqReads
return FastqReads(args.fastaFile, readClass=readClass)
else:
from dark.fasta_ss import SSFastaReads
return SSFastaReads(args.fastaFile, readClass=readClass) | python | def parseFASTACommandLineOptions(args):
"""
Examine parsed command-line options and return a Reads instance.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@return: A C{Reads} subclass instance, depending on the type of FASTA file
given.
"""
# Set default FASTA type.
if not (args.fasta or args.fastq or args.fasta_ss):
args.fasta = True
readClass = readClassNameToClass[args.readClass]
if args.fasta:
from dark.fasta import FastaReads
return FastaReads(args.fastaFile, readClass=readClass)
elif args.fastq:
from dark.fastq import FastqReads
return FastqReads(args.fastaFile, readClass=readClass)
else:
from dark.fasta_ss import SSFastaReads
return SSFastaReads(args.fastaFile, readClass=readClass) | [
"def",
"parseFASTACommandLineOptions",
"(",
"args",
")",
":",
"# Set default FASTA type.",
"if",
"not",
"(",
"args",
".",
"fasta",
"or",
"args",
".",
"fastq",
"or",
"args",
".",
"fasta_ss",
")",
":",
"args",
".",
"fasta",
"=",
"True",
"readClass",
"=",
"re... | Examine parsed command-line options and return a Reads instance.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@return: A C{Reads} subclass instance, depending on the type of FASTA file
given. | [
"Examine",
"parsed",
"command",
"-",
"line",
"options",
"and",
"return",
"a",
"Reads",
"instance",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L1513-L1536 |
acorg/dark-matter | dark/reads.py | _NucleotideRead.translations | def translations(self):
"""
Yield all six translations of a nucleotide sequence.
@return: A generator that produces six L{TranslatedRead} instances.
"""
rc = self.reverseComplement().sequence
for reverseComplemented in False, True:
for frame in 0, 1, 2:
seq = rc if reverseComplemented else self.sequence
# Get the suffix of the sequence for translation. I.e.,
# skip 0, 1, or 2 initial bases, depending on the frame.
# Note that this makes a copy of the sequence, which we can
# then safely append 'N' bases to to adjust its length to
# be zero mod 3.
suffix = seq[frame:]
lengthMod3 = len(suffix) % 3
if lengthMod3:
suffix += ('NN' if lengthMod3 == 1 else 'N')
yield TranslatedRead(self, translate(suffix), frame,
reverseComplemented) | python | def translations(self):
"""
Yield all six translations of a nucleotide sequence.
@return: A generator that produces six L{TranslatedRead} instances.
"""
rc = self.reverseComplement().sequence
for reverseComplemented in False, True:
for frame in 0, 1, 2:
seq = rc if reverseComplemented else self.sequence
# Get the suffix of the sequence for translation. I.e.,
# skip 0, 1, or 2 initial bases, depending on the frame.
# Note that this makes a copy of the sequence, which we can
# then safely append 'N' bases to to adjust its length to
# be zero mod 3.
suffix = seq[frame:]
lengthMod3 = len(suffix) % 3
if lengthMod3:
suffix += ('NN' if lengthMod3 == 1 else 'N')
yield TranslatedRead(self, translate(suffix), frame,
reverseComplemented) | [
"def",
"translations",
"(",
"self",
")",
":",
"rc",
"=",
"self",
".",
"reverseComplement",
"(",
")",
".",
"sequence",
"for",
"reverseComplemented",
"in",
"False",
",",
"True",
":",
"for",
"frame",
"in",
"0",
",",
"1",
",",
"2",
":",
"seq",
"=",
"rc",... | Yield all six translations of a nucleotide sequence.
@return: A generator that produces six L{TranslatedRead} instances. | [
"Yield",
"all",
"six",
"translations",
"of",
"a",
"nucleotide",
"sequence",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L275-L295 |
acorg/dark-matter | dark/reads.py | _NucleotideRead.reverseComplement | def reverseComplement(self):
"""
Reverse complement a nucleotide sequence.
@return: The reverse complemented sequence as an instance of the
current class.
"""
quality = None if self.quality is None else self.quality[::-1]
sequence = self.sequence.translate(self.COMPLEMENT_TABLE)[::-1]
return self.__class__(self.id, sequence, quality) | python | def reverseComplement(self):
"""
Reverse complement a nucleotide sequence.
@return: The reverse complemented sequence as an instance of the
current class.
"""
quality = None if self.quality is None else self.quality[::-1]
sequence = self.sequence.translate(self.COMPLEMENT_TABLE)[::-1]
return self.__class__(self.id, sequence, quality) | [
"def",
"reverseComplement",
"(",
"self",
")",
":",
"quality",
"=",
"None",
"if",
"self",
".",
"quality",
"is",
"None",
"else",
"self",
".",
"quality",
"[",
":",
":",
"-",
"1",
"]",
"sequence",
"=",
"self",
".",
"sequence",
".",
"translate",
"(",
"sel... | Reverse complement a nucleotide sequence.
@return: The reverse complemented sequence as an instance of the
current class. | [
"Reverse",
"complement",
"a",
"nucleotide",
"sequence",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L297-L306 |
acorg/dark-matter | dark/reads.py | AARead.checkAlphabet | def checkAlphabet(self, count=10):
"""
A function which checks if an AA read really contains amino acids. This
additional testing is needed, because the letters in the DNA alphabet
are also in the AA alphabet.
@param count: An C{int}, indicating how many bases or amino acids at
the start of the sequence should be considered. If C{None}, all
bases are checked.
@return: C{True} if the alphabet characters in the first C{count}
positions of sequence is a subset of the allowed alphabet for this
read class, or if the read class has a C{None} alphabet.
@raise ValueError: If a DNA sequence has been passed to AARead().
"""
if six.PY3:
readLetters = super().checkAlphabet(count)
else:
readLetters = Read.checkAlphabet(self, count)
if len(self) > 10 and readLetters.issubset(set('ACGT')):
raise ValueError('It looks like a DNA sequence has been passed to '
'AARead().')
return readLetters | python | def checkAlphabet(self, count=10):
"""
A function which checks if an AA read really contains amino acids. This
additional testing is needed, because the letters in the DNA alphabet
are also in the AA alphabet.
@param count: An C{int}, indicating how many bases or amino acids at
the start of the sequence should be considered. If C{None}, all
bases are checked.
@return: C{True} if the alphabet characters in the first C{count}
positions of sequence is a subset of the allowed alphabet for this
read class, or if the read class has a C{None} alphabet.
@raise ValueError: If a DNA sequence has been passed to AARead().
"""
if six.PY3:
readLetters = super().checkAlphabet(count)
else:
readLetters = Read.checkAlphabet(self, count)
if len(self) > 10 and readLetters.issubset(set('ACGT')):
raise ValueError('It looks like a DNA sequence has been passed to '
'AARead().')
return readLetters | [
"def",
"checkAlphabet",
"(",
"self",
",",
"count",
"=",
"10",
")",
":",
"if",
"six",
".",
"PY3",
":",
"readLetters",
"=",
"super",
"(",
")",
".",
"checkAlphabet",
"(",
"count",
")",
"else",
":",
"readLetters",
"=",
"Read",
".",
"checkAlphabet",
"(",
... | A function which checks if an AA read really contains amino acids. This
additional testing is needed, because the letters in the DNA alphabet
are also in the AA alphabet.
@param count: An C{int}, indicating how many bases or amino acids at
the start of the sequence should be considered. If C{None}, all
bases are checked.
@return: C{True} if the alphabet characters in the first C{count}
positions of sequence is a subset of the allowed alphabet for this
read class, or if the read class has a C{None} alphabet.
@raise ValueError: If a DNA sequence has been passed to AARead(). | [
"A",
"function",
"which",
"checks",
"if",
"an",
"AA",
"read",
"really",
"contains",
"amino",
"acids",
".",
"This",
"additional",
"testing",
"is",
"needed",
"because",
"the",
"letters",
"in",
"the",
"DNA",
"alphabet",
"are",
"also",
"in",
"the",
"AA",
"alph... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L385-L406 |
acorg/dark-matter | dark/reads.py | AARead.ORFs | def ORFs(self, openORFs=False):
"""
Find all ORFs in our sequence.
@param openORFs: If C{True} allow ORFs that do not have a start codon
and/or do not have a stop codon.
@return: A generator that yields AAReadORF instances that correspond
to the ORFs found in the AA sequence.
"""
# Return open ORFs to the left and right and closed ORFs within the
# sequence.
if openORFs:
ORFStart = 0
inOpenORF = True # open on the left
inORF = False
for index, residue in enumerate(self.sequence):
if residue == '*':
if inOpenORF:
if index:
yield AAReadORF(self, ORFStart, index, True, False)
inOpenORF = False
elif inORF:
if ORFStart != index:
yield AAReadORF(self, ORFStart, index,
False, False)
inORF = False
elif residue == 'M':
if not inOpenORF and not inORF:
ORFStart = index + 1
inORF = True
# End of sequence. Yield the final ORF, open to the right, if
# there is one and it has non-zero length.
length = len(self.sequence)
if inOpenORF and length > 0:
yield AAReadORF(self, ORFStart, length, True, True)
elif inORF and ORFStart < length:
yield AAReadORF(self, ORFStart, length, False, True)
# Return only closed ORFs.
else:
inORF = False
for index, residue in enumerate(self.sequence):
if residue == 'M':
if not inORF:
inORF = True
ORFStart = index + 1
elif residue == '*':
if inORF:
if not ORFStart == index:
yield AAReadORF(self, ORFStart,
index, False, False)
inORF = False | python | def ORFs(self, openORFs=False):
"""
Find all ORFs in our sequence.
@param openORFs: If C{True} allow ORFs that do not have a start codon
and/or do not have a stop codon.
@return: A generator that yields AAReadORF instances that correspond
to the ORFs found in the AA sequence.
"""
# Return open ORFs to the left and right and closed ORFs within the
# sequence.
if openORFs:
ORFStart = 0
inOpenORF = True # open on the left
inORF = False
for index, residue in enumerate(self.sequence):
if residue == '*':
if inOpenORF:
if index:
yield AAReadORF(self, ORFStart, index, True, False)
inOpenORF = False
elif inORF:
if ORFStart != index:
yield AAReadORF(self, ORFStart, index,
False, False)
inORF = False
elif residue == 'M':
if not inOpenORF and not inORF:
ORFStart = index + 1
inORF = True
# End of sequence. Yield the final ORF, open to the right, if
# there is one and it has non-zero length.
length = len(self.sequence)
if inOpenORF and length > 0:
yield AAReadORF(self, ORFStart, length, True, True)
elif inORF and ORFStart < length:
yield AAReadORF(self, ORFStart, length, False, True)
# Return only closed ORFs.
else:
inORF = False
for index, residue in enumerate(self.sequence):
if residue == 'M':
if not inORF:
inORF = True
ORFStart = index + 1
elif residue == '*':
if inORF:
if not ORFStart == index:
yield AAReadORF(self, ORFStart,
index, False, False)
inORF = False | [
"def",
"ORFs",
"(",
"self",
",",
"openORFs",
"=",
"False",
")",
":",
"# Return open ORFs to the left and right and closed ORFs within the",
"# sequence.",
"if",
"openORFs",
":",
"ORFStart",
"=",
"0",
"inOpenORF",
"=",
"True",
"# open on the left",
"inORF",
"=",
"False... | Find all ORFs in our sequence.
@param openORFs: If C{True} allow ORFs that do not have a start codon
and/or do not have a stop codon.
@return: A generator that yields AAReadORF instances that correspond
to the ORFs found in the AA sequence. | [
"Find",
"all",
"ORFs",
"in",
"our",
"sequence",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L427-L482 |
acorg/dark-matter | dark/reads.py | AAReadORF.toDict | def toDict(self):
"""
Get information about this read in a dictionary.
@return: A C{dict} with keys/values for the attributes of self.
"""
if six.PY3:
result = super().toDict()
else:
result = AARead.toDict(self)
result.update({
'start': self.start,
'stop': self.stop,
'openLeft': self.openLeft,
'openRight': self.openRight,
})
return result | python | def toDict(self):
"""
Get information about this read in a dictionary.
@return: A C{dict} with keys/values for the attributes of self.
"""
if six.PY3:
result = super().toDict()
else:
result = AARead.toDict(self)
result.update({
'start': self.start,
'stop': self.stop,
'openLeft': self.openLeft,
'openRight': self.openRight,
})
return result | [
"def",
"toDict",
"(",
"self",
")",
":",
"if",
"six",
".",
"PY3",
":",
"result",
"=",
"super",
"(",
")",
".",
"toDict",
"(",
")",
"else",
":",
"result",
"=",
"AARead",
".",
"toDict",
"(",
"self",
")",
"result",
".",
"update",
"(",
"{",
"'start'",
... | Get information about this read in a dictionary.
@return: A C{dict} with keys/values for the attributes of self. | [
"Get",
"information",
"about",
"this",
"read",
"in",
"a",
"dictionary",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L535-L553 |
acorg/dark-matter | dark/reads.py | AAReadORF.fromDict | def fromDict(cls, d):
"""
Create a new instance from attribute values provided in a dictionary.
@param d: A C{dict} with keys/values for the attributes of a new
instance of this class. Keys 'id' and 'sequence' with C{str} values
must be provided. A 'quality' C{str} key is optional. Keys 'start'
and 'stop' must have C{int} values. Keys 'openLeft' and 'openRight'
are C{bool}, all keys are as described in the docstring for this
class.
@return: A new instance of this class, with values taken from C{d}.
"""
# Make a dummy instance whose attributes we can set explicitly.
new = cls(AARead('', ''), 0, 0, True, True)
new.id = d['id']
new.sequence = d['sequence']
new.quality = d.get('quality')
new.start = d['start']
new.stop = d['stop']
new.openLeft = d['openLeft']
new.openRight = d['openRight']
return new | python | def fromDict(cls, d):
"""
Create a new instance from attribute values provided in a dictionary.
@param d: A C{dict} with keys/values for the attributes of a new
instance of this class. Keys 'id' and 'sequence' with C{str} values
must be provided. A 'quality' C{str} key is optional. Keys 'start'
and 'stop' must have C{int} values. Keys 'openLeft' and 'openRight'
are C{bool}, all keys are as described in the docstring for this
class.
@return: A new instance of this class, with values taken from C{d}.
"""
# Make a dummy instance whose attributes we can set explicitly.
new = cls(AARead('', ''), 0, 0, True, True)
new.id = d['id']
new.sequence = d['sequence']
new.quality = d.get('quality')
new.start = d['start']
new.stop = d['stop']
new.openLeft = d['openLeft']
new.openRight = d['openRight']
return new | [
"def",
"fromDict",
"(",
"cls",
",",
"d",
")",
":",
"# Make a dummy instance whose attributes we can set explicitly.",
"new",
"=",
"cls",
"(",
"AARead",
"(",
"''",
",",
"''",
")",
",",
"0",
",",
"0",
",",
"True",
",",
"True",
")",
"new",
".",
"id",
"=",
... | Create a new instance from attribute values provided in a dictionary.
@param d: A C{dict} with keys/values for the attributes of a new
instance of this class. Keys 'id' and 'sequence' with C{str} values
must be provided. A 'quality' C{str} key is optional. Keys 'start'
and 'stop' must have C{int} values. Keys 'openLeft' and 'openRight'
are C{bool}, all keys are as described in the docstring for this
class.
@return: A new instance of this class, with values taken from C{d}. | [
"Create",
"a",
"new",
"instance",
"from",
"attribute",
"values",
"provided",
"in",
"a",
"dictionary",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L556-L577 |
acorg/dark-matter | dark/reads.py | SSAARead.toString | def toString(self, format_='fasta-ss', structureSuffix=':structure'):
"""
Convert the read to a string in PDB format (sequence & structure). This
consists of two FASTA records, one for the sequence then one for the
structure.
@param format_: Either 'fasta-ss' or 'fasta'. In the former case, the
structure information is returned. Otherwise, plain FASTA is
returned.
@param structureSuffix: The C{str} suffix to append to the read id
for the second FASTA record, containing the structure information.
@raise ValueError: If C{format_} is not 'fasta'.
@return: A C{str} representing the read sequence and structure in PDB
FASTA format.
"""
if format_ == 'fasta-ss':
return '>%s\n%s\n>%s%s\n%s\n' % (
self.id, self.sequence, self.id, structureSuffix,
self.structure)
else:
if six.PY3:
return super().toString(format_=format_)
else:
return AARead.toString(self, format_=format_) | python | def toString(self, format_='fasta-ss', structureSuffix=':structure'):
"""
Convert the read to a string in PDB format (sequence & structure). This
consists of two FASTA records, one for the sequence then one for the
structure.
@param format_: Either 'fasta-ss' or 'fasta'. In the former case, the
structure information is returned. Otherwise, plain FASTA is
returned.
@param structureSuffix: The C{str} suffix to append to the read id
for the second FASTA record, containing the structure information.
@raise ValueError: If C{format_} is not 'fasta'.
@return: A C{str} representing the read sequence and structure in PDB
FASTA format.
"""
if format_ == 'fasta-ss':
return '>%s\n%s\n>%s%s\n%s\n' % (
self.id, self.sequence, self.id, structureSuffix,
self.structure)
else:
if six.PY3:
return super().toString(format_=format_)
else:
return AARead.toString(self, format_=format_) | [
"def",
"toString",
"(",
"self",
",",
"format_",
"=",
"'fasta-ss'",
",",
"structureSuffix",
"=",
"':structure'",
")",
":",
"if",
"format_",
"==",
"'fasta-ss'",
":",
"return",
"'>%s\\n%s\\n>%s%s\\n%s\\n'",
"%",
"(",
"self",
".",
"id",
",",
"self",
".",
"sequen... | Convert the read to a string in PDB format (sequence & structure). This
consists of two FASTA records, one for the sequence then one for the
structure.
@param format_: Either 'fasta-ss' or 'fasta'. In the former case, the
structure information is returned. Otherwise, plain FASTA is
returned.
@param structureSuffix: The C{str} suffix to append to the read id
for the second FASTA record, containing the structure information.
@raise ValueError: If C{format_} is not 'fasta'.
@return: A C{str} representing the read sequence and structure in PDB
FASTA format. | [
"Convert",
"the",
"read",
"to",
"a",
"string",
"in",
"PDB",
"format",
"(",
"sequence",
"&",
"structure",
")",
".",
"This",
"consists",
"of",
"two",
"FASTA",
"records",
"one",
"for",
"the",
"sequence",
"then",
"one",
"for",
"the",
"structure",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L624-L647 |
acorg/dark-matter | dark/reads.py | SSAARead.newFromSites | def newFromSites(self, sites, exclude=False):
"""
Create a new read from self, with only certain sites.
@param sites: A set of C{int} 0-based sites (i.e., indices) in
sequences that should be kept. If C{None} (the default), all sites
are kept.
@param exclude: If C{True} the C{sites} will be excluded, not
included.
"""
if exclude:
sites = set(range(len(self))) - sites
newSequence = []
newStructure = []
for index, (base, structure) in enumerate(zip(self.sequence,
self.structure)):
if index in sites:
newSequence.append(base)
newStructure.append(structure)
read = self.__class__(self.id, ''.join(newSequence),
''.join(newStructure))
return read | python | def newFromSites(self, sites, exclude=False):
"""
Create a new read from self, with only certain sites.
@param sites: A set of C{int} 0-based sites (i.e., indices) in
sequences that should be kept. If C{None} (the default), all sites
are kept.
@param exclude: If C{True} the C{sites} will be excluded, not
included.
"""
if exclude:
sites = set(range(len(self))) - sites
newSequence = []
newStructure = []
for index, (base, structure) in enumerate(zip(self.sequence,
self.structure)):
if index in sites:
newSequence.append(base)
newStructure.append(structure)
read = self.__class__(self.id, ''.join(newSequence),
''.join(newStructure))
return read | [
"def",
"newFromSites",
"(",
"self",
",",
"sites",
",",
"exclude",
"=",
"False",
")",
":",
"if",
"exclude",
":",
"sites",
"=",
"set",
"(",
"range",
"(",
"len",
"(",
"self",
")",
")",
")",
"-",
"sites",
"newSequence",
"=",
"[",
"]",
"newStructure",
"... | Create a new read from self, with only certain sites.
@param sites: A set of C{int} 0-based sites (i.e., indices) in
sequences that should be kept. If C{None} (the default), all sites
are kept.
@param exclude: If C{True} the C{sites} will be excluded, not
included. | [
"Create",
"a",
"new",
"read",
"from",
"self",
"with",
"only",
"certain",
"sites",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L673-L696 |
acorg/dark-matter | dark/reads.py | TranslatedRead.toDict | def toDict(self):
"""
Get information about this read in a dictionary.
@return: A C{dict} with keys/values for the attributes of self.
"""
if six.PY3:
result = super().toDict()
else:
result = AARead.toDict(self)
result.update({
'frame': self.frame,
'reverseComplemented': self.reverseComplemented,
})
return result | python | def toDict(self):
"""
Get information about this read in a dictionary.
@return: A C{dict} with keys/values for the attributes of self.
"""
if six.PY3:
result = super().toDict()
else:
result = AARead.toDict(self)
result.update({
'frame': self.frame,
'reverseComplemented': self.reverseComplemented,
})
return result | [
"def",
"toDict",
"(",
"self",
")",
":",
"if",
"six",
".",
"PY3",
":",
"result",
"=",
"super",
"(",
")",
".",
"toDict",
"(",
")",
"else",
":",
"result",
"=",
"AARead",
".",
"toDict",
"(",
"self",
")",
"result",
".",
"update",
"(",
"{",
"'frame'",
... | Get information about this read in a dictionary.
@return: A C{dict} with keys/values for the attributes of self. | [
"Get",
"information",
"about",
"this",
"read",
"in",
"a",
"dictionary",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L736-L752 |
acorg/dark-matter | dark/reads.py | TranslatedRead.fromDict | def fromDict(cls, d):
"""
Create a new instance from attribute values provided in a dictionary.
@param d: A C{dict} with keys/values for the attributes of a new
instance of this class. Keys 'id' and 'sequence' with C{str} values
must be provided. A 'quality' C{str} key is optional. Key 'frame'
must have an C{int} value. Key 'reverseComplemented' must be a
C{bool}, all keys are as described in the docstring for this class.
@return: A new instance of this class, with values taken from C{d}.
"""
# Make a dummy instance whose attributes we can set explicitly.
new = cls(AARead('', ''), 0, True)
new.id = d['id']
new.sequence = d['sequence']
new.quality = d.get('quality')
new.frame = d['frame']
new.reverseComplemented = d['reverseComplemented']
return new | python | def fromDict(cls, d):
"""
Create a new instance from attribute values provided in a dictionary.
@param d: A C{dict} with keys/values for the attributes of a new
instance of this class. Keys 'id' and 'sequence' with C{str} values
must be provided. A 'quality' C{str} key is optional. Key 'frame'
must have an C{int} value. Key 'reverseComplemented' must be a
C{bool}, all keys are as described in the docstring for this class.
@return: A new instance of this class, with values taken from C{d}.
"""
# Make a dummy instance whose attributes we can set explicitly.
new = cls(AARead('', ''), 0, True)
new.id = d['id']
new.sequence = d['sequence']
new.quality = d.get('quality')
new.frame = d['frame']
new.reverseComplemented = d['reverseComplemented']
return new | [
"def",
"fromDict",
"(",
"cls",
",",
"d",
")",
":",
"# Make a dummy instance whose attributes we can set explicitly.",
"new",
"=",
"cls",
"(",
"AARead",
"(",
"''",
",",
"''",
")",
",",
"0",
",",
"True",
")",
"new",
".",
"id",
"=",
"d",
"[",
"'id'",
"]",
... | Create a new instance from attribute values provided in a dictionary.
@param d: A C{dict} with keys/values for the attributes of a new
instance of this class. Keys 'id' and 'sequence' with C{str} values
must be provided. A 'quality' C{str} key is optional. Key 'frame'
must have an C{int} value. Key 'reverseComplemented' must be a
C{bool}, all keys are as described in the docstring for this class.
@return: A new instance of this class, with values taken from C{d}. | [
"Create",
"a",
"new",
"instance",
"from",
"attribute",
"values",
"provided",
"in",
"a",
"dictionary",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L755-L773 |
acorg/dark-matter | dark/reads.py | TranslatedRead.maximumORFLength | def maximumORFLength(self, openORFs=True):
"""
Return the length of the longest (possibly partial) ORF in a translated
read. The ORF may originate or terminate outside the sequence, which is
why the length is just a lower bound.
"""
return max(len(orf) for orf in self.ORFs(openORFs)) | python | def maximumORFLength(self, openORFs=True):
"""
Return the length of the longest (possibly partial) ORF in a translated
read. The ORF may originate or terminate outside the sequence, which is
why the length is just a lower bound.
"""
return max(len(orf) for orf in self.ORFs(openORFs)) | [
"def",
"maximumORFLength",
"(",
"self",
",",
"openORFs",
"=",
"True",
")",
":",
"return",
"max",
"(",
"len",
"(",
"orf",
")",
"for",
"orf",
"in",
"self",
".",
"ORFs",
"(",
"openORFs",
")",
")"
] | Return the length of the longest (possibly partial) ORF in a translated
read. The ORF may originate or terminate outside the sequence, which is
why the length is just a lower bound. | [
"Return",
"the",
"length",
"of",
"the",
"longest",
"(",
"possibly",
"partial",
")",
"ORF",
"in",
"a",
"translated",
"read",
".",
"The",
"ORF",
"may",
"originate",
"or",
"terminate",
"outside",
"the",
"sequence",
"which",
"is",
"why",
"the",
"length",
"is",... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L775-L781 |
acorg/dark-matter | dark/reads.py | ReadFilter.filter | def filter(self, read):
"""
Check if a read passes the filter.
@param read: A C{Read} instance.
@return: C{read} if C{read} passes the filter, C{False} if not.
"""
self.readIndex += 1
if self.alwaysFalse:
return False
if self.wantedSequenceNumberGeneratorExhausted:
return False
if self.nextWantedSequenceNumber is not None:
if self.readIndex + 1 == self.nextWantedSequenceNumber:
# We want this sequence.
try:
self.nextWantedSequenceNumber = next(
self.wantedSequenceNumberGenerator)
except StopIteration:
# The sequence number iterator ran out of sequence
# numbers. We must let the rest of the filtering
# continue for the current sequence in case we
# throw it out for other reasons (as we might have
# done for any of the earlier wanted sequence
# numbers).
self.wantedSequenceNumberGeneratorExhausted = True
else:
# This sequence isn't one of the ones that's wanted.
return False
if (self.sampleFraction is not None and
uniform(0.0, 1.0) > self.sampleFraction):
# Note that we don't have to worry about the 0.0 or 1.0
# cases in the above 'if', as they have been dealt with
# in self.__init__.
return False
if self.randomSubset is not None:
if self.yieldCount == self.randomSubset:
# The random subset has already been fully returned.
# There's no point in going any further through the input.
self.alwaysFalse = True
return False
elif uniform(0.0, 1.0) > ((self.randomSubset - self.yieldCount) /
(self.trueLength - self.readIndex)):
return False
if self.head is not None and self.readIndex == self.head:
# We're completely done.
self.alwaysFalse = True
return False
readLen = len(read)
if ((self.minLength is not None and readLen < self.minLength) or
(self.maxLength is not None and readLen > self.maxLength)):
return False
if self.removeGaps:
if read.quality is None:
read = read.__class__(read.id, read.sequence.replace('-', ''))
else:
newSequence = []
newQuality = []
for base, quality in zip(read.sequence, read.quality):
if base != '-':
newSequence.append(base)
newQuality.append(quality)
read = read.__class__(
read.id, ''.join(newSequence), ''.join(newQuality))
if (self.titleFilter and
self.titleFilter.accept(read.id) == TitleFilter.REJECT):
return False
if (self.keepSequences is not None and
self.readIndex not in self.keepSequences):
return False
if (self.removeSequences is not None and
self.readIndex in self.removeSequences):
return False
if self.removeDuplicates:
if read.sequence in self.sequencesSeen:
return False
self.sequencesSeen.add(read.sequence)
if self.removeDuplicatesById:
if read.id in self.idsSeen:
return False
self.idsSeen.add(read.id)
if self.modifier:
modified = self.modifier(read)
if modified is None:
return False
else:
read = modified
# We have to use 'is not None' in the following tests so the empty set
# is processed properly.
if self.keepSites is not None:
read = read.newFromSites(self.keepSites)
elif self.removeSites is not None:
read = read.newFromSites(self.removeSites, exclude=True)
if self.idLambda:
newId = self.idLambda(read.id)
if newId is None:
return False
else:
read.id = newId
if self.readLambda:
newRead = self.readLambda(read)
if newRead is None:
return False
else:
read = newRead
if self.removeDescriptions:
read.id = read.id.split()[0]
if self.reverse:
read = read.reverse()
elif self.reverseComplement:
read = read.reverseComplement()
self.yieldCount += 1
return read | python | def filter(self, read):
"""
Check if a read passes the filter.
@param read: A C{Read} instance.
@return: C{read} if C{read} passes the filter, C{False} if not.
"""
self.readIndex += 1
if self.alwaysFalse:
return False
if self.wantedSequenceNumberGeneratorExhausted:
return False
if self.nextWantedSequenceNumber is not None:
if self.readIndex + 1 == self.nextWantedSequenceNumber:
# We want this sequence.
try:
self.nextWantedSequenceNumber = next(
self.wantedSequenceNumberGenerator)
except StopIteration:
# The sequence number iterator ran out of sequence
# numbers. We must let the rest of the filtering
# continue for the current sequence in case we
# throw it out for other reasons (as we might have
# done for any of the earlier wanted sequence
# numbers).
self.wantedSequenceNumberGeneratorExhausted = True
else:
# This sequence isn't one of the ones that's wanted.
return False
if (self.sampleFraction is not None and
uniform(0.0, 1.0) > self.sampleFraction):
# Note that we don't have to worry about the 0.0 or 1.0
# cases in the above 'if', as they have been dealt with
# in self.__init__.
return False
if self.randomSubset is not None:
if self.yieldCount == self.randomSubset:
# The random subset has already been fully returned.
# There's no point in going any further through the input.
self.alwaysFalse = True
return False
elif uniform(0.0, 1.0) > ((self.randomSubset - self.yieldCount) /
(self.trueLength - self.readIndex)):
return False
if self.head is not None and self.readIndex == self.head:
# We're completely done.
self.alwaysFalse = True
return False
readLen = len(read)
if ((self.minLength is not None and readLen < self.minLength) or
(self.maxLength is not None and readLen > self.maxLength)):
return False
if self.removeGaps:
if read.quality is None:
read = read.__class__(read.id, read.sequence.replace('-', ''))
else:
newSequence = []
newQuality = []
for base, quality in zip(read.sequence, read.quality):
if base != '-':
newSequence.append(base)
newQuality.append(quality)
read = read.__class__(
read.id, ''.join(newSequence), ''.join(newQuality))
if (self.titleFilter and
self.titleFilter.accept(read.id) == TitleFilter.REJECT):
return False
if (self.keepSequences is not None and
self.readIndex not in self.keepSequences):
return False
if (self.removeSequences is not None and
self.readIndex in self.removeSequences):
return False
if self.removeDuplicates:
if read.sequence in self.sequencesSeen:
return False
self.sequencesSeen.add(read.sequence)
if self.removeDuplicatesById:
if read.id in self.idsSeen:
return False
self.idsSeen.add(read.id)
if self.modifier:
modified = self.modifier(read)
if modified is None:
return False
else:
read = modified
# We have to use 'is not None' in the following tests so the empty set
# is processed properly.
if self.keepSites is not None:
read = read.newFromSites(self.keepSites)
elif self.removeSites is not None:
read = read.newFromSites(self.removeSites, exclude=True)
if self.idLambda:
newId = self.idLambda(read.id)
if newId is None:
return False
else:
read.id = newId
if self.readLambda:
newRead = self.readLambda(read)
if newRead is None:
return False
else:
read = newRead
if self.removeDescriptions:
read.id = read.id.split()[0]
if self.reverse:
read = read.reverse()
elif self.reverseComplement:
read = read.reverseComplement()
self.yieldCount += 1
return read | [
"def",
"filter",
"(",
"self",
",",
"read",
")",
":",
"self",
".",
"readIndex",
"+=",
"1",
"if",
"self",
".",
"alwaysFalse",
":",
"return",
"False",
"if",
"self",
".",
"wantedSequenceNumberGeneratorExhausted",
":",
"return",
"False",
"if",
"self",
".",
"nex... | Check if a read passes the filter.
@param read: A C{Read} instance.
@return: C{read} if C{read} passes the filter, C{False} if not. | [
"Check",
"if",
"a",
"read",
"passes",
"the",
"filter",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L1039-L1171 |
acorg/dark-matter | dark/reads.py | Reads.filterRead | def filterRead(self, read):
"""
Filter a read, according to our set of filters.
@param read: A C{Read} instance or one of its subclasses.
@return: C{False} if the read fails any of our filters, else the
C{Read} instance returned by our list of filters.
"""
for filterFunc in self._filters:
filteredRead = filterFunc(read)
if filteredRead is False:
return False
else:
read = filteredRead
return read | python | def filterRead(self, read):
"""
Filter a read, according to our set of filters.
@param read: A C{Read} instance or one of its subclasses.
@return: C{False} if the read fails any of our filters, else the
C{Read} instance returned by our list of filters.
"""
for filterFunc in self._filters:
filteredRead = filterFunc(read)
if filteredRead is False:
return False
else:
read = filteredRead
return read | [
"def",
"filterRead",
"(",
"self",
",",
"read",
")",
":",
"for",
"filterFunc",
"in",
"self",
".",
"_filters",
":",
"filteredRead",
"=",
"filterFunc",
"(",
"read",
")",
"if",
"filteredRead",
"is",
"False",
":",
"return",
"False",
"else",
":",
"read",
"=",
... | Filter a read, according to our set of filters.
@param read: A C{Read} instance or one of its subclasses.
@return: C{False} if the read fails any of our filters, else the
C{Read} instance returned by our list of filters. | [
"Filter",
"a",
"read",
"according",
"to",
"our",
"set",
"of",
"filters",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L1221-L1235 |
acorg/dark-matter | dark/reads.py | Reads.save | def save(self, filename, format_='fasta'):
"""
Write the reads to C{filename} in the requested format.
@param filename: Either a C{str} file name to save into (the file will
be overwritten) or an open file descriptor (e.g., sys.stdout).
@param format_: A C{str} format to save as, either 'fasta', 'fastq' or
'fasta-ss'.
@raise ValueError: if C{format_} is 'fastq' and a read with no quality
is present, or if an unknown format is requested.
@return: An C{int} giving the number of reads in C{self}.
"""
format_ = format_.lower()
count = 0
if isinstance(filename, str):
try:
with open(filename, 'w') as fp:
for read in self:
fp.write(read.toString(format_))
count += 1
except ValueError:
unlink(filename)
raise
else:
# We have a file-like object.
for read in self:
filename.write(read.toString(format_))
count += 1
return count | python | def save(self, filename, format_='fasta'):
"""
Write the reads to C{filename} in the requested format.
@param filename: Either a C{str} file name to save into (the file will
be overwritten) or an open file descriptor (e.g., sys.stdout).
@param format_: A C{str} format to save as, either 'fasta', 'fastq' or
'fasta-ss'.
@raise ValueError: if C{format_} is 'fastq' and a read with no quality
is present, or if an unknown format is requested.
@return: An C{int} giving the number of reads in C{self}.
"""
format_ = format_.lower()
count = 0
if isinstance(filename, str):
try:
with open(filename, 'w') as fp:
for read in self:
fp.write(read.toString(format_))
count += 1
except ValueError:
unlink(filename)
raise
else:
# We have a file-like object.
for read in self:
filename.write(read.toString(format_))
count += 1
return count | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"format_",
"=",
"'fasta'",
")",
":",
"format_",
"=",
"format_",
".",
"lower",
"(",
")",
"count",
"=",
"0",
"if",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"try",
":",
"with",
"open",
"(",... | Write the reads to C{filename} in the requested format.
@param filename: Either a C{str} file name to save into (the file will
be overwritten) or an open file descriptor (e.g., sys.stdout).
@param format_: A C{str} format to save as, either 'fasta', 'fastq' or
'fasta-ss'.
@raise ValueError: if C{format_} is 'fastq' and a read with no quality
is present, or if an unknown format is requested.
@return: An C{int} giving the number of reads in C{self}. | [
"Write",
"the",
"reads",
"to",
"C",
"{",
"filename",
"}",
"in",
"the",
"requested",
"format",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L1323-L1352 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.