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/blast/hacks.py | printBlastRecordForDerek | def printBlastRecordForDerek(record):
"""
This is a hacked version of printBlastRecord that I wrote in
Addenbrookes hospital so Derek could try hacking on the reads
that had low e values. It's called by bin/print-blast-xml-for-derek.py
"""
if len(record.alignments) == 0:
return 0
if record.descriptions[0].e > 1e-120:
return 0
print(record.query, end=' ')
for i, alignment in enumerate(record.alignments):
print(record.descriptions[i].e, end=' ')
for hspIndex, hsp in enumerate(alignment.hsps, start=1):
if hsp.sbjct_start < hsp.sbjct_end:
sense = 1
if hsp.sbjct_start < 2200:
side = 'left'
else:
side = 'right'
else:
sense = -1
if hsp.sbjct_end < 2200:
side = 'left'
else:
side = 'right'
print(sense, side)
break
return 1 | python | def printBlastRecordForDerek(record):
"""
This is a hacked version of printBlastRecord that I wrote in
Addenbrookes hospital so Derek could try hacking on the reads
that had low e values. It's called by bin/print-blast-xml-for-derek.py
"""
if len(record.alignments) == 0:
return 0
if record.descriptions[0].e > 1e-120:
return 0
print(record.query, end=' ')
for i, alignment in enumerate(record.alignments):
print(record.descriptions[i].e, end=' ')
for hspIndex, hsp in enumerate(alignment.hsps, start=1):
if hsp.sbjct_start < hsp.sbjct_end:
sense = 1
if hsp.sbjct_start < 2200:
side = 'left'
else:
side = 'right'
else:
sense = -1
if hsp.sbjct_end < 2200:
side = 'left'
else:
side = 'right'
print(sense, side)
break
return 1 | [
"def",
"printBlastRecordForDerek",
"(",
"record",
")",
":",
"if",
"len",
"(",
"record",
".",
"alignments",
")",
"==",
"0",
":",
"return",
"0",
"if",
"record",
".",
"descriptions",
"[",
"0",
"]",
".",
"e",
">",
"1e-120",
":",
"return",
"0",
"print",
"... | This is a hacked version of printBlastRecord that I wrote in
Addenbrookes hospital so Derek could try hacking on the reads
that had low e values. It's called by bin/print-blast-xml-for-derek.py | [
"This",
"is",
"a",
"hacked",
"version",
"of",
"printBlastRecord",
"that",
"I",
"wrote",
"in",
"Addenbrookes",
"hospital",
"so",
"Derek",
"could",
"try",
"hacking",
"on",
"the",
"reads",
"that",
"had",
"low",
"e",
"values",
".",
"It",
"s",
"called",
"by",
... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/hacks.py#L4-L32 |
acorg/dark-matter | dark/proteins.py | splitNames | def splitNames(names):
"""
Split a sequence id string like "Protein name [pathogen name]" into two
pieces using the final square brackets to delimit the pathogen name.
@param names: A C{str} "protein name [pathogen name]" string.
@return: A 2-C{tuple} giving the C{str} protein name and C{str} pathogen
name. If C{names} cannot be split on square brackets, it is
returned as the first tuple element, followed by _NO_PATHOGEN_NAME.
"""
match = _PATHOGEN_RE.match(names)
if match:
proteinName = match.group(1).strip()
pathogenName = match.group(2).strip()
else:
proteinName = names
pathogenName = _NO_PATHOGEN_NAME
return proteinName, pathogenName | python | def splitNames(names):
"""
Split a sequence id string like "Protein name [pathogen name]" into two
pieces using the final square brackets to delimit the pathogen name.
@param names: A C{str} "protein name [pathogen name]" string.
@return: A 2-C{tuple} giving the C{str} protein name and C{str} pathogen
name. If C{names} cannot be split on square brackets, it is
returned as the first tuple element, followed by _NO_PATHOGEN_NAME.
"""
match = _PATHOGEN_RE.match(names)
if match:
proteinName = match.group(1).strip()
pathogenName = match.group(2).strip()
else:
proteinName = names
pathogenName = _NO_PATHOGEN_NAME
return proteinName, pathogenName | [
"def",
"splitNames",
"(",
"names",
")",
":",
"match",
"=",
"_PATHOGEN_RE",
".",
"match",
"(",
"names",
")",
"if",
"match",
":",
"proteinName",
"=",
"match",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"pathogenName",
"=",
"match",
".",
"grou... | Split a sequence id string like "Protein name [pathogen name]" into two
pieces using the final square brackets to delimit the pathogen name.
@param names: A C{str} "protein name [pathogen name]" string.
@return: A 2-C{tuple} giving the C{str} protein name and C{str} pathogen
name. If C{names} cannot be split on square brackets, it is
returned as the first tuple element, followed by _NO_PATHOGEN_NAME. | [
"Split",
"a",
"sequence",
"id",
"string",
"like",
"Protein",
"name",
"[",
"pathogen",
"name",
"]",
"into",
"two",
"pieces",
"using",
"the",
"final",
"square",
"brackets",
"to",
"delimit",
"the",
"pathogen",
"name",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L44-L62 |
acorg/dark-matter | dark/proteins.py | getPathogenProteinCounts | def getPathogenProteinCounts(filenames):
"""
Get the number of proteins for each pathogen in C{filenames}.
@param filenames: Either C{None} or a C{list} of C{str} FASTA file names.
If C{None} an empty C{Counter} is returned. If FASTA file names are
given, their sequence ids should have the format used in the NCBI
bacterial and viral protein reference sequence files, in which the
protein name is followed by the pathogen name in square brackets.
@return: A C{Counter} keyed by C{str} pathogen name, whose values are
C{int}s with the count of the number of proteins for the pathogen.
"""
result = Counter()
if filenames:
for filename in filenames:
for protein in FastaReads(filename):
_, pathogenName = splitNames(protein.id)
if pathogenName != _NO_PATHOGEN_NAME:
result[pathogenName] += 1
return result | python | def getPathogenProteinCounts(filenames):
"""
Get the number of proteins for each pathogen in C{filenames}.
@param filenames: Either C{None} or a C{list} of C{str} FASTA file names.
If C{None} an empty C{Counter} is returned. If FASTA file names are
given, their sequence ids should have the format used in the NCBI
bacterial and viral protein reference sequence files, in which the
protein name is followed by the pathogen name in square brackets.
@return: A C{Counter} keyed by C{str} pathogen name, whose values are
C{int}s with the count of the number of proteins for the pathogen.
"""
result = Counter()
if filenames:
for filename in filenames:
for protein in FastaReads(filename):
_, pathogenName = splitNames(protein.id)
if pathogenName != _NO_PATHOGEN_NAME:
result[pathogenName] += 1
return result | [
"def",
"getPathogenProteinCounts",
"(",
"filenames",
")",
":",
"result",
"=",
"Counter",
"(",
")",
"if",
"filenames",
":",
"for",
"filename",
"in",
"filenames",
":",
"for",
"protein",
"in",
"FastaReads",
"(",
"filename",
")",
":",
"_",
",",
"pathogenName",
... | Get the number of proteins for each pathogen in C{filenames}.
@param filenames: Either C{None} or a C{list} of C{str} FASTA file names.
If C{None} an empty C{Counter} is returned. If FASTA file names are
given, their sequence ids should have the format used in the NCBI
bacterial and viral protein reference sequence files, in which the
protein name is followed by the pathogen name in square brackets.
@return: A C{Counter} keyed by C{str} pathogen name, whose values are
C{int}s with the count of the number of proteins for the pathogen. | [
"Get",
"the",
"number",
"of",
"proteins",
"for",
"each",
"pathogen",
"in",
"C",
"{",
"filenames",
"}",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L65-L85 |
acorg/dark-matter | dark/proteins.py | PathogenSampleFiles.add | def add(self, pathogenName, sampleName):
"""
Add a (pathogen name, sample name) combination and get its FASTA/FASTQ
file name and unique read count. Write the FASTA/FASTQ file if it does
not already exist. Save the unique read count into
C{self._proteinGrouper}.
@param pathogenName: A C{str} pathogen name.
@param sampleName: A C{str} sample name.
@return: A C{str} giving the FASTA/FASTQ file name holding all the
reads (without duplicates, by id) from the sample that matched the
proteins in the given pathogen.
"""
pathogenIndex = self._pathogens.setdefault(pathogenName,
len(self._pathogens))
sampleIndex = self._samples.setdefault(sampleName, len(self._samples))
try:
return self._readsFilenames[(pathogenIndex, sampleIndex)]
except KeyError:
reads = Reads()
for proteinMatch in self._proteinGrouper.pathogenNames[
pathogenName][sampleName]['proteins'].values():
for read in self._readsClass(proteinMatch['readsFilename']):
reads.add(read)
saveFilename = join(
proteinMatch['outDir'],
'pathogen-%d-sample-%d.%s' % (pathogenIndex, sampleIndex,
self._format))
reads.filter(removeDuplicatesById=True)
nReads = reads.save(saveFilename, format_=self._format)
# Save the unique read count into self._proteinGrouper
self._proteinGrouper.pathogenNames[
pathogenName][sampleName]['uniqueReadCount'] = nReads
self._readsFilenames[(pathogenIndex, sampleIndex)] = saveFilename
return saveFilename | python | def add(self, pathogenName, sampleName):
"""
Add a (pathogen name, sample name) combination and get its FASTA/FASTQ
file name and unique read count. Write the FASTA/FASTQ file if it does
not already exist. Save the unique read count into
C{self._proteinGrouper}.
@param pathogenName: A C{str} pathogen name.
@param sampleName: A C{str} sample name.
@return: A C{str} giving the FASTA/FASTQ file name holding all the
reads (without duplicates, by id) from the sample that matched the
proteins in the given pathogen.
"""
pathogenIndex = self._pathogens.setdefault(pathogenName,
len(self._pathogens))
sampleIndex = self._samples.setdefault(sampleName, len(self._samples))
try:
return self._readsFilenames[(pathogenIndex, sampleIndex)]
except KeyError:
reads = Reads()
for proteinMatch in self._proteinGrouper.pathogenNames[
pathogenName][sampleName]['proteins'].values():
for read in self._readsClass(proteinMatch['readsFilename']):
reads.add(read)
saveFilename = join(
proteinMatch['outDir'],
'pathogen-%d-sample-%d.%s' % (pathogenIndex, sampleIndex,
self._format))
reads.filter(removeDuplicatesById=True)
nReads = reads.save(saveFilename, format_=self._format)
# Save the unique read count into self._proteinGrouper
self._proteinGrouper.pathogenNames[
pathogenName][sampleName]['uniqueReadCount'] = nReads
self._readsFilenames[(pathogenIndex, sampleIndex)] = saveFilename
return saveFilename | [
"def",
"add",
"(",
"self",
",",
"pathogenName",
",",
"sampleName",
")",
":",
"pathogenIndex",
"=",
"self",
".",
"_pathogens",
".",
"setdefault",
"(",
"pathogenName",
",",
"len",
"(",
"self",
".",
"_pathogens",
")",
")",
"sampleIndex",
"=",
"self",
".",
"... | Add a (pathogen name, sample name) combination and get its FASTA/FASTQ
file name and unique read count. Write the FASTA/FASTQ file if it does
not already exist. Save the unique read count into
C{self._proteinGrouper}.
@param pathogenName: A C{str} pathogen name.
@param sampleName: A C{str} sample name.
@return: A C{str} giving the FASTA/FASTQ file name holding all the
reads (without duplicates, by id) from the sample that matched the
proteins in the given pathogen. | [
"Add",
"a",
"(",
"pathogen",
"name",
"sample",
"name",
")",
"combination",
"and",
"get",
"its",
"FASTA",
"/",
"FASTQ",
"file",
"name",
"and",
"unique",
"read",
"count",
".",
"Write",
"the",
"FASTA",
"/",
"FASTQ",
"file",
"if",
"it",
"does",
"not",
"alr... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L110-L145 |
acorg/dark-matter | dark/proteins.py | PathogenSampleFiles.lookup | def lookup(self, pathogenName, sampleName):
"""
Look up a pathogen name, sample name combination and get its
FASTA/FASTQ file name and unique read count.
This method should be used instead of C{add} in situations where
you want an exception to be raised if a pathogen/sample combination has
not already been passed to C{add}.
@param pathogenName: A C{str} pathogen name.
@param sampleName: A C{str} sample name.
@raise KeyError: If the pathogen name or sample name have not been
seen, either individually or in combination.
@return: A (C{str}, C{int}) tuple retrieved from self._readsFilenames
"""
pathogenIndex = self._pathogens[pathogenName]
sampleIndex = self._samples[sampleName]
return self._readsFilenames[(pathogenIndex, sampleIndex)] | python | def lookup(self, pathogenName, sampleName):
"""
Look up a pathogen name, sample name combination and get its
FASTA/FASTQ file name and unique read count.
This method should be used instead of C{add} in situations where
you want an exception to be raised if a pathogen/sample combination has
not already been passed to C{add}.
@param pathogenName: A C{str} pathogen name.
@param sampleName: A C{str} sample name.
@raise KeyError: If the pathogen name or sample name have not been
seen, either individually or in combination.
@return: A (C{str}, C{int}) tuple retrieved from self._readsFilenames
"""
pathogenIndex = self._pathogens[pathogenName]
sampleIndex = self._samples[sampleName]
return self._readsFilenames[(pathogenIndex, sampleIndex)] | [
"def",
"lookup",
"(",
"self",
",",
"pathogenName",
",",
"sampleName",
")",
":",
"pathogenIndex",
"=",
"self",
".",
"_pathogens",
"[",
"pathogenName",
"]",
"sampleIndex",
"=",
"self",
".",
"_samples",
"[",
"sampleName",
"]",
"return",
"self",
".",
"_readsFile... | Look up a pathogen name, sample name combination and get its
FASTA/FASTQ file name and unique read count.
This method should be used instead of C{add} in situations where
you want an exception to be raised if a pathogen/sample combination has
not already been passed to C{add}.
@param pathogenName: A C{str} pathogen name.
@param sampleName: A C{str} sample name.
@raise KeyError: If the pathogen name or sample name have not been
seen, either individually or in combination.
@return: A (C{str}, C{int}) tuple retrieved from self._readsFilenames | [
"Look",
"up",
"a",
"pathogen",
"name",
"sample",
"name",
"combination",
"and",
"get",
"its",
"FASTA",
"/",
"FASTQ",
"file",
"name",
"and",
"unique",
"read",
"count",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L147-L164 |
acorg/dark-matter | dark/proteins.py | PathogenSampleFiles.writeSampleIndex | def writeSampleIndex(self, fp):
"""
Write a file of sample indices and names, sorted by index.
@param fp: A file-like object, opened for writing.
"""
print('\n'.join(
'%d %s' % (index, name) for (index, name) in
sorted((index, name) for (name, index) in self._samples.items())
), file=fp) | python | def writeSampleIndex(self, fp):
"""
Write a file of sample indices and names, sorted by index.
@param fp: A file-like object, opened for writing.
"""
print('\n'.join(
'%d %s' % (index, name) for (index, name) in
sorted((index, name) for (name, index) in self._samples.items())
), file=fp) | [
"def",
"writeSampleIndex",
"(",
"self",
",",
"fp",
")",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"'%d %s'",
"%",
"(",
"index",
",",
"name",
")",
"for",
"(",
"index",
",",
"name",
")",
"in",
"sorted",
"(",
"(",
"index",
",",
"name",
")",
"for... | Write a file of sample indices and names, sorted by index.
@param fp: A file-like object, opened for writing. | [
"Write",
"a",
"file",
"of",
"sample",
"indices",
"and",
"names",
"sorted",
"by",
"index",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L166-L175 |
acorg/dark-matter | dark/proteins.py | PathogenSampleFiles.writePathogenIndex | def writePathogenIndex(self, fp):
"""
Write a file of pathogen indices and names, sorted by index.
@param fp: A file-like object, opened for writing.
"""
print('\n'.join(
'%d %s' % (index, name) for (index, name) in
sorted((index, name) for (name, index) in self._pathogens.items())
), file=fp) | python | def writePathogenIndex(self, fp):
"""
Write a file of pathogen indices and names, sorted by index.
@param fp: A file-like object, opened for writing.
"""
print('\n'.join(
'%d %s' % (index, name) for (index, name) in
sorted((index, name) for (name, index) in self._pathogens.items())
), file=fp) | [
"def",
"writePathogenIndex",
"(",
"self",
",",
"fp",
")",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"'%d %s'",
"%",
"(",
"index",
",",
"name",
")",
"for",
"(",
"index",
",",
"name",
")",
"in",
"sorted",
"(",
"(",
"index",
",",
"name",
")",
"f... | Write a file of pathogen indices and names, sorted by index.
@param fp: A file-like object, opened for writing. | [
"Write",
"a",
"file",
"of",
"pathogen",
"indices",
"and",
"names",
"sorted",
"by",
"index",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L177-L186 |
acorg/dark-matter | dark/proteins.py | ProteinGrouper._title | def _title(self):
"""
Create a title summarizing the pathogens and samples.
@return: A C{str} title.
"""
return (
'Overall, proteins from %d pathogen%s were found in %d sample%s.' %
(len(self.pathogenNames),
'' if len(self.pathogenNames) == 1 else 's',
len(self.sampleNames),
'' if len(self.sampleNames) == 1 else 's')) | python | def _title(self):
"""
Create a title summarizing the pathogens and samples.
@return: A C{str} title.
"""
return (
'Overall, proteins from %d pathogen%s were found in %d sample%s.' %
(len(self.pathogenNames),
'' if len(self.pathogenNames) == 1 else 's',
len(self.sampleNames),
'' if len(self.sampleNames) == 1 else 's')) | [
"def",
"_title",
"(",
"self",
")",
":",
"return",
"(",
"'Overall, proteins from %d pathogen%s were found in %d sample%s.'",
"%",
"(",
"len",
"(",
"self",
".",
"pathogenNames",
")",
",",
"''",
"if",
"len",
"(",
"self",
".",
"pathogenNames",
")",
"==",
"1",
"els... | Create a title summarizing the pathogens and samples.
@return: A C{str} title. | [
"Create",
"a",
"title",
"summarizing",
"the",
"pathogens",
"and",
"samples",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L244-L255 |
acorg/dark-matter | dark/proteins.py | ProteinGrouper.addFile | def addFile(self, filename, fp):
"""
Read and record protein information for a sample.
@param filename: A C{str} file name.
@param fp: An open file pointer to read the file's data from.
@raise ValueError: If information for a pathogen/protein/sample
combination is given more than once.
"""
if self._sampleName:
sampleName = self._sampleName
elif self._sampleNameRegex:
match = self._sampleNameRegex.search(filename)
if match:
sampleName = match.group(1)
else:
sampleName = filename
else:
sampleName = filename
outDir = join(dirname(filename), self._assetDir)
self.sampleNames[sampleName] = join(outDir, 'index.html')
for index, proteinLine in enumerate(fp):
proteinLine = proteinLine[:-1]
(coverage, medianScore, bestScore, readCount, hspCount,
proteinLength, names) = proteinLine.split(None, 6)
proteinName, pathogenName = splitNames(names)
if pathogenName not in self.pathogenNames:
self.pathogenNames[pathogenName] = {}
if sampleName not in self.pathogenNames[pathogenName]:
self.pathogenNames[pathogenName][sampleName] = {
'proteins': {},
'uniqueReadCount': None,
}
proteins = self.pathogenNames[pathogenName][sampleName]['proteins']
# We should only receive one line of information for a given
# pathogen/sample/protein combination.
if proteinName in proteins:
raise ValueError(
'Protein %r already seen for pathogen %r sample %r.' %
(proteinName, pathogenName, sampleName))
readsFilename = join(outDir, '%d.%s' % (index, self._format))
proteins[proteinName] = {
'bestScore': float(bestScore),
'bluePlotFilename': join(outDir, '%d.png' % index),
'coverage': float(coverage),
'readsFilename': readsFilename,
'hspCount': int(hspCount),
'index': index,
'medianScore': float(medianScore),
'outDir': outDir,
'proteinLength': int(proteinLength),
'proteinName': proteinName,
'proteinURL': NCBISequenceLinkURL(proteinName),
'readCount': int(readCount),
}
if self._saveReadLengths:
readsClass = (FastaReads if self._format == 'fasta'
else FastqReads)
proteins[proteinName]['readLengths'] = tuple(
len(read) for read in readsClass(readsFilename)) | python | def addFile(self, filename, fp):
"""
Read and record protein information for a sample.
@param filename: A C{str} file name.
@param fp: An open file pointer to read the file's data from.
@raise ValueError: If information for a pathogen/protein/sample
combination is given more than once.
"""
if self._sampleName:
sampleName = self._sampleName
elif self._sampleNameRegex:
match = self._sampleNameRegex.search(filename)
if match:
sampleName = match.group(1)
else:
sampleName = filename
else:
sampleName = filename
outDir = join(dirname(filename), self._assetDir)
self.sampleNames[sampleName] = join(outDir, 'index.html')
for index, proteinLine in enumerate(fp):
proteinLine = proteinLine[:-1]
(coverage, medianScore, bestScore, readCount, hspCount,
proteinLength, names) = proteinLine.split(None, 6)
proteinName, pathogenName = splitNames(names)
if pathogenName not in self.pathogenNames:
self.pathogenNames[pathogenName] = {}
if sampleName not in self.pathogenNames[pathogenName]:
self.pathogenNames[pathogenName][sampleName] = {
'proteins': {},
'uniqueReadCount': None,
}
proteins = self.pathogenNames[pathogenName][sampleName]['proteins']
# We should only receive one line of information for a given
# pathogen/sample/protein combination.
if proteinName in proteins:
raise ValueError(
'Protein %r already seen for pathogen %r sample %r.' %
(proteinName, pathogenName, sampleName))
readsFilename = join(outDir, '%d.%s' % (index, self._format))
proteins[proteinName] = {
'bestScore': float(bestScore),
'bluePlotFilename': join(outDir, '%d.png' % index),
'coverage': float(coverage),
'readsFilename': readsFilename,
'hspCount': int(hspCount),
'index': index,
'medianScore': float(medianScore),
'outDir': outDir,
'proteinLength': int(proteinLength),
'proteinName': proteinName,
'proteinURL': NCBISequenceLinkURL(proteinName),
'readCount': int(readCount),
}
if self._saveReadLengths:
readsClass = (FastaReads if self._format == 'fasta'
else FastqReads)
proteins[proteinName]['readLengths'] = tuple(
len(read) for read in readsClass(readsFilename)) | [
"def",
"addFile",
"(",
"self",
",",
"filename",
",",
"fp",
")",
":",
"if",
"self",
".",
"_sampleName",
":",
"sampleName",
"=",
"self",
".",
"_sampleName",
"elif",
"self",
".",
"_sampleNameRegex",
":",
"match",
"=",
"self",
".",
"_sampleNameRegex",
".",
"... | Read and record protein information for a sample.
@param filename: A C{str} file name.
@param fp: An open file pointer to read the file's data from.
@raise ValueError: If information for a pathogen/protein/sample
combination is given more than once. | [
"Read",
"and",
"record",
"protein",
"information",
"for",
"a",
"sample",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L257-L327 |
acorg/dark-matter | dark/proteins.py | ProteinGrouper._computeUniqueReadCounts | def _computeUniqueReadCounts(self):
"""
Add all pathogen / sample combinations to self.pathogenSampleFiles.
This will make all de-duplicated (by id) FASTA/FASTQ files and store
the number of de-duplicated reads into C{self.pathogenNames}.
"""
for pathogenName, samples in self.pathogenNames.items():
for sampleName in samples:
self.pathogenSampleFiles.add(pathogenName, sampleName) | python | def _computeUniqueReadCounts(self):
"""
Add all pathogen / sample combinations to self.pathogenSampleFiles.
This will make all de-duplicated (by id) FASTA/FASTQ files and store
the number of de-duplicated reads into C{self.pathogenNames}.
"""
for pathogenName, samples in self.pathogenNames.items():
for sampleName in samples:
self.pathogenSampleFiles.add(pathogenName, sampleName) | [
"def",
"_computeUniqueReadCounts",
"(",
"self",
")",
":",
"for",
"pathogenName",
",",
"samples",
"in",
"self",
".",
"pathogenNames",
".",
"items",
"(",
")",
":",
"for",
"sampleName",
"in",
"samples",
":",
"self",
".",
"pathogenSampleFiles",
".",
"add",
"(",
... | Add all pathogen / sample combinations to self.pathogenSampleFiles.
This will make all de-duplicated (by id) FASTA/FASTQ files and store
the number of de-duplicated reads into C{self.pathogenNames}. | [
"Add",
"all",
"pathogen",
"/",
"sample",
"combinations",
"to",
"self",
".",
"pathogenSampleFiles",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L329-L338 |
acorg/dark-matter | dark/proteins.py | ProteinGrouper.toStr | def toStr(self):
"""
Produce a string representation of the pathogen summary.
@return: A C{str} suitable for printing.
"""
# Note that the string representation contains much less
# information than the HTML summary. E.g., it does not contain the
# unique (de-duplicated, by id) read count, since that is only computed
# when we are making combined FASTA files of reads matching a
# pathogen.
readCountGetter = itemgetter('readCount')
result = []
append = result.append
append(self._title())
append('')
for pathogenName in sorted(self.pathogenNames):
samples = self.pathogenNames[pathogenName]
sampleCount = len(samples)
append('%s (in %d sample%s)' %
(pathogenName,
sampleCount, '' if sampleCount == 1 else 's'))
for sampleName in sorted(samples):
proteins = samples[sampleName]['proteins']
proteinCount = len(proteins)
totalReads = sum(readCountGetter(p) for p in proteins.values())
append(' %s (%d protein%s, %d read%s)' %
(sampleName,
proteinCount, '' if proteinCount == 1 else 's',
totalReads, '' if totalReads == 1 else 's'))
for proteinName in sorted(proteins):
append(
' %(coverage).2f\t%(medianScore).2f\t'
'%(bestScore).2f\t%(readCount)4d\t%(hspCount)4d\t'
'%(index)3d\t%(proteinName)s'
% proteins[proteinName])
append('')
return '\n'.join(result) | python | def toStr(self):
"""
Produce a string representation of the pathogen summary.
@return: A C{str} suitable for printing.
"""
# Note that the string representation contains much less
# information than the HTML summary. E.g., it does not contain the
# unique (de-duplicated, by id) read count, since that is only computed
# when we are making combined FASTA files of reads matching a
# pathogen.
readCountGetter = itemgetter('readCount')
result = []
append = result.append
append(self._title())
append('')
for pathogenName in sorted(self.pathogenNames):
samples = self.pathogenNames[pathogenName]
sampleCount = len(samples)
append('%s (in %d sample%s)' %
(pathogenName,
sampleCount, '' if sampleCount == 1 else 's'))
for sampleName in sorted(samples):
proteins = samples[sampleName]['proteins']
proteinCount = len(proteins)
totalReads = sum(readCountGetter(p) for p in proteins.values())
append(' %s (%d protein%s, %d read%s)' %
(sampleName,
proteinCount, '' if proteinCount == 1 else 's',
totalReads, '' if totalReads == 1 else 's'))
for proteinName in sorted(proteins):
append(
' %(coverage).2f\t%(medianScore).2f\t'
'%(bestScore).2f\t%(readCount)4d\t%(hspCount)4d\t'
'%(index)3d\t%(proteinName)s'
% proteins[proteinName])
append('')
return '\n'.join(result) | [
"def",
"toStr",
"(",
"self",
")",
":",
"# Note that the string representation contains much less",
"# information than the HTML summary. E.g., it does not contain the",
"# unique (de-duplicated, by id) read count, since that is only computed",
"# when we are making combined FASTA files of reads ma... | Produce a string representation of the pathogen summary.
@return: A C{str} suitable for printing. | [
"Produce",
"a",
"string",
"representation",
"of",
"the",
"pathogen",
"summary",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L340-L380 |
acorg/dark-matter | dark/proteins.py | ProteinGrouper.toHTML | def toHTML(self, pathogenPanelFilename=None, minProteinFraction=0.0,
pathogenType='viral', sampleIndexFilename=None,
pathogenIndexFilename=None):
"""
Produce an HTML string representation of the pathogen summary.
@param pathogenPanelFilename: If not C{None}, a C{str} filename to
write a pathogen panel PNG image to.
@param minProteinFraction: The C{float} minimum fraction of proteins
in a pathogen that must be matched by a sample in order for that
pathogen to be displayed for that sample.
@param pathogenType: A C{str} giving the type of the pathogen involved,
either 'bacterial' or 'viral'.
@param sampleIndexFilename: A C{str} filename to write a sample index
file to. Lines in the file will have an integer index, a space, and
then the sample name.
@param pathogenIndexFilename: A C{str} filename to write a pathogen
index file to. Lines in the file will have an integer index, a
space, and then the pathogen name.
@return: An HTML C{str} suitable for printing.
"""
if pathogenType not in ('bacterial', 'viral'):
raise ValueError(
"Unrecognized pathogenType argument: %r. Value must be either "
"'bacterial' or 'viral'." % pathogenType)
highlightSymbol = '★'
self._computeUniqueReadCounts()
if pathogenPanelFilename:
self.pathogenPanel(pathogenPanelFilename)
if sampleIndexFilename:
with open(sampleIndexFilename, 'w') as fp:
self.pathogenSampleFiles.writeSampleIndex(fp)
if pathogenIndexFilename:
with open(pathogenIndexFilename, 'w') as fp:
self.pathogenSampleFiles.writePathogenIndex(fp)
toDelete = defaultdict(list)
for pathogenName in self.pathogenNames:
proteinCount = self._pathogenProteinCount[pathogenName]
for s in self.pathogenNames[pathogenName]:
if proteinCount:
sampleProteinFraction = (
len(self.pathogenNames[pathogenName][s]['proteins']) /
proteinCount)
else:
sampleProteinFraction = 1.0
if sampleProteinFraction < minProteinFraction:
toDelete[pathogenName].append(s)
for pathogenName in toDelete:
for sample in toDelete[pathogenName]:
del self.pathogenNames[pathogenName][sample]
pathogenNames = sorted(
pathogenName for pathogenName in self.pathogenNames
if len(self.pathogenNames[pathogenName]) > 0)
nPathogenNames = len(pathogenNames)
sampleNames = sorted(self.sampleNames)
result = [
'<html>',
'<head>',
'<title>',
'Summary of pathogens',
'</title>',
'<meta charset="UTF-8">',
'</head>',
'<body>',
'<style>',
'''\
body {
margin-left: 2%;
margin-right: 2%;
}
hr {
display: block;
margin-top: 0.5em;
margin-bottom: 0.5em;
margin-left: auto;
margin-right: auto;
border-style: inset;
border-width: 1px;
}
p.pathogen {
margin-top: 10px;
margin-bottom: 3px;
}
p.sample {
margin-top: 10px;
margin-bottom: 3px;
}
.significant {
color: red;
margin-right: 2px;
}
.sample {
margin-top: 5px;
margin-bottom: 2px;
}
ul {
margin-bottom: 2px;
}
.indented {
margin-left: 2em;
}
.sample-name {
font-size: 125%;
font-weight: bold;
}
.pathogen-name {
font-size: 125%;
font-weight: bold;
}
.index-name {
font-weight: bold;
}
.index {
font-size: small;
}
.protein-name {
font-family: "Courier New", Courier, monospace;
}
.stats {
font-family: "Courier New", Courier, monospace;
white-space: pre;
}
.protein-list {
margin-top: 2px;
}''',
'</style>',
'</head>',
'<body>',
]
proteinFieldsDescription = [
'<p>',
'In all bullet point protein lists below, there are the following '
'fields:',
'<ol>',
'<li>Coverage fraction.</li>',
'<li>Median bit score.</li>',
'<li>Best bit score.</li>',
'<li>Read count.</li>',
'<li>HSP count (a read can match a protein more than once).</li>',
'<li>Protein length (in AAs).</li>',
'<li>Index (just ignore this).</li>',
]
if self._saveReadLengths:
proteinFieldsDescription.append(
'<li>All read lengths (in parentheses).</li>')
proteinFieldsDescription.extend([
'<li>Protein name.</li>',
'</ol>',
'</p>',
])
append = result.append
append('<h1>Summary of pathogens</h1>')
append('<p>')
append(self._title())
if self._pathogenProteinCount:
percent = minProteinFraction * 100.0
if nPathogenNames < len(self.pathogenNames):
if nPathogenNames == 1:
append('Pathogen protein fraction filtering has been '
'applied, so information on only 1 pathogen is '
'displayed. This is the only pathogen for which at '
'least one sample matches at least %.2f%% of the '
'pathogen proteins.' % percent)
else:
append('Pathogen protein fraction filtering has been '
'applied, so information on only %d pathogens is '
'displayed. These are the only pathogens for which '
'at least one sample matches at least %.2f%% of '
'the pathogen proteins.' % (nPathogenNames,
percent))
else:
append('Pathogen protein fraction filtering has been applied, '
'but all pathogens have at least %.2f%% of their '
'proteins matched by at least one sample.' % percent)
append('Samples that match a pathogen (and pathogens with a '
'matching sample) with at least this protein fraction are '
'highlighted using <span class="significant">%s</span>.' %
highlightSymbol)
append('</p>')
if pathogenPanelFilename:
append('<p>')
append('<a href="%s">Panel showing read count per pathogen, per '
'sample.</a>' % pathogenPanelFilename)
append('Red vertical bars indicate samples with an unusually high '
'read count.')
append('</p>')
result.extend(proteinFieldsDescription)
# Write a linked table of contents by pathogen.
append('<p><span class="index-name">Pathogen index:</span>')
append('<span class="index">')
for pathogenName in pathogenNames:
append('<a href="#pathogen-%s">%s</a>' % (pathogenName,
pathogenName))
append('·')
# Get rid of final middle dot and add a period.
result.pop()
result[-1] += '.'
append('</span></p>')
# Write a linked table of contents by sample.
append('<p><span class="index-name">Sample index:</span>')
append('<span class="index">')
for sampleName in sampleNames:
append('<a href="#sample-%s">%s</a>' % (sampleName, sampleName))
append('·')
# Get rid of final middle dot and add a period.
result.pop()
result[-1] += '.'
append('</span></p>')
# Write all pathogens (with samples (with proteins)).
append('<hr>')
append('<h1>Pathogens by sample</h1>')
for pathogenName in pathogenNames:
samples = self.pathogenNames[pathogenName]
sampleCount = len(samples)
pathogenProteinCount = self._pathogenProteinCount[pathogenName]
if pathogenType == 'viral':
pathogenNameHTML = '<a href="%s%s">%s</a>' % (
self.VIRALZONE, quote(pathogenName), pathogenName)
else:
pathogenNameHTML = pathogenName
append(
'<a id="pathogen-%s"></a>'
'<p class="pathogen"><span class="pathogen-name">%s</span>'
'%s, was matched by %d sample%s:</p>' %
(pathogenName, pathogenNameHTML,
((' (with %d protein%s)' %
(pathogenProteinCount,
'' if pathogenProteinCount == 1 else 's'))
if pathogenProteinCount else ''),
sampleCount,
'' if sampleCount == 1 else 's'))
for sampleName in sorted(samples):
readsFileName = self.pathogenSampleFiles.lookup(
pathogenName, sampleName)
proteins = samples[sampleName]['proteins']
proteinCount = len(proteins)
uniqueReadCount = samples[sampleName]['uniqueReadCount']
if pathogenProteinCount and (
proteinCount / pathogenProteinCount >=
minProteinFraction):
highlight = ('<span class="significant">%s</span>' %
highlightSymbol)
else:
highlight = ''
append(
'<p class="sample indented">'
'%sSample <a href="#sample-%s">%s</a> '
'(%d protein%s, <a href="%s">%d de-duplicated (by id) '
'read%s</a>, <a href="%s">panel</a>):</p>' %
(highlight, sampleName, sampleName,
proteinCount, '' if proteinCount == 1 else 's',
readsFileName,
uniqueReadCount, '' if uniqueReadCount == 1 else 's',
self.sampleNames[sampleName]))
append('<ul class="protein-list indented">')
for proteinName in sorted(proteins):
proteinMatch = proteins[proteinName]
append(
'<li>'
'<span class="stats">'
'%(coverage).2f %(medianScore)6.2f %(bestScore)6.2f '
'%(readCount)5d %(hspCount)5d %(proteinLength)4d '
'%(index)3d '
% proteinMatch
)
if self._saveReadLengths:
append('(%s) ' % ', '.join(
map(str, sorted(proteinMatch['readLengths']))))
append(
'</span> '
'<span class="protein-name">'
'%(proteinName)s'
'</span> '
'(<a href="%(bluePlotFilename)s">blue plot</a>, '
'<a href="%(readsFilename)s">reads</a>'
% proteinMatch)
if proteinMatch['proteinURL']:
# Append this directly to the last string in result, to
# avoid introducing whitespace when we join result
# using '\n'.
result[-1] += (', <a href="%s">NCBI</a>' %
proteinMatch['proteinURL'])
result[-1] += ')'
append('</li>')
append('</ul>')
# Write all samples (with pathogens (with proteins)).
append('<hr>')
append('<h1>Samples by pathogen</h1>')
for sampleName in sampleNames:
samplePathogenNames = [
pathName for pathName in self.pathogenNames
if sampleName in self.pathogenNames[pathName]]
append(
'<a id="sample-%s"></a>'
'<p class="sample">Sample <span class="sample-name">%s</span> '
'matched proteins from %d pathogen%s, '
'<a href="%s">panel</a>:</p>' %
(sampleName, sampleName, len(samplePathogenNames),
'' if len(samplePathogenNames) == 1 else 's',
self.sampleNames[sampleName]))
for pathogenName in sorted(samplePathogenNames):
readsFileName = self.pathogenSampleFiles.lookup(pathogenName,
sampleName)
proteins = self.pathogenNames[pathogenName][sampleName][
'proteins']
uniqueReadCount = self.pathogenNames[
pathogenName][sampleName]['uniqueReadCount']
proteinCount = len(proteins)
pathogenProteinCount = self._pathogenProteinCount[pathogenName]
highlight = ''
if pathogenProteinCount:
proteinCountStr = '%d/%d protein%s' % (
proteinCount, pathogenProteinCount,
'' if pathogenProteinCount == 1 else 's')
if (proteinCount / pathogenProteinCount >=
minProteinFraction):
highlight = ('<span class="significant">%s</span>' %
highlightSymbol)
else:
proteinCountStr = '%d protein%s' % (
proteinCount, '' if proteinCount == 1 else 's')
append(
'<p class="sample indented">'
'%s<a href="#pathogen-%s">%s</a> %s, '
'<a href="%s">%d de-duplicated (by id) read%s</a>:</p>' %
(highlight, pathogenName, pathogenName,
proteinCountStr, readsFileName,
uniqueReadCount, '' if uniqueReadCount == 1 else 's'))
append('<ul class="protein-list indented">')
for proteinName in sorted(proteins):
proteinMatch = proteins[proteinName]
append(
'<li>'
'<span class="stats">'
'%(coverage).2f %(medianScore)6.2f %(bestScore)6.2f '
'%(readCount)5d %(hspCount)5d %(proteinLength)4d '
'%(index)3d '
'</span> '
'<span class="protein-name">'
'%(proteinName)s'
'</span> '
'(<a href="%(bluePlotFilename)s">blue plot</a>, '
'<a href="%(readsFilename)s">reads</a>'
% proteinMatch)
if proteinMatch['proteinURL']:
# Append this directly to the last string in result, to
# avoid introducing whitespace when we join result
# using '\n'.
result[-1] += (', <a href="%s">NCBI</a>' %
proteinMatch['proteinURL'])
result[-1] += ')'
append('</li>')
append('</ul>')
append('</body>')
append('</html>')
return '\n'.join(result) | python | def toHTML(self, pathogenPanelFilename=None, minProteinFraction=0.0,
pathogenType='viral', sampleIndexFilename=None,
pathogenIndexFilename=None):
"""
Produce an HTML string representation of the pathogen summary.
@param pathogenPanelFilename: If not C{None}, a C{str} filename to
write a pathogen panel PNG image to.
@param minProteinFraction: The C{float} minimum fraction of proteins
in a pathogen that must be matched by a sample in order for that
pathogen to be displayed for that sample.
@param pathogenType: A C{str} giving the type of the pathogen involved,
either 'bacterial' or 'viral'.
@param sampleIndexFilename: A C{str} filename to write a sample index
file to. Lines in the file will have an integer index, a space, and
then the sample name.
@param pathogenIndexFilename: A C{str} filename to write a pathogen
index file to. Lines in the file will have an integer index, a
space, and then the pathogen name.
@return: An HTML C{str} suitable for printing.
"""
if pathogenType not in ('bacterial', 'viral'):
raise ValueError(
"Unrecognized pathogenType argument: %r. Value must be either "
"'bacterial' or 'viral'." % pathogenType)
highlightSymbol = '★'
self._computeUniqueReadCounts()
if pathogenPanelFilename:
self.pathogenPanel(pathogenPanelFilename)
if sampleIndexFilename:
with open(sampleIndexFilename, 'w') as fp:
self.pathogenSampleFiles.writeSampleIndex(fp)
if pathogenIndexFilename:
with open(pathogenIndexFilename, 'w') as fp:
self.pathogenSampleFiles.writePathogenIndex(fp)
toDelete = defaultdict(list)
for pathogenName in self.pathogenNames:
proteinCount = self._pathogenProteinCount[pathogenName]
for s in self.pathogenNames[pathogenName]:
if proteinCount:
sampleProteinFraction = (
len(self.pathogenNames[pathogenName][s]['proteins']) /
proteinCount)
else:
sampleProteinFraction = 1.0
if sampleProteinFraction < minProteinFraction:
toDelete[pathogenName].append(s)
for pathogenName in toDelete:
for sample in toDelete[pathogenName]:
del self.pathogenNames[pathogenName][sample]
pathogenNames = sorted(
pathogenName for pathogenName in self.pathogenNames
if len(self.pathogenNames[pathogenName]) > 0)
nPathogenNames = len(pathogenNames)
sampleNames = sorted(self.sampleNames)
result = [
'<html>',
'<head>',
'<title>',
'Summary of pathogens',
'</title>',
'<meta charset="UTF-8">',
'</head>',
'<body>',
'<style>',
'''\
body {
margin-left: 2%;
margin-right: 2%;
}
hr {
display: block;
margin-top: 0.5em;
margin-bottom: 0.5em;
margin-left: auto;
margin-right: auto;
border-style: inset;
border-width: 1px;
}
p.pathogen {
margin-top: 10px;
margin-bottom: 3px;
}
p.sample {
margin-top: 10px;
margin-bottom: 3px;
}
.significant {
color: red;
margin-right: 2px;
}
.sample {
margin-top: 5px;
margin-bottom: 2px;
}
ul {
margin-bottom: 2px;
}
.indented {
margin-left: 2em;
}
.sample-name {
font-size: 125%;
font-weight: bold;
}
.pathogen-name {
font-size: 125%;
font-weight: bold;
}
.index-name {
font-weight: bold;
}
.index {
font-size: small;
}
.protein-name {
font-family: "Courier New", Courier, monospace;
}
.stats {
font-family: "Courier New", Courier, monospace;
white-space: pre;
}
.protein-list {
margin-top: 2px;
}''',
'</style>',
'</head>',
'<body>',
]
proteinFieldsDescription = [
'<p>',
'In all bullet point protein lists below, there are the following '
'fields:',
'<ol>',
'<li>Coverage fraction.</li>',
'<li>Median bit score.</li>',
'<li>Best bit score.</li>',
'<li>Read count.</li>',
'<li>HSP count (a read can match a protein more than once).</li>',
'<li>Protein length (in AAs).</li>',
'<li>Index (just ignore this).</li>',
]
if self._saveReadLengths:
proteinFieldsDescription.append(
'<li>All read lengths (in parentheses).</li>')
proteinFieldsDescription.extend([
'<li>Protein name.</li>',
'</ol>',
'</p>',
])
append = result.append
append('<h1>Summary of pathogens</h1>')
append('<p>')
append(self._title())
if self._pathogenProteinCount:
percent = minProteinFraction * 100.0
if nPathogenNames < len(self.pathogenNames):
if nPathogenNames == 1:
append('Pathogen protein fraction filtering has been '
'applied, so information on only 1 pathogen is '
'displayed. This is the only pathogen for which at '
'least one sample matches at least %.2f%% of the '
'pathogen proteins.' % percent)
else:
append('Pathogen protein fraction filtering has been '
'applied, so information on only %d pathogens is '
'displayed. These are the only pathogens for which '
'at least one sample matches at least %.2f%% of '
'the pathogen proteins.' % (nPathogenNames,
percent))
else:
append('Pathogen protein fraction filtering has been applied, '
'but all pathogens have at least %.2f%% of their '
'proteins matched by at least one sample.' % percent)
append('Samples that match a pathogen (and pathogens with a '
'matching sample) with at least this protein fraction are '
'highlighted using <span class="significant">%s</span>.' %
highlightSymbol)
append('</p>')
if pathogenPanelFilename:
append('<p>')
append('<a href="%s">Panel showing read count per pathogen, per '
'sample.</a>' % pathogenPanelFilename)
append('Red vertical bars indicate samples with an unusually high '
'read count.')
append('</p>')
result.extend(proteinFieldsDescription)
# Write a linked table of contents by pathogen.
append('<p><span class="index-name">Pathogen index:</span>')
append('<span class="index">')
for pathogenName in pathogenNames:
append('<a href="#pathogen-%s">%s</a>' % (pathogenName,
pathogenName))
append('·')
# Get rid of final middle dot and add a period.
result.pop()
result[-1] += '.'
append('</span></p>')
# Write a linked table of contents by sample.
append('<p><span class="index-name">Sample index:</span>')
append('<span class="index">')
for sampleName in sampleNames:
append('<a href="#sample-%s">%s</a>' % (sampleName, sampleName))
append('·')
# Get rid of final middle dot and add a period.
result.pop()
result[-1] += '.'
append('</span></p>')
# Write all pathogens (with samples (with proteins)).
append('<hr>')
append('<h1>Pathogens by sample</h1>')
for pathogenName in pathogenNames:
samples = self.pathogenNames[pathogenName]
sampleCount = len(samples)
pathogenProteinCount = self._pathogenProteinCount[pathogenName]
if pathogenType == 'viral':
pathogenNameHTML = '<a href="%s%s">%s</a>' % (
self.VIRALZONE, quote(pathogenName), pathogenName)
else:
pathogenNameHTML = pathogenName
append(
'<a id="pathogen-%s"></a>'
'<p class="pathogen"><span class="pathogen-name">%s</span>'
'%s, was matched by %d sample%s:</p>' %
(pathogenName, pathogenNameHTML,
((' (with %d protein%s)' %
(pathogenProteinCount,
'' if pathogenProteinCount == 1 else 's'))
if pathogenProteinCount else ''),
sampleCount,
'' if sampleCount == 1 else 's'))
for sampleName in sorted(samples):
readsFileName = self.pathogenSampleFiles.lookup(
pathogenName, sampleName)
proteins = samples[sampleName]['proteins']
proteinCount = len(proteins)
uniqueReadCount = samples[sampleName]['uniqueReadCount']
if pathogenProteinCount and (
proteinCount / pathogenProteinCount >=
minProteinFraction):
highlight = ('<span class="significant">%s</span>' %
highlightSymbol)
else:
highlight = ''
append(
'<p class="sample indented">'
'%sSample <a href="#sample-%s">%s</a> '
'(%d protein%s, <a href="%s">%d de-duplicated (by id) '
'read%s</a>, <a href="%s">panel</a>):</p>' %
(highlight, sampleName, sampleName,
proteinCount, '' if proteinCount == 1 else 's',
readsFileName,
uniqueReadCount, '' if uniqueReadCount == 1 else 's',
self.sampleNames[sampleName]))
append('<ul class="protein-list indented">')
for proteinName in sorted(proteins):
proteinMatch = proteins[proteinName]
append(
'<li>'
'<span class="stats">'
'%(coverage).2f %(medianScore)6.2f %(bestScore)6.2f '
'%(readCount)5d %(hspCount)5d %(proteinLength)4d '
'%(index)3d '
% proteinMatch
)
if self._saveReadLengths:
append('(%s) ' % ', '.join(
map(str, sorted(proteinMatch['readLengths']))))
append(
'</span> '
'<span class="protein-name">'
'%(proteinName)s'
'</span> '
'(<a href="%(bluePlotFilename)s">blue plot</a>, '
'<a href="%(readsFilename)s">reads</a>'
% proteinMatch)
if proteinMatch['proteinURL']:
# Append this directly to the last string in result, to
# avoid introducing whitespace when we join result
# using '\n'.
result[-1] += (', <a href="%s">NCBI</a>' %
proteinMatch['proteinURL'])
result[-1] += ')'
append('</li>')
append('</ul>')
# Write all samples (with pathogens (with proteins)).
append('<hr>')
append('<h1>Samples by pathogen</h1>')
for sampleName in sampleNames:
samplePathogenNames = [
pathName for pathName in self.pathogenNames
if sampleName in self.pathogenNames[pathName]]
append(
'<a id="sample-%s"></a>'
'<p class="sample">Sample <span class="sample-name">%s</span> '
'matched proteins from %d pathogen%s, '
'<a href="%s">panel</a>:</p>' %
(sampleName, sampleName, len(samplePathogenNames),
'' if len(samplePathogenNames) == 1 else 's',
self.sampleNames[sampleName]))
for pathogenName in sorted(samplePathogenNames):
readsFileName = self.pathogenSampleFiles.lookup(pathogenName,
sampleName)
proteins = self.pathogenNames[pathogenName][sampleName][
'proteins']
uniqueReadCount = self.pathogenNames[
pathogenName][sampleName]['uniqueReadCount']
proteinCount = len(proteins)
pathogenProteinCount = self._pathogenProteinCount[pathogenName]
highlight = ''
if pathogenProteinCount:
proteinCountStr = '%d/%d protein%s' % (
proteinCount, pathogenProteinCount,
'' if pathogenProteinCount == 1 else 's')
if (proteinCount / pathogenProteinCount >=
minProteinFraction):
highlight = ('<span class="significant">%s</span>' %
highlightSymbol)
else:
proteinCountStr = '%d protein%s' % (
proteinCount, '' if proteinCount == 1 else 's')
append(
'<p class="sample indented">'
'%s<a href="#pathogen-%s">%s</a> %s, '
'<a href="%s">%d de-duplicated (by id) read%s</a>:</p>' %
(highlight, pathogenName, pathogenName,
proteinCountStr, readsFileName,
uniqueReadCount, '' if uniqueReadCount == 1 else 's'))
append('<ul class="protein-list indented">')
for proteinName in sorted(proteins):
proteinMatch = proteins[proteinName]
append(
'<li>'
'<span class="stats">'
'%(coverage).2f %(medianScore)6.2f %(bestScore)6.2f '
'%(readCount)5d %(hspCount)5d %(proteinLength)4d '
'%(index)3d '
'</span> '
'<span class="protein-name">'
'%(proteinName)s'
'</span> '
'(<a href="%(bluePlotFilename)s">blue plot</a>, '
'<a href="%(readsFilename)s">reads</a>'
% proteinMatch)
if proteinMatch['proteinURL']:
# Append this directly to the last string in result, to
# avoid introducing whitespace when we join result
# using '\n'.
result[-1] += (', <a href="%s">NCBI</a>' %
proteinMatch['proteinURL'])
result[-1] += ')'
append('</li>')
append('</ul>')
append('</body>')
append('</html>')
return '\n'.join(result) | [
"def",
"toHTML",
"(",
"self",
",",
"pathogenPanelFilename",
"=",
"None",
",",
"minProteinFraction",
"=",
"0.0",
",",
"pathogenType",
"=",
"'viral'",
",",
"sampleIndexFilename",
"=",
"None",
",",
"pathogenIndexFilename",
"=",
"None",
")",
":",
"if",
"pathogenType... | Produce an HTML string representation of the pathogen summary.
@param pathogenPanelFilename: If not C{None}, a C{str} filename to
write a pathogen panel PNG image to.
@param minProteinFraction: The C{float} minimum fraction of proteins
in a pathogen that must be matched by a sample in order for that
pathogen to be displayed for that sample.
@param pathogenType: A C{str} giving the type of the pathogen involved,
either 'bacterial' or 'viral'.
@param sampleIndexFilename: A C{str} filename to write a sample index
file to. Lines in the file will have an integer index, a space, and
then the sample name.
@param pathogenIndexFilename: A C{str} filename to write a pathogen
index file to. Lines in the file will have an integer index, a
space, and then the pathogen name.
@return: An HTML C{str} suitable for printing. | [
"Produce",
"an",
"HTML",
"string",
"representation",
"of",
"the",
"pathogen",
"summary",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L382-L776 |
acorg/dark-matter | dark/proteins.py | ProteinGrouper._pathogenSamplePlot | def _pathogenSamplePlot(self, pathogenName, sampleNames, ax):
"""
Make an image of a graph giving pathogen read count (Y axis) versus
sample id (X axis).
@param pathogenName: A C{str} pathogen name.
@param sampleNames: A sorted C{list} of sample names.
@param ax: A matplotlib C{axes} instance.
"""
readCounts = []
for i, sampleName in enumerate(sampleNames):
try:
readCount = self.pathogenNames[pathogenName][sampleName][
'uniqueReadCount']
except KeyError:
readCount = 0
readCounts.append(readCount)
highlight = 'r'
normal = 'gray'
sdMultiple = 2.5
minReadsForHighlighting = 10
highlighted = []
if len(readCounts) == 1:
if readCounts[0] > minReadsForHighlighting:
color = [highlight]
highlighted.append(sampleNames[0])
else:
color = [normal]
else:
mean = np.mean(readCounts)
sd = np.std(readCounts)
color = []
for readCount, sampleName in zip(readCounts, sampleNames):
if (readCount > (sdMultiple * sd) + mean and
readCount >= minReadsForHighlighting):
color.append(highlight)
highlighted.append(sampleName)
else:
color.append(normal)
nSamples = len(sampleNames)
x = np.arange(nSamples)
yMin = np.zeros(nSamples)
ax.set_xticks([])
ax.set_xlim((-0.5, nSamples - 0.5))
ax.vlines(x, yMin, readCounts, color=color)
if highlighted:
title = '%s\nIn red: %s' % (
pathogenName, fill(', '.join(highlighted), 50))
else:
# Add a newline to keep the first line of each title at the
# same place as those titles that have an "In red:" second
# line.
title = pathogenName + '\n'
ax.set_title(title, fontsize=10)
ax.tick_params(axis='both', which='major', labelsize=8)
ax.tick_params(axis='both', which='minor', labelsize=6) | python | def _pathogenSamplePlot(self, pathogenName, sampleNames, ax):
"""
Make an image of a graph giving pathogen read count (Y axis) versus
sample id (X axis).
@param pathogenName: A C{str} pathogen name.
@param sampleNames: A sorted C{list} of sample names.
@param ax: A matplotlib C{axes} instance.
"""
readCounts = []
for i, sampleName in enumerate(sampleNames):
try:
readCount = self.pathogenNames[pathogenName][sampleName][
'uniqueReadCount']
except KeyError:
readCount = 0
readCounts.append(readCount)
highlight = 'r'
normal = 'gray'
sdMultiple = 2.5
minReadsForHighlighting = 10
highlighted = []
if len(readCounts) == 1:
if readCounts[0] > minReadsForHighlighting:
color = [highlight]
highlighted.append(sampleNames[0])
else:
color = [normal]
else:
mean = np.mean(readCounts)
sd = np.std(readCounts)
color = []
for readCount, sampleName in zip(readCounts, sampleNames):
if (readCount > (sdMultiple * sd) + mean and
readCount >= minReadsForHighlighting):
color.append(highlight)
highlighted.append(sampleName)
else:
color.append(normal)
nSamples = len(sampleNames)
x = np.arange(nSamples)
yMin = np.zeros(nSamples)
ax.set_xticks([])
ax.set_xlim((-0.5, nSamples - 0.5))
ax.vlines(x, yMin, readCounts, color=color)
if highlighted:
title = '%s\nIn red: %s' % (
pathogenName, fill(', '.join(highlighted), 50))
else:
# Add a newline to keep the first line of each title at the
# same place as those titles that have an "In red:" second
# line.
title = pathogenName + '\n'
ax.set_title(title, fontsize=10)
ax.tick_params(axis='both', which='major', labelsize=8)
ax.tick_params(axis='both', which='minor', labelsize=6) | [
"def",
"_pathogenSamplePlot",
"(",
"self",
",",
"pathogenName",
",",
"sampleNames",
",",
"ax",
")",
":",
"readCounts",
"=",
"[",
"]",
"for",
"i",
",",
"sampleName",
"in",
"enumerate",
"(",
"sampleNames",
")",
":",
"try",
":",
"readCount",
"=",
"self",
".... | Make an image of a graph giving pathogen read count (Y axis) versus
sample id (X axis).
@param pathogenName: A C{str} pathogen name.
@param sampleNames: A sorted C{list} of sample names.
@param ax: A matplotlib C{axes} instance. | [
"Make",
"an",
"image",
"of",
"a",
"graph",
"giving",
"pathogen",
"read",
"count",
"(",
"Y",
"axis",
")",
"versus",
"sample",
"id",
"(",
"X",
"axis",
")",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L778-L837 |
acorg/dark-matter | dark/proteins.py | ProteinGrouper.pathogenPanel | def pathogenPanel(self, filename):
"""
Make a panel of images, with each image being a graph giving pathogen
de-duplicated (by id) read count (Y axis) versus sample id (X axis).
@param filename: A C{str} file name to write the image to.
"""
import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
self._computeUniqueReadCounts()
pathogenNames = sorted(self.pathogenNames)
sampleNames = sorted(self.sampleNames)
cols = 5
rows = int(len(pathogenNames) / cols) + (
0 if len(pathogenNames) % cols == 0 else 1)
figure, ax = plt.subplots(rows, cols, squeeze=False)
coords = dimensionalIterator((rows, cols))
for i, pathogenName in enumerate(pathogenNames):
row, col = next(coords)
self._pathogenSamplePlot(pathogenName, sampleNames, ax[row][col])
# Hide the final panel graphs (if any) that have no content. We do
# this because the panel is a rectangular grid and some of the
# plots at the end of the last row may be unused.
for row, col in coords:
ax[row][col].axis('off')
figure.suptitle(
('Per-sample read count for %d pathogen%s and %d sample%s.\n\n'
'Sample name%s: %s') % (
len(pathogenNames),
'' if len(pathogenNames) == 1 else 's',
len(sampleNames),
'' if len(sampleNames) == 1 else 's',
'' if len(sampleNames) == 1 else 's',
fill(', '.join(sampleNames), 50)),
fontsize=20)
figure.set_size_inches(5.0 * cols, 2.0 * rows, forward=True)
plt.subplots_adjust(hspace=0.4)
figure.savefig(filename) | python | def pathogenPanel(self, filename):
"""
Make a panel of images, with each image being a graph giving pathogen
de-duplicated (by id) read count (Y axis) versus sample id (X axis).
@param filename: A C{str} file name to write the image to.
"""
import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
self._computeUniqueReadCounts()
pathogenNames = sorted(self.pathogenNames)
sampleNames = sorted(self.sampleNames)
cols = 5
rows = int(len(pathogenNames) / cols) + (
0 if len(pathogenNames) % cols == 0 else 1)
figure, ax = plt.subplots(rows, cols, squeeze=False)
coords = dimensionalIterator((rows, cols))
for i, pathogenName in enumerate(pathogenNames):
row, col = next(coords)
self._pathogenSamplePlot(pathogenName, sampleNames, ax[row][col])
# Hide the final panel graphs (if any) that have no content. We do
# this because the panel is a rectangular grid and some of the
# plots at the end of the last row may be unused.
for row, col in coords:
ax[row][col].axis('off')
figure.suptitle(
('Per-sample read count for %d pathogen%s and %d sample%s.\n\n'
'Sample name%s: %s') % (
len(pathogenNames),
'' if len(pathogenNames) == 1 else 's',
len(sampleNames),
'' if len(sampleNames) == 1 else 's',
'' if len(sampleNames) == 1 else 's',
fill(', '.join(sampleNames), 50)),
fontsize=20)
figure.set_size_inches(5.0 * cols, 2.0 * rows, forward=True)
plt.subplots_adjust(hspace=0.4)
figure.savefig(filename) | [
"def",
"pathogenPanel",
"(",
"self",
",",
"filename",
")",
":",
"import",
"matplotlib",
"matplotlib",
".",
"use",
"(",
"'PDF'",
")",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"self",
".",
"_computeUniqueReadCounts",
"(",
")",
"pathogenNames",
"=",
... | Make a panel of images, with each image being a graph giving pathogen
de-duplicated (by id) read count (Y axis) versus sample id (X axis).
@param filename: A C{str} file name to write the image to. | [
"Make",
"a",
"panel",
"of",
"images",
"with",
"each",
"image",
"being",
"a",
"graph",
"giving",
"pathogen",
"de",
"-",
"duplicated",
"(",
"by",
"id",
")",
"read",
"count",
"(",
"Y",
"axis",
")",
"versus",
"sample",
"id",
"(",
"X",
"axis",
")",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/proteins.py#L839-L884 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | get_args | def get_args(request_args, allowed_int_args=[], allowed_str_args=[]):
"""Check allowed argument names and return is as dictionary"""
args = {}
for allowed_int_arg in allowed_int_args:
int_value = request_args.get(allowed_int_arg, default=None, type=None)
if int_value:
args[allowed_int_arg] = int(int_value)
for allowed_str_arg in allowed_str_args:
str_value = request_args.get(allowed_str_arg, default=None, type=None)
if str_value:
args[allowed_str_arg] = str_value
return args | python | def get_args(request_args, allowed_int_args=[], allowed_str_args=[]):
"""Check allowed argument names and return is as dictionary"""
args = {}
for allowed_int_arg in allowed_int_args:
int_value = request_args.get(allowed_int_arg, default=None, type=None)
if int_value:
args[allowed_int_arg] = int(int_value)
for allowed_str_arg in allowed_str_args:
str_value = request_args.get(allowed_str_arg, default=None, type=None)
if str_value:
args[allowed_str_arg] = str_value
return args | [
"def",
"get_args",
"(",
"request_args",
",",
"allowed_int_args",
"=",
"[",
"]",
",",
"allowed_str_args",
"=",
"[",
"]",
")",
":",
"args",
"=",
"{",
"}",
"for",
"allowed_int_arg",
"in",
"allowed_int_args",
":",
"int_value",
"=",
"request_args",
".",
"get",
... | Check allowed argument names and return is as dictionary | [
"Check",
"allowed",
"argument",
"names",
"and",
"return",
"is",
"as",
"dictionary"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L31-L45 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_disease | def query_disease():
"""
Returns list of diseases by query parameters
---
tags:
- Query functions
parameters:
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: DI-03832
- name: ref_id
in: query
type: string
required: false
description: reference identifier
default: 104300
- name: ref_type
in: query
type: string
required: false
description: Reference type
default: MIM
- name: name
in: query
type: string
required: false
description: Disease name
default: Alzheimer disease
- name: acronym
in: query
type: string
required: false
description: Disease acronym
default: AD
- name: description
in: query
type: string
required: false
description: Description of disease
default: '%neurodegenerative disorder%'
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
allowed_str_args = ['identifier', 'ref_id', 'ref_type', 'name', 'acronym', 'description']
args = get_args(
request_args=request.args,
allowed_str_args=allowed_str_args
)
return jsonify(query.disease(**args)) | python | def query_disease():
"""
Returns list of diseases by query parameters
---
tags:
- Query functions
parameters:
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: DI-03832
- name: ref_id
in: query
type: string
required: false
description: reference identifier
default: 104300
- name: ref_type
in: query
type: string
required: false
description: Reference type
default: MIM
- name: name
in: query
type: string
required: false
description: Disease name
default: Alzheimer disease
- name: acronym
in: query
type: string
required: false
description: Disease acronym
default: AD
- name: description
in: query
type: string
required: false
description: Description of disease
default: '%neurodegenerative disorder%'
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
allowed_str_args = ['identifier', 'ref_id', 'ref_type', 'name', 'acronym', 'description']
args = get_args(
request_args=request.args,
allowed_str_args=allowed_str_args
)
return jsonify(query.disease(**args)) | [
"def",
"query_disease",
"(",
")",
":",
"allowed_str_args",
"=",
"[",
"'identifier'",
",",
"'ref_id'",
",",
"'ref_type'",
",",
"'name'",
",",
"'acronym'",
",",
"'description'",
"]",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",... | Returns list of diseases by query parameters
---
tags:
- Query functions
parameters:
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: DI-03832
- name: ref_id
in: query
type: string
required: false
description: reference identifier
default: 104300
- name: ref_type
in: query
type: string
required: false
description: Reference type
default: MIM
- name: name
in: query
type: string
required: false
description: Disease name
default: Alzheimer disease
- name: acronym
in: query
type: string
required: false
description: Disease acronym
default: AD
- name: description
in: query
type: string
required: false
description: Description of disease
default: '%neurodegenerative disorder%'
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"diseases",
"by",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L364-L431 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_alternative_full_name | def query_alternative_full_name():
"""
Returns list of alternative full name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative full name
default: 'Alzheimer disease amyloid protein'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.alternative_full_name(**args)) | python | def query_alternative_full_name():
"""
Returns list of alternative full name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative full name
default: 'Alzheimer disease amyloid protein'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.alternative_full_name(**args)) | [
"def",
"query_alternative_full_name",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'name'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
"re... | Returns list of alternative full name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative full name
default: 'Alzheimer disease amyloid protein'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"alternative",
"full",
"name",
"by",
"query",
"query",
"parameters",
"---",
"tags",
":"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L435-L473 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_alternative_short_name | def query_alternative_short_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.alternative_short_name(**args)) | python | def query_alternative_short_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.alternative_short_name(**args)) | [
"def",
"query_alternative_short_name",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'name'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
"r... | Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"alternative",
"short",
"name",
"by",
"query",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L477-L516 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_other_gene_name | def query_other_gene_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: name
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.other_gene_name(**args)) | python | def query_other_gene_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: name
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.other_gene_name(**args)) | [
"def",
"query_other_gene_name",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'name'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
"return",... | Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: name
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"alternative",
"short",
"name",
"by",
"query",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L520-L566 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_accession | def query_accession():
"""
Returns list of accession numbers by query query parameters
---
tags:
- Query functions
parameters:
- name: accession
in: query
type: string
required: false
description: UniProt accession number
default: P05067
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['accession', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.accession(**args)) | python | def query_accession():
"""
Returns list of accession numbers by query query parameters
---
tags:
- Query functions
parameters:
- name: accession
in: query
type: string
required: false
description: UniProt accession number
default: P05067
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['accession', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.accession(**args)) | [
"def",
"query_accession",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'accession'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
"return",
... | Returns list of accession numbers by query query parameters
---
tags:
- Query functions
parameters:
- name: accession
in: query
type: string
required: false
description: UniProt accession number
default: P05067
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"accession",
"numbers",
"by",
"query",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L570-L609 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_pmid | def query_pmid():
"""
Returns list of PubMed identifier by query parameters
---
tags:
- Query functions
parameters:
- name: pmid
in: query
type: string
required: false
description: PubMed identifier
default: 20697050
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: first
in: query
type: string
required: false
description: first page
default: 987
- name: last
in: query
type: string
required: false
description: last page
default: 995
- name: volume
in: query
type: string
required: false
description: Volume
default: 67
- name: name
in: query
type: string
required: false
description: Name of journal
default: 'Arch. Neurol.'
- name: date
in: query
type: string
required: false
description: Publication date
default: 2010
- name: title
in: query
type: string
required: false
description: Title of publication
default: '%amyloidosis%'
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['first', 'last', 'volume', 'name', 'date', 'title', 'entry_name'],
allowed_int_args=['pmid', 'limit']
)
return jsonify(query.pmid(**args)) | python | def query_pmid():
"""
Returns list of PubMed identifier by query parameters
---
tags:
- Query functions
parameters:
- name: pmid
in: query
type: string
required: false
description: PubMed identifier
default: 20697050
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: first
in: query
type: string
required: false
description: first page
default: 987
- name: last
in: query
type: string
required: false
description: last page
default: 995
- name: volume
in: query
type: string
required: false
description: Volume
default: 67
- name: name
in: query
type: string
required: false
description: Name of journal
default: 'Arch. Neurol.'
- name: date
in: query
type: string
required: false
description: Publication date
default: 2010
- name: title
in: query
type: string
required: false
description: Title of publication
default: '%amyloidosis%'
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['first', 'last', 'volume', 'name', 'date', 'title', 'entry_name'],
allowed_int_args=['pmid', 'limit']
)
return jsonify(query.pmid(**args)) | [
"def",
"query_pmid",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'first'",
",",
"'last'",
",",
"'volume'",
",",
"'name'",
",",
"'date'",
",",
"'title'",
",",
"'entry_name'",
... | Returns list of PubMed identifier by query parameters
---
tags:
- Query functions
parameters:
- name: pmid
in: query
type: string
required: false
description: PubMed identifier
default: 20697050
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: first
in: query
type: string
required: false
description: first page
default: 987
- name: last
in: query
type: string
required: false
description: last page
default: 995
- name: volume
in: query
type: string
required: false
description: Volume
default: 67
- name: name
in: query
type: string
required: false
description: Name of journal
default: 'Arch. Neurol.'
- name: date
in: query
type: string
required: false
description: Publication date
default: 2010
- name: title
in: query
type: string
required: false
description: Title of publication
default: '%amyloidosis%'
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"PubMed",
"identifier",
"by",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L613-L693 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_organism_host | def query_organism_host():
"""
Returns list of host organism by query parameters
---
tags:
- Query functions
parameters:
- name: taxid
in: query
type: integer
required: false
description: NCBI taxonomy identifier
default: 9606
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['entry_name'],
allowed_int_args=['taxid', 'limit']
)
return jsonify(query.organism_host(**args)) | python | def query_organism_host():
"""
Returns list of host organism by query parameters
---
tags:
- Query functions
parameters:
- name: taxid
in: query
type: integer
required: false
description: NCBI taxonomy identifier
default: 9606
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['entry_name'],
allowed_int_args=['taxid', 'limit']
)
return jsonify(query.organism_host(**args)) | [
"def",
"query_organism_host",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'taxid'",
",",
"'limit'",
"]",
")",
"return",
... | Returns list of host organism by query parameters
---
tags:
- Query functions
parameters:
- name: taxid
in: query
type: integer
required: false
description: NCBI taxonomy identifier
default: 9606
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"host",
"organism",
"by",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L697-L735 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_db_reference | def query_db_reference():
"""
Returns list of cross references by query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Reference type
default: EMBL
- name: identifier
in: query
type: string
required: false
description: reference identifier
default: Y00264
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['type_', 'identifier', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.db_reference(**args)) | python | def query_db_reference():
"""
Returns list of cross references by query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Reference type
default: EMBL
- name: identifier
in: query
type: string
required: false
description: reference identifier
default: Y00264
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['type_', 'identifier', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.db_reference(**args)) | [
"def",
"query_db_reference",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'type_'",
",",
"'identifier'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
... | Returns list of cross references by query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Reference type
default: EMBL
- name: identifier
in: query
type: string
required: false
description: reference identifier
default: Y00264
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"cross",
"references",
"by",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L739-L784 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_feature | def query_feature():
"""
Returns list of sequence feature by query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Feature type
default: 'splice variant'
- name: identifier
in: query
type: string
required: false
description: Feature identifier
default: VSP_045447
- name: description
in: query
type: string
required: false
description: Feature description
default: 'In isoform 11.'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['type_', 'identifier', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.feature(**args)) | python | def query_feature():
"""
Returns list of sequence feature by query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Feature type
default: 'splice variant'
- name: identifier
in: query
type: string
required: false
description: Feature identifier
default: VSP_045447
- name: description
in: query
type: string
required: false
description: Feature description
default: 'In isoform 11.'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['type_', 'identifier', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.feature(**args)) | [
"def",
"query_feature",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'type_'",
",",
"'identifier'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
... | Returns list of sequence feature by query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Feature type
default: 'splice variant'
- name: identifier
in: query
type: string
required: false
description: Feature identifier
default: VSP_045447
- name: description
in: query
type: string
required: false
description: Feature description
default: 'In isoform 11.'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"sequence",
"feature",
"by",
"query",
"parameters",
"---",
"tags",
":"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L788-L839 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_function | def query_function():
"""
Returns list of functions by query parameters
---
tags:
- Query functions
parameters:
- name: text
in: query
type: string
required: false
description: Text describing protein function
default: '%axonogenesis%'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['text', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.function(**args)) | python | def query_function():
"""
Returns list of functions by query parameters
---
tags:
- Query functions
parameters:
- name: text
in: query
type: string
required: false
description: Text describing protein function
default: '%axonogenesis%'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['text', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.function(**args)) | [
"def",
"query_function",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'text'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
"return",
"jso... | Returns list of functions by query parameters
---
tags:
- Query functions
parameters:
- name: text
in: query
type: string
required: false
description: Text describing protein function
default: '%axonogenesis%'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"functions",
"by",
"query",
"parameters",
"---",
"tags",
":"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L843-L880 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_keyword | def query_keyword():
"""
Returns list of keywords linked to entries by query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Disease identifier
default: 'Ubl conjugation'
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: KW-0832
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'identifier', 'entry_name'],
allowed_int_args=['limit']
)
print(args)
return jsonify(query.keyword(**args)) | python | def query_keyword():
"""
Returns list of keywords linked to entries by query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Disease identifier
default: 'Ubl conjugation'
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: KW-0832
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'identifier', 'entry_name'],
allowed_int_args=['limit']
)
print(args)
return jsonify(query.keyword(**args)) | [
"def",
"query_keyword",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'name'",
",",
"'identifier'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
... | Returns list of keywords linked to entries by query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Disease identifier
default: 'Ubl conjugation'
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: KW-0832
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"keywords",
"linked",
"to",
"entries",
"by",
"query",
"parameters",
"---",
"tags",
":"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L884-L930 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_ec_number | def query_ec_number():
"""
Returns list of Enzyme Commission Numbers (EC numbers) by query parameters
---
tags:
- Query functions
parameters:
- name: ec_number
in: query
type: string
required: false
description: Enzyme Commission Number
default: '1.1.1.1'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: ADHX_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['ec_number', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.ec_number(**args)) | python | def query_ec_number():
"""
Returns list of Enzyme Commission Numbers (EC numbers) by query parameters
---
tags:
- Query functions
parameters:
- name: ec_number
in: query
type: string
required: false
description: Enzyme Commission Number
default: '1.1.1.1'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: ADHX_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['ec_number', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.ec_number(**args)) | [
"def",
"query_ec_number",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'ec_number'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
"return",
... | Returns list of Enzyme Commission Numbers (EC numbers) by query parameters
---
tags:
- Query functions
parameters:
- name: ec_number
in: query
type: string
required: false
description: Enzyme Commission Number
default: '1.1.1.1'
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: ADHX_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"Enzyme",
"Commission",
"Numbers",
"(",
"EC",
"numbers",
")",
"by",
"query",
"parameters",
"---",
"tags",
":"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L934-L970 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_subcellular_location | def query_subcellular_location():
"""
Returns list of subcellular locations by query parameters
---
tags:
- Query functions
parameters:
- name: location
in: query
type: string
required: false
description: Subcellular location
default: 'Clathrin-coated pit'
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['location', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.subcellular_location(**args)) | python | def query_subcellular_location():
"""
Returns list of subcellular locations by query parameters
---
tags:
- Query functions
parameters:
- name: location
in: query
type: string
required: false
description: Subcellular location
default: 'Clathrin-coated pit'
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['location', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.subcellular_location(**args)) | [
"def",
"query_subcellular_location",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'location'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
... | Returns list of subcellular locations by query parameters
---
tags:
- Query functions
parameters:
- name: location
in: query
type: string
required: false
description: Subcellular location
default: 'Clathrin-coated pit'
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"subcellular",
"locations",
"by",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L974-L1011 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_tissue_specificity | def query_tissue_specificity():
"""
Returns list of tissue specificity by query parameters
---
tags:
- Query functions
parameters:
- name: comment
in: query
type: string
required: false
description: Comment to tissue specificity
default: '%APP695%'
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['comment', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.tissue_specificity(**args)) | python | def query_tissue_specificity():
"""
Returns list of tissue specificity by query parameters
---
tags:
- Query functions
parameters:
- name: comment
in: query
type: string
required: false
description: Comment to tissue specificity
default: '%APP695%'
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['comment', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.tissue_specificity(**args)) | [
"def",
"query_tissue_specificity",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'comment'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
"re... | Returns list of tissue specificity by query parameters
---
tags:
- Query functions
parameters:
- name: comment
in: query
type: string
required: false
description: Comment to tissue specificity
default: '%APP695%'
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"tissue",
"specificity",
"by",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L1015-L1053 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_tissue_in_reference | def query_tissue_in_reference():
"""
Returns list of tissues linked to references by query parameters
---
tags:
- Query functions
parameters:
- name: tissue
in: query
type: string
required: false
description: Tissue
default: brain
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 1
"""
args = get_args(
request_args=request.args,
allowed_str_args=['tissue', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.tissue_in_reference(**args)) | python | def query_tissue_in_reference():
"""
Returns list of tissues linked to references by query parameters
---
tags:
- Query functions
parameters:
- name: tissue
in: query
type: string
required: false
description: Tissue
default: brain
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 1
"""
args = get_args(
request_args=request.args,
allowed_str_args=['tissue', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.tissue_in_reference(**args)) | [
"def",
"query_tissue_in_reference",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'tissue'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
"re... | Returns list of tissues linked to references by query parameters
---
tags:
- Query functions
parameters:
- name: tissue
in: query
type: string
required: false
description: Tissue
default: brain
- name: entry_name
in: query
type: string
required: false
description: UniProt entry name
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 1 | [
"Returns",
"list",
"of",
"tissues",
"linked",
"to",
"references",
"by",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L1057-L1094 |
cebel/pyuniprot | src/pyuniprot/webserver/web.py | query_disease_comment | def query_disease_comment():
"""
Returns list of diseases comments by query parameters
---
tags:
- Query functions
parameters:
- name: comment
in: query
type: string
required: false
description: Comment on disease linked to UniProt entry
default: '%mutations%'
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['comment', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.disease_comment(**args)) | python | def query_disease_comment():
"""
Returns list of diseases comments by query parameters
---
tags:
- Query functions
parameters:
- name: comment
in: query
type: string
required: false
description: Comment on disease linked to UniProt entry
default: '%mutations%'
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10
"""
args = get_args(
request_args=request.args,
allowed_str_args=['comment', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.disease_comment(**args)) | [
"def",
"query_disease_comment",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'comment'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
"retur... | Returns list of diseases comments by query parameters
---
tags:
- Query functions
parameters:
- name: comment
in: query
type: string
required: false
description: Comment on disease linked to UniProt entry
default: '%mutations%'
- name: entry_name
in: query
type: string
required: false
description: reference identifier
default: A4_HUMAN
- name: limit
in: query
type: integer
required: false
description: limit of results numbers
default: 10 | [
"Returns",
"list",
"of",
"diseases",
"comments",
"by",
"query",
"parameters",
"---"
] | train | https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/webserver/web.py#L1098-L1135 |
acorg/dark-matter | dark/fasta_ss.py | SSFastaReads.iter | def iter(self):
"""
Iterate over the sequences in self.file_, yielding each as an
instance of the desired read class.
@raise ValueError: If the input file has an odd number of records or
if any sequence has a different length than its predicted
secondary structure.
"""
upperCase = self._upperCase
for _file in self._files:
with asHandle(_file) as fp:
records = SeqIO.parse(fp, 'fasta')
while True:
try:
record = next(records)
except StopIteration:
break
try:
structureRecord = next(records)
except StopIteration:
raise ValueError('Structure file %r has an odd number '
'of records.' % _file)
if len(structureRecord) != len(record):
raise ValueError(
'Sequence %r length (%d) is not equal to '
'structure %r length (%d) in input file %r.' % (
record.description, len(record),
structureRecord.description,
len(structureRecord), _file))
if upperCase:
read = self._readClass(
record.description,
str(record.seq.upper()),
str(structureRecord.seq.upper()))
else:
read = self._readClass(record.description,
str(record.seq),
str(structureRecord.seq))
yield read | python | def iter(self):
"""
Iterate over the sequences in self.file_, yielding each as an
instance of the desired read class.
@raise ValueError: If the input file has an odd number of records or
if any sequence has a different length than its predicted
secondary structure.
"""
upperCase = self._upperCase
for _file in self._files:
with asHandle(_file) as fp:
records = SeqIO.parse(fp, 'fasta')
while True:
try:
record = next(records)
except StopIteration:
break
try:
structureRecord = next(records)
except StopIteration:
raise ValueError('Structure file %r has an odd number '
'of records.' % _file)
if len(structureRecord) != len(record):
raise ValueError(
'Sequence %r length (%d) is not equal to '
'structure %r length (%d) in input file %r.' % (
record.description, len(record),
structureRecord.description,
len(structureRecord), _file))
if upperCase:
read = self._readClass(
record.description,
str(record.seq.upper()),
str(structureRecord.seq.upper()))
else:
read = self._readClass(record.description,
str(record.seq),
str(structureRecord.seq))
yield read | [
"def",
"iter",
"(",
"self",
")",
":",
"upperCase",
"=",
"self",
".",
"_upperCase",
"for",
"_file",
"in",
"self",
".",
"_files",
":",
"with",
"asHandle",
"(",
"_file",
")",
"as",
"fp",
":",
"records",
"=",
"SeqIO",
".",
"parse",
"(",
"fp",
",",
"'fa... | Iterate over the sequences in self.file_, yielding each as an
instance of the desired read class.
@raise ValueError: If the input file has an odd number of records or
if any sequence has a different length than its predicted
secondary structure. | [
"Iterate",
"over",
"the",
"sequences",
"in",
"self",
".",
"file_",
"yielding",
"each",
"as",
"an",
"instance",
"of",
"the",
"desired",
"read",
"class",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/fasta_ss.py#L43-L85 |
Snaipe/python-rst2ansi | rst2ansi/functional.py | npartial | def npartial(func, *args, **kwargs):
"""
Returns a partial node visitor function
"""
def wrapped(self, node):
func(self, *args, **kwargs)
return wrapped | python | def npartial(func, *args, **kwargs):
"""
Returns a partial node visitor function
"""
def wrapped(self, node):
func(self, *args, **kwargs)
return wrapped | [
"def",
"npartial",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrapped",
"(",
"self",
",",
"node",
")",
":",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped"
] | Returns a partial node visitor function | [
"Returns",
"a",
"partial",
"node",
"visitor",
"function"
] | train | https://github.com/Snaipe/python-rst2ansi/blob/1b1b963804bcc87a7187d07c3943585d9385ea92/rst2ansi/functional.py#L26-L32 |
biocommons/bioutils | src/bioutils/sequences.py | aa3_to_aa1 | def aa3_to_aa1(seq):
"""convert string of 3-letter amino acids to 1-letter amino acids
>>> aa3_to_aa1("CysAlaThrSerAlaArgGluLeuAlaMetGlu")
'CATSARELAME'
>>> aa3_to_aa1(None)
"""
if seq is None:
return None
return "".join(aa3_to_aa1_lut[aa3]
for aa3 in [seq[i:i + 3] for i in range(0, len(seq), 3)]) | python | def aa3_to_aa1(seq):
"""convert string of 3-letter amino acids to 1-letter amino acids
>>> aa3_to_aa1("CysAlaThrSerAlaArgGluLeuAlaMetGlu")
'CATSARELAME'
>>> aa3_to_aa1(None)
"""
if seq is None:
return None
return "".join(aa3_to_aa1_lut[aa3]
for aa3 in [seq[i:i + 3] for i in range(0, len(seq), 3)]) | [
"def",
"aa3_to_aa1",
"(",
"seq",
")",
":",
"if",
"seq",
"is",
"None",
":",
"return",
"None",
"return",
"\"\"",
".",
"join",
"(",
"aa3_to_aa1_lut",
"[",
"aa3",
"]",
"for",
"aa3",
"in",
"[",
"seq",
"[",
"i",
":",
"i",
"+",
"3",
"]",
"for",
"i",
"... | convert string of 3-letter amino acids to 1-letter amino acids
>>> aa3_to_aa1("CysAlaThrSerAlaArgGluLeuAlaMetGlu")
'CATSARELAME'
>>> aa3_to_aa1(None) | [
"convert",
"string",
"of",
"3",
"-",
"letter",
"amino",
"acids",
"to",
"1",
"-",
"letter",
"amino",
"acids"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/sequences.py#L158-L170 |
biocommons/bioutils | src/bioutils/sequences.py | elide_sequence | def elide_sequence(s, flank=5, elision="..."):
"""trim a sequence to include the left and right flanking sequences of
size `flank`, with the intervening sequence elided by `elision`.
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
'ABCDE...VWXYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=3)
'ABC...XYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", elision="..")
'ABCDE..VWXYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=12)
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=12, elision=".")
'ABCDEFGHIJKL.OPQRSTUVWXYZ'
"""
elided_sequence_len = flank + flank + len(elision)
if len(s) <= elided_sequence_len:
return s
return s[:flank] + elision + s[-flank:] | python | def elide_sequence(s, flank=5, elision="..."):
"""trim a sequence to include the left and right flanking sequences of
size `flank`, with the intervening sequence elided by `elision`.
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
'ABCDE...VWXYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=3)
'ABC...XYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", elision="..")
'ABCDE..VWXYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=12)
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=12, elision=".")
'ABCDEFGHIJKL.OPQRSTUVWXYZ'
"""
elided_sequence_len = flank + flank + len(elision)
if len(s) <= elided_sequence_len:
return s
return s[:flank] + elision + s[-flank:] | [
"def",
"elide_sequence",
"(",
"s",
",",
"flank",
"=",
"5",
",",
"elision",
"=",
"\"...\"",
")",
":",
"elided_sequence_len",
"=",
"flank",
"+",
"flank",
"+",
"len",
"(",
"elision",
")",
"if",
"len",
"(",
"s",
")",
"<=",
"elided_sequence_len",
":",
"retu... | trim a sequence to include the left and right flanking sequences of
size `flank`, with the intervening sequence elided by `elision`.
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
'ABCDE...VWXYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=3)
'ABC...XYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", elision="..")
'ABCDE..VWXYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=12)
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=12, elision=".")
'ABCDEFGHIJKL.OPQRSTUVWXYZ' | [
"trim",
"a",
"sequence",
"to",
"include",
"the",
"left",
"and",
"right",
"flanking",
"sequences",
"of",
"size",
"flank",
"with",
"the",
"intervening",
"sequence",
"elided",
"by",
"elision",
"."
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/sequences.py#L188-L212 |
biocommons/bioutils | src/bioutils/sequences.py | normalize_sequence | def normalize_sequence(seq):
"""return normalized representation of sequence for hashing
This really means ensuring that the sequence is represented as a
binary blob and removing whitespace and asterisks and uppercasing.
>>> normalize_sequence("ACGT")
'ACGT'
>>> normalize_sequence(" A C G T * ")
'ACGT'
>>> normalize_sequence("ACGT1")
Traceback (most recent call last):
...
RuntimeError: Normalized sequence contains non-alphabetic characters
"""
nseq = re.sub(r"[\s\*]", "", seq).upper()
m = re.search("[^A-Z]", nseq)
if m:
_logger.debug("Original sequence: " + seq)
_logger.debug("Normalized sequence: " + nseq)
_logger.debug("First non-[A-Z] at {}".format(m.start()))
raise RuntimeError("Normalized sequence contains non-alphabetic characters")
return nseq | python | def normalize_sequence(seq):
"""return normalized representation of sequence for hashing
This really means ensuring that the sequence is represented as a
binary blob and removing whitespace and asterisks and uppercasing.
>>> normalize_sequence("ACGT")
'ACGT'
>>> normalize_sequence(" A C G T * ")
'ACGT'
>>> normalize_sequence("ACGT1")
Traceback (most recent call last):
...
RuntimeError: Normalized sequence contains non-alphabetic characters
"""
nseq = re.sub(r"[\s\*]", "", seq).upper()
m = re.search("[^A-Z]", nseq)
if m:
_logger.debug("Original sequence: " + seq)
_logger.debug("Normalized sequence: " + nseq)
_logger.debug("First non-[A-Z] at {}".format(m.start()))
raise RuntimeError("Normalized sequence contains non-alphabetic characters")
return nseq | [
"def",
"normalize_sequence",
"(",
"seq",
")",
":",
"nseq",
"=",
"re",
".",
"sub",
"(",
"r\"[\\s\\*]\"",
",",
"\"\"",
",",
"seq",
")",
".",
"upper",
"(",
")",
"m",
"=",
"re",
".",
"search",
"(",
"\"[^A-Z]\"",
",",
"nseq",
")",
"if",
"m",
":",
"_lo... | return normalized representation of sequence for hashing
This really means ensuring that the sequence is represented as a
binary blob and removing whitespace and asterisks and uppercasing.
>>> normalize_sequence("ACGT")
'ACGT'
>>> normalize_sequence(" A C G T * ")
'ACGT'
>>> normalize_sequence("ACGT1")
Traceback (most recent call last):
...
RuntimeError: Normalized sequence contains non-alphabetic characters | [
"return",
"normalized",
"representation",
"of",
"sequence",
"for",
"hashing"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/sequences.py#L221-L247 |
biocommons/bioutils | src/bioutils/sequences.py | translate_cds | def translate_cds(seq, full_codons=True, ter_symbol="*"):
"""translate a DNA or RNA sequence into a single-letter amino acid sequence
using the standard translation table
If full_codons is True, a sequence whose length isn't a multiple of three
generates a ValueError; else an 'X' will be added as the last amino acid.
This matches biopython's behaviour when padding the last codon with 'N's.
>>> translate_cds("ATGCGA")
'MR'
>>> translate_cds("AUGCGA")
'MR'
>>> translate_cds(None)
>>> translate_cds("")
''
>>> translate_cds("AUGCG")
Traceback (most recent call last):
...
ValueError: Sequence length must be a multiple of three
>>> translate_cds("AUGCG", full_codons=False)
'M*'
>>> translate_cds("AUGCGQ")
Traceback (most recent call last):
...
ValueError: Codon CGQ at position 4..6 is undefined in codon table
"""
if seq is None:
return None
if len(seq) == 0:
return ""
if full_codons and len(seq) % 3 != 0:
raise ValueError("Sequence length must be a multiple of three")
seq = replace_u_to_t(seq)
seq = seq.upper()
protein_seq = list()
for i in range(0, len(seq) - len(seq) % 3, 3):
try:
aa = dna_to_aa1_lut[seq[i:i + 3]]
except KeyError:
raise ValueError("Codon {} at position {}..{} is undefined in codon table".format(
seq[i:i + 3], i+1, i+3))
protein_seq.append(aa)
# check for trailing bases and add the ter symbol if required
if not full_codons and len(seq) % 3 != 0:
protein_seq.append(ter_symbol)
return ''.join(protein_seq) | python | def translate_cds(seq, full_codons=True, ter_symbol="*"):
"""translate a DNA or RNA sequence into a single-letter amino acid sequence
using the standard translation table
If full_codons is True, a sequence whose length isn't a multiple of three
generates a ValueError; else an 'X' will be added as the last amino acid.
This matches biopython's behaviour when padding the last codon with 'N's.
>>> translate_cds("ATGCGA")
'MR'
>>> translate_cds("AUGCGA")
'MR'
>>> translate_cds(None)
>>> translate_cds("")
''
>>> translate_cds("AUGCG")
Traceback (most recent call last):
...
ValueError: Sequence length must be a multiple of three
>>> translate_cds("AUGCG", full_codons=False)
'M*'
>>> translate_cds("AUGCGQ")
Traceback (most recent call last):
...
ValueError: Codon CGQ at position 4..6 is undefined in codon table
"""
if seq is None:
return None
if len(seq) == 0:
return ""
if full_codons and len(seq) % 3 != 0:
raise ValueError("Sequence length must be a multiple of three")
seq = replace_u_to_t(seq)
seq = seq.upper()
protein_seq = list()
for i in range(0, len(seq) - len(seq) % 3, 3):
try:
aa = dna_to_aa1_lut[seq[i:i + 3]]
except KeyError:
raise ValueError("Codon {} at position {}..{} is undefined in codon table".format(
seq[i:i + 3], i+1, i+3))
protein_seq.append(aa)
# check for trailing bases and add the ter symbol if required
if not full_codons and len(seq) % 3 != 0:
protein_seq.append(ter_symbol)
return ''.join(protein_seq) | [
"def",
"translate_cds",
"(",
"seq",
",",
"full_codons",
"=",
"True",
",",
"ter_symbol",
"=",
"\"*\"",
")",
":",
"if",
"seq",
"is",
"None",
":",
"return",
"None",
"if",
"len",
"(",
"seq",
")",
"==",
"0",
":",
"return",
"\"\"",
"if",
"full_codons",
"an... | translate a DNA or RNA sequence into a single-letter amino acid sequence
using the standard translation table
If full_codons is True, a sequence whose length isn't a multiple of three
generates a ValueError; else an 'X' will be added as the last amino acid.
This matches biopython's behaviour when padding the last codon with 'N's.
>>> translate_cds("ATGCGA")
'MR'
>>> translate_cds("AUGCGA")
'MR'
>>> translate_cds(None)
>>> translate_cds("")
''
>>> translate_cds("AUGCG")
Traceback (most recent call last):
...
ValueError: Sequence length must be a multiple of three
>>> translate_cds("AUGCG", full_codons=False)
'M*'
>>> translate_cds("AUGCGQ")
Traceback (most recent call last):
...
ValueError: Codon CGQ at position 4..6 is undefined in codon table | [
"translate",
"a",
"DNA",
"or",
"RNA",
"sequence",
"into",
"a",
"single",
"-",
"letter",
"amino",
"acid",
"sequence",
"using",
"the",
"standard",
"translation",
"table"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/sequences.py#L290-L349 |
vovanec/httputil | httputil/request_engines/base.py | BaseRequestEngine.request | def request(self, url, *,
method='GET', headers=None, data=None, result_callback=None):
"""Perform request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: request data.
:param object -> object result_callback: result callback.
:rtype: dict
:raise: APIError
"""
url = self._make_full_url(url)
self._log.debug('Performing %s request to %s', method, url)
return self._request(url, method=method, headers=headers, data=data,
result_callback=result_callback) | python | def request(self, url, *,
method='GET', headers=None, data=None, result_callback=None):
"""Perform request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: request data.
:param object -> object result_callback: result callback.
:rtype: dict
:raise: APIError
"""
url = self._make_full_url(url)
self._log.debug('Performing %s request to %s', method, url)
return self._request(url, method=method, headers=headers, data=data,
result_callback=result_callback) | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"*",
",",
"method",
"=",
"'GET'",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
",",
"result_callback",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_make_full_url",
"(",
"url",
")",
"sel... | Perform request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: request data.
:param object -> object result_callback: result callback.
:rtype: dict
:raise: APIError | [
"Perform",
"request",
"."
] | train | https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/request_engines/base.py#L47-L65 |
vovanec/httputil | httputil/request_engines/base.py | BaseRequestEngine._make_full_url | def _make_full_url(self, url):
"""Given base and relative URL, construct the full URL.
:param str url: relative URL.
:return: full URL.
:rtype: str
"""
return SLASH.join([self._api_base_url, url.lstrip(SLASH)]) | python | def _make_full_url(self, url):
"""Given base and relative URL, construct the full URL.
:param str url: relative URL.
:return: full URL.
:rtype: str
"""
return SLASH.join([self._api_base_url, url.lstrip(SLASH)]) | [
"def",
"_make_full_url",
"(",
"self",
",",
"url",
")",
":",
"return",
"SLASH",
".",
"join",
"(",
"[",
"self",
".",
"_api_base_url",
",",
"url",
".",
"lstrip",
"(",
"SLASH",
")",
"]",
")"
] | Given base and relative URL, construct the full URL.
:param str url: relative URL.
:return: full URL.
:rtype: str | [
"Given",
"base",
"and",
"relative",
"URL",
"construct",
"the",
"full",
"URL",
"."
] | train | https://github.com/vovanec/httputil/blob/0b8dab5a23166cceb7dbc2a1dbc802ab5b311347/httputil/request_engines/base.py#L84-L93 |
mikebryant/django-autoconfig | django_autoconfig/autoconfig.py | merge_dictionaries | def merge_dictionaries(current, new, only_defaults=False, template_special_case=False):
'''
Merge two settings dictionaries, recording how many changes were needed.
'''
changes = 0
for key, value in new.items():
if key not in current:
if hasattr(global_settings, key):
current[key] = getattr(global_settings, key)
LOGGER.debug("Set %r to global default %r.", key, current[key])
else:
current[key] = copy.copy(value)
LOGGER.debug("Set %r to %r.", key, current[key])
changes += 1
continue
elif only_defaults:
continue
current_value = current[key]
if hasattr(current_value, 'items'):
changes += merge_dictionaries(current_value, value)
elif isinstance(current_value, (list, tuple)):
for element in value:
if element not in current_value:
if template_special_case and key == 'TEMPLATES':
existing_matches = [
template for template in current_value if template['BACKEND'] == element['BACKEND']
]
if existing_matches:
changes += merge_dictionaries(existing_matches[0], element)
else:
current[key] = list(current_value) + [element]
LOGGER.debug("Added %r to %r.", element, key)
changes += 1
else:
current[key] = list(current_value) + [element]
LOGGER.debug("Added %r to %r.", element, key)
changes += 1
elif isinstance(current_value, Promise) or isinstance(value, Promise):
# If we don't know what to do with it, replace it.
if current_value is not value:
current[key] = value
LOGGER.debug("Set %r to %r.", key, current[key])
changes += 1
else:
# If we don't know what to do with it, replace it.
if current_value != value:
current[key] = value
LOGGER.debug("Set %r to %r.", key, current[key])
changes += 1
return changes | python | def merge_dictionaries(current, new, only_defaults=False, template_special_case=False):
'''
Merge two settings dictionaries, recording how many changes were needed.
'''
changes = 0
for key, value in new.items():
if key not in current:
if hasattr(global_settings, key):
current[key] = getattr(global_settings, key)
LOGGER.debug("Set %r to global default %r.", key, current[key])
else:
current[key] = copy.copy(value)
LOGGER.debug("Set %r to %r.", key, current[key])
changes += 1
continue
elif only_defaults:
continue
current_value = current[key]
if hasattr(current_value, 'items'):
changes += merge_dictionaries(current_value, value)
elif isinstance(current_value, (list, tuple)):
for element in value:
if element not in current_value:
if template_special_case and key == 'TEMPLATES':
existing_matches = [
template for template in current_value if template['BACKEND'] == element['BACKEND']
]
if existing_matches:
changes += merge_dictionaries(existing_matches[0], element)
else:
current[key] = list(current_value) + [element]
LOGGER.debug("Added %r to %r.", element, key)
changes += 1
else:
current[key] = list(current_value) + [element]
LOGGER.debug("Added %r to %r.", element, key)
changes += 1
elif isinstance(current_value, Promise) or isinstance(value, Promise):
# If we don't know what to do with it, replace it.
if current_value is not value:
current[key] = value
LOGGER.debug("Set %r to %r.", key, current[key])
changes += 1
else:
# If we don't know what to do with it, replace it.
if current_value != value:
current[key] = value
LOGGER.debug("Set %r to %r.", key, current[key])
changes += 1
return changes | [
"def",
"merge_dictionaries",
"(",
"current",
",",
"new",
",",
"only_defaults",
"=",
"False",
",",
"template_special_case",
"=",
"False",
")",
":",
"changes",
"=",
"0",
"for",
"key",
",",
"value",
"in",
"new",
".",
"items",
"(",
")",
":",
"if",
"key",
"... | Merge two settings dictionaries, recording how many changes were needed. | [
"Merge",
"two",
"settings",
"dictionaries",
"recording",
"how",
"many",
"changes",
"were",
"needed",
"."
] | train | https://github.com/mikebryant/django-autoconfig/blob/1ce793e95b024dccb189de1dc111dc4ae6c2f3a6/django_autoconfig/autoconfig.py#L94-L144 |
mikebryant/django-autoconfig | django_autoconfig/autoconfig.py | configure_settings | def configure_settings(settings, environment_settings=True):
'''
Given a settings object, run automatic configuration of all
the apps in INSTALLED_APPS.
'''
changes = 1
iterations = 0
while changes:
changes = 0
app_names = ['django_autoconfig'] + list(settings['INSTALLED_APPS'])
if environment_settings:
app_names.append('django_autoconfig.environment_settings')
for app_name in app_names:
import django_autoconfig.contrib
if autoconfig_module_exists(app_name):
module = importlib.import_module("%s.autoconfig" % (app_name,))
elif app_name in django_autoconfig.contrib.CONTRIB_CONFIGS:
module = django_autoconfig.contrib.CONTRIB_CONFIGS[app_name]
else:
continue
changes += merge_dictionaries(
settings,
getattr(module, 'SETTINGS', {}),
template_special_case=True,
)
changes += merge_dictionaries(
settings,
getattr(module, 'DEFAULT_SETTINGS', {}),
only_defaults=True,
)
for relationship in getattr(module, 'RELATIONSHIPS', []):
changes += relationship.apply_changes(settings)
if iterations >= MAX_ITERATIONS:
raise ImproperlyConfigured(
'Autoconfiguration could not reach a consistent state'
)
iterations += 1
LOGGER.debug("Autoconfiguration took %d iterations.", iterations) | python | def configure_settings(settings, environment_settings=True):
'''
Given a settings object, run automatic configuration of all
the apps in INSTALLED_APPS.
'''
changes = 1
iterations = 0
while changes:
changes = 0
app_names = ['django_autoconfig'] + list(settings['INSTALLED_APPS'])
if environment_settings:
app_names.append('django_autoconfig.environment_settings')
for app_name in app_names:
import django_autoconfig.contrib
if autoconfig_module_exists(app_name):
module = importlib.import_module("%s.autoconfig" % (app_name,))
elif app_name in django_autoconfig.contrib.CONTRIB_CONFIGS:
module = django_autoconfig.contrib.CONTRIB_CONFIGS[app_name]
else:
continue
changes += merge_dictionaries(
settings,
getattr(module, 'SETTINGS', {}),
template_special_case=True,
)
changes += merge_dictionaries(
settings,
getattr(module, 'DEFAULT_SETTINGS', {}),
only_defaults=True,
)
for relationship in getattr(module, 'RELATIONSHIPS', []):
changes += relationship.apply_changes(settings)
if iterations >= MAX_ITERATIONS:
raise ImproperlyConfigured(
'Autoconfiguration could not reach a consistent state'
)
iterations += 1
LOGGER.debug("Autoconfiguration took %d iterations.", iterations) | [
"def",
"configure_settings",
"(",
"settings",
",",
"environment_settings",
"=",
"True",
")",
":",
"changes",
"=",
"1",
"iterations",
"=",
"0",
"while",
"changes",
":",
"changes",
"=",
"0",
"app_names",
"=",
"[",
"'django_autoconfig'",
"]",
"+",
"list",
"(",
... | Given a settings object, run automatic configuration of all
the apps in INSTALLED_APPS. | [
"Given",
"a",
"settings",
"object",
"run",
"automatic",
"configuration",
"of",
"all",
"the",
"apps",
"in",
"INSTALLED_APPS",
"."
] | train | https://github.com/mikebryant/django-autoconfig/blob/1ce793e95b024dccb189de1dc111dc4ae6c2f3a6/django_autoconfig/autoconfig.py#L158-L197 |
mikebryant/django-autoconfig | django_autoconfig/autoconfig.py | configure_urls | def configure_urls(apps, index_view=None, prefixes=None):
'''
Configure urls from a list of apps.
'''
prefixes = prefixes or {}
urlpatterns = patterns('')
if index_view:
from django.views.generic.base import RedirectView
urlpatterns += patterns('',
url(r'^$', RedirectView.as_view(pattern_name=index_view, permanent=False)),
)
for app_name in apps:
app_module = importlib.import_module(app_name)
if module_has_submodule(app_module, 'urls'):
module = importlib.import_module("%s.urls" % app_name)
if not hasattr(module, 'urlpatterns'):
# Resolver will break if the urls.py file is completely blank.
continue
app_prefix = prefixes.get(app_name, app_name.replace("_","-"))
urlpatterns += patterns(
'',
url(
r'^%s/' % app_prefix if app_prefix else '',
include("%s.urls" % app_name),
),
)
return urlpatterns | python | def configure_urls(apps, index_view=None, prefixes=None):
'''
Configure urls from a list of apps.
'''
prefixes = prefixes or {}
urlpatterns = patterns('')
if index_view:
from django.views.generic.base import RedirectView
urlpatterns += patterns('',
url(r'^$', RedirectView.as_view(pattern_name=index_view, permanent=False)),
)
for app_name in apps:
app_module = importlib.import_module(app_name)
if module_has_submodule(app_module, 'urls'):
module = importlib.import_module("%s.urls" % app_name)
if not hasattr(module, 'urlpatterns'):
# Resolver will break if the urls.py file is completely blank.
continue
app_prefix = prefixes.get(app_name, app_name.replace("_","-"))
urlpatterns += patterns(
'',
url(
r'^%s/' % app_prefix if app_prefix else '',
include("%s.urls" % app_name),
),
)
return urlpatterns | [
"def",
"configure_urls",
"(",
"apps",
",",
"index_view",
"=",
"None",
",",
"prefixes",
"=",
"None",
")",
":",
"prefixes",
"=",
"prefixes",
"or",
"{",
"}",
"urlpatterns",
"=",
"patterns",
"(",
"''",
")",
"if",
"index_view",
":",
"from",
"django",
".",
"... | Configure urls from a list of apps. | [
"Configure",
"urls",
"from",
"a",
"list",
"of",
"apps",
"."
] | train | https://github.com/mikebryant/django-autoconfig/blob/1ce793e95b024dccb189de1dc111dc4ae6c2f3a6/django_autoconfig/autoconfig.py#L200-L230 |
thunder-project/thunder-registration | registration/utils.py | check_images | def check_images(data):
"""
Check and reformat input images if needed
"""
if isinstance(data, ndarray):
data = fromarray(data)
if not isinstance(data, Images):
data = fromarray(asarray(data))
if len(data.shape) not in set([3, 4]):
raise Exception('Number of image dimensions %s must be 2 or 3' % (len(data.shape)))
return data | python | def check_images(data):
"""
Check and reformat input images if needed
"""
if isinstance(data, ndarray):
data = fromarray(data)
if not isinstance(data, Images):
data = fromarray(asarray(data))
if len(data.shape) not in set([3, 4]):
raise Exception('Number of image dimensions %s must be 2 or 3' % (len(data.shape)))
return data | [
"def",
"check_images",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"ndarray",
")",
":",
"data",
"=",
"fromarray",
"(",
"data",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"Images",
")",
":",
"data",
"=",
"fromarray",
"(",
"asar... | Check and reformat input images if needed | [
"Check",
"and",
"reformat",
"input",
"images",
"if",
"needed"
] | train | https://github.com/thunder-project/thunder-registration/blob/286f091e6c402d592e9686d4821e0fd80dbf86ec/registration/utils.py#L4-L17 |
thunder-project/thunder-registration | registration/utils.py | check_reference | def check_reference(images, reference):
"""
Ensure the reference matches image dimensions
"""
if not images.shape[1:] == reference.shape:
raise Exception('Image shape %s and reference shape %s must match'
% (images.shape[1:], reference.shape))
return reference | python | def check_reference(images, reference):
"""
Ensure the reference matches image dimensions
"""
if not images.shape[1:] == reference.shape:
raise Exception('Image shape %s and reference shape %s must match'
% (images.shape[1:], reference.shape))
return reference | [
"def",
"check_reference",
"(",
"images",
",",
"reference",
")",
":",
"if",
"not",
"images",
".",
"shape",
"[",
"1",
":",
"]",
"==",
"reference",
".",
"shape",
":",
"raise",
"Exception",
"(",
"'Image shape %s and reference shape %s must match'",
"%",
"(",
"imag... | Ensure the reference matches image dimensions | [
"Ensure",
"the",
"reference",
"matches",
"image",
"dimensions"
] | train | https://github.com/thunder-project/thunder-registration/blob/286f091e6c402d592e9686d4821e0fd80dbf86ec/registration/utils.py#L19-L26 |
flo-compbio/genometools | genometools/expression/gene.py | ExpGene.from_dict | def from_dict(cls, data: Dict[str, Union[str, int]]):
"""Generate an `ExpGene` object from a dictionary.
Parameters
----------
data : dict
A dictionary with keys corresponding to attribute names.
Attributes with missing keys will be assigned `None`.
Returns
-------
`ExpGene`
The gene.
"""
assert isinstance(data, dict)
if 'ensembl_id' not in data:
raise ValueError('An "ensembl_id" key is missing!')
# make a copy
data = dict(data)
for attr in ['name', 'chromosome', 'position', 'length',
'type', 'source']:
if attr in data and data[attr] == '':
data[attr] = None
data['type_'] = data['type']
del data['type']
return cls(**data) | python | def from_dict(cls, data: Dict[str, Union[str, int]]):
"""Generate an `ExpGene` object from a dictionary.
Parameters
----------
data : dict
A dictionary with keys corresponding to attribute names.
Attributes with missing keys will be assigned `None`.
Returns
-------
`ExpGene`
The gene.
"""
assert isinstance(data, dict)
if 'ensembl_id' not in data:
raise ValueError('An "ensembl_id" key is missing!')
# make a copy
data = dict(data)
for attr in ['name', 'chromosome', 'position', 'length',
'type', 'source']:
if attr in data and data[attr] == '':
data[attr] = None
data['type_'] = data['type']
del data['type']
return cls(**data) | [
"def",
"from_dict",
"(",
"cls",
",",
"data",
":",
"Dict",
"[",
"str",
",",
"Union",
"[",
"str",
",",
"int",
"]",
"]",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"dict",
")",
"if",
"'ensembl_id'",
"not",
"in",
"data",
":",
"raise",
"ValueEr... | Generate an `ExpGene` object from a dictionary.
Parameters
----------
data : dict
A dictionary with keys corresponding to attribute names.
Attributes with missing keys will be assigned `None`.
Returns
-------
`ExpGene`
The gene. | [
"Generate",
"an",
"ExpGene",
"object",
"from",
"a",
"dictionary",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/gene.py#L156-L186 |
acorg/dark-matter | dark/intervals.py | ReadIntervals.add | def add(self, start, end):
"""
Add the start and end offsets of a matching read.
@param start: The C{int} start offset of the read match in the subject.
@param end: The C{int} end offset of the read match in the subject.
This is Python-style: the end offset is not included in the match.
"""
assert start <= end
self._intervals.append((start, end)) | python | def add(self, start, end):
"""
Add the start and end offsets of a matching read.
@param start: The C{int} start offset of the read match in the subject.
@param end: The C{int} end offset of the read match in the subject.
This is Python-style: the end offset is not included in the match.
"""
assert start <= end
self._intervals.append((start, end)) | [
"def",
"add",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"assert",
"start",
"<=",
"end",
"self",
".",
"_intervals",
".",
"append",
"(",
"(",
"start",
",",
"end",
")",
")"
] | Add the start and end offsets of a matching read.
@param start: The C{int} start offset of the read match in the subject.
@param end: The C{int} end offset of the read match in the subject.
This is Python-style: the end offset is not included in the match. | [
"Add",
"the",
"start",
"and",
"end",
"offsets",
"of",
"a",
"matching",
"read",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/intervals.py#L20-L29 |
acorg/dark-matter | dark/intervals.py | ReadIntervals.walk | def walk(self):
"""
Get the non-overlapping read intervals that match the subject.
@return: A generator that produces (TYPE, (START, END)) tuples, where
where TYPE is either self.EMPTY or self.FULL and (START, STOP) is
the interval. The endpoint (STOP) of the interval is not considered
to be in the interval. I.e., the interval is really [START, STOP).
"""
intervals = sorted(self._intervals)
def nextFull():
start, stop = intervals.pop(0)
while intervals:
if intervals[0][0] <= stop:
_, thisStop = intervals.pop(0)
if thisStop > stop:
stop = thisStop
else:
break
return (start, stop)
if intervals:
# If the first interval (read) starts after zero, yield an
# initial empty section to get us to the first interval.
if intervals[0][0] > 0:
yield (self.EMPTY, (0, intervals[0][0]))
while intervals:
# Yield a full interval followed by an empty one (if there
# is another interval pending).
lastFull = nextFull()
yield (self.FULL, lastFull)
if intervals:
yield (self.EMPTY, (lastFull[1], intervals[0][0]))
# Yield the final empty section, if any.
if lastFull[1] < self._targetLength:
yield (self.EMPTY, (lastFull[1], self._targetLength))
else:
yield (self.EMPTY, (0, self._targetLength)) | python | def walk(self):
"""
Get the non-overlapping read intervals that match the subject.
@return: A generator that produces (TYPE, (START, END)) tuples, where
where TYPE is either self.EMPTY or self.FULL and (START, STOP) is
the interval. The endpoint (STOP) of the interval is not considered
to be in the interval. I.e., the interval is really [START, STOP).
"""
intervals = sorted(self._intervals)
def nextFull():
start, stop = intervals.pop(0)
while intervals:
if intervals[0][0] <= stop:
_, thisStop = intervals.pop(0)
if thisStop > stop:
stop = thisStop
else:
break
return (start, stop)
if intervals:
# If the first interval (read) starts after zero, yield an
# initial empty section to get us to the first interval.
if intervals[0][0] > 0:
yield (self.EMPTY, (0, intervals[0][0]))
while intervals:
# Yield a full interval followed by an empty one (if there
# is another interval pending).
lastFull = nextFull()
yield (self.FULL, lastFull)
if intervals:
yield (self.EMPTY, (lastFull[1], intervals[0][0]))
# Yield the final empty section, if any.
if lastFull[1] < self._targetLength:
yield (self.EMPTY, (lastFull[1], self._targetLength))
else:
yield (self.EMPTY, (0, self._targetLength)) | [
"def",
"walk",
"(",
"self",
")",
":",
"intervals",
"=",
"sorted",
"(",
"self",
".",
"_intervals",
")",
"def",
"nextFull",
"(",
")",
":",
"start",
",",
"stop",
"=",
"intervals",
".",
"pop",
"(",
"0",
")",
"while",
"intervals",
":",
"if",
"intervals",
... | Get the non-overlapping read intervals that match the subject.
@return: A generator that produces (TYPE, (START, END)) tuples, where
where TYPE is either self.EMPTY or self.FULL and (START, STOP) is
the interval. The endpoint (STOP) of the interval is not considered
to be in the interval. I.e., the interval is really [START, STOP). | [
"Get",
"the",
"non",
"-",
"overlapping",
"read",
"intervals",
"that",
"match",
"the",
"subject",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/intervals.py#L31-L72 |
acorg/dark-matter | dark/intervals.py | ReadIntervals.coverage | def coverage(self):
"""
Get the fraction of a subject is matched by its set of reads.
@return: The C{float} fraction of a subject matched by its reads.
"""
if self._targetLength == 0:
return 0.0
coverage = 0
for (intervalType, (start, end)) in self.walk():
if intervalType == self.FULL:
# Adjust start and end to ignore areas where the read falls
# outside the target.
coverage += (min(end, self._targetLength) - max(0, start))
return float(coverage) / self._targetLength | python | def coverage(self):
"""
Get the fraction of a subject is matched by its set of reads.
@return: The C{float} fraction of a subject matched by its reads.
"""
if self._targetLength == 0:
return 0.0
coverage = 0
for (intervalType, (start, end)) in self.walk():
if intervalType == self.FULL:
# Adjust start and end to ignore areas where the read falls
# outside the target.
coverage += (min(end, self._targetLength) - max(0, start))
return float(coverage) / self._targetLength | [
"def",
"coverage",
"(",
"self",
")",
":",
"if",
"self",
".",
"_targetLength",
"==",
"0",
":",
"return",
"0.0",
"coverage",
"=",
"0",
"for",
"(",
"intervalType",
",",
"(",
"start",
",",
"end",
")",
")",
"in",
"self",
".",
"walk",
"(",
")",
":",
"i... | Get the fraction of a subject is matched by its set of reads.
@return: The C{float} fraction of a subject matched by its reads. | [
"Get",
"the",
"fraction",
"of",
"a",
"subject",
"is",
"matched",
"by",
"its",
"set",
"of",
"reads",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/intervals.py#L74-L89 |
acorg/dark-matter | dark/intervals.py | ReadIntervals.coverageCounts | def coverageCounts(self):
"""
For each location in the subject, return a count of how many times that
location is covered by a read.
@return: a C{Counter} where the keys are the C{int} locations on the
subject and the value is the number of times the location is
covered by a read.
"""
coverageCounts = Counter()
for start, end in self._intervals:
coverageCounts.update(range(max(0, start),
min(self._targetLength, end)))
return coverageCounts | python | def coverageCounts(self):
"""
For each location in the subject, return a count of how many times that
location is covered by a read.
@return: a C{Counter} where the keys are the C{int} locations on the
subject and the value is the number of times the location is
covered by a read.
"""
coverageCounts = Counter()
for start, end in self._intervals:
coverageCounts.update(range(max(0, start),
min(self._targetLength, end)))
return coverageCounts | [
"def",
"coverageCounts",
"(",
"self",
")",
":",
"coverageCounts",
"=",
"Counter",
"(",
")",
"for",
"start",
",",
"end",
"in",
"self",
".",
"_intervals",
":",
"coverageCounts",
".",
"update",
"(",
"range",
"(",
"max",
"(",
"0",
",",
"start",
")",
",",
... | For each location in the subject, return a count of how many times that
location is covered by a read.
@return: a C{Counter} where the keys are the C{int} locations on the
subject and the value is the number of times the location is
covered by a read. | [
"For",
"each",
"location",
"in",
"the",
"subject",
"return",
"a",
"count",
"of",
"how",
"many",
"times",
"that",
"location",
"is",
"covered",
"by",
"a",
"read",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/intervals.py#L91-L104 |
acorg/dark-matter | dark/intervals.py | OffsetAdjuster._reductionForOffset | def _reductionForOffset(self, offset):
"""
Calculate the total reduction for a given X axis offset.
@param offset: The C{int} offset.
@return: The total C{float} reduction that should be made for this
offset.
"""
reduction = 0
for (thisOffset, thisReduction) in self._adjustments:
if offset >= thisOffset:
reduction += thisReduction
else:
break
return reduction | python | def _reductionForOffset(self, offset):
"""
Calculate the total reduction for a given X axis offset.
@param offset: The C{int} offset.
@return: The total C{float} reduction that should be made for this
offset.
"""
reduction = 0
for (thisOffset, thisReduction) in self._adjustments:
if offset >= thisOffset:
reduction += thisReduction
else:
break
return reduction | [
"def",
"_reductionForOffset",
"(",
"self",
",",
"offset",
")",
":",
"reduction",
"=",
"0",
"for",
"(",
"thisOffset",
",",
"thisReduction",
")",
"in",
"self",
".",
"_adjustments",
":",
"if",
"offset",
">=",
"thisOffset",
":",
"reduction",
"+=",
"thisReduction... | Calculate the total reduction for a given X axis offset.
@param offset: The C{int} offset.
@return: The total C{float} reduction that should be made for this
offset. | [
"Calculate",
"the",
"total",
"reduction",
"for",
"a",
"given",
"X",
"axis",
"offset",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/intervals.py#L136-L150 |
acorg/dark-matter | dark/intervals.py | OffsetAdjuster.adjustHSP | def adjustHSP(self, hsp):
"""
Adjust the read and subject start and end offsets in an HSP.
@param hsp: a L{dark.hsp.HSP} or L{dark.hsp.LSP} instance.
"""
reduction = self._reductionForOffset(
min(hsp.readStartInSubject, hsp.subjectStart))
hsp.readEndInSubject = hsp.readEndInSubject - reduction
hsp.readStartInSubject = hsp.readStartInSubject - reduction
hsp.subjectEnd = hsp.subjectEnd - reduction
hsp.subjectStart = hsp.subjectStart - reduction | python | def adjustHSP(self, hsp):
"""
Adjust the read and subject start and end offsets in an HSP.
@param hsp: a L{dark.hsp.HSP} or L{dark.hsp.LSP} instance.
"""
reduction = self._reductionForOffset(
min(hsp.readStartInSubject, hsp.subjectStart))
hsp.readEndInSubject = hsp.readEndInSubject - reduction
hsp.readStartInSubject = hsp.readStartInSubject - reduction
hsp.subjectEnd = hsp.subjectEnd - reduction
hsp.subjectStart = hsp.subjectStart - reduction | [
"def",
"adjustHSP",
"(",
"self",
",",
"hsp",
")",
":",
"reduction",
"=",
"self",
".",
"_reductionForOffset",
"(",
"min",
"(",
"hsp",
".",
"readStartInSubject",
",",
"hsp",
".",
"subjectStart",
")",
")",
"hsp",
".",
"readEndInSubject",
"=",
"hsp",
".",
"r... | Adjust the read and subject start and end offsets in an HSP.
@param hsp: a L{dark.hsp.HSP} or L{dark.hsp.LSP} instance. | [
"Adjust",
"the",
"read",
"and",
"subject",
"start",
"and",
"end",
"offsets",
"in",
"an",
"HSP",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/intervals.py#L161-L173 |
flo-compbio/genometools | genometools/basic/gene_set_collection.py | GeneSetCollection.get_by_index | def get_by_index(self, i):
"""Look up a gene set by its index.
Parameters
----------
i: int
The index of the gene set.
Returns
-------
GeneSet
The gene set.
Raises
------
ValueError
If the given index is out of bounds.
"""
if i >= self.n:
raise ValueError('Index %d out of bounds ' % i +
'for database with %d gene sets.' % self.n)
return self._gene_sets[self._gene_set_ids[i]] | python | def get_by_index(self, i):
"""Look up a gene set by its index.
Parameters
----------
i: int
The index of the gene set.
Returns
-------
GeneSet
The gene set.
Raises
------
ValueError
If the given index is out of bounds.
"""
if i >= self.n:
raise ValueError('Index %d out of bounds ' % i +
'for database with %d gene sets.' % self.n)
return self._gene_sets[self._gene_set_ids[i]] | [
"def",
"get_by_index",
"(",
"self",
",",
"i",
")",
":",
"if",
"i",
">=",
"self",
".",
"n",
":",
"raise",
"ValueError",
"(",
"'Index %d out of bounds '",
"%",
"i",
"+",
"'for database with %d gene sets.'",
"%",
"self",
".",
"n",
")",
"return",
"self",
".",
... | Look up a gene set by its index.
Parameters
----------
i: int
The index of the gene set.
Returns
-------
GeneSet
The gene set.
Raises
------
ValueError
If the given index is out of bounds. | [
"Look",
"up",
"a",
"gene",
"set",
"by",
"its",
"index",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/basic/gene_set_collection.py#L159-L180 |
flo-compbio/genometools | genometools/basic/gene_set_collection.py | GeneSetCollection.read_tsv | def read_tsv(cls, path, encoding='utf-8'):
"""Read a gene set database from a tab-delimited text file.
Parameters
----------
path: str
The path name of the the file.
encoding: str
The encoding of the text file.
Returns
-------
None
"""
gene_sets = []
n = 0
with open(path, 'rb') as fh:
reader = csv.reader(fh, dialect='excel-tab', encoding=encoding)
for l in reader:
n += 1
gs = GeneSet.from_list(l)
gene_sets.append(gs)
logger.debug('Read %d gene sets.', n)
logger.debug('Size of gene set list: %d', len(gene_sets))
return cls(gene_sets) | python | def read_tsv(cls, path, encoding='utf-8'):
"""Read a gene set database from a tab-delimited text file.
Parameters
----------
path: str
The path name of the the file.
encoding: str
The encoding of the text file.
Returns
-------
None
"""
gene_sets = []
n = 0
with open(path, 'rb') as fh:
reader = csv.reader(fh, dialect='excel-tab', encoding=encoding)
for l in reader:
n += 1
gs = GeneSet.from_list(l)
gene_sets.append(gs)
logger.debug('Read %d gene sets.', n)
logger.debug('Size of gene set list: %d', len(gene_sets))
return cls(gene_sets) | [
"def",
"read_tsv",
"(",
"cls",
",",
"path",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"gene_sets",
"=",
"[",
"]",
"n",
"=",
"0",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"fh",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"fh",
",... | Read a gene set database from a tab-delimited text file.
Parameters
----------
path: str
The path name of the the file.
encoding: str
The encoding of the text file.
Returns
-------
None | [
"Read",
"a",
"gene",
"set",
"database",
"from",
"a",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/basic/gene_set_collection.py#L206-L230 |
flo-compbio/genometools | genometools/basic/gene_set_collection.py | GeneSetCollection.write_tsv | def write_tsv(self, path):
"""Write the database to a tab-delimited text file.
Parameters
----------
path: str
The path name of the file.
Returns
-------
None
"""
with open(path, 'wb') as ofh:
writer = csv.writer(
ofh, dialect='excel-tab',
quoting=csv.QUOTE_NONE, lineterminator=os.linesep
)
for gs in self._gene_sets.values():
writer.writerow(gs.to_list()) | python | def write_tsv(self, path):
"""Write the database to a tab-delimited text file.
Parameters
----------
path: str
The path name of the file.
Returns
-------
None
"""
with open(path, 'wb') as ofh:
writer = csv.writer(
ofh, dialect='excel-tab',
quoting=csv.QUOTE_NONE, lineterminator=os.linesep
)
for gs in self._gene_sets.values():
writer.writerow(gs.to_list()) | [
"def",
"write_tsv",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"ofh",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"ofh",
",",
"dialect",
"=",
"'excel-tab'",
",",
"quoting",
"=",
"csv",
".",
"QUOTE_NO... | Write the database to a tab-delimited text file.
Parameters
----------
path: str
The path name of the file.
Returns
-------
None | [
"Write",
"the",
"database",
"to",
"a",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/basic/gene_set_collection.py#L232-L250 |
flo-compbio/genometools | genometools/basic/gene_set_collection.py | GeneSetCollection.read_msigdb_xml | def read_msigdb_xml(cls, path, entrez2gene, species=None): # pragma: no cover
"""Read the complete MSigDB database from an XML file.
The XML file can be downloaded from here:
http://software.broadinstitute.org/gsea/msigdb/download_file.jsp?filePath=/resources/msigdb/5.0/msigdb_v5.0.xml
Parameters
----------
path: str
The path name of the XML file.
entrez2gene: dict or OrderedDict (str: str)
A dictionary mapping Entrez Gene IDs to gene symbols (names).
species: str, optional
A species name (e.g., "Homo_sapiens"). Only gene sets for that
species will be retained. (None)
Returns
-------
GeneSetCollection
The gene set database containing the MSigDB gene sets.
"""
# note: is XML file really encoded in UTF-8?
assert isinstance(path, (str, _oldstr))
assert isinstance(entrez2gene, (dict, OrderedDict))
assert species is None or isinstance(species, (str, _oldstr))
logger.debug('Path: %s', path)
logger.debug('entrez2gene type: %s', str(type(entrez2gene)))
i = [0]
gene_sets = []
total_gs = [0]
total_genes = [0]
species_excl = [0]
unknown_entrezid = [0]
src = 'MSigDB'
def handle_item(pth, item):
# callback function for xmltodict.parse()
total_gs[0] += 1
data = pth[1][1]
spec = data['ORGANISM']
# filter by species
if species is not None and spec != species:
species_excl[0] += 1
return True
id_ = data['SYSTEMATIC_NAME']
name = data['STANDARD_NAME']
coll = data['CATEGORY_CODE']
desc = data['DESCRIPTION_BRIEF']
entrez = data['MEMBERS_EZID'].split(',')
genes = []
for e in entrez:
total_genes[0] += 1
try:
genes.append(entrez2gene[e])
except KeyError:
unknown_entrezid[0] += 1
if not genes:
logger.warning('Gene set "%s" (%s) has no known genes!',
name, id_)
return True
gs = GeneSet(id_, name, genes, source=src,
collection=coll, description=desc)
gene_sets.append(gs)
i[0] += 1
return True
# parse the XML file using the xmltodict package
with io.open(path, 'rb') as fh:
xmltodict.parse(fh.read(), encoding='UTF-8', item_depth=2,
item_callback=handle_item)
# report some statistics
if species_excl[0] > 0:
kept = total_gs[0] - species_excl[0]
perc = 100 * (kept / float(total_gs[0]))
logger.info('%d of all %d gene sets (%.1f %%) belonged to the '
'specified species.', kept, total_gs[0], perc)
if unknown_entrezid[0] > 0:
unkn = unknown_entrezid[0]
# known = total_genes[0] - unknown_entrezid[0]
perc = 100 * (unkn / float(total_genes[0]))
logger.warning('%d of a total of %d genes (%.1f %%) had an ' +
'unknown Entrez ID.', unkn, total_genes[0], perc)
logger.info('Parsed %d entries, resulting in %d gene sets.',
total_gs[0], len(gene_sets))
return cls(gene_sets) | python | def read_msigdb_xml(cls, path, entrez2gene, species=None): # pragma: no cover
"""Read the complete MSigDB database from an XML file.
The XML file can be downloaded from here:
http://software.broadinstitute.org/gsea/msigdb/download_file.jsp?filePath=/resources/msigdb/5.0/msigdb_v5.0.xml
Parameters
----------
path: str
The path name of the XML file.
entrez2gene: dict or OrderedDict (str: str)
A dictionary mapping Entrez Gene IDs to gene symbols (names).
species: str, optional
A species name (e.g., "Homo_sapiens"). Only gene sets for that
species will be retained. (None)
Returns
-------
GeneSetCollection
The gene set database containing the MSigDB gene sets.
"""
# note: is XML file really encoded in UTF-8?
assert isinstance(path, (str, _oldstr))
assert isinstance(entrez2gene, (dict, OrderedDict))
assert species is None or isinstance(species, (str, _oldstr))
logger.debug('Path: %s', path)
logger.debug('entrez2gene type: %s', str(type(entrez2gene)))
i = [0]
gene_sets = []
total_gs = [0]
total_genes = [0]
species_excl = [0]
unknown_entrezid = [0]
src = 'MSigDB'
def handle_item(pth, item):
# callback function for xmltodict.parse()
total_gs[0] += 1
data = pth[1][1]
spec = data['ORGANISM']
# filter by species
if species is not None and spec != species:
species_excl[0] += 1
return True
id_ = data['SYSTEMATIC_NAME']
name = data['STANDARD_NAME']
coll = data['CATEGORY_CODE']
desc = data['DESCRIPTION_BRIEF']
entrez = data['MEMBERS_EZID'].split(',')
genes = []
for e in entrez:
total_genes[0] += 1
try:
genes.append(entrez2gene[e])
except KeyError:
unknown_entrezid[0] += 1
if not genes:
logger.warning('Gene set "%s" (%s) has no known genes!',
name, id_)
return True
gs = GeneSet(id_, name, genes, source=src,
collection=coll, description=desc)
gene_sets.append(gs)
i[0] += 1
return True
# parse the XML file using the xmltodict package
with io.open(path, 'rb') as fh:
xmltodict.parse(fh.read(), encoding='UTF-8', item_depth=2,
item_callback=handle_item)
# report some statistics
if species_excl[0] > 0:
kept = total_gs[0] - species_excl[0]
perc = 100 * (kept / float(total_gs[0]))
logger.info('%d of all %d gene sets (%.1f %%) belonged to the '
'specified species.', kept, total_gs[0], perc)
if unknown_entrezid[0] > 0:
unkn = unknown_entrezid[0]
# known = total_genes[0] - unknown_entrezid[0]
perc = 100 * (unkn / float(total_genes[0]))
logger.warning('%d of a total of %d genes (%.1f %%) had an ' +
'unknown Entrez ID.', unkn, total_genes[0], perc)
logger.info('Parsed %d entries, resulting in %d gene sets.',
total_gs[0], len(gene_sets))
return cls(gene_sets) | [
"def",
"read_msigdb_xml",
"(",
"cls",
",",
"path",
",",
"entrez2gene",
",",
"species",
"=",
"None",
")",
":",
"# pragma: no cover",
"# note: is XML file really encoded in UTF-8?",
"assert",
"isinstance",
"(",
"path",
",",
"(",
"str",
",",
"_oldstr",
")",
")",
"a... | Read the complete MSigDB database from an XML file.
The XML file can be downloaded from here:
http://software.broadinstitute.org/gsea/msigdb/download_file.jsp?filePath=/resources/msigdb/5.0/msigdb_v5.0.xml
Parameters
----------
path: str
The path name of the XML file.
entrez2gene: dict or OrderedDict (str: str)
A dictionary mapping Entrez Gene IDs to gene symbols (names).
species: str, optional
A species name (e.g., "Homo_sapiens"). Only gene sets for that
species will be retained. (None)
Returns
-------
GeneSetCollection
The gene set database containing the MSigDB gene sets. | [
"Read",
"the",
"complete",
"MSigDB",
"database",
"from",
"an",
"XML",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/basic/gene_set_collection.py#L253-L354 |
acorg/dark-matter | dark/features.py | Feature.legendLabel | def legendLabel(self):
"""
Provide a textual description of the feature and its qualifiers to be
used as a label in a plot legend.
@return: A C{str} description of the feature.
"""
excludedQualifiers = set((
'codon_start', 'db_xref', 'protein_id', 'region_name',
'ribosomal_slippage', 'rpt_type', 'translation', 'transl_except',
'transl_table')
)
maxValueLength = 30
result = []
if self.feature.qualifiers:
for qualifier in sorted(self.feature.qualifiers.keys()):
if qualifier not in excludedQualifiers:
value = ', '.join(self.feature.qualifiers[qualifier])
if qualifier == 'site_type' and value == 'other':
continue
if len(value) > maxValueLength:
value = value[:maxValueLength - 3] + '...'
result.append('%s: %s' % (qualifier, value))
return '%d-%d %s%s.%s' % (
int(self.feature.location.start),
int(self.feature.location.end),
self.feature.type,
' (subfeature)' if self.subfeature else '',
' ' + ', '.join(result) if result else '') | python | def legendLabel(self):
"""
Provide a textual description of the feature and its qualifiers to be
used as a label in a plot legend.
@return: A C{str} description of the feature.
"""
excludedQualifiers = set((
'codon_start', 'db_xref', 'protein_id', 'region_name',
'ribosomal_slippage', 'rpt_type', 'translation', 'transl_except',
'transl_table')
)
maxValueLength = 30
result = []
if self.feature.qualifiers:
for qualifier in sorted(self.feature.qualifiers.keys()):
if qualifier not in excludedQualifiers:
value = ', '.join(self.feature.qualifiers[qualifier])
if qualifier == 'site_type' and value == 'other':
continue
if len(value) > maxValueLength:
value = value[:maxValueLength - 3] + '...'
result.append('%s: %s' % (qualifier, value))
return '%d-%d %s%s.%s' % (
int(self.feature.location.start),
int(self.feature.location.end),
self.feature.type,
' (subfeature)' if self.subfeature else '',
' ' + ', '.join(result) if result else '') | [
"def",
"legendLabel",
"(",
"self",
")",
":",
"excludedQualifiers",
"=",
"set",
"(",
"(",
"'codon_start'",
",",
"'db_xref'",
",",
"'protein_id'",
",",
"'region_name'",
",",
"'ribosomal_slippage'",
",",
"'rpt_type'",
",",
"'translation'",
",",
"'transl_except'",
","... | Provide a textual description of the feature and its qualifiers to be
used as a label in a plot legend.
@return: A C{str} description of the feature. | [
"Provide",
"a",
"textual",
"description",
"of",
"the",
"feature",
"and",
"its",
"qualifiers",
"to",
"be",
"used",
"as",
"a",
"label",
"in",
"a",
"plot",
"legend",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/features.py#L52-L80 |
acorg/dark-matter | dark/features.py | _FeatureAdder.add | def add(self, fig, title, minX, maxX, offsetAdjuster=None,
sequenceFetcher=None):
"""
Find the features for a sequence title. If there aren't too many, add
the features to C{fig}. Return information about the features, as
described below.
@param fig: A matplotlib figure.
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011818.1| Description...'.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
for plotting.
@param sequenceFetcher: A function that takes a sequence title and a
database name and returns a C{Bio.SeqIO} instance. If C{None}, use
L{dark.entrez.getSequence}.
@return: If we seem to be offline, return C{None}. Otherwise, return
a L{FeatureList} instance.
"""
offsetAdjuster = offsetAdjuster or (lambda x: x)
fig.set_title('Target sequence features', fontsize=self.TITLE_FONTSIZE)
fig.set_yticks([])
features = FeatureList(title, self.DATABASE, self.WANTED_TYPES,
sequenceFetcher=sequenceFetcher)
if features.offline:
fig.text(minX + (maxX - minX) / 3.0, 0,
'You (or Genbank) appear to be offline.',
fontsize=self.FONTSIZE)
fig.axis([minX, maxX, -1, 1])
return None
# If no interesting features were found, display a message saying
# so in the figure. Otherwise, if we don't have too many features
# to plot, add the feature info to the figure.
nFeatures = len(features)
if nFeatures == 0:
# fig.text(minX + (maxX - minX) / 3.0, 0, 'No features found',
# fontsize=self.FONTSIZE)
fig.text(0.5, 0.5, 'No features found',
horizontalalignment='center', verticalalignment='center',
transform=fig.transAxes, fontsize=self.FONTSIZE)
fig.axis([minX, maxX, -1, 1])
elif nFeatures <= self.MAX_FEATURES_TO_DISPLAY:
# Call the method in our subclass to do the figure display.
self._displayFeatures(fig, features, minX, maxX, offsetAdjuster)
else:
self.tooManyFeaturesToPlot = True
# fig.text(minX + (maxX - minX) / 3.0, 0,
# 'Too many features to plot.', fontsize=self.FONTSIZE)
fig.text(0.5, 0.5, 'Too many features to plot',
horizontalalignment='center', verticalalignment='center',
fontsize=self.FONTSIZE, transform=fig.transAxes)
fig.axis([minX, maxX, -1, 1])
return features | python | def add(self, fig, title, minX, maxX, offsetAdjuster=None,
sequenceFetcher=None):
"""
Find the features for a sequence title. If there aren't too many, add
the features to C{fig}. Return information about the features, as
described below.
@param fig: A matplotlib figure.
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011818.1| Description...'.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
for plotting.
@param sequenceFetcher: A function that takes a sequence title and a
database name and returns a C{Bio.SeqIO} instance. If C{None}, use
L{dark.entrez.getSequence}.
@return: If we seem to be offline, return C{None}. Otherwise, return
a L{FeatureList} instance.
"""
offsetAdjuster = offsetAdjuster or (lambda x: x)
fig.set_title('Target sequence features', fontsize=self.TITLE_FONTSIZE)
fig.set_yticks([])
features = FeatureList(title, self.DATABASE, self.WANTED_TYPES,
sequenceFetcher=sequenceFetcher)
if features.offline:
fig.text(minX + (maxX - minX) / 3.0, 0,
'You (or Genbank) appear to be offline.',
fontsize=self.FONTSIZE)
fig.axis([minX, maxX, -1, 1])
return None
# If no interesting features were found, display a message saying
# so in the figure. Otherwise, if we don't have too many features
# to plot, add the feature info to the figure.
nFeatures = len(features)
if nFeatures == 0:
# fig.text(minX + (maxX - minX) / 3.0, 0, 'No features found',
# fontsize=self.FONTSIZE)
fig.text(0.5, 0.5, 'No features found',
horizontalalignment='center', verticalalignment='center',
transform=fig.transAxes, fontsize=self.FONTSIZE)
fig.axis([minX, maxX, -1, 1])
elif nFeatures <= self.MAX_FEATURES_TO_DISPLAY:
# Call the method in our subclass to do the figure display.
self._displayFeatures(fig, features, minX, maxX, offsetAdjuster)
else:
self.tooManyFeaturesToPlot = True
# fig.text(minX + (maxX - minX) / 3.0, 0,
# 'Too many features to plot.', fontsize=self.FONTSIZE)
fig.text(0.5, 0.5, 'Too many features to plot',
horizontalalignment='center', verticalalignment='center',
fontsize=self.FONTSIZE, transform=fig.transAxes)
fig.axis([minX, maxX, -1, 1])
return features | [
"def",
"add",
"(",
"self",
",",
"fig",
",",
"title",
",",
"minX",
",",
"maxX",
",",
"offsetAdjuster",
"=",
"None",
",",
"sequenceFetcher",
"=",
"None",
")",
":",
"offsetAdjuster",
"=",
"offsetAdjuster",
"or",
"(",
"lambda",
"x",
":",
"x",
")",
"fig",
... | Find the features for a sequence title. If there aren't too many, add
the features to C{fig}. Return information about the features, as
described below.
@param fig: A matplotlib figure.
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011818.1| Description...'.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
for plotting.
@param sequenceFetcher: A function that takes a sequence title and a
database name and returns a C{Bio.SeqIO} instance. If C{None}, use
L{dark.entrez.getSequence}.
@return: If we seem to be offline, return C{None}. Otherwise, return
a L{FeatureList} instance. | [
"Find",
"the",
"features",
"for",
"a",
"sequence",
"title",
".",
"If",
"there",
"aren",
"t",
"too",
"many",
"add",
"the",
"features",
"to",
"C",
"{",
"fig",
"}",
".",
"Return",
"information",
"about",
"the",
"features",
"as",
"described",
"below",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/features.py#L136-L195 |
acorg/dark-matter | dark/features.py | ProteinFeatureAdder._displayFeatures | def _displayFeatures(self, fig, features, minX, maxX, offsetAdjuster):
"""
Add the given C{features} to the figure in C{fig}.
@param fig: A matplotlib figure.
@param features: A C{FeatureList} instance.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
for plotting.
"""
labels = []
for index, feature in enumerate(features):
fig.plot([offsetAdjuster(feature.start),
offsetAdjuster(feature.end)],
[index * -0.2, index * -0.2], color=feature.color,
linewidth=2)
labels.append(feature.legendLabel())
# Note that minX and maxX do not need to be adjusted by the offset
# adjuster. They are the already-adjusted min/max values as
# computed in computePlotInfo in blast.py
fig.axis([minX, maxX, (len(features) + 1) * -0.2, 0.2])
if labels:
# Put a legend above the figure.
box = fig.get_position()
fig.set_position([box.x0, box.y0,
box.width, box.height * 0.2])
fig.legend(labels, loc='lower center', bbox_to_anchor=(0.5, 1.4),
fancybox=True, shadow=True, ncol=2) | python | def _displayFeatures(self, fig, features, minX, maxX, offsetAdjuster):
"""
Add the given C{features} to the figure in C{fig}.
@param fig: A matplotlib figure.
@param features: A C{FeatureList} instance.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
for plotting.
"""
labels = []
for index, feature in enumerate(features):
fig.plot([offsetAdjuster(feature.start),
offsetAdjuster(feature.end)],
[index * -0.2, index * -0.2], color=feature.color,
linewidth=2)
labels.append(feature.legendLabel())
# Note that minX and maxX do not need to be adjusted by the offset
# adjuster. They are the already-adjusted min/max values as
# computed in computePlotInfo in blast.py
fig.axis([minX, maxX, (len(features) + 1) * -0.2, 0.2])
if labels:
# Put a legend above the figure.
box = fig.get_position()
fig.set_position([box.x0, box.y0,
box.width, box.height * 0.2])
fig.legend(labels, loc='lower center', bbox_to_anchor=(0.5, 1.4),
fancybox=True, shadow=True, ncol=2) | [
"def",
"_displayFeatures",
"(",
"self",
",",
"fig",
",",
"features",
",",
"minX",
",",
"maxX",
",",
"offsetAdjuster",
")",
":",
"labels",
"=",
"[",
"]",
"for",
"index",
",",
"feature",
"in",
"enumerate",
"(",
"features",
")",
":",
"fig",
".",
"plot",
... | Add the given C{features} to the figure in C{fig}.
@param fig: A matplotlib figure.
@param features: A C{FeatureList} instance.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
for plotting. | [
"Add",
"the",
"given",
"C",
"{",
"features",
"}",
"to",
"the",
"figure",
"in",
"C",
"{",
"fig",
"}",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/features.py#L220-L250 |
acorg/dark-matter | dark/features.py | NucleotideFeatureAdder._displayFeatures | def _displayFeatures(self, fig, features, minX, maxX, offsetAdjuster):
"""
Add the given C{features} to the figure in C{fig}.
@param fig: A matplotlib figure.
@param features: A C{FeatureList} instance.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
for plotting.
"""
frame = None
labels = []
for feature in features:
start = offsetAdjuster(feature.start)
end = offsetAdjuster(feature.end)
if feature.subfeature:
subfeatureFrame = start % 3
if subfeatureFrame == frame:
# Move overlapping subfeatures down a little to make them
# visible.
y = subfeatureFrame - 0.2
else:
y = subfeatureFrame
else:
frame = start % 3
# If we have a polyprotein, shift it up slightly so we can see
# its components below it.
product = feature.feature.qualifiers.get('product', [''])[0]
if product.lower().find('polyprotein') > -1:
y = frame + 0.2
else:
y = frame
fig.plot([start, end], [y, y], color=feature.color, linewidth=2)
labels.append(feature.legendLabel())
# Note that minX and maxX do not need to be adjusted by the offset
# adjuster. They are the already-adjusted min/max values as
# computed in computePlotInfo in blast.py
fig.axis([minX, maxX, -0.5, 2.5])
fig.set_yticks(np.arange(3))
fig.set_ylabel('Frame')
if labels:
# Put a legend above the figure.
box = fig.get_position()
fig.set_position([box.x0, box.y0,
box.width, box.height * 0.3])
fig.legend(labels, loc='lower center', bbox_to_anchor=(0.5, 2.5),
fancybox=True, shadow=True, ncol=2) | python | def _displayFeatures(self, fig, features, minX, maxX, offsetAdjuster):
"""
Add the given C{features} to the figure in C{fig}.
@param fig: A matplotlib figure.
@param features: A C{FeatureList} instance.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
for plotting.
"""
frame = None
labels = []
for feature in features:
start = offsetAdjuster(feature.start)
end = offsetAdjuster(feature.end)
if feature.subfeature:
subfeatureFrame = start % 3
if subfeatureFrame == frame:
# Move overlapping subfeatures down a little to make them
# visible.
y = subfeatureFrame - 0.2
else:
y = subfeatureFrame
else:
frame = start % 3
# If we have a polyprotein, shift it up slightly so we can see
# its components below it.
product = feature.feature.qualifiers.get('product', [''])[0]
if product.lower().find('polyprotein') > -1:
y = frame + 0.2
else:
y = frame
fig.plot([start, end], [y, y], color=feature.color, linewidth=2)
labels.append(feature.legendLabel())
# Note that minX and maxX do not need to be adjusted by the offset
# adjuster. They are the already-adjusted min/max values as
# computed in computePlotInfo in blast.py
fig.axis([minX, maxX, -0.5, 2.5])
fig.set_yticks(np.arange(3))
fig.set_ylabel('Frame')
if labels:
# Put a legend above the figure.
box = fig.get_position()
fig.set_position([box.x0, box.y0,
box.width, box.height * 0.3])
fig.legend(labels, loc='lower center', bbox_to_anchor=(0.5, 2.5),
fancybox=True, shadow=True, ncol=2) | [
"def",
"_displayFeatures",
"(",
"self",
",",
"fig",
",",
"features",
",",
"minX",
",",
"maxX",
",",
"offsetAdjuster",
")",
":",
"frame",
"=",
"None",
"labels",
"=",
"[",
"]",
"for",
"feature",
"in",
"features",
":",
"start",
"=",
"offsetAdjuster",
"(",
... | Add the given C{features} to the figure in C{fig}.
@param fig: A matplotlib figure.
@param features: A C{FeatureList} instance.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
for plotting. | [
"Add",
"the",
"given",
"C",
"{",
"features",
"}",
"to",
"the",
"figure",
"in",
"C",
"{",
"fig",
"}",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/features.py#L263-L312 |
zniper/simple-article | article/templatetags/article_tags.py | recent_articles | def recent_articles(limit=10, exclude=None):
"""Returns list of latest article"""
queryset = Article.objects.filter(published=True).order_by('-modified')
if exclude:
if hasattr(exclude, '__iter__'):
queryset = queryset.exclude(pk__in=exclude)
else:
queryset = queryset.exclude(pk=exclude)
return queryset | python | def recent_articles(limit=10, exclude=None):
"""Returns list of latest article"""
queryset = Article.objects.filter(published=True).order_by('-modified')
if exclude:
if hasattr(exclude, '__iter__'):
queryset = queryset.exclude(pk__in=exclude)
else:
queryset = queryset.exclude(pk=exclude)
return queryset | [
"def",
"recent_articles",
"(",
"limit",
"=",
"10",
",",
"exclude",
"=",
"None",
")",
":",
"queryset",
"=",
"Article",
".",
"objects",
".",
"filter",
"(",
"published",
"=",
"True",
")",
".",
"order_by",
"(",
"'-modified'",
")",
"if",
"exclude",
":",
"if... | Returns list of latest article | [
"Returns",
"list",
"of",
"latest",
"article"
] | train | https://github.com/zniper/simple-article/blob/db605bdd966e7023f27870d040804798db606522/article/templatetags/article_tags.py#L9-L17 |
digidotcom/python-streamexpect | streamexpect.py | _flatten | def _flatten(n):
"""Recursively flatten a mixed sequence of sub-sequences and items"""
if isinstance(n, collections.Sequence):
for x in n:
for y in _flatten(x):
yield y
else:
yield n | python | def _flatten(n):
"""Recursively flatten a mixed sequence of sub-sequences and items"""
if isinstance(n, collections.Sequence):
for x in n:
for y in _flatten(x):
yield y
else:
yield n | [
"def",
"_flatten",
"(",
"n",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"collections",
".",
"Sequence",
")",
":",
"for",
"x",
"in",
"n",
":",
"for",
"y",
"in",
"_flatten",
"(",
"x",
")",
":",
"yield",
"y",
"else",
":",
"yield",
"n"
] | Recursively flatten a mixed sequence of sub-sequences and items | [
"Recursively",
"flatten",
"a",
"mixed",
"sequence",
"of",
"sub",
"-",
"sequences",
"and",
"items"
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L259-L266 |
digidotcom/python-streamexpect | streamexpect.py | wrap | def wrap(stream, unicode=False, window=1024, echo=False, close_stream=True):
"""Wrap a stream to implement expect functionality.
This function provides a convenient way to wrap any Python stream (a
file-like object) or socket with an appropriate :class:`Expecter` class for
the stream type. The returned object adds an :func:`Expect.expect` method
to the stream, while passing normal stream functions like *read*/*recv*
and *write*/*send* through to the underlying stream.
Here's an example of opening and wrapping a pair of network sockets::
import socket
import streamexpect
source, drain = socket.socketpair()
expecter = streamexpect.wrap(drain)
source.sendall(b'this is a test')
match = expecter.expect_bytes(b'test', timeout=5)
assert match is not None
:param stream: The stream/socket to wrap.
:param bool unicode: If ``True``, the wrapper will be configured for
Unicode matching, otherwise matching will be done on binary.
:param int window: Historical characters to buffer.
:param bool echo: If ``True``, echoes received characters to stdout.
:param bool close_stream: If ``True``, and the wrapper is used as a context
manager, closes the stream at the end of the context manager.
"""
if hasattr(stream, 'read'):
proxy = PollingStreamAdapter(stream)
elif hasattr(stream, 'recv'):
proxy = PollingSocketStreamAdapter(stream)
else:
raise TypeError('stream must have either read or recv method')
if echo and unicode:
callback = _echo_text
elif echo and not unicode:
callback = _echo_bytes
else:
callback = None
if unicode:
expecter = TextExpecter(proxy, input_callback=callback, window=window,
close_adapter=close_stream)
else:
expecter = BytesExpecter(proxy, input_callback=callback, window=window,
close_adapter=close_stream)
return expecter | python | def wrap(stream, unicode=False, window=1024, echo=False, close_stream=True):
"""Wrap a stream to implement expect functionality.
This function provides a convenient way to wrap any Python stream (a
file-like object) or socket with an appropriate :class:`Expecter` class for
the stream type. The returned object adds an :func:`Expect.expect` method
to the stream, while passing normal stream functions like *read*/*recv*
and *write*/*send* through to the underlying stream.
Here's an example of opening and wrapping a pair of network sockets::
import socket
import streamexpect
source, drain = socket.socketpair()
expecter = streamexpect.wrap(drain)
source.sendall(b'this is a test')
match = expecter.expect_bytes(b'test', timeout=5)
assert match is not None
:param stream: The stream/socket to wrap.
:param bool unicode: If ``True``, the wrapper will be configured for
Unicode matching, otherwise matching will be done on binary.
:param int window: Historical characters to buffer.
:param bool echo: If ``True``, echoes received characters to stdout.
:param bool close_stream: If ``True``, and the wrapper is used as a context
manager, closes the stream at the end of the context manager.
"""
if hasattr(stream, 'read'):
proxy = PollingStreamAdapter(stream)
elif hasattr(stream, 'recv'):
proxy = PollingSocketStreamAdapter(stream)
else:
raise TypeError('stream must have either read or recv method')
if echo and unicode:
callback = _echo_text
elif echo and not unicode:
callback = _echo_bytes
else:
callback = None
if unicode:
expecter = TextExpecter(proxy, input_callback=callback, window=window,
close_adapter=close_stream)
else:
expecter = BytesExpecter(proxy, input_callback=callback, window=window,
close_adapter=close_stream)
return expecter | [
"def",
"wrap",
"(",
"stream",
",",
"unicode",
"=",
"False",
",",
"window",
"=",
"1024",
",",
"echo",
"=",
"False",
",",
"close_stream",
"=",
"True",
")",
":",
"if",
"hasattr",
"(",
"stream",
",",
"'read'",
")",
":",
"proxy",
"=",
"PollingStreamAdapter"... | Wrap a stream to implement expect functionality.
This function provides a convenient way to wrap any Python stream (a
file-like object) or socket with an appropriate :class:`Expecter` class for
the stream type. The returned object adds an :func:`Expect.expect` method
to the stream, while passing normal stream functions like *read*/*recv*
and *write*/*send* through to the underlying stream.
Here's an example of opening and wrapping a pair of network sockets::
import socket
import streamexpect
source, drain = socket.socketpair()
expecter = streamexpect.wrap(drain)
source.sendall(b'this is a test')
match = expecter.expect_bytes(b'test', timeout=5)
assert match is not None
:param stream: The stream/socket to wrap.
:param bool unicode: If ``True``, the wrapper will be configured for
Unicode matching, otherwise matching will be done on binary.
:param int window: Historical characters to buffer.
:param bool echo: If ``True``, echoes received characters to stdout.
:param bool close_stream: If ``True``, and the wrapper is used as a context
manager, closes the stream at the end of the context manager. | [
"Wrap",
"a",
"stream",
"to",
"implement",
"expect",
"functionality",
"."
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L740-L790 |
digidotcom/python-streamexpect | streamexpect.py | Searcher._check_type | def _check_type(self, value):
"""Checks that *value* matches the type of this *Searcher*.
Checks that *value* matches the type of this *Searcher*, returning the
value if it does and raising a `TypeError` if it does not.
:return: *value* if type of *value* matches type of this *Searcher*.
:raises TypeError: if type of *value* does not match the type of this
*Searcher*
"""
if not isinstance(value, self.match_type):
raise TypeError('Type ' + str(type(value)) + ' does not match '
'expected type ' + str(self.match_type))
else:
return value | python | def _check_type(self, value):
"""Checks that *value* matches the type of this *Searcher*.
Checks that *value* matches the type of this *Searcher*, returning the
value if it does and raising a `TypeError` if it does not.
:return: *value* if type of *value* matches type of this *Searcher*.
:raises TypeError: if type of *value* does not match the type of this
*Searcher*
"""
if not isinstance(value, self.match_type):
raise TypeError('Type ' + str(type(value)) + ' does not match '
'expected type ' + str(self.match_type))
else:
return value | [
"def",
"_check_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"match_type",
")",
":",
"raise",
"TypeError",
"(",
"'Type '",
"+",
"str",
"(",
"type",
"(",
"value",
")",
")",
"+",
"' does not match ... | Checks that *value* matches the type of this *Searcher*.
Checks that *value* matches the type of this *Searcher*, returning the
value if it does and raising a `TypeError` if it does not.
:return: *value* if type of *value* matches type of this *Searcher*.
:raises TypeError: if type of *value* does not match the type of this
*Searcher* | [
"Checks",
"that",
"*",
"value",
"*",
"matches",
"the",
"type",
"of",
"this",
"*",
"Searcher",
"*",
"."
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L101-L115 |
digidotcom/python-streamexpect | streamexpect.py | BytesSearcher.search | def search(self, buf):
"""Search the provided buffer for matching bytes.
Search the provided buffer for matching bytes. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`SequenceMatch` if matched, None if no match was found.
"""
idx = self._check_type(buf).find(self._bytes)
if idx < 0:
return None
else:
start = idx
end = idx + len(self._bytes)
return SequenceMatch(self, buf[start:end], start, end) | python | def search(self, buf):
"""Search the provided buffer for matching bytes.
Search the provided buffer for matching bytes. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`SequenceMatch` if matched, None if no match was found.
"""
idx = self._check_type(buf).find(self._bytes)
if idx < 0:
return None
else:
start = idx
end = idx + len(self._bytes)
return SequenceMatch(self, buf[start:end], start, end) | [
"def",
"search",
"(",
"self",
",",
"buf",
")",
":",
"idx",
"=",
"self",
".",
"_check_type",
"(",
"buf",
")",
".",
"find",
"(",
"self",
".",
"_bytes",
")",
"if",
"idx",
"<",
"0",
":",
"return",
"None",
"else",
":",
"start",
"=",
"idx",
"end",
"=... | Search the provided buffer for matching bytes.
Search the provided buffer for matching bytes. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`SequenceMatch` if matched, None if no match was found. | [
"Search",
"the",
"provided",
"buffer",
"for",
"matching",
"bytes",
"."
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L143-L158 |
digidotcom/python-streamexpect | streamexpect.py | TextSearcher.search | def search(self, buf):
"""Search the provided buffer for matching text.
Search the provided buffer for matching text. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`SequenceMatch` if matched, None if no match was found.
"""
self._check_type(buf)
normalized = unicodedata.normalize(self.FORM, buf)
idx = normalized.find(self._text)
if idx < 0:
return None
start = idx
end = idx + len(self._text)
return SequenceMatch(self, normalized[start:end], start, end) | python | def search(self, buf):
"""Search the provided buffer for matching text.
Search the provided buffer for matching text. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`SequenceMatch` if matched, None if no match was found.
"""
self._check_type(buf)
normalized = unicodedata.normalize(self.FORM, buf)
idx = normalized.find(self._text)
if idx < 0:
return None
start = idx
end = idx + len(self._text)
return SequenceMatch(self, normalized[start:end], start, end) | [
"def",
"search",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"_check_type",
"(",
"buf",
")",
"normalized",
"=",
"unicodedata",
".",
"normalize",
"(",
"self",
".",
"FORM",
",",
"buf",
")",
"idx",
"=",
"normalized",
".",
"find",
"(",
"self",
".",
... | Search the provided buffer for matching text.
Search the provided buffer for matching text. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`SequenceMatch` if matched, None if no match was found. | [
"Search",
"the",
"provided",
"buffer",
"for",
"matching",
"text",
"."
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L193-L209 |
digidotcom/python-streamexpect | streamexpect.py | RegexSearcher.search | def search(self, buf):
"""Search the provided buffer for a match to the object's regex.
Search the provided buffer for a match to the object's regex. If the
*match* is found, returns a :class:`RegexMatch` object, otherwise
returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`RegexMatch` if matched, None if no match was found.
"""
match = self._regex.search(self._check_type(buf))
if match is not None:
start = match.start()
end = match.end()
return RegexMatch(self, buf[start:end], start, end, match.groups()) | python | def search(self, buf):
"""Search the provided buffer for a match to the object's regex.
Search the provided buffer for a match to the object's regex. If the
*match* is found, returns a :class:`RegexMatch` object, otherwise
returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`RegexMatch` if matched, None if no match was found.
"""
match = self._regex.search(self._check_type(buf))
if match is not None:
start = match.start()
end = match.end()
return RegexMatch(self, buf[start:end], start, end, match.groups()) | [
"def",
"search",
"(",
"self",
",",
"buf",
")",
":",
"match",
"=",
"self",
".",
"_regex",
".",
"search",
"(",
"self",
".",
"_check_type",
"(",
"buf",
")",
")",
"if",
"match",
"is",
"not",
"None",
":",
"start",
"=",
"match",
".",
"start",
"(",
")",... | Search the provided buffer for a match to the object's regex.
Search the provided buffer for a match to the object's regex. If the
*match* is found, returns a :class:`RegexMatch` object, otherwise
returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`RegexMatch` if matched, None if no match was found. | [
"Search",
"the",
"provided",
"buffer",
"for",
"a",
"match",
"to",
"the",
"object",
"s",
"regex",
"."
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L242-L256 |
digidotcom/python-streamexpect | streamexpect.py | SearcherCollection.search | def search(self, buf):
"""Search the provided buffer for a match to any sub-searchers.
Search the provided buffer for a match to any of this collection's
sub-searchers. If a single matching sub-searcher is found, returns that
sub-searcher's *match* object. If multiple matches are found, the match
with the smallest index is returned. If no matches are found, returns
``None``.
:param buf: Buffer to search for a match.
:return: :class:`RegexMatch` if matched, None if no match was found.
"""
self._check_type(buf)
best_match = None
best_index = sys.maxsize
for searcher in self:
match = searcher.search(buf)
if match and match.start < best_index:
best_match = match
best_index = match.start
return best_match | python | def search(self, buf):
"""Search the provided buffer for a match to any sub-searchers.
Search the provided buffer for a match to any of this collection's
sub-searchers. If a single matching sub-searcher is found, returns that
sub-searcher's *match* object. If multiple matches are found, the match
with the smallest index is returned. If no matches are found, returns
``None``.
:param buf: Buffer to search for a match.
:return: :class:`RegexMatch` if matched, None if no match was found.
"""
self._check_type(buf)
best_match = None
best_index = sys.maxsize
for searcher in self:
match = searcher.search(buf)
if match and match.start < best_index:
best_match = match
best_index = match.start
return best_match | [
"def",
"search",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"_check_type",
"(",
"buf",
")",
"best_match",
"=",
"None",
"best_index",
"=",
"sys",
".",
"maxsize",
"for",
"searcher",
"in",
"self",
":",
"match",
"=",
"searcher",
".",
"search",
"(",
... | Search the provided buffer for a match to any sub-searchers.
Search the provided buffer for a match to any of this collection's
sub-searchers. If a single matching sub-searcher is found, returns that
sub-searcher's *match* object. If multiple matches are found, the match
with the smallest index is returned. If no matches are found, returns
``None``.
:param buf: Buffer to search for a match.
:return: :class:`RegexMatch` if matched, None if no match was found. | [
"Search",
"the",
"provided",
"buffer",
"for",
"a",
"match",
"to",
"any",
"sub",
"-",
"searchers",
"."
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L316-L336 |
digidotcom/python-streamexpect | streamexpect.py | PollingStreamAdapter.poll | def poll(self, timeout):
"""
:param float timeout: Timeout in seconds.
"""
timeout = float(timeout)
end_time = time.time() + timeout
while True:
# Keep reading until data is received or timeout
incoming = self.stream.read(self._max_read)
if incoming:
return incoming
if (end_time - time.time()) < 0:
raise ExpectTimeout()
time.sleep(self._poll_period) | python | def poll(self, timeout):
"""
:param float timeout: Timeout in seconds.
"""
timeout = float(timeout)
end_time = time.time() + timeout
while True:
# Keep reading until data is received or timeout
incoming = self.stream.read(self._max_read)
if incoming:
return incoming
if (end_time - time.time()) < 0:
raise ExpectTimeout()
time.sleep(self._poll_period) | [
"def",
"poll",
"(",
"self",
",",
"timeout",
")",
":",
"timeout",
"=",
"float",
"(",
"timeout",
")",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"while",
"True",
":",
"# Keep reading until data is received or timeout",
"incoming",
"=",
"se... | :param float timeout: Timeout in seconds. | [
":",
"param",
"float",
"timeout",
":",
"Timeout",
"in",
"seconds",
"."
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L441-L454 |
digidotcom/python-streamexpect | streamexpect.py | PollingSocketStreamAdapter.poll | def poll(self, timeout):
"""
:param float timeout: Timeout in seconds. A timeout that is less than
the poll_period will still cause a single read that may take up to
poll_period seconds.
"""
now = time.time()
end_time = now + float(timeout)
prev_timeout = self.stream.gettimeout()
self.stream.settimeout(self._poll_period)
incoming = None
try:
while (end_time - now) >= 0:
try:
incoming = self.stream.recv(self._max_read)
except socket.timeout:
pass
if incoming:
return incoming
now = time.time()
raise ExpectTimeout()
finally:
self.stream.settimeout(prev_timeout) | python | def poll(self, timeout):
"""
:param float timeout: Timeout in seconds. A timeout that is less than
the poll_period will still cause a single read that may take up to
poll_period seconds.
"""
now = time.time()
end_time = now + float(timeout)
prev_timeout = self.stream.gettimeout()
self.stream.settimeout(self._poll_period)
incoming = None
try:
while (end_time - now) >= 0:
try:
incoming = self.stream.recv(self._max_read)
except socket.timeout:
pass
if incoming:
return incoming
now = time.time()
raise ExpectTimeout()
finally:
self.stream.settimeout(prev_timeout) | [
"def",
"poll",
"(",
"self",
",",
"timeout",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"end_time",
"=",
"now",
"+",
"float",
"(",
"timeout",
")",
"prev_timeout",
"=",
"self",
".",
"stream",
".",
"gettimeout",
"(",
")",
"self",
".",
"strea... | :param float timeout: Timeout in seconds. A timeout that is less than
the poll_period will still cause a single read that may take up to
poll_period seconds. | [
":",
"param",
"float",
"timeout",
":",
"Timeout",
"in",
"seconds",
".",
"A",
"timeout",
"that",
"is",
"less",
"than",
"the",
"poll_period",
"will",
"still",
"cause",
"a",
"single",
"read",
"that",
"may",
"take",
"up",
"to",
"poll_period",
"seconds",
"."
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L475-L497 |
digidotcom/python-streamexpect | streamexpect.py | ExpectRegexMixin.expect_regex | def expect_regex(self, pattern, timeout=3, regex_options=0):
"""Wait for a match to the regex in *pattern* to appear on the stream.
Waits for input matching the regex *pattern* for up to *timeout*
seconds. If a match is found, a :class:`RegexMatch` result is returned.
If no match is found within *timeout* seconds, raise an
:class:`ExpectTimeout` exception.
:param pattern: The pattern to search for, as a single compiled regex
or a string that will be processed as a regex.
:param float timeout: Timeout in seconds.
:param regex_options: Options passed to the regex engine.
:return: :class:`RegexMatch` if matched, None if no match was found.
"""
return self.expect(RegexSearcher(pattern, regex_options), timeout) | python | def expect_regex(self, pattern, timeout=3, regex_options=0):
"""Wait for a match to the regex in *pattern* to appear on the stream.
Waits for input matching the regex *pattern* for up to *timeout*
seconds. If a match is found, a :class:`RegexMatch` result is returned.
If no match is found within *timeout* seconds, raise an
:class:`ExpectTimeout` exception.
:param pattern: The pattern to search for, as a single compiled regex
or a string that will be processed as a regex.
:param float timeout: Timeout in seconds.
:param regex_options: Options passed to the regex engine.
:return: :class:`RegexMatch` if matched, None if no match was found.
"""
return self.expect(RegexSearcher(pattern, regex_options), timeout) | [
"def",
"expect_regex",
"(",
"self",
",",
"pattern",
",",
"timeout",
"=",
"3",
",",
"regex_options",
"=",
"0",
")",
":",
"return",
"self",
".",
"expect",
"(",
"RegexSearcher",
"(",
"pattern",
",",
"regex_options",
")",
",",
"timeout",
")"
] | Wait for a match to the regex in *pattern* to appear on the stream.
Waits for input matching the regex *pattern* for up to *timeout*
seconds. If a match is found, a :class:`RegexMatch` result is returned.
If no match is found within *timeout* seconds, raise an
:class:`ExpectTimeout` exception.
:param pattern: The pattern to search for, as a single compiled regex
or a string that will be processed as a regex.
:param float timeout: Timeout in seconds.
:param regex_options: Options passed to the regex engine.
:return: :class:`RegexMatch` if matched, None if no match was found. | [
"Wait",
"for",
"a",
"match",
"to",
"the",
"regex",
"in",
"*",
"pattern",
"*",
"to",
"appear",
"on",
"the",
"stream",
"."
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L536-L550 |
digidotcom/python-streamexpect | streamexpect.py | BytesExpecter.expect | def expect(self, searcher, timeout=3):
"""Wait for input matching *searcher*
Waits for input matching *searcher* for up to *timeout* seconds. If
a match is found, the match result is returned (the specific type of
returned result depends on the :class:`Searcher` type). If no match is
found within *timeout* seconds, raise an :class:`ExpectTimeout`
exception.
:param Searcher searcher: :class:`Searcher` to apply to underlying
stream.
:param float timeout: Timeout in seconds.
"""
timeout = float(timeout)
end = time.time() + timeout
match = searcher.search(self._history[self._start:])
while not match:
# poll() will raise ExpectTimeout if time is exceeded
incoming = self._stream_adapter.poll(end - time.time())
self.input_callback(incoming)
self._history += incoming
match = searcher.search(self._history[self._start:])
trimlength = len(self._history) - self._window
if trimlength > 0:
self._start -= trimlength
self._history = self._history[trimlength:]
self._start += match.end
if (self._start < 0):
self._start = 0
return match | python | def expect(self, searcher, timeout=3):
"""Wait for input matching *searcher*
Waits for input matching *searcher* for up to *timeout* seconds. If
a match is found, the match result is returned (the specific type of
returned result depends on the :class:`Searcher` type). If no match is
found within *timeout* seconds, raise an :class:`ExpectTimeout`
exception.
:param Searcher searcher: :class:`Searcher` to apply to underlying
stream.
:param float timeout: Timeout in seconds.
"""
timeout = float(timeout)
end = time.time() + timeout
match = searcher.search(self._history[self._start:])
while not match:
# poll() will raise ExpectTimeout if time is exceeded
incoming = self._stream_adapter.poll(end - time.time())
self.input_callback(incoming)
self._history += incoming
match = searcher.search(self._history[self._start:])
trimlength = len(self._history) - self._window
if trimlength > 0:
self._start -= trimlength
self._history = self._history[trimlength:]
self._start += match.end
if (self._start < 0):
self._start = 0
return match | [
"def",
"expect",
"(",
"self",
",",
"searcher",
",",
"timeout",
"=",
"3",
")",
":",
"timeout",
"=",
"float",
"(",
"timeout",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"match",
"=",
"searcher",
".",
"search",
"(",
"self",
".",
... | Wait for input matching *searcher*
Waits for input matching *searcher* for up to *timeout* seconds. If
a match is found, the match result is returned (the specific type of
returned result depends on the :class:`Searcher` type). If no match is
found within *timeout* seconds, raise an :class:`ExpectTimeout`
exception.
:param Searcher searcher: :class:`Searcher` to apply to underlying
stream.
:param float timeout: Timeout in seconds. | [
"Wait",
"for",
"input",
"matching",
"*",
"searcher",
"*"
] | train | https://github.com/digidotcom/python-streamexpect/blob/9ab894506ffd679b37230e935158ff3b0aa170ab/streamexpect.py#L646-L677 |
Peter-Slump/django-dynamic-fixtures | src/dynamic_fixtures/fixtures/runner.py | LoadFixtureRunner.init_graph | def init_graph(self):
"""
Initialize graph
Load all nodes and set dependencies.
To avoid errors about missing nodes all nodes get loaded first before
setting the dependencies.
"""
self._graph = Graph()
# First add all nodes
for key in self.loader.disk_fixtures.keys():
self.graph.add_node(key)
# Then set dependencies
for key, fixture in self.loader.disk_fixtures.items():
for dependency in fixture.dependencies:
self.graph.add_dependency(key, dependency) | python | def init_graph(self):
"""
Initialize graph
Load all nodes and set dependencies.
To avoid errors about missing nodes all nodes get loaded first before
setting the dependencies.
"""
self._graph = Graph()
# First add all nodes
for key in self.loader.disk_fixtures.keys():
self.graph.add_node(key)
# Then set dependencies
for key, fixture in self.loader.disk_fixtures.items():
for dependency in fixture.dependencies:
self.graph.add_dependency(key, dependency) | [
"def",
"init_graph",
"(",
"self",
")",
":",
"self",
".",
"_graph",
"=",
"Graph",
"(",
")",
"# First add all nodes",
"for",
"key",
"in",
"self",
".",
"loader",
".",
"disk_fixtures",
".",
"keys",
"(",
")",
":",
"self",
".",
"graph",
".",
"add_node",
"(",... | Initialize graph
Load all nodes and set dependencies.
To avoid errors about missing nodes all nodes get loaded first before
setting the dependencies. | [
"Initialize",
"graph",
"Load",
"all",
"nodes",
"and",
"set",
"dependencies",
"."
] | train | https://github.com/Peter-Slump/django-dynamic-fixtures/blob/da99b4b12b11be28ea4b36b6cf2896ca449c73c1/src/dynamic_fixtures/fixtures/runner.py#L26-L43 |
Peter-Slump/django-dynamic-fixtures | src/dynamic_fixtures/fixtures/runner.py | LoadFixtureRunner.get_app_nodes | def get_app_nodes(self, app_label):
"""
Get all nodes for given app
:param str app_label: app label
:rtype: list
"""
return [node for node in self.graph.nodes if node[0] == app_label] | python | def get_app_nodes(self, app_label):
"""
Get all nodes for given app
:param str app_label: app label
:rtype: list
"""
return [node for node in self.graph.nodes if node[0] == app_label] | [
"def",
"get_app_nodes",
"(",
"self",
",",
"app_label",
")",
":",
"return",
"[",
"node",
"for",
"node",
"in",
"self",
".",
"graph",
".",
"nodes",
"if",
"node",
"[",
"0",
"]",
"==",
"app_label",
"]"
] | Get all nodes for given app
:param str app_label: app label
:rtype: list | [
"Get",
"all",
"nodes",
"for",
"given",
"app",
":",
"param",
"str",
"app_label",
":",
"app",
"label",
":",
"rtype",
":",
"list"
] | train | https://github.com/Peter-Slump/django-dynamic-fixtures/blob/da99b4b12b11be28ea4b36b6cf2896ca449c73c1/src/dynamic_fixtures/fixtures/runner.py#L45-L51 |
Peter-Slump/django-dynamic-fixtures | src/dynamic_fixtures/fixtures/runner.py | LoadFixtureRunner.get_fixture_node | def get_fixture_node(self, app_label, fixture_prefix):
"""
Get all fixtures in given app with given prefix.
:param str app_label: App label
:param str fixture_prefix: first part of the fixture name
:return: list of found fixtures.
"""
app_nodes = self.get_app_nodes(app_label=app_label)
nodes = [
node for node in app_nodes if node[1].startswith(fixture_prefix)
]
if len(nodes) > 1:
raise MultipleFixturesFound(
"The following fixtures with prefix '%s' are found in app '%s'"
": %s" % (
fixture_prefix, app_label, ', '.join(
[node[1] for node in nodes]
)
)
)
elif len(nodes) == 0:
raise FixtureNotFound("Fixture with prefix '%s' not found in app "
"'%s'" % (fixture_prefix, app_label))
return nodes | python | def get_fixture_node(self, app_label, fixture_prefix):
"""
Get all fixtures in given app with given prefix.
:param str app_label: App label
:param str fixture_prefix: first part of the fixture name
:return: list of found fixtures.
"""
app_nodes = self.get_app_nodes(app_label=app_label)
nodes = [
node for node in app_nodes if node[1].startswith(fixture_prefix)
]
if len(nodes) > 1:
raise MultipleFixturesFound(
"The following fixtures with prefix '%s' are found in app '%s'"
": %s" % (
fixture_prefix, app_label, ', '.join(
[node[1] for node in nodes]
)
)
)
elif len(nodes) == 0:
raise FixtureNotFound("Fixture with prefix '%s' not found in app "
"'%s'" % (fixture_prefix, app_label))
return nodes | [
"def",
"get_fixture_node",
"(",
"self",
",",
"app_label",
",",
"fixture_prefix",
")",
":",
"app_nodes",
"=",
"self",
".",
"get_app_nodes",
"(",
"app_label",
"=",
"app_label",
")",
"nodes",
"=",
"[",
"node",
"for",
"node",
"in",
"app_nodes",
"if",
"node",
"... | Get all fixtures in given app with given prefix.
:param str app_label: App label
:param str fixture_prefix: first part of the fixture name
:return: list of found fixtures. | [
"Get",
"all",
"fixtures",
"in",
"given",
"app",
"with",
"given",
"prefix",
".",
":",
"param",
"str",
"app_label",
":",
"App",
"label",
":",
"param",
"str",
"fixture_prefix",
":",
"first",
"part",
"of",
"the",
"fixture",
"name",
":",
"return",
":",
"list"... | train | https://github.com/Peter-Slump/django-dynamic-fixtures/blob/da99b4b12b11be28ea4b36b6cf2896ca449c73c1/src/dynamic_fixtures/fixtures/runner.py#L53-L77 |
Peter-Slump/django-dynamic-fixtures | src/dynamic_fixtures/fixtures/runner.py | LoadFixtureRunner.load_fixtures | def load_fixtures(self, nodes=None, progress_callback=None, dry_run=False):
"""Load all fixtures for given nodes.
If no nodes are given all fixtures will be loaded.
:param list nodes: list of nodes to be loaded.
:param callable progress_callback: Callback which will be called while
handling the nodes.
"""
if progress_callback and not callable(progress_callback):
raise Exception('Callback should be callable')
plan = self.get_plan(nodes=nodes)
try:
with transaction.atomic():
self.load_plan(plan=plan, progress_callback=progress_callback)
if dry_run:
raise DryRun
except DryRun:
# Dry-run to get the atomic transaction rolled back
pass
return len(plan) | python | def load_fixtures(self, nodes=None, progress_callback=None, dry_run=False):
"""Load all fixtures for given nodes.
If no nodes are given all fixtures will be loaded.
:param list nodes: list of nodes to be loaded.
:param callable progress_callback: Callback which will be called while
handling the nodes.
"""
if progress_callback and not callable(progress_callback):
raise Exception('Callback should be callable')
plan = self.get_plan(nodes=nodes)
try:
with transaction.atomic():
self.load_plan(plan=plan, progress_callback=progress_callback)
if dry_run:
raise DryRun
except DryRun:
# Dry-run to get the atomic transaction rolled back
pass
return len(plan) | [
"def",
"load_fixtures",
"(",
"self",
",",
"nodes",
"=",
"None",
",",
"progress_callback",
"=",
"None",
",",
"dry_run",
"=",
"False",
")",
":",
"if",
"progress_callback",
"and",
"not",
"callable",
"(",
"progress_callback",
")",
":",
"raise",
"Exception",
"(",... | Load all fixtures for given nodes.
If no nodes are given all fixtures will be loaded.
:param list nodes: list of nodes to be loaded.
:param callable progress_callback: Callback which will be called while
handling the nodes. | [
"Load",
"all",
"fixtures",
"for",
"given",
"nodes",
"."
] | train | https://github.com/Peter-Slump/django-dynamic-fixtures/blob/da99b4b12b11be28ea4b36b6cf2896ca449c73c1/src/dynamic_fixtures/fixtures/runner.py#L79-L102 |
Peter-Slump/django-dynamic-fixtures | src/dynamic_fixtures/fixtures/runner.py | LoadFixtureRunner.get_plan | def get_plan(self, nodes=None):
"""
Retrieve a plan, e.g. a list of fixtures to be loaded sorted on
dependency.
:param list nodes: list of nodes to be loaded.
:return:
"""
if nodes:
plan = self.graph.resolve_nodes(nodes)
else:
plan = self.graph.resolve_node()
return plan | python | def get_plan(self, nodes=None):
"""
Retrieve a plan, e.g. a list of fixtures to be loaded sorted on
dependency.
:param list nodes: list of nodes to be loaded.
:return:
"""
if nodes:
plan = self.graph.resolve_nodes(nodes)
else:
plan = self.graph.resolve_node()
return plan | [
"def",
"get_plan",
"(",
"self",
",",
"nodes",
"=",
"None",
")",
":",
"if",
"nodes",
":",
"plan",
"=",
"self",
".",
"graph",
".",
"resolve_nodes",
"(",
"nodes",
")",
"else",
":",
"plan",
"=",
"self",
".",
"graph",
".",
"resolve_node",
"(",
")",
"ret... | Retrieve a plan, e.g. a list of fixtures to be loaded sorted on
dependency.
:param list nodes: list of nodes to be loaded.
:return: | [
"Retrieve",
"a",
"plan",
"e",
".",
"g",
".",
"a",
"list",
"of",
"fixtures",
"to",
"be",
"loaded",
"sorted",
"on",
"dependency",
"."
] | train | https://github.com/Peter-Slump/django-dynamic-fixtures/blob/da99b4b12b11be28ea4b36b6cf2896ca449c73c1/src/dynamic_fixtures/fixtures/runner.py#L115-L128 |
acorg/dark-matter | dark/mutations.py | basePlotter | def basePlotter(blastHits, title):
"""
Plot the reads and the subject, so that bases in the reads which are
different from the subject are shown. Else a '.' is shown.
like so:
subject_gi ATGCGTACGTACGACACC
read_1 A......TTC..T
@param blastHits: A L{dark.blast.BlastHits} instance.
@param title: A C{str} sequence title that was matched by BLAST. We plot
the reads that matched this title.
"""
result = []
params = blastHits.plotParams
assert params is not None, ('Oops, it looks like you forgot to run '
'computePlotInfo.')
sequence = ncbidb.getSequence(title, blastHits.records.blastDb)
subject = sequence.seq
gi = title.split('|')[1]
sub = '%s\t \t \t%s' % (gi, subject)
result.append(sub)
plotInfo = blastHits.titles[title]['plotInfo']
assert plotInfo is not None, ('Oops, it looks like you forgot to run '
'computePlotInfo.')
items = plotInfo['items']
count = 0
for item in items:
count += 1
hsp = item['hsp']
queryTitle = blastHits.fasta[item['readNum']].id
# If the product of the subject and query frame values is +ve,
# then they're either both +ve or both -ve, so we just use the
# query as is. Otherwise, we need to reverse complement it.
if item['frame']['subject'] * item['frame']['query'] > 0:
query = blastHits.fasta[item['readNum']].seq
reverse = False
else:
# One of the subject or query has negative sense.
query = blastHits.fasta[
item['readNum']].reverse_complement().seq
reverse = True
query = query.upper()
queryStart = hsp['queryStart']
subjectStart = hsp['subjectStart']
queryEnd = hsp['queryEnd']
subjectEnd = hsp['subjectEnd']
# Before comparing the read to the subject, make a string of the
# same length as the subject, which contains the read and
# has ' ' where the read does not match.
# 3 parts need to be taken into account:
# 1) the left offset (if the query doesn't stick out to the left)
# 2) the query. if the frame is -1, it has to be reversed.
# The query consists of 3 parts: left, middle (control for gaps)
# 3) the right offset
# Do part 1) and 2).
if queryStart < 0:
# The query is sticking out to the left.
leftQuery = ''
if subjectStart == 0:
# The match starts at the first base of the subject.
middleLeftQuery = ''
else:
# The match starts into the subject.
# Determine the length of the not matching query
# part to the left.
leftOffset = -1 * queryStart
rightOffset = subjectStart + leftOffset
middleLeftQuery = query[leftOffset:rightOffset]
else:
# The query is not sticking out to the left
# make the left offset.
leftQuery = queryStart * ' '
leftQueryOffset = subjectStart - queryStart
middleLeftQuery = query[:leftQueryOffset]
# Do part 3).
# Disregard gaps in subject while adding.
matchQuery = item['origHsp'].query
matchSubject = item['origHsp'].sbjct
index = 0
mid = ''
for item in range(len(matchQuery)):
if matchSubject[index] != ' ':
mid += matchQuery[index]
index += 1
# if the query has been reversed, turn the matched part around
if reverse:
rev = ''
toReverse = mid
reverseDict = {' ': ' ', '-': '-', 'A': 'T', 'T': 'A',
'C': 'G', 'G': 'C', '.': '.', 'N': 'N'}
for item in toReverse:
newItem = reverseDict[item]
rev += newItem
mid = rev[::-1]
middleQuery = middleLeftQuery + mid
# add right not-matching part of the query
rightQueryOffset = queryEnd - subjectEnd
rightQuery = query[-rightQueryOffset:]
middleQuery += rightQuery
read = leftQuery + middleQuery
# do part 3)
offset = len(subject) - len(read)
# if the read is sticking out to the right
# chop it off
if offset < 0:
read = read[:offset]
# if it's not sticking out, fill the space with ' '
elif offset > 0:
read += offset * ' '
# compare the subject and the read, make a string
# called 'comparison', which contains a '.' if the bases
# are equal and the letter of the read if they are not.
comparison = ''
for readBase, subjectBase in zip(read, subject):
if readBase == ' ':
comparison += ' '
elif readBase == subjectBase:
comparison += '.'
elif readBase != subjectBase:
comparison += readBase
index += 1
que = '%s \t %s' % (queryTitle, comparison)
result.append(que)
# sanity checks
assert (len(comparison) == len(subject)), (
'%d != %d' % (len(comparison), len(subject)))
index = 0
if comparison[index] == ' ':
index += 1
else:
start = index - 1
assert (start == queryStart or start == -1), (
'%s != %s or %s != -1' % (start, queryStart, start))
return result | python | def basePlotter(blastHits, title):
"""
Plot the reads and the subject, so that bases in the reads which are
different from the subject are shown. Else a '.' is shown.
like so:
subject_gi ATGCGTACGTACGACACC
read_1 A......TTC..T
@param blastHits: A L{dark.blast.BlastHits} instance.
@param title: A C{str} sequence title that was matched by BLAST. We plot
the reads that matched this title.
"""
result = []
params = blastHits.plotParams
assert params is not None, ('Oops, it looks like you forgot to run '
'computePlotInfo.')
sequence = ncbidb.getSequence(title, blastHits.records.blastDb)
subject = sequence.seq
gi = title.split('|')[1]
sub = '%s\t \t \t%s' % (gi, subject)
result.append(sub)
plotInfo = blastHits.titles[title]['plotInfo']
assert plotInfo is not None, ('Oops, it looks like you forgot to run '
'computePlotInfo.')
items = plotInfo['items']
count = 0
for item in items:
count += 1
hsp = item['hsp']
queryTitle = blastHits.fasta[item['readNum']].id
# If the product of the subject and query frame values is +ve,
# then they're either both +ve or both -ve, so we just use the
# query as is. Otherwise, we need to reverse complement it.
if item['frame']['subject'] * item['frame']['query'] > 0:
query = blastHits.fasta[item['readNum']].seq
reverse = False
else:
# One of the subject or query has negative sense.
query = blastHits.fasta[
item['readNum']].reverse_complement().seq
reverse = True
query = query.upper()
queryStart = hsp['queryStart']
subjectStart = hsp['subjectStart']
queryEnd = hsp['queryEnd']
subjectEnd = hsp['subjectEnd']
# Before comparing the read to the subject, make a string of the
# same length as the subject, which contains the read and
# has ' ' where the read does not match.
# 3 parts need to be taken into account:
# 1) the left offset (if the query doesn't stick out to the left)
# 2) the query. if the frame is -1, it has to be reversed.
# The query consists of 3 parts: left, middle (control for gaps)
# 3) the right offset
# Do part 1) and 2).
if queryStart < 0:
# The query is sticking out to the left.
leftQuery = ''
if subjectStart == 0:
# The match starts at the first base of the subject.
middleLeftQuery = ''
else:
# The match starts into the subject.
# Determine the length of the not matching query
# part to the left.
leftOffset = -1 * queryStart
rightOffset = subjectStart + leftOffset
middleLeftQuery = query[leftOffset:rightOffset]
else:
# The query is not sticking out to the left
# make the left offset.
leftQuery = queryStart * ' '
leftQueryOffset = subjectStart - queryStart
middleLeftQuery = query[:leftQueryOffset]
# Do part 3).
# Disregard gaps in subject while adding.
matchQuery = item['origHsp'].query
matchSubject = item['origHsp'].sbjct
index = 0
mid = ''
for item in range(len(matchQuery)):
if matchSubject[index] != ' ':
mid += matchQuery[index]
index += 1
# if the query has been reversed, turn the matched part around
if reverse:
rev = ''
toReverse = mid
reverseDict = {' ': ' ', '-': '-', 'A': 'T', 'T': 'A',
'C': 'G', 'G': 'C', '.': '.', 'N': 'N'}
for item in toReverse:
newItem = reverseDict[item]
rev += newItem
mid = rev[::-1]
middleQuery = middleLeftQuery + mid
# add right not-matching part of the query
rightQueryOffset = queryEnd - subjectEnd
rightQuery = query[-rightQueryOffset:]
middleQuery += rightQuery
read = leftQuery + middleQuery
# do part 3)
offset = len(subject) - len(read)
# if the read is sticking out to the right
# chop it off
if offset < 0:
read = read[:offset]
# if it's not sticking out, fill the space with ' '
elif offset > 0:
read += offset * ' '
# compare the subject and the read, make a string
# called 'comparison', which contains a '.' if the bases
# are equal and the letter of the read if they are not.
comparison = ''
for readBase, subjectBase in zip(read, subject):
if readBase == ' ':
comparison += ' '
elif readBase == subjectBase:
comparison += '.'
elif readBase != subjectBase:
comparison += readBase
index += 1
que = '%s \t %s' % (queryTitle, comparison)
result.append(que)
# sanity checks
assert (len(comparison) == len(subject)), (
'%d != %d' % (len(comparison), len(subject)))
index = 0
if comparison[index] == ' ':
index += 1
else:
start = index - 1
assert (start == queryStart or start == -1), (
'%s != %s or %s != -1' % (start, queryStart, start))
return result | [
"def",
"basePlotter",
"(",
"blastHits",
",",
"title",
")",
":",
"result",
"=",
"[",
"]",
"params",
"=",
"blastHits",
".",
"plotParams",
"assert",
"params",
"is",
"not",
"None",
",",
"(",
"'Oops, it looks like you forgot to run '",
"'computePlotInfo.'",
")",
"seq... | Plot the reads and the subject, so that bases in the reads which are
different from the subject are shown. Else a '.' is shown.
like so:
subject_gi ATGCGTACGTACGACACC
read_1 A......TTC..T
@param blastHits: A L{dark.blast.BlastHits} instance.
@param title: A C{str} sequence title that was matched by BLAST. We plot
the reads that matched this title. | [
"Plot",
"the",
"reads",
"and",
"the",
"subject",
"so",
"that",
"bases",
"in",
"the",
"reads",
"which",
"are",
"different",
"from",
"the",
"subject",
"are",
"shown",
".",
"Else",
"a",
".",
"is",
"shown",
".",
"like",
"so",
":",
"subject_gi",
"ATGCGTACGTAC... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/mutations.py#L30-L178 |
acorg/dark-matter | dark/mutations.py | getAPOBECFrequencies | def getAPOBECFrequencies(dotAlignment, orig, new, pattern):
"""
Gets mutation frequencies if they are in a certain pattern.
@param dotAlignment: result from calling basePlotter
@param orig: A C{str}, naming the original base
@param new: A C{str}, what orig was mutated to
@param pattern: A C{str}m which pattern we're looking for
(must be one of 'cPattern', 'tPattern')
"""
cPattern = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG', 'CCT',
'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC', 'TCG', 'TCT']
tPattern = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG', 'CTT',
'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC', 'TTG', 'TTT']
# choose the right pattern
if pattern == 'cPattern':
patterns = cPattern
middleBase = 'C'
else:
patterns = tPattern
middleBase = 'T'
# generate the freqs dict with the right pattern
freqs = defaultdict(int)
for pattern in patterns:
freqs[pattern] = 0
# get the subject sequence from dotAlignment
subject = dotAlignment[0].split('\t')[3]
# exclude the subject from the dotAlignment, so just the queries
# are left over
queries = dotAlignment[1:]
for item in queries:
query = item.split('\t')[1]
index = 0
for queryBase in query:
qBase = query[index]
sBase = subject[index]
if qBase == new and sBase == orig:
try:
plusSb = subject[index + 1]
minusSb = subject[index - 1]
except IndexError:
plusSb = 'end'
motif = '%s%s%s' % (minusSb, middleBase, plusSb)
if motif in freqs:
freqs[motif] += 1
index += 1
return freqs | python | def getAPOBECFrequencies(dotAlignment, orig, new, pattern):
"""
Gets mutation frequencies if they are in a certain pattern.
@param dotAlignment: result from calling basePlotter
@param orig: A C{str}, naming the original base
@param new: A C{str}, what orig was mutated to
@param pattern: A C{str}m which pattern we're looking for
(must be one of 'cPattern', 'tPattern')
"""
cPattern = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG', 'CCT',
'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC', 'TCG', 'TCT']
tPattern = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG', 'CTT',
'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC', 'TTG', 'TTT']
# choose the right pattern
if pattern == 'cPattern':
patterns = cPattern
middleBase = 'C'
else:
patterns = tPattern
middleBase = 'T'
# generate the freqs dict with the right pattern
freqs = defaultdict(int)
for pattern in patterns:
freqs[pattern] = 0
# get the subject sequence from dotAlignment
subject = dotAlignment[0].split('\t')[3]
# exclude the subject from the dotAlignment, so just the queries
# are left over
queries = dotAlignment[1:]
for item in queries:
query = item.split('\t')[1]
index = 0
for queryBase in query:
qBase = query[index]
sBase = subject[index]
if qBase == new and sBase == orig:
try:
plusSb = subject[index + 1]
minusSb = subject[index - 1]
except IndexError:
plusSb = 'end'
motif = '%s%s%s' % (minusSb, middleBase, plusSb)
if motif in freqs:
freqs[motif] += 1
index += 1
return freqs | [
"def",
"getAPOBECFrequencies",
"(",
"dotAlignment",
",",
"orig",
",",
"new",
",",
"pattern",
")",
":",
"cPattern",
"=",
"[",
"'ACA'",
",",
"'ACC'",
",",
"'ACG'",
",",
"'ACT'",
",",
"'CCA'",
",",
"'CCC'",
",",
"'CCG'",
",",
"'CCT'",
",",
"'GCA'",
",",
... | Gets mutation frequencies if they are in a certain pattern.
@param dotAlignment: result from calling basePlotter
@param orig: A C{str}, naming the original base
@param new: A C{str}, what orig was mutated to
@param pattern: A C{str}m which pattern we're looking for
(must be one of 'cPattern', 'tPattern') | [
"Gets",
"mutation",
"frequencies",
"if",
"they",
"are",
"in",
"a",
"certain",
"pattern",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/mutations.py#L181-L228 |
acorg/dark-matter | dark/mutations.py | getCompleteFreqs | def getCompleteFreqs(blastHits):
"""
Make a dictionary which collects all mutation frequencies from
all reads.
Calls basePlotter to get dotAlignment, which is passed to
getAPOBECFrequencies with the respective parameter, to collect
the frequencies.
@param blastHits: A L{dark.blast.BlastHits} instance.
"""
allFreqs = {}
for title in blastHits.titles:
allFreqs[title] = {
'C>A': {},
'C>G': {},
'C>T': {},
'T>A': {},
'T>C': {},
'T>G': {},
}
basesPlotted = basePlotter(blastHits, title)
for mutation in allFreqs[title]:
orig = mutation[0]
new = mutation[2]
if orig == 'C':
pattern = 'cPattern'
else:
pattern = 'tPattern'
freqs = getAPOBECFrequencies(basesPlotted, orig, new, pattern)
allFreqs[title][mutation] = freqs
numberOfReads = len(blastHits.titles[title]['plotInfo']['items'])
allFreqs[title]['numberOfReads'] = numberOfReads
allFreqs[title]['bitScoreMax'] = blastHits.titles[
title]['plotInfo']['bitScoreMax']
return allFreqs | python | def getCompleteFreqs(blastHits):
"""
Make a dictionary which collects all mutation frequencies from
all reads.
Calls basePlotter to get dotAlignment, which is passed to
getAPOBECFrequencies with the respective parameter, to collect
the frequencies.
@param blastHits: A L{dark.blast.BlastHits} instance.
"""
allFreqs = {}
for title in blastHits.titles:
allFreqs[title] = {
'C>A': {},
'C>G': {},
'C>T': {},
'T>A': {},
'T>C': {},
'T>G': {},
}
basesPlotted = basePlotter(blastHits, title)
for mutation in allFreqs[title]:
orig = mutation[0]
new = mutation[2]
if orig == 'C':
pattern = 'cPattern'
else:
pattern = 'tPattern'
freqs = getAPOBECFrequencies(basesPlotted, orig, new, pattern)
allFreqs[title][mutation] = freqs
numberOfReads = len(blastHits.titles[title]['plotInfo']['items'])
allFreqs[title]['numberOfReads'] = numberOfReads
allFreqs[title]['bitScoreMax'] = blastHits.titles[
title]['plotInfo']['bitScoreMax']
return allFreqs | [
"def",
"getCompleteFreqs",
"(",
"blastHits",
")",
":",
"allFreqs",
"=",
"{",
"}",
"for",
"title",
"in",
"blastHits",
".",
"titles",
":",
"allFreqs",
"[",
"title",
"]",
"=",
"{",
"'C>A'",
":",
"{",
"}",
",",
"'C>G'",
":",
"{",
"}",
",",
"'C>T'",
":"... | Make a dictionary which collects all mutation frequencies from
all reads.
Calls basePlotter to get dotAlignment, which is passed to
getAPOBECFrequencies with the respective parameter, to collect
the frequencies.
@param blastHits: A L{dark.blast.BlastHits} instance. | [
"Make",
"a",
"dictionary",
"which",
"collects",
"all",
"mutation",
"frequencies",
"from",
"all",
"reads",
".",
"Calls",
"basePlotter",
"to",
"get",
"dotAlignment",
"which",
"is",
"passed",
"to",
"getAPOBECFrequencies",
"with",
"the",
"respective",
"parameter",
"to... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/mutations.py#L231-L265 |
acorg/dark-matter | dark/mutations.py | makeFrequencyGraph | def makeFrequencyGraph(allFreqs, title, substitution, pattern,
color='blue', createFigure=True, showFigure=True,
readsAx=False):
"""
For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param title: A C{str}, title of virus of which frequencies should be
plotted.
@param substitution: A C{str}, which substitution should be plotted;
must be one of 'C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G'.
@param pattern: A C{str}, which pattern we're looking for ( must be
one of 'cPattern', 'tPattern')
@param color: A C{str}, color of bars.
@param createFigure: If C{True}, create a figure.
@param showFigure: If C{True}, show the created figure.
@param readsAx: If not None, use this as the subplot for displaying reads.
"""
cPattern = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG', 'CCT',
'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC', 'TCG', 'TCT']
tPattern = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG', 'CTT',
'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC', 'TTG', 'TTT']
# choose the right pattern
if pattern == 'cPattern':
patterns = cPattern
else:
patterns = tPattern
fig = plt.figure(figsize=(10, 10))
ax = readsAx or fig.add_subplot(111)
# how many bars
N = 16
ind = np.arange(N)
width = 0.4
# make a list in the right order, so that it can be plotted easily
divisor = allFreqs[title]['numberOfReads']
toPlot = allFreqs[title][substitution]
index = 0
data = []
for item in patterns:
newData = toPlot[patterns[index]] / divisor
data.append(newData)
index += 1
# create the bars
ax.bar(ind, data, width, color=color)
maxY = np.max(data) + 5
# axes and labels
if createFigure:
title = title.split('|')[4][:50]
ax.set_title('%s \n %s' % (title, substitution), fontsize=20)
ax.set_ylim(0, maxY)
ax.set_ylabel('Absolute Number of Mutations', fontsize=16)
ax.set_xticks(ind + width)
ax.set_xticklabels(patterns, rotation=45, fontsize=8)
if createFigure is False:
ax.set_xticks(ind + width)
ax.set_xticklabels(patterns, rotation=45, fontsize=0)
else:
if showFigure:
plt.show()
return maxY | python | def makeFrequencyGraph(allFreqs, title, substitution, pattern,
color='blue', createFigure=True, showFigure=True,
readsAx=False):
"""
For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param title: A C{str}, title of virus of which frequencies should be
plotted.
@param substitution: A C{str}, which substitution should be plotted;
must be one of 'C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G'.
@param pattern: A C{str}, which pattern we're looking for ( must be
one of 'cPattern', 'tPattern')
@param color: A C{str}, color of bars.
@param createFigure: If C{True}, create a figure.
@param showFigure: If C{True}, show the created figure.
@param readsAx: If not None, use this as the subplot for displaying reads.
"""
cPattern = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG', 'CCT',
'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC', 'TCG', 'TCT']
tPattern = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG', 'CTT',
'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC', 'TTG', 'TTT']
# choose the right pattern
if pattern == 'cPattern':
patterns = cPattern
else:
patterns = tPattern
fig = plt.figure(figsize=(10, 10))
ax = readsAx or fig.add_subplot(111)
# how many bars
N = 16
ind = np.arange(N)
width = 0.4
# make a list in the right order, so that it can be plotted easily
divisor = allFreqs[title]['numberOfReads']
toPlot = allFreqs[title][substitution]
index = 0
data = []
for item in patterns:
newData = toPlot[patterns[index]] / divisor
data.append(newData)
index += 1
# create the bars
ax.bar(ind, data, width, color=color)
maxY = np.max(data) + 5
# axes and labels
if createFigure:
title = title.split('|')[4][:50]
ax.set_title('%s \n %s' % (title, substitution), fontsize=20)
ax.set_ylim(0, maxY)
ax.set_ylabel('Absolute Number of Mutations', fontsize=16)
ax.set_xticks(ind + width)
ax.set_xticklabels(patterns, rotation=45, fontsize=8)
if createFigure is False:
ax.set_xticks(ind + width)
ax.set_xticklabels(patterns, rotation=45, fontsize=0)
else:
if showFigure:
plt.show()
return maxY | [
"def",
"makeFrequencyGraph",
"(",
"allFreqs",
",",
"title",
",",
"substitution",
",",
"pattern",
",",
"color",
"=",
"'blue'",
",",
"createFigure",
"=",
"True",
",",
"showFigure",
"=",
"True",
",",
"readsAx",
"=",
"False",
")",
":",
"cPattern",
"=",
"[",
... | For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param title: A C{str}, title of virus of which frequencies should be
plotted.
@param substitution: A C{str}, which substitution should be plotted;
must be one of 'C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G'.
@param pattern: A C{str}, which pattern we're looking for ( must be
one of 'cPattern', 'tPattern')
@param color: A C{str}, color of bars.
@param createFigure: If C{True}, create a figure.
@param showFigure: If C{True}, show the created figure.
@param readsAx: If not None, use this as the subplot for displaying reads. | [
"For",
"a",
"title",
"make",
"a",
"graph",
"showing",
"the",
"frequencies",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/mutations.py#L268-L329 |
acorg/dark-matter | dark/mutations.py | makeFrequencyPanel | def makeFrequencyPanel(allFreqs, patientName):
"""
For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param patientName: A C{str}, title for the panel
"""
titles = sorted(
iter(allFreqs.keys()),
key=lambda title: (allFreqs[title]['bitScoreMax'], title))
origMaxY = 0
cols = 6
rows = len(allFreqs)
figure, ax = plt.subplots(rows, cols, squeeze=False)
substitutions = ['C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G']
colors = ['blue', 'black', 'red', 'yellow', 'green', 'orange']
for i, title in enumerate(titles):
for index in range(6):
for subst in allFreqs[str(title)]:
substitution = substitutions[index]
print(i, index, title, 'substitution', substitutions[index])
if substitution[0] == 'C':
pattern = 'cPattern'
else:
pattern = 'tPattern'
maxY = makeFrequencyGraph(allFreqs, title, substitution,
pattern, color=colors[index],
createFigure=False, showFigure=False,
readsAx=ax[i][index])
if maxY > origMaxY:
origMaxY = maxY
# add title for individual plot.
# if used for other viruses, this will have to be adapted.
if index == 0:
gi = title.split('|')[1]
titles = title.split(' ')
try:
typeIndex = titles.index('type')
except ValueError:
typeNumber = 'gi: %s' % gi
else:
typeNumber = titles[typeIndex + 1]
ax[i][index].set_ylabel(('Type %s \n maxBitScore: %s' % (
typeNumber, allFreqs[title]['bitScoreMax'])), fontsize=10)
# add xAxis tick labels
if i == 0:
ax[i][index].set_title(substitution, fontsize=13)
if i == len(allFreqs) - 1 or i == (len(allFreqs) - 1) / 2:
if index < 3:
pat = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG',
'CCT', 'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC',
'TCG', 'TCT']
else:
pat = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG',
'CTT', 'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC',
'TTG', 'TTT']
ax[i][index].set_xticklabels(pat, rotation=45, fontsize=8)
# make Y-axis equal
for i, title in enumerate(allFreqs):
for index in range(6):
a = ax[i][index]
a.set_ylim([0, origMaxY])
# add title of whole panel
figure.suptitle('Mutation Signatures in %s' % patientName, fontsize=20)
figure.set_size_inches(5 * cols, 3 * rows, forward=True)
figure.show()
return allFreqs | python | def makeFrequencyPanel(allFreqs, patientName):
"""
For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param patientName: A C{str}, title for the panel
"""
titles = sorted(
iter(allFreqs.keys()),
key=lambda title: (allFreqs[title]['bitScoreMax'], title))
origMaxY = 0
cols = 6
rows = len(allFreqs)
figure, ax = plt.subplots(rows, cols, squeeze=False)
substitutions = ['C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G']
colors = ['blue', 'black', 'red', 'yellow', 'green', 'orange']
for i, title in enumerate(titles):
for index in range(6):
for subst in allFreqs[str(title)]:
substitution = substitutions[index]
print(i, index, title, 'substitution', substitutions[index])
if substitution[0] == 'C':
pattern = 'cPattern'
else:
pattern = 'tPattern'
maxY = makeFrequencyGraph(allFreqs, title, substitution,
pattern, color=colors[index],
createFigure=False, showFigure=False,
readsAx=ax[i][index])
if maxY > origMaxY:
origMaxY = maxY
# add title for individual plot.
# if used for other viruses, this will have to be adapted.
if index == 0:
gi = title.split('|')[1]
titles = title.split(' ')
try:
typeIndex = titles.index('type')
except ValueError:
typeNumber = 'gi: %s' % gi
else:
typeNumber = titles[typeIndex + 1]
ax[i][index].set_ylabel(('Type %s \n maxBitScore: %s' % (
typeNumber, allFreqs[title]['bitScoreMax'])), fontsize=10)
# add xAxis tick labels
if i == 0:
ax[i][index].set_title(substitution, fontsize=13)
if i == len(allFreqs) - 1 or i == (len(allFreqs) - 1) / 2:
if index < 3:
pat = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG',
'CCT', 'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC',
'TCG', 'TCT']
else:
pat = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG',
'CTT', 'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC',
'TTG', 'TTT']
ax[i][index].set_xticklabels(pat, rotation=45, fontsize=8)
# make Y-axis equal
for i, title in enumerate(allFreqs):
for index in range(6):
a = ax[i][index]
a.set_ylim([0, origMaxY])
# add title of whole panel
figure.suptitle('Mutation Signatures in %s' % patientName, fontsize=20)
figure.set_size_inches(5 * cols, 3 * rows, forward=True)
figure.show()
return allFreqs | [
"def",
"makeFrequencyPanel",
"(",
"allFreqs",
",",
"patientName",
")",
":",
"titles",
"=",
"sorted",
"(",
"iter",
"(",
"allFreqs",
".",
"keys",
"(",
")",
")",
",",
"key",
"=",
"lambda",
"title",
":",
"(",
"allFreqs",
"[",
"title",
"]",
"[",
"'bitScoreM... | For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param patientName: A C{str}, title for the panel | [
"For",
"a",
"title",
"make",
"a",
"graph",
"showing",
"the",
"frequencies",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/mutations.py#L332-L404 |
acorg/dark-matter | dark/mutations.py | mutateString | def mutateString(original, n, replacements='acgt'):
"""
Mutate C{original} in C{n} places with chars chosen from C{replacements}.
@param original: The original C{str} to mutate.
@param n: The C{int} number of locations to mutate.
@param replacements: The C{str} of replacement letters.
@return: A new C{str} with C{n} places of C{original} mutated.
@raises ValueError: if C{n} is too high, or C{replacement} contains
duplicates, or if no replacement can be made at a certain locus
because C{replacements} is of length one, or if C{original} is of
zero length.
"""
if not original:
raise ValueError('Empty original string passed.')
if n > len(original):
raise ValueError('Cannot make %d mutations in a string of length %d' %
(n, len(original)))
if len(replacements) != len(set(replacements)):
raise ValueError('Replacement string contains duplicates')
if len(replacements) == 1 and original.find(replacements) != -1:
raise ValueError('Impossible replacement')
result = list(original)
length = len(original)
for offset in range(length):
if uniform(0.0, 1.0) < float(n) / (length - offset):
# Mutate.
while True:
new = choice(replacements)
if new != result[offset]:
result[offset] = new
break
n -= 1
if n == 0:
break
return ''.join(result) | python | def mutateString(original, n, replacements='acgt'):
"""
Mutate C{original} in C{n} places with chars chosen from C{replacements}.
@param original: The original C{str} to mutate.
@param n: The C{int} number of locations to mutate.
@param replacements: The C{str} of replacement letters.
@return: A new C{str} with C{n} places of C{original} mutated.
@raises ValueError: if C{n} is too high, or C{replacement} contains
duplicates, or if no replacement can be made at a certain locus
because C{replacements} is of length one, or if C{original} is of
zero length.
"""
if not original:
raise ValueError('Empty original string passed.')
if n > len(original):
raise ValueError('Cannot make %d mutations in a string of length %d' %
(n, len(original)))
if len(replacements) != len(set(replacements)):
raise ValueError('Replacement string contains duplicates')
if len(replacements) == 1 and original.find(replacements) != -1:
raise ValueError('Impossible replacement')
result = list(original)
length = len(original)
for offset in range(length):
if uniform(0.0, 1.0) < float(n) / (length - offset):
# Mutate.
while True:
new = choice(replacements)
if new != result[offset]:
result[offset] = new
break
n -= 1
if n == 0:
break
return ''.join(result) | [
"def",
"mutateString",
"(",
"original",
",",
"n",
",",
"replacements",
"=",
"'acgt'",
")",
":",
"if",
"not",
"original",
":",
"raise",
"ValueError",
"(",
"'Empty original string passed.'",
")",
"if",
"n",
">",
"len",
"(",
"original",
")",
":",
"raise",
"Va... | Mutate C{original} in C{n} places with chars chosen from C{replacements}.
@param original: The original C{str} to mutate.
@param n: The C{int} number of locations to mutate.
@param replacements: The C{str} of replacement letters.
@return: A new C{str} with C{n} places of C{original} mutated.
@raises ValueError: if C{n} is too high, or C{replacement} contains
duplicates, or if no replacement can be made at a certain locus
because C{replacements} is of length one, or if C{original} is of
zero length. | [
"Mutate",
"C",
"{",
"original",
"}",
"in",
"C",
"{",
"n",
"}",
"places",
"with",
"chars",
"chosen",
"from",
"C",
"{",
"replacements",
"}",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/mutations.py#L407-L449 |
acorg/dark-matter | bin/filter-fasta-by-taxonomy.py | writeDetails | def writeDetails(accept, readId, taxonomy, fp):
"""
Write read and taxonomy details.
@param accept: A C{bool} indicating whether the read was accepted,
according to its taxonomy.
@param readId: The C{str} id of the read.
@taxonomy: A C{list} of taxonomy C{str} levels.
@fp: An open file pointer to write to.
"""
fp.write('%s %s\n %s\n\n' % (
'MATCH:' if accept else 'MISS: ', readId,
' | '.join(taxonomy) if taxonomy else 'No taxonomy found.')) | python | def writeDetails(accept, readId, taxonomy, fp):
"""
Write read and taxonomy details.
@param accept: A C{bool} indicating whether the read was accepted,
according to its taxonomy.
@param readId: The C{str} id of the read.
@taxonomy: A C{list} of taxonomy C{str} levels.
@fp: An open file pointer to write to.
"""
fp.write('%s %s\n %s\n\n' % (
'MATCH:' if accept else 'MISS: ', readId,
' | '.join(taxonomy) if taxonomy else 'No taxonomy found.')) | [
"def",
"writeDetails",
"(",
"accept",
",",
"readId",
",",
"taxonomy",
",",
"fp",
")",
":",
"fp",
".",
"write",
"(",
"'%s %s\\n %s\\n\\n'",
"%",
"(",
"'MATCH:'",
"if",
"accept",
"else",
"'MISS: '",
",",
"readId",
",",
"' | '",
".",
"join",
"(",
"tax... | Write read and taxonomy details.
@param accept: A C{bool} indicating whether the read was accepted,
according to its taxonomy.
@param readId: The C{str} id of the read.
@taxonomy: A C{list} of taxonomy C{str} levels.
@fp: An open file pointer to write to. | [
"Write",
"read",
"and",
"taxonomy",
"details",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/filter-fasta-by-taxonomy.py#L32-L44 |
ikegami-yukino/shellinford-python | shellinford/shellinford.py | FMIndex.build | def build(self, docs=None, filename=None):
"""Build FM-index
Params:
<iterator> | <generator> docs
<str> filename
"""
if docs:
if hasattr(docs, 'items'):
for (idx, doc) in sorted(getattr(docs, 'items')(),
key=lambda x: x[0]):
self.fm.push_back(doc)
else:
for doc in filter(bool, docs):
self.fm.push_back(doc)
self.fm.build()
if filename:
self.fm.write(filename) | python | def build(self, docs=None, filename=None):
"""Build FM-index
Params:
<iterator> | <generator> docs
<str> filename
"""
if docs:
if hasattr(docs, 'items'):
for (idx, doc) in sorted(getattr(docs, 'items')(),
key=lambda x: x[0]):
self.fm.push_back(doc)
else:
for doc in filter(bool, docs):
self.fm.push_back(doc)
self.fm.build()
if filename:
self.fm.write(filename) | [
"def",
"build",
"(",
"self",
",",
"docs",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"docs",
":",
"if",
"hasattr",
"(",
"docs",
",",
"'items'",
")",
":",
"for",
"(",
"idx",
",",
"doc",
")",
"in",
"sorted",
"(",
"getattr",
"(",
"... | Build FM-index
Params:
<iterator> | <generator> docs
<str> filename | [
"Build",
"FM",
"-",
"index",
"Params",
":",
"<iterator",
">",
"|",
"<generator",
">",
"docs",
"<str",
">",
"filename"
] | train | https://github.com/ikegami-yukino/shellinford-python/blob/ea4d4280e05a15543aa5cd405f90b2c503916dc9/shellinford/shellinford.py#L419-L435 |
ikegami-yukino/shellinford-python | shellinford/shellinford.py | FMIndex._merge_search_result | def _merge_search_result(self, search_results, _or=False):
"""Merge of filter search results
Params:
<str> | <Sequential> query
<bool> _or
Return:
<list> computed_dids
"""
all_docids = reduce(add, [list(x.keys()) for x in search_results])
if _or:
return sorted(set(all_docids), key=all_docids.index)
return [docid for docid in set(all_docids) if all_docids.count(docid) > 1] | python | def _merge_search_result(self, search_results, _or=False):
"""Merge of filter search results
Params:
<str> | <Sequential> query
<bool> _or
Return:
<list> computed_dids
"""
all_docids = reduce(add, [list(x.keys()) for x in search_results])
if _or:
return sorted(set(all_docids), key=all_docids.index)
return [docid for docid in set(all_docids) if all_docids.count(docid) > 1] | [
"def",
"_merge_search_result",
"(",
"self",
",",
"search_results",
",",
"_or",
"=",
"False",
")",
":",
"all_docids",
"=",
"reduce",
"(",
"add",
",",
"[",
"list",
"(",
"x",
".",
"keys",
"(",
")",
")",
"for",
"x",
"in",
"search_results",
"]",
")",
"if"... | Merge of filter search results
Params:
<str> | <Sequential> query
<bool> _or
Return:
<list> computed_dids | [
"Merge",
"of",
"filter",
"search",
"results",
"Params",
":",
"<str",
">",
"|",
"<Sequential",
">",
"query",
"<bool",
">",
"_or",
"Return",
":",
"<list",
">",
"computed_dids"
] | train | https://github.com/ikegami-yukino/shellinford-python/blob/ea4d4280e05a15543aa5cd405f90b2c503916dc9/shellinford/shellinford.py#L437-L448 |
ikegami-yukino/shellinford-python | shellinford/shellinford.py | FMIndex.search | def search(self, query, _or=False, ignores=[]):
"""Search word from FM-index
Params:
<str> | <Sequential> query
<bool> _or
<list <str> > ignores
Return:
<list>SEARCH_RESULT(<int> document_id,
<list <int> > counts
<str> doc)
"""
if isinstance(query, str):
dids = MapIntInt({})
self.fm.search(query, dids)
dids = dids.asdict()
result = []
for did in sorted(dids.keys()):
doc = self.fm.get_document(did)
if not any(ignore in doc for ignore in ignores):
count = dids[did]
result.append(SEARCH_RESULT(int(did), [count], doc))
return result
search_results = []
for q in query:
dids = MapIntInt({})
self.fm.search(q, dids)
search_results.append(dids.asdict())
merged_dids = self._merge_search_result(search_results, _or)
result = []
for did in merged_dids:
doc = self.fm.get_document(did)
if not any(ignore in doc for ignore in ignores):
counts = map(lambda x: int(x.pop(did, 0)), search_results)
result.append(SEARCH_RESULT(int(did), list(counts), doc))
return result | python | def search(self, query, _or=False, ignores=[]):
"""Search word from FM-index
Params:
<str> | <Sequential> query
<bool> _or
<list <str> > ignores
Return:
<list>SEARCH_RESULT(<int> document_id,
<list <int> > counts
<str> doc)
"""
if isinstance(query, str):
dids = MapIntInt({})
self.fm.search(query, dids)
dids = dids.asdict()
result = []
for did in sorted(dids.keys()):
doc = self.fm.get_document(did)
if not any(ignore in doc for ignore in ignores):
count = dids[did]
result.append(SEARCH_RESULT(int(did), [count], doc))
return result
search_results = []
for q in query:
dids = MapIntInt({})
self.fm.search(q, dids)
search_results.append(dids.asdict())
merged_dids = self._merge_search_result(search_results, _or)
result = []
for did in merged_dids:
doc = self.fm.get_document(did)
if not any(ignore in doc for ignore in ignores):
counts = map(lambda x: int(x.pop(did, 0)), search_results)
result.append(SEARCH_RESULT(int(did), list(counts), doc))
return result | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"_or",
"=",
"False",
",",
"ignores",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"query",
",",
"str",
")",
":",
"dids",
"=",
"MapIntInt",
"(",
"{",
"}",
")",
"self",
".",
"fm",
".",
"search... | Search word from FM-index
Params:
<str> | <Sequential> query
<bool> _or
<list <str> > ignores
Return:
<list>SEARCH_RESULT(<int> document_id,
<list <int> > counts
<str> doc) | [
"Search",
"word",
"from",
"FM",
"-",
"index",
"Params",
":",
"<str",
">",
"|",
"<Sequential",
">",
"query",
"<bool",
">",
"_or",
"<list",
"<str",
">",
">",
"ignores",
"Return",
":",
"<list",
">",
"SEARCH_RESULT",
"(",
"<int",
">",
"document_id",
"<list",... | train | https://github.com/ikegami-yukino/shellinford-python/blob/ea4d4280e05a15543aa5cd405f90b2c503916dc9/shellinford/shellinford.py#L450-L485 |
ikegami-yukino/shellinford-python | shellinford/shellinford.py | FMIndex.count | def count(self, query, _or=False):
"""Count word from FM-index
Params:
<str> | <Sequential> query
<bool> _or
<list <str> > ignores
Return:
<int> counts
"""
if isinstance(query, str):
return self.fm.count(query, MapIntInt({}))
else:
search_results = []
for q in query:
dids = MapIntInt({})
self.fm.search(q, dids)
search_results.append(dids.asdict())
merged_dids = self._merge_search_result(search_results, _or)
counts = 0
for did in merged_dids:
if _or:
counts += reduce(add, [int(x.pop(did, 0)) for x in search_results])
else:
counts += min([int(x.pop(did, 0)) for x in search_results])
return counts | python | def count(self, query, _or=False):
"""Count word from FM-index
Params:
<str> | <Sequential> query
<bool> _or
<list <str> > ignores
Return:
<int> counts
"""
if isinstance(query, str):
return self.fm.count(query, MapIntInt({}))
else:
search_results = []
for q in query:
dids = MapIntInt({})
self.fm.search(q, dids)
search_results.append(dids.asdict())
merged_dids = self._merge_search_result(search_results, _or)
counts = 0
for did in merged_dids:
if _or:
counts += reduce(add, [int(x.pop(did, 0)) for x in search_results])
else:
counts += min([int(x.pop(did, 0)) for x in search_results])
return counts | [
"def",
"count",
"(",
"self",
",",
"query",
",",
"_or",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"query",
",",
"str",
")",
":",
"return",
"self",
".",
"fm",
".",
"count",
"(",
"query",
",",
"MapIntInt",
"(",
"{",
"}",
")",
")",
"else",
"... | Count word from FM-index
Params:
<str> | <Sequential> query
<bool> _or
<list <str> > ignores
Return:
<int> counts | [
"Count",
"word",
"from",
"FM",
"-",
"index",
"Params",
":",
"<str",
">",
"|",
"<Sequential",
">",
"query",
"<bool",
">",
"_or",
"<list",
"<str",
">",
">",
"ignores",
"Return",
":",
"<int",
">",
"counts"
] | train | https://github.com/ikegami-yukino/shellinford-python/blob/ea4d4280e05a15543aa5cd405f90b2c503916dc9/shellinford/shellinford.py#L487-L511 |
invenia/Arbiter | arbiter/graph.py | Graph.add | def add(self, name, parents=None):
"""
add a node to the graph.
Raises an exception if the node cannot be added (i.e., if a node
that name already exists, or if it would create a cycle.
NOTE: A node can be added before its parents are added.
name: The name of the node to add to the graph. Name can be any
unique Hashable value.
parents: (optional, None) The name of the nodes parents.
"""
if not isinstance(name, Hashable):
raise TypeError(name)
parents = set(parents or ())
is_stub = False
if name in self._nodes:
if name in self._stubs:
node = Node(name, self._nodes[name].children, parents)
is_stub = True
else:
raise ValueError(name)
else:
node = Node(name, set(), parents)
# cycle detection
visited = set()
for parent in parents:
if self.ancestor_of(parent, name, visited=visited):
raise ValueError(parent)
elif parent == name:
raise ValueError(parent)
# Node safe to add
if is_stub:
self._stubs.remove(name)
if parents:
for parent_name in parents:
parent_node = self._nodes.get(parent_name)
if parent_node is not None:
parent_node.children.add(name)
else: # add stub
self._nodes[parent_name] = Node(
name=parent_name,
children=set((name,)),
parents=frozenset(),
)
self._stubs.add(parent_name)
else:
self._roots.add(name)
self._nodes[name] = node | python | def add(self, name, parents=None):
"""
add a node to the graph.
Raises an exception if the node cannot be added (i.e., if a node
that name already exists, or if it would create a cycle.
NOTE: A node can be added before its parents are added.
name: The name of the node to add to the graph. Name can be any
unique Hashable value.
parents: (optional, None) The name of the nodes parents.
"""
if not isinstance(name, Hashable):
raise TypeError(name)
parents = set(parents or ())
is_stub = False
if name in self._nodes:
if name in self._stubs:
node = Node(name, self._nodes[name].children, parents)
is_stub = True
else:
raise ValueError(name)
else:
node = Node(name, set(), parents)
# cycle detection
visited = set()
for parent in parents:
if self.ancestor_of(parent, name, visited=visited):
raise ValueError(parent)
elif parent == name:
raise ValueError(parent)
# Node safe to add
if is_stub:
self._stubs.remove(name)
if parents:
for parent_name in parents:
parent_node = self._nodes.get(parent_name)
if parent_node is not None:
parent_node.children.add(name)
else: # add stub
self._nodes[parent_name] = Node(
name=parent_name,
children=set((name,)),
parents=frozenset(),
)
self._stubs.add(parent_name)
else:
self._roots.add(name)
self._nodes[name] = node | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"parents",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"Hashable",
")",
":",
"raise",
"TypeError",
"(",
"name",
")",
"parents",
"=",
"set",
"(",
"parents",
"or",
"(",
")",
")",
... | add a node to the graph.
Raises an exception if the node cannot be added (i.e., if a node
that name already exists, or if it would create a cycle.
NOTE: A node can be added before its parents are added.
name: The name of the node to add to the graph. Name can be any
unique Hashable value.
parents: (optional, None) The name of the nodes parents. | [
"add",
"a",
"node",
"to",
"the",
"graph",
"."
] | train | https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/graph.py#L27-L84 |
invenia/Arbiter | arbiter/graph.py | Graph.remove | def remove(self, name, strategy=Strategy.promote):
"""
Remove a node from the graph. Returns the set of nodes that were
removed.
If the node doesn't exist, an exception will be raised.
name: The name of the node to remove.
strategy: (Optional, Strategy.promote) What to do with children
or removed nodes. The options are:
orphan: remove the node from the child's set of parents.
promote: replace the node with the the node's parents in the
childs set of parents.
remove: recursively remove all children of the node.
"""
removed = set()
stack = [name]
while stack:
current = stack.pop()
node = self._nodes.pop(current)
if strategy == Strategy.remove:
for child_name in node.children:
child_node = self._nodes[child_name]
child_node.parents.remove(current)
stack.append(child_name)
else:
for child_name in node.children:
child_node = self._nodes[child_name]
child_node.parents.remove(current)
if strategy == Strategy.promote:
for parent_name in node.parents:
parent_node = self._nodes[parent_name]
parent_node.children.add(child_name)
child_node.parents.add(parent_name)
if not child_node.parents:
self._roots.add(child_name)
if current in self._stubs:
self._stubs.remove(current)
elif current in self._roots:
self._roots.remove(current)
else: # stubs and roots (by definition) don't have parents
for parent_name in node.parents:
parent_node = self._nodes[parent_name]
parent_node.children.remove(current)
if parent_name in self._stubs and not parent_node.children:
stack.append(parent_name)
removed.add(current)
return removed | python | def remove(self, name, strategy=Strategy.promote):
"""
Remove a node from the graph. Returns the set of nodes that were
removed.
If the node doesn't exist, an exception will be raised.
name: The name of the node to remove.
strategy: (Optional, Strategy.promote) What to do with children
or removed nodes. The options are:
orphan: remove the node from the child's set of parents.
promote: replace the node with the the node's parents in the
childs set of parents.
remove: recursively remove all children of the node.
"""
removed = set()
stack = [name]
while stack:
current = stack.pop()
node = self._nodes.pop(current)
if strategy == Strategy.remove:
for child_name in node.children:
child_node = self._nodes[child_name]
child_node.parents.remove(current)
stack.append(child_name)
else:
for child_name in node.children:
child_node = self._nodes[child_name]
child_node.parents.remove(current)
if strategy == Strategy.promote:
for parent_name in node.parents:
parent_node = self._nodes[parent_name]
parent_node.children.add(child_name)
child_node.parents.add(parent_name)
if not child_node.parents:
self._roots.add(child_name)
if current in self._stubs:
self._stubs.remove(current)
elif current in self._roots:
self._roots.remove(current)
else: # stubs and roots (by definition) don't have parents
for parent_name in node.parents:
parent_node = self._nodes[parent_name]
parent_node.children.remove(current)
if parent_name in self._stubs and not parent_node.children:
stack.append(parent_name)
removed.add(current)
return removed | [
"def",
"remove",
"(",
"self",
",",
"name",
",",
"strategy",
"=",
"Strategy",
".",
"promote",
")",
":",
"removed",
"=",
"set",
"(",
")",
"stack",
"=",
"[",
"name",
"]",
"while",
"stack",
":",
"current",
"=",
"stack",
".",
"pop",
"(",
")",
"node",
... | Remove a node from the graph. Returns the set of nodes that were
removed.
If the node doesn't exist, an exception will be raised.
name: The name of the node to remove.
strategy: (Optional, Strategy.promote) What to do with children
or removed nodes. The options are:
orphan: remove the node from the child's set of parents.
promote: replace the node with the the node's parents in the
childs set of parents.
remove: recursively remove all children of the node. | [
"Remove",
"a",
"node",
"from",
"the",
"graph",
".",
"Returns",
"the",
"set",
"of",
"nodes",
"that",
"were",
"removed",
"."
] | train | https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/graph.py#L86-L148 |
invenia/Arbiter | arbiter/graph.py | Graph.ancestor_of | def ancestor_of(self, name, ancestor, visited=None):
"""
Check whether a node has another node as an ancestor.
name: The name of the node being checked.
ancestor: The name of the (possible) ancestor node.
visited: (optional, None) If given, a set of nodes that have
already been traversed. NOTE: The set will be updated with
any new nodes that are visited.
NOTE: If node doesn't exist, the method will return False.
"""
if visited is None:
visited = set()
node = self._nodes.get(name)
if node is None or name not in self._nodes:
return False
stack = list(node.parents)
while stack:
current = stack.pop()
if current == ancestor:
return True
if current not in visited:
visited.add(current)
node = self._nodes.get(current)
if node is not None:
stack.extend(node.parents)
return False | python | def ancestor_of(self, name, ancestor, visited=None):
"""
Check whether a node has another node as an ancestor.
name: The name of the node being checked.
ancestor: The name of the (possible) ancestor node.
visited: (optional, None) If given, a set of nodes that have
already been traversed. NOTE: The set will be updated with
any new nodes that are visited.
NOTE: If node doesn't exist, the method will return False.
"""
if visited is None:
visited = set()
node = self._nodes.get(name)
if node is None or name not in self._nodes:
return False
stack = list(node.parents)
while stack:
current = stack.pop()
if current == ancestor:
return True
if current not in visited:
visited.add(current)
node = self._nodes.get(current)
if node is not None:
stack.extend(node.parents)
return False | [
"def",
"ancestor_of",
"(",
"self",
",",
"name",
",",
"ancestor",
",",
"visited",
"=",
"None",
")",
":",
"if",
"visited",
"is",
"None",
":",
"visited",
"=",
"set",
"(",
")",
"node",
"=",
"self",
".",
"_nodes",
".",
"get",
"(",
"name",
")",
"if",
"... | Check whether a node has another node as an ancestor.
name: The name of the node being checked.
ancestor: The name of the (possible) ancestor node.
visited: (optional, None) If given, a set of nodes that have
already been traversed. NOTE: The set will be updated with
any new nodes that are visited.
NOTE: If node doesn't exist, the method will return False. | [
"Check",
"whether",
"a",
"node",
"has",
"another",
"node",
"as",
"an",
"ancestor",
"."
] | train | https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/graph.py#L184-L219 |
invenia/Arbiter | arbiter/graph.py | Graph.prune | def prune(self):
"""
Remove any tasks that have stubs as ancestors (and the stubs
themselves).
Returns the set of nodes which were removed.
"""
pruned = set()
stubs = frozenset(self._stubs)
for stub in stubs:
pruned.update(self.remove(stub, strategy=Strategy.remove))
return pruned - stubs | python | def prune(self):
"""
Remove any tasks that have stubs as ancestors (and the stubs
themselves).
Returns the set of nodes which were removed.
"""
pruned = set()
stubs = frozenset(self._stubs)
for stub in stubs:
pruned.update(self.remove(stub, strategy=Strategy.remove))
return pruned - stubs | [
"def",
"prune",
"(",
"self",
")",
":",
"pruned",
"=",
"set",
"(",
")",
"stubs",
"=",
"frozenset",
"(",
"self",
".",
"_stubs",
")",
"for",
"stub",
"in",
"stubs",
":",
"pruned",
".",
"update",
"(",
"self",
".",
"remove",
"(",
"stub",
",",
"strategy",... | Remove any tasks that have stubs as ancestors (and the stubs
themselves).
Returns the set of nodes which were removed. | [
"Remove",
"any",
"tasks",
"that",
"have",
"stubs",
"as",
"ancestors",
"(",
"and",
"the",
"stubs",
"themselves",
")",
"."
] | train | https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/graph.py#L221-L234 |
disqus/overseer | overseer/views.py | respond | def respond(template, context={}, request=None, **kwargs):
"Calls render_to_response with a RequestConext"
from django.http import HttpResponse
from django.template import RequestContext
from django.template.loader import render_to_string
if request:
default = context_processors.default(request)
default.update(context)
else:
default = context.copy()
rendered = render_to_string(template, default, context_instance=request and RequestContext(request) or None)
return HttpResponse(rendered, **kwargs) | python | def respond(template, context={}, request=None, **kwargs):
"Calls render_to_response with a RequestConext"
from django.http import HttpResponse
from django.template import RequestContext
from django.template.loader import render_to_string
if request:
default = context_processors.default(request)
default.update(context)
else:
default = context.copy()
rendered = render_to_string(template, default, context_instance=request and RequestContext(request) or None)
return HttpResponse(rendered, **kwargs) | [
"def",
"respond",
"(",
"template",
",",
"context",
"=",
"{",
"}",
",",
"request",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"django",
".",
"http",
"import",
"HttpResponse",
"from",
"django",
".",
"template",
"import",
"RequestContext",
"fro... | Calls render_to_response with a RequestConext | [
"Calls",
"render_to_response",
"with",
"a",
"RequestConext"
] | train | https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/views.py#L38-L51 |
disqus/overseer | overseer/views.py | index | def index(request):
"Displays a list of all services and their current status."
service_list = Service.objects.all()
event_list = list(Event.objects\
.filter(Q(status__gt=0) | Q(date_updated__gte=datetime.datetime.now()-datetime.timedelta(days=1)))\
.order_by('-date_created')[0:6])
if event_list:
latest_event, event_list = event_list[0], event_list[1:]
else:
latest_event = None
return respond('overseer/index.html', {
'service_list': service_list,
'event_list': event_list,
'latest_event': latest_event,
}, request) | python | def index(request):
"Displays a list of all services and their current status."
service_list = Service.objects.all()
event_list = list(Event.objects\
.filter(Q(status__gt=0) | Q(date_updated__gte=datetime.datetime.now()-datetime.timedelta(days=1)))\
.order_by('-date_created')[0:6])
if event_list:
latest_event, event_list = event_list[0], event_list[1:]
else:
latest_event = None
return respond('overseer/index.html', {
'service_list': service_list,
'event_list': event_list,
'latest_event': latest_event,
}, request) | [
"def",
"index",
"(",
"request",
")",
":",
"service_list",
"=",
"Service",
".",
"objects",
".",
"all",
"(",
")",
"event_list",
"=",
"list",
"(",
"Event",
".",
"objects",
".",
"filter",
"(",
"Q",
"(",
"status__gt",
"=",
"0",
")",
"|",
"Q",
"(",
"date... | Displays a list of all services and their current status. | [
"Displays",
"a",
"list",
"of",
"all",
"services",
"and",
"their",
"current",
"status",
"."
] | train | https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/views.py#L53-L71 |
disqus/overseer | overseer/views.py | service | def service(request, slug):
"Displays a list of all services and their current status."
try:
service = Service.objects.get(slug=slug)
except Service.DoesNotExist:
return HttpResponseRedirect(reverse('overseer:index'))
event_list = service.event_set.order_by('-date_created')
return respond('overseer/service.html', {
'service': service,
'event_list': event_list,
}, request) | python | def service(request, slug):
"Displays a list of all services and their current status."
try:
service = Service.objects.get(slug=slug)
except Service.DoesNotExist:
return HttpResponseRedirect(reverse('overseer:index'))
event_list = service.event_set.order_by('-date_created')
return respond('overseer/service.html', {
'service': service,
'event_list': event_list,
}, request) | [
"def",
"service",
"(",
"request",
",",
"slug",
")",
":",
"try",
":",
"service",
"=",
"Service",
".",
"objects",
".",
"get",
"(",
"slug",
"=",
"slug",
")",
"except",
"Service",
".",
"DoesNotExist",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(... | Displays a list of all services and their current status. | [
"Displays",
"a",
"list",
"of",
"all",
"services",
"and",
"their",
"current",
"status",
"."
] | train | https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/views.py#L73-L86 |
disqus/overseer | overseer/views.py | event | def event(request, id):
"Displays a list of all services and their current status."
try:
evt = Event.objects.get(pk=id)
except Event.DoesNotExist:
return HttpResponseRedirect(reverse('overseer:index'))
update_list = list(evt.eventupdate_set.order_by('-date_created'))
return respond('overseer/event.html', {
'event': evt,
'update_list': update_list,
}, request) | python | def event(request, id):
"Displays a list of all services and their current status."
try:
evt = Event.objects.get(pk=id)
except Event.DoesNotExist:
return HttpResponseRedirect(reverse('overseer:index'))
update_list = list(evt.eventupdate_set.order_by('-date_created'))
return respond('overseer/event.html', {
'event': evt,
'update_list': update_list,
}, request) | [
"def",
"event",
"(",
"request",
",",
"id",
")",
":",
"try",
":",
"evt",
"=",
"Event",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"id",
")",
"except",
"Event",
".",
"DoesNotExist",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'overseer:... | Displays a list of all services and their current status. | [
"Displays",
"a",
"list",
"of",
"all",
"services",
"and",
"their",
"current",
"status",
"."
] | train | https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/views.py#L88-L101 |
disqus/overseer | overseer/views.py | last_event | def last_event(request, slug):
"Displays a list of all services and their current status."
try:
service = Service.objects.get(slug=slug)
except Service.DoesNotExist:
return HttpResponseRedirect(reverse('overseer:index'))
try:
evt = service.event_set.order_by('-date_created')[0]
except IndexError:
return HttpResponseRedirect(service.get_absolute_url())
return event(request, evt.pk) | python | def last_event(request, slug):
"Displays a list of all services and their current status."
try:
service = Service.objects.get(slug=slug)
except Service.DoesNotExist:
return HttpResponseRedirect(reverse('overseer:index'))
try:
evt = service.event_set.order_by('-date_created')[0]
except IndexError:
return HttpResponseRedirect(service.get_absolute_url())
return event(request, evt.pk) | [
"def",
"last_event",
"(",
"request",
",",
"slug",
")",
":",
"try",
":",
"service",
"=",
"Service",
".",
"objects",
".",
"get",
"(",
"slug",
"=",
"slug",
")",
"except",
"Service",
".",
"DoesNotExist",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
... | Displays a list of all services and their current status. | [
"Displays",
"a",
"list",
"of",
"all",
"services",
"and",
"their",
"current",
"status",
"."
] | train | https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/views.py#L103-L116 |
disqus/overseer | overseer/views.py | update_subscription | def update_subscription(request, ident):
"Shows subscriptions options for a verified subscriber."
try:
subscription = Subscription.objects.get(ident=ident)
except Subscription.DoesNotExist:
return respond('overseer/invalid_subscription_token.html', {}, request)
if request.POST:
form = UpdateSubscriptionForm(request.POST, instance=subscription)
if form.is_valid():
if form.cleaned_data['unsubscribe']:
subscription.delete()
return respond('overseer/unsubscribe_confirmed.html', {
'email': subscription.email,
})
else:
form.save()
return HttpResponseRedirect(request.get_full_path())
else:
form = UpdateSubscriptionForm(instance=subscription)
context = csrf(request)
context.update({
'form': form,
'subscription': subscription,
'service_list': Service.objects.all(),
})
return respond('overseer/update_subscription.html', context, request) | python | def update_subscription(request, ident):
"Shows subscriptions options for a verified subscriber."
try:
subscription = Subscription.objects.get(ident=ident)
except Subscription.DoesNotExist:
return respond('overseer/invalid_subscription_token.html', {}, request)
if request.POST:
form = UpdateSubscriptionForm(request.POST, instance=subscription)
if form.is_valid():
if form.cleaned_data['unsubscribe']:
subscription.delete()
return respond('overseer/unsubscribe_confirmed.html', {
'email': subscription.email,
})
else:
form.save()
return HttpResponseRedirect(request.get_full_path())
else:
form = UpdateSubscriptionForm(instance=subscription)
context = csrf(request)
context.update({
'form': form,
'subscription': subscription,
'service_list': Service.objects.all(),
})
return respond('overseer/update_subscription.html', context, request) | [
"def",
"update_subscription",
"(",
"request",
",",
"ident",
")",
":",
"try",
":",
"subscription",
"=",
"Subscription",
".",
"objects",
".",
"get",
"(",
"ident",
"=",
"ident",
")",
"except",
"Subscription",
".",
"DoesNotExist",
":",
"return",
"respond",
"(",
... | Shows subscriptions options for a verified subscriber. | [
"Shows",
"subscriptions",
"options",
"for",
"a",
"verified",
"subscriber",
"."
] | train | https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/views.py#L120-L151 |
disqus/overseer | overseer/views.py | create_subscription | def create_subscription(request):
"Shows subscriptions options for a new subscriber."
if request.POST:
form = NewSubscriptionForm(request.POST)
if form.is_valid():
unverified = form.save()
body = """Please confirm your email address to subscribe to status updates from %(name)s:\n\n%(link)s""" % dict(
name=conf.NAME,
link=urlparse.urljoin(conf.BASE_URL, reverse('overseer:verify_subscription', args=[unverified.ident]))
)
# Send verification email
from_mail = conf.FROM_EMAIL
if not from_mail:
from_mail = 'overseer@%s' % request.get_host().split(':', 1)[0]
send_mail('Confirm Subscription', body, from_mail, [unverified.email],
fail_silently=True)
# Show success page
return respond('overseer/create_subscription_complete.html', {
'subscription': unverified,
}, request)
else:
form = NewSubscriptionForm()
context = csrf(request)
context.update({
'form': form,
'service_list': Service.objects.all(),
})
return respond('overseer/create_subscription.html', context, request) | python | def create_subscription(request):
"Shows subscriptions options for a new subscriber."
if request.POST:
form = NewSubscriptionForm(request.POST)
if form.is_valid():
unverified = form.save()
body = """Please confirm your email address to subscribe to status updates from %(name)s:\n\n%(link)s""" % dict(
name=conf.NAME,
link=urlparse.urljoin(conf.BASE_URL, reverse('overseer:verify_subscription', args=[unverified.ident]))
)
# Send verification email
from_mail = conf.FROM_EMAIL
if not from_mail:
from_mail = 'overseer@%s' % request.get_host().split(':', 1)[0]
send_mail('Confirm Subscription', body, from_mail, [unverified.email],
fail_silently=True)
# Show success page
return respond('overseer/create_subscription_complete.html', {
'subscription': unverified,
}, request)
else:
form = NewSubscriptionForm()
context = csrf(request)
context.update({
'form': form,
'service_list': Service.objects.all(),
})
return respond('overseer/create_subscription.html', context, request) | [
"def",
"create_subscription",
"(",
"request",
")",
":",
"if",
"request",
".",
"POST",
":",
"form",
"=",
"NewSubscriptionForm",
"(",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"unverified",
"=",
"form",
".",
"save",
"(",
... | Shows subscriptions options for a new subscriber. | [
"Shows",
"subscriptions",
"options",
"for",
"a",
"new",
"subscriber",
"."
] | train | https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/views.py#L155-L189 |
disqus/overseer | overseer/views.py | verify_subscription | def verify_subscription(request, ident):
"""
Verifies an unverified subscription and create or appends
to an existing subscription.
"""
try:
unverified = UnverifiedSubscription.objects.get(ident=ident)
except UnverifiedSubscription.DoesNotExist:
return respond('overseer/invalid_subscription_token.html', {}, request)
subscription = Subscription.objects.get_or_create(email=unverified.email, defaults={
'ident': unverified.ident,
})[0]
subscription.services = unverified.services.all()
unverified.delete()
return respond('overseer/subscription_confirmed.html', {
'subscription': subscription,
}, request) | python | def verify_subscription(request, ident):
"""
Verifies an unverified subscription and create or appends
to an existing subscription.
"""
try:
unverified = UnverifiedSubscription.objects.get(ident=ident)
except UnverifiedSubscription.DoesNotExist:
return respond('overseer/invalid_subscription_token.html', {}, request)
subscription = Subscription.objects.get_or_create(email=unverified.email, defaults={
'ident': unverified.ident,
})[0]
subscription.services = unverified.services.all()
unverified.delete()
return respond('overseer/subscription_confirmed.html', {
'subscription': subscription,
}, request) | [
"def",
"verify_subscription",
"(",
"request",
",",
"ident",
")",
":",
"try",
":",
"unverified",
"=",
"UnverifiedSubscription",
".",
"objects",
".",
"get",
"(",
"ident",
"=",
"ident",
")",
"except",
"UnverifiedSubscription",
".",
"DoesNotExist",
":",
"return",
... | Verifies an unverified subscription and create or appends
to an existing subscription. | [
"Verifies",
"an",
"unverified",
"subscription",
"and",
"create",
"or",
"appends",
"to",
"an",
"existing",
"subscription",
"."
] | train | https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/views.py#L192-L213 |
flo-compbio/genometools | genometools/gcloud/storage.py | get_client | def get_client(key, project):
"""Gets a `Client` object (required by the other functions).
TODO: docstring"""
cred = get_storage_credentials(key)
return storage.Client(project=project, credentials=cred) | python | def get_client(key, project):
"""Gets a `Client` object (required by the other functions).
TODO: docstring"""
cred = get_storage_credentials(key)
return storage.Client(project=project, credentials=cred) | [
"def",
"get_client",
"(",
"key",
",",
"project",
")",
":",
"cred",
"=",
"get_storage_credentials",
"(",
"key",
")",
"return",
"storage",
".",
"Client",
"(",
"project",
"=",
"project",
",",
"credentials",
"=",
"cred",
")"
] | Gets a `Client` object (required by the other functions).
TODO: docstring | [
"Gets",
"a",
"Client",
"object",
"(",
"required",
"by",
"the",
"other",
"functions",
")",
".",
"TODO",
":",
"docstring"
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/storage.py#L56-L61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.