INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return a string representation of a patsy ModelDesc object | def _modeldesc_to_dict(self, md):
"""Return a string representation of a patsy ModelDesc object"""
d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]}
rhs_termlist = []
# add other terms, if any
for term in md.rhs_termlist[:]:
if len(term.factors) == 0:
... |
Return a string representation of a patsy ModelDesc object | def _modeldesc_from_dict(self, d):
"""Return a string representation of a patsy ModelDesc object"""
lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])]
rhs_termlist = []
for name in d['rhs_termlist']:
if name == '':
rhs_termlist.append(Term([]))
... |
Calculate the relative abundance of each OTUID in a Sample. | def relative_abundance(biomf, sampleIDs=None):
"""
Calculate the relative abundance of each OTUID in a Sample.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:type sampleIDs: list
:param sampleIDs: A list of sample id's from BIOM format OTU table.
:rtype: dict
:return: Retu... |
Calculate the mean OTU abundance percentage. | def mean_otu_pct_abundance(ra, otuIDs):
"""
Calculate the mean OTU abundance percentage.
:type ra: Dict
:param ra: 'ra' refers to a dictionary keyed on SampleIDs, and the values are
dictionaries keyed on OTUID's and their values represent the relative
abundance of that OTU... |
Calculate the mean relative abundance percentage. | def MRA(biomf, sampleIDs=None, transform=None):
"""
Calculate the mean relative abundance percentage.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:type sampleIDs: list
:param sampleIDs: A list of sample id's from BIOM format OTU table.
:param transform: Mathematical function... |
Calculate the total number of sequences in each OTU or SampleID. | def raw_abundance(biomf, sampleIDs=None, sample_abd=True):
"""
Calculate the total number of sequences in each OTU or SampleID.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:type sampleIDs: List
:param sampleIDs: A list of column id's from BIOM format OTU table. By default, the
... |
Function to transform the total abundance calculation for each sample ID to another format based on user given transformation function. | def transform_raw_abundance(biomf, fn=math.log10, sampleIDs=None, sample_abd=True):
"""
Function to transform the total abundance calculation for each sample ID to another
format based on user given transformation function.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:param fn: M... |
Takes the proportion data from relative_abundance () and applies the variance stabilizing arcsine square root transformation: | def arcsine_sqrt_transform(rel_abd):
"""
Takes the proportion data from relative_abundance() and applies the
variance stabilizing arcsine square root transformation:
X = sin^{-1} \sqrt p
"""
arcsint = lambda p: math.asin(math.sqrt(p))
return {col_id: {row_id: arcsint(rel_abd[col_id][row_id]... |
find and replace elements in lookup within file | def f2lookup(f, lookup):
"""
find and replace elements in lookup within file
"""
lookup = {i: r for i, r in [l.strip().split('\t')[0:2] for l in lookup]}
for line in f:
line = line.strip().split()
for i, w in enumerate(line):
if w in lookup:
line[i] = look... |
Compute the Mann - Whitney U test for unequal group sample sizes. | def print_MannWhitneyU(div_calc):
"""
Compute the Mann-Whitney U test for unequal group sample sizes.
"""
try:
x = div_calc.values()[0].values()
y = div_calc.values()[1].values()
except:
return "Error setting up input arrays for Mann-Whitney U Test. Skipping "\
... |
Compute the Kruskal - Wallis H - test for independent samples. A typical rule is that each group must have at least 5 measurements. | def print_KruskalWallisH(div_calc):
"""
Compute the Kruskal-Wallis H-test for independent samples. A typical rule is that
each group must have at least 5 measurements.
"""
calc = defaultdict(list)
try:
for k1, v1 in div_calc.iteritems():
for k2, v2 in v1.iteritems():
... |
Given a dictionary of diversity calculations ( keyed by method ) write out the data to a file. | def write_diversity_metrics(data, sample_ids, fp=None):
"""
Given a dictionary of diversity calculations (keyed by method)
write out the data to a file.
"""
if fp is None:
fp = "./diversity_data.txt"
with open(fp, "w") as outf:
out = csv.writer(outf, delimiter="\t")
out.... |
Parses the given options passed in at the command line. | def handle_program_options():
"""Parses the given options passed in at the command line."""
parser = argparse.ArgumentParser(description="Calculate the alpha diversity\
of a set of samples using one or more \
metrics and output a kernal d... |
make blast db | def blastdb(fasta, maxfile = 10000000):
"""
make blast db
"""
db = fasta.rsplit('.', 1)[0]
type = check_type(fasta)
if type == 'nucl':
type = ['nhr', type]
else:
type = ['phr', type]
if os.path.exists('%s.%s' % (db, type[0])) is False \
and os.path.exists('%s.... |
make usearch db | def usearchdb(fasta, alignment = 'local', usearch_loc = 'usearch'):
"""
make usearch db
"""
if '.udb' in fasta:
print('# ... database found: %s' % (fasta), file=sys.stderr)
return fasta
type = check_type(fasta)
db = '%s.%s.udb' % (fasta.rsplit('.', 1)[0], type)
if os.path.exi... |
run phmmer | def phmmer(query, db, type, out, threads = '4', evalue = '0.01'):
"""
run phmmer
"""
if os.path.exists(out) is False:
print('# ... running phmmer with %s as query and %s as database' % (query, db))
os.system('phmmer -o %s.ph1 --tblout %s.ph2 --acc --noali --notextw -E %s --cpu %s %s %s' ... |
run blast | def blast(query, db, type, out, threads = '4', maxtargets = '100', megablast = False):
"""
run blast
"""
if os.path.exists(out) is False:
db = blastdb(db) # make the database file, if necessary
print('# ... running blast with %s as query and %s as database' % (query, db))
if typ... |
run usearch | def usearch5(query, db, type, out, threads = '4', evalue = '100', alignment = 'local'):
"""
run usearch
"""
if os.path.exists(out) is False:
print('# ... running usearch with %s as query and %s as database' % (query, db))
if type[1] == 'nucl':
threads = ''
else:
... |
run usearch | def usearch(query, db, type, out, threads = '6', evalue = '100', alignment = 'local', max_hits = 100, cluster = False):
"""
run usearch
"""
if 'usearch64' in os.environ:
usearch_loc = os.environ['usearch64']
else:
usearch_loc = 'usearch'
if os.path.exists(out) is False:
d... |
run | def run(self):
"""run"""
if self.callback:
log.info(("{} - using callback={}")
.format(self.name,
self.callback))
self.callback(name=self.response_name,
task_queue=self.task_queue,
... |
Pretty print. | def _pp(dict_data):
"""Pretty print."""
for key, val in dict_data.items():
# pylint: disable=superfluous-parens
print('{0:<11}: {1}'.format(key, val)) |
Print licenses. | def print_licences(params, metadata):
"""Print licenses.
:param argparse.Namespace params: parameter
:param bootstrap_py.classifier.Classifiers metadata: package metadata
"""
if hasattr(params, 'licenses'):
if params.licenses:
_pp(metadata.licenses_desc())
sys.exit(0) |
Check repository existence. | def check_repository_existence(params):
"""Check repository existence.
:param argparse.Namespace params: parameters
"""
repodir = os.path.join(params.outdir, params.name)
if os.path.isdir(repodir):
raise Conflict(
'Package repository "{0}" has already exists.'.format(repodir)) |
Generate package repository. | def generate_package(params):
"""Generate package repository.
:param argparse.Namespace params: parameters
"""
pkg_data = package.PackageData(params)
pkg_tree = package.PackageTree(pkg_data)
pkg_tree.generate()
pkg_tree.move()
VCS(os.path.join(pkg_tree.outdir, pkg_tree.name), pkg_tree.p... |
print single reads to stderr | def print_single(line, rev):
"""
print single reads to stderr
"""
if rev is True:
seq = rc(['', line[9]])[1]
qual = line[10][::-1]
else:
seq = line[9]
qual = line[10]
fq = ['@%s' % line[0], seq, '+%s' % line[0], qual]
print('\n'.join(fq), file = sys.stderr) |
convert sam to fastq | def sam2fastq(sam, singles = False, force = False):
"""
convert sam to fastq
"""
L, R = None, None
for line in sam:
if line.startswith('@') is True:
continue
line = line.strip().split()
bit = [True if i == '1' else False \
for i in bin(int(line[1])... |
sort sam file | def sort_sam(sam, sort):
"""
sort sam file
"""
tempdir = '%s/' % (os.path.abspath(sam).rsplit('/', 1)[0])
if sort is True:
mapping = '%s.sorted.sam' % (sam.rsplit('.', 1)[0])
if sam != '-':
if os.path.exists(mapping) is False:
os.system("\
... |
randomly subset sam file | def sub_sam(sam, percent, sort = True, sbuffer = False):
"""
randomly subset sam file
"""
mapping = sort_sam(sam, sort)
pool = [1 for i in range(0, percent)] + [0 for i in range(0, 100 - percent)]
c = cycle([1, 2])
for line in mapping:
line = line.strip().split()
if line[0].s... |
convert fq to fa | def fq2fa(fq):
"""
convert fq to fa
"""
c = cycle([1, 2, 3, 4])
for line in fq:
n = next(c)
if n == 1:
seq = ['>%s' % (line.strip().split('@', 1)[1])]
if n == 2:
seq.append(line.strip())
yield seq |
find and replace elements in lookup within file | def f2lookup(f, lookup):
"""
find and replace elements in lookup within file
"""
lookup = {i: r for i, r in [l.strip().split('\t')[0:2] for l in lookup]}
for line in f:
line = line.strip()
for find, replace in list(lookup.items()):
line = line.replace(find, replace)
yield line |
Converts the returned value of wrapped function to the type of the first arg or to the type specified by a kwarg key return_type s value. | def change_return_type(f):
"""
Converts the returned value of wrapped function to the type of the
first arg or to the type specified by a kwarg key return_type's value.
"""
@wraps(f)
def wrapper(*args, **kwargs):
if kwargs.has_key('return_type'):
return_type = kwargs['return_... |
Converts all args to set type via self. setify function. | def convert_args_to_sets(f):
"""
Converts all args to 'set' type via self.setify function.
"""
@wraps(f)
def wrapper(*args, **kwargs):
args = (setify(x) for x in args)
return f(*args, **kwargs)
return wrapper |
Makes class properties accessible to self. __class__ ( i hope ) to via creation of an _accessible_<property > attr. | def accessible(f):
"""
Makes class properties accessible to self.__class__ (i hope) to via creation of an '_accessible_<property>' attr.
"""
@wraps(f)
def wrapper(*args, **kwargs):
print 'KWARGS= ', kwargs
setattr(args[0], kwargs['name'], args[1])
print "property: ", str(geta... |
Tokenize a string ( passed as argument or read from stdin ) | def tokenize(args):
"""
Tokenize a string (passed as argument or read from stdin)
segments [--profile=PATH/TO/PROFILE] tokenize [STRING]
"""
if args.profile and not Path(args.profile).exists(): # pragma: no cover
raise ParserError('--profile must be a path for an existing file')
_write... |
Mengambil semua teks dalam sup label HTML ( tanpa anak - anaknya ). | def ambil_teks_dalam_label(sup):
"""Mengambil semua teks dalam sup label HTML (tanpa anak-anaknya).
:param sup: BeautifulSoup dari suatu label HTML
:type sup: BeautifulSoup
:returns: String semua teks dalam sup label HTML
:rtype: str
"""
return ''.join(i.strip() for i in sup.find_all(text=T... |
Membuat objek - objek entri dari laman yang diambil. | def _init_entri(self, laman):
"""Membuat objek-objek entri dari laman yang diambil.
:param laman: Laman respons yang dikembalikan oleh KBBI daring.
:type laman: Response
"""
sup = BeautifulSoup(laman.text, 'html.parser')
estr = ''
for label in sup.find('hr').nex... |
Memproses kata dasar yang ada dalam nama entri. | def _init_kata_dasar(self, dasar):
"""Memproses kata dasar yang ada dalam nama entri.
:param dasar: ResultSet untuk label HTML dengan class="rootword"
:type dasar: ResultSet
"""
for tiap in dasar:
kata = tiap.find('a')
dasar_no = kata.find('sup')
... |
Mengembalikan hasil serialisasi objek Entri ini. | def serialisasi(self):
"""Mengembalikan hasil serialisasi objek Entri ini.
:returns: Dictionary hasil serialisasi
:rtype: dict
"""
return {
"nama": self.nama,
"nomor": self.nomor,
"kata_dasar": self.kata_dasar,
"pelafalan": self.p... |
Mengembalikan representasi string untuk semua makna entri ini. | def _makna(self):
"""Mengembalikan representasi string untuk semua makna entri ini.
:returns: String representasi makna-makna
:rtype: str
"""
if len(self.makna) > 1:
return '\n'.join(
str(i) + ". " + str(makna)
for i, makna in enumera... |
Mengembalikan representasi string untuk nama entri ini. | def _nama(self):
"""Mengembalikan representasi string untuk nama entri ini.
:returns: String representasi nama entri
:rtype: str
"""
hasil = self.nama
if self.nomor:
hasil += " [{}]".format(self.nomor)
if self.kata_dasar:
hasil = " » ".jo... |
Mengembalikan representasi string untuk varian entri ini. Dapat digunakan untuk Varian maupun Bentuk tidak baku. | def _varian(self, varian):
"""Mengembalikan representasi string untuk varian entri ini.
Dapat digunakan untuk "Varian" maupun "Bentuk tidak baku".
:param varian: List bentuk tidak baku atau varian
:type varian: list
:returns: String representasi varian atau bentuk tidak baku
... |
Memproses kelas kata yang ada dalam makna. | def _init_kelas(self, makna_label):
"""Memproses kelas kata yang ada dalam makna.
:param makna_label: BeautifulSoup untuk makna yang ingin diproses.
:type makna_label: BeautifulSoup
"""
kelas = makna_label.find(color='red')
lain = makna_label.find(color='darkgreen')
... |
Memproses contoh yang ada dalam makna. | def _init_contoh(self, makna_label):
"""Memproses contoh yang ada dalam makna.
:param makna_label: BeautifulSoup untuk makna yang ingin diproses.
:type makna_label: BeautifulSoup
"""
indeks = makna_label.text.find(': ')
if indeks != -1:
contoh = makna_label.... |
Mengembalikan hasil serialisasi objek Makna ini. | def serialisasi(self):
"""Mengembalikan hasil serialisasi objek Makna ini.
:returns: Dictionary hasil serialisasi
:rtype: dict
"""
return {
"kelas": self.kelas,
"submakna": self.submakna,
"info": self.info,
"contoh": self.contoh
... |
send_tcp_message | def send_tcp_message():
"""send_tcp_message
Send a ``TCP`` message to port 80 by default.
"""
need_response = os.getenv("NEED_RESPONSE", "0") == "1"
msg = os.getenv(
"MSG",
"testing msg time={} - {}".format(
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:... |
Build sphinx documentation. | def build_sphinx(pkg_data, projectdir):
"""Build sphinx documentation.
:rtype: int
:return: subprocess.call return code
:param `bootstrap_py.control.PackageData` pkg_data: package meta data
:param str projectdir: project root directory
"""
try:
version, _minor_version = pkg_data.ve... |
A decorator which ensures that once a method has been marked as resolved ( via Class. __resolved )) will then propagate the attribute ( function ) call upstream. | def promise_method(func):
"""
A decorator which ensures that once a method has been marked as resolved
(via Class.__resolved)) will then propagate the attribute (function) call
upstream.
"""
name = func.__name__
@wraps(func)
def wrapped(self, *args, **kwargs):
cls_name = type(se... |
make bowtie db | def bowtiedb(fa, keepDB):
"""
make bowtie db
"""
btdir = '%s/bt2' % (os.getcwd())
# make directory for
if not os.path.exists(btdir):
os.mkdir(btdir)
btdb = '%s/%s' % (btdir, fa.rsplit('/', 1)[-1])
if keepDB is True:
if os.path.exists('%s.1.bt2' % (btdb)):
retu... |
generate bowtie2 command | def bowtie(sam, btd, f, r, u, opt, no_shrink, threads):
"""
generate bowtie2 command
"""
bt2 = 'bowtie2 -x %s -p %s ' % (btd, threads)
if f is not False:
bt2 += '-1 %s -2 %s ' % (f, r)
if u is not False:
bt2 += '-U %s ' % (u)
bt2 += opt
if no_shrink is False:
if f... |
map all read sets against all fasta files | def crossmap(fas, reads, options, no_shrink, keepDB, threads, cluster, nodes):
"""
map all read sets against all fasta files
"""
if cluster is True:
threads = '48'
btc = []
for fa in fas:
btd = bowtiedb(fa, keepDB)
F, R, U = reads
if F is not False:
if... |
Returns a connection object from the router given args. | def get_conn(self, *args, **kwargs):
"""
Returns a connection object from the router given ``args``.
Useful in cases where a connection cannot be automatically determined
during all steps of the process. An example of this would be
Redis pipelines.
"""
connection... |
mask ( make lower case ) regions of sequence found in gaps between model alignments | def mask_sequence(seq, gaps):
"""
mask (make lower case) regions of sequence found in gaps between model alignments
"""
seq = [i.upper() for i in seq]
for gap in gaps:
for i in range(gap[0] - 1, gap[1]):
seq[i] = seq[i].lower()
return ''.join(seq) |
1 ) parse hmm output into dictionary ( sequence must pass bit_thresh and inc == ! ) seq2hmm [ seq ] = { model: [ sstart ssend length strand score ] } 2 ) determine which model ( archaea bacteria eukarya ) the sequence most closely matches seq2hmm [ seq ] = [ model sstart send length strand score ] [ model2 sstart2 send... | def find_23S(fastas, hmms, bit_thresh = float(20), length_thresh = 500, masking = True, buffer = 0):
"""
1) parse hmm output into dictionary (sequence must pass bit_thresh and inc == '!')
seq2hmm[seq] = {model: [sstart, ssend, length, strand, score]}
2) determine which model (archaea, bacteria, euk... |
run cmsearch: comapre 23S sequences to ssu - align s CM | def run_cmsearch(fastas, threads, cm):
"""
run cmsearch: comapre 23S sequences to ssu-align's CM
"""
out = []
for fasta in fastas:
cmsearch = '%s.23S.cmsearch' % (fasta.name.rsplit('.', 1)[0])
if os.path.exists(cmsearch) is False:
p = Popen('\
cmsearch... |
return the non - direct init if the direct algorithm has been selected. | def __get_nondirect_init(self, init):
"""
return the non-direct init if the direct algorithm has been selected.
"""
crc = init
for i in range(self.Width):
bit = crc & 0x01
if bit:
crc^= self.Poly
crc >>= 1
if bit:
... |
reflect a data word i. e. reverts the bit order. | def reflect(self, data, width):
"""
reflect a data word, i.e. reverts the bit order.
"""
x = data & 0x01
for i in range(width - 1):
data >>= 1
x = (x << 1) | (data & 0x01)
return x |
Classic simple and slow CRC implementation. This function iterates bit by bit over the augmented input message and returns the calculated CRC value at the end. | def bit_by_bit(self, in_data):
"""
Classic simple and slow CRC implementation. This function iterates bit
by bit over the augmented input message and returns the calculated CRC
value at the end.
"""
# If the input data is a string, convert to bytes.
if isinstance... |
This function generates the CRC table used for the table_driven CRC algorithm. The Python version cannot handle tables of an index width other than 8. See the generated C code for tables with different sizes instead. | def gen_table(self):
"""
This function generates the CRC table used for the table_driven CRC
algorithm. The Python version cannot handle tables of an index width
other than 8. See the generated C code for tables with different sizes
instead.
"""
table_length = 1... |
The Standard table_driven CRC algorithm. | def table_driven(self, in_data):
"""
The Standard table_driven CRC algorithm.
"""
# If the input data is a string, convert to bytes.
if isinstance(in_data, str):
in_data = [ord(c) for c in in_data]
tbl = self.gen_table()
register = self.DirectInit <<... |
: type taxF: file: param taxF: The taxonomy output file to parse: type level: string: param level: The level of the phylogenetic assignment at which to cut off every assigned taxonomic string. | def prune_taxonomy(taxF, level):
"""
:type taxF: file
:param taxF: The taxonomy output file to parse
:type level: string
:param level: The level of the phylogenetic assignment at which to cut off
every assigned taxonomic string.
:rtype: dict
:return: A dictionary of taxon... |
get_publisher | def get_publisher():
"""get_publisher"""
log.info("initializing publisher")
pub = None
auth_url = ""
if FORWARD_ENDPOINT_TYPE == "redis":
auth_url = FORWARD_BROKER_URL
else:
auth_url = FORWARD_BROKER_URL
pub = Publisher(name="{}_{}".format(SOURCE, "-redis"),
... |
recv_msg | def recv_msg(body,
message):
"""recv_msg
Handler method - fires when a messages is consumed from
the ``FORWARD_QUEUE`` queue running in the ``FORWARD_BROKER_URL``
broker.
:param body: message body
:param message: message object can ack, requeue or reject
"""
log.info(("ca... |
consume_network_packet_messages_from_redis | def consume_network_packet_messages_from_redis():
"""consume_network_packet_messages_from_redis
Setup a ``celery_connectors.KombuSubscriber`` to consume meessages
from the ``FORWARD_BROKER_URL`` broker in the ``FORWARD_QUEUE``
queue.
"""
# end of recv_message
# Initialize KombuSubscriber
... |
parse masked sequence into non - masked and masked regions | def parse_masked(seq, min_len):
"""
parse masked sequence into non-masked and masked regions
"""
nm, masked = [], [[]]
prev = None
for base in seq[1]:
if base.isupper():
nm.append(base)
if masked != [[]] and len(masked[-1]) < min_len:
nm.extend(mas... |
remove masked regions from fasta file as long as they are longer than min_len | def strip_masked(fasta, min_len, print_masked):
"""
remove masked regions from fasta file as long as
they are longer than min_len
"""
for seq in parse_fasta(fasta):
nm, masked = parse_masked(seq, min_len)
nm = ['%s removed_masked >=%s' % (seq[0], min_len), ''.join(nm)]
yield ... |
Return arcsine transformed relative abundance from a BIOM format file. | def get_relative_abundance(biomfile):
"""
Return arcsine transformed relative abundance from a BIOM format file.
:type biomfile: BIOM format file
:param biomfile: BIOM format file used to obtain relative abundances for each OTU in
a SampleID, which are used as node sizes in network... |
build_training_request | def build_training_request(
csv_file=ev(
"CSV_FILE",
"/tmp/cleaned_attack_scans.csv"),
meta_file=ev(
"CSV_META_FILE",
"/tmp/cleaned_metadata.json"),
predict_feature=ev(
"PREDICT_FEATURE",
"label_value"),
ignore_featu... |
Find an OTU ID in a Newick - format tree. Return the starting position of the ID or None if not found. | def find_otu(otuid, tree):
"""
Find an OTU ID in a Newick-format tree.
Return the starting position of the ID or None if not found.
"""
for m in re.finditer(otuid, tree):
before, after = tree[m.start()-1], tree[m.start()+len(otuid)]
if before in ["(", ",", ")"] and after in [":", ";"... |
Replace the OTU ids in the Newick phylogenetic tree format with truncated OTU names | def newick_replace_otuids(tree, biomf):
"""
Replace the OTU ids in the Newick phylogenetic tree format with truncated
OTU names
"""
for val, id_, md in biomf.iter(axis="observation"):
otu_loc = find_otu(id_, tree)
if otu_loc is not None:
tree = tree[:otu_loc] + \
... |
start_consumers_for_queue | def start_consumers_for_queue(prefix_name="worker",
num_workers=2,
tasks=None,
queue_to_consume=None,
shutdown_msg="SHUTDOWN",
consumer_class=None,
... |
Create mash files for multiple fasta files Input: fastas <list [ str ] > -- paths to fasta files mash_file <str > -- path to output mash file threads <int > -- # threads for parallelization kmer <int > -- kmer size for mash sketching force <boolean > -- force overwrite of all mash files | def make_mashes(fastas, mash_file, threads, kmer = 21, force = False):
"""
Create mash files for multiple fasta files
Input:
fastas <list[str]> -- paths to fasta files
mash_file <str> -- path to output mash file
threads <int> -- # threads for parallelization
kmer <... |
Combine mash files into single sketch Input: sketches <list [ str ] > -- paths to sketch files pasted_mash <str > -- path to output mash file force <boolean > -- force overwrite of all mash file | def paste_mashes(sketches, pasted_mash, force = False):
"""
Combine mash files into single sketch
Input:
sketches <list[str]> -- paths to sketch files
pasted_mash <str> -- path to output mash file
force <boolean> -- force overwrite of all mash file
"""
if os.path.isf... |
Use mash to estimate ANI of genomes Input: fastas <list [ str ] > -- paths to fasta files sim_threshold <float > -- fractional cutoff % identity for cluster joining mash_file <str > -- pasted sketch file of all fastas being compared threads <int > -- number threads for distance estimation | def ani(fastas, mash_file, sim_threshold, threads):
"""
Use mash to estimate ANI of genomes
Input:
fastas <list[str]> -- paths to fasta files
sim_threshold <float> -- fractional cutoff % identity for cluster joining
mash_file <str> -- pasted sketch file of all fastas b... |
return genome info for choosing representative | def genome_info(genome, info):
"""
return genome info for choosing representative
if ggKbase table provided - choose rep based on SCGs and genome length
- priority for most SCGs - extra SCGs, then largest genome
otherwise, based on largest genome
"""
try:
scg = info['#SCG... |
choose represenative genome and print cluster information | def print_clusters(fastas, info, ANI):
"""
choose represenative genome and
print cluster information
*if ggKbase table is provided, use SCG info to choose best genome
"""
header = ['#cluster', 'num. genomes', 'rep.', 'genome', '#SCGs', '#SCG duplicates', \
'genome size (bp)', 'fragm... |
convert ggKbase genome info tables to dictionary | def parse_ggKbase_tables(tables, id_type):
"""
convert ggKbase genome info tables to dictionary
"""
g2info = {}
for table in tables:
for line in open(table):
line = line.strip().split('\t')
if line[0].startswith('name'):
header = line
h... |
convert checkM genome info tables to dictionary | def parse_checkM_tables(tables):
"""
convert checkM genome info tables to dictionary
"""
g2info = {}
for table in tables:
for line in open(table):
line = line.strip().split('\t')
if line[0].startswith('Bin Id'):
header = line
header[8] ... |
get genome lengths | def genome_lengths(fastas, info):
"""
get genome lengths
"""
if info is False:
info = {}
for genome in fastas:
name = genome.rsplit('.', 1)[0].rsplit('/', 1)[-1].rsplit('.contigs')[0]
if name in info:
continue
length = 0
fragments = 0
for s... |
listen_on_tcp_port | def listen_on_tcp_port():
"""listen_on_tcp_port
Run a simple server for processing messages over ``TCP``.
``LISTEN_ON_HOST`` - listen on this host ip address
``LISTEN_ON_PORT`` - listen on this ``TCP`` port
``LISTEN_SIZE`` - listen on to packets of this size
``LISTEN_SLEEP`` - sleep this nu... |
Returns a list of db keys to route the given call to. | def get_dbs(self, attr, args, kwargs, **fkwargs):
"""
Returns a list of db keys to route the given call to.
:param attr: Name of attribute being called on the connection.
:param args: List of arguments being passed to ``attr``.
:param kwargs: Dictionary of keyword arguments bein... |
Call method to perform any setup | def setup_router(self, args, kwargs, **fkwargs):
"""
Call method to perform any setup
"""
self._ready = self._setup_router(args=args, kwargs=kwargs, **fkwargs)
return self._ready |
Perform routing and return db_nums | def _route(self, attr, args, kwargs, **fkwargs):
"""
Perform routing and return db_nums
"""
return self.cluster.hosts.keys() |
Iterates through all connections which were previously listed as unavailable and marks any that have expired their retry_timeout as being up. | def check_down_connections(self):
"""
Iterates through all connections which were previously listed as unavailable
and marks any that have expired their retry_timeout as being up.
"""
now = time.time()
for db_num, marked_down_at in self._down_connections.items():
... |
Marks all connections which were previously listed as unavailable as being up. | def flush_down_connections(self):
"""
Marks all connections which were previously listed as unavailable as being up.
"""
self._get_db_attempts = 0
for db_num in self._down_connections.keys():
self.mark_connection_up(db_num) |
Compute standby power | def standby(df, resolution='24h', time_window=None):
"""
Compute standby power
Parameters
----------
df : pandas.DataFrame or pandas.Series
Electricity Power
resolution : str, default='d'
Resolution of the computation. Data will be resampled to this resolution (as mean) before ... |
Compute the share of the standby power in the total consumption. | def share_of_standby(df, resolution='24h', time_window=None):
"""
Compute the share of the standby power in the total consumption.
Parameters
----------
df : pandas.DataFrame or pandas.Series
Power (typically electricity, can be anything)
resolution : str, default='d'
Resolution... |
Toggle counter for gas boilers | def count_peaks(ts):
"""
Toggle counter for gas boilers
Counts the number of times the gas consumption increases with more than 3kW
Parameters
----------
ts: Pandas Series
Gas consumption in minute resolution
Returns
-------
int
"""
on_toggles = ts.diff() > 3000
... |
Calculate the ratio of input vs. norm over a given interval. | def load_factor(ts, resolution=None, norm=None):
"""
Calculate the ratio of input vs. norm over a given interval.
Parameters
----------
ts : pandas.Series
timeseries
resolution : str, optional
interval over which to calculate the ratio
default: resolution of the input ti... |
build_new_deep_neural_network_from_env_variables | def build_new_deep_neural_network_from_env_variables():
"""build_new_deep_neural_network_from_env_variables
Build a new deep neural network from environment variables:
``CSV_FILE`` - file to process created during prepare dataset
``CSV_META_FILE`` - metadata header file created during prepare dataset
... |
create_layer_2_socket | def create_layer_2_socket():
"""create_layer_2_socket"""
# create a socket for recording layer 2, 3 and 4 frames
s = None
try:
log.info("Creating l234 socket")
s = socket.socket(socket.AF_PACKET,
socket.SOCK_RAW,
socket.ntohs(0x0003))
... |
get top hits after sorting by column number | def top_hits(hits, num, column, reverse):
"""
get top hits after sorting by column number
"""
hits.sort(key = itemgetter(column), reverse = reverse)
for hit in hits[0:num]:
yield hit |
parse b6 output with sorting | def numBlast_sort(blast, numHits, evalueT, bitT):
"""
parse b6 output with sorting
"""
header = ['#query', 'target', 'pident', 'alen', 'mismatch', 'gapopen',
'qstart', 'qend', 'tstart', 'tend', 'evalue', 'bitscore']
yield header
hmm = {h:[] for h in header}
for line in blast:
... |
parse b6 output | def numBlast(blast, numHits, evalueT = False, bitT = False, sort = False):
"""
parse b6 output
"""
if sort is True:
for hit in numBlast_sort(blast, numHits, evalueT, bitT):
yield hit
return
header = ['#query', 'target', 'pident', 'alen', 'mismatch', 'gapopen',
... |
parse hmm domain table output this version is faster but does not work unless the table is sorted | def numDomtblout(domtblout, numHits, evalueT, bitT, sort):
"""
parse hmm domain table output
this version is faster but does not work unless the table is sorted
"""
if sort is True:
for hit in numDomtblout_sort(domtblout, numHits, evalueT, bitT):
yield hit
return
head... |
convert stockholm to fasta | def stock2fa(stock):
"""
convert stockholm to fasta
"""
seqs = {}
for line in stock:
if line.startswith('#') is False and line.startswith(' ') is False and len(line) > 3:
id, seq = line.strip().split()
id = id.rsplit('/', 1)[0]
id = re.split('[0-9]\|', id,... |
concatenate alignments | def concat_align(fastas):
"""
concatenate alignments
"""
# read in sequences
fa2len = {}
seqs = {}
IDs = []
for fasta in fastas:
seqs[fasta] = {}
for seq in parse_fasta(fasta):
ID = seq[0].split('>')[1].split()[0]
IDs.append(ID)
seqs[fa... |
Return boolean time series following given week schedule. | def week_schedule(index, on_time=None, off_time=None, off_days=None):
""" Return boolean time series following given week schedule.
Parameters
----------
index : pandas.DatetimeIndex
Datetime index
on_time : str or datetime.time
Daily opening time. Default: '09:00'
off_time : st... |
Draw a carpet plot of a pandas timeseries. | def carpet(timeseries, **kwargs):
"""
Draw a carpet plot of a pandas timeseries.
The carpet plot reads like a letter. Every day one line is added to the
bottom of the figure, minute for minute moving from left (morning) to right
(evening).
The color denotes the level of consumption and is scale... |
Plot boxplots | def boxplot(df, plot_mean=False, plot_ids=None, title=None, xlabel=None, ylabel=None):
"""
Plot boxplots
Plot the boxplots of a dataframe in time
Parameters
----------
df: Pandas Dataframe
Every collumn is a timeseries
plot_mean: bool
Wether or not to plot the means
plo... |
calculate percent identity | def calc_pident_ignore_gaps(a, b):
"""
calculate percent identity
"""
m = 0 # matches
mm = 0 # mismatches
for A, B in zip(list(a), list(b)):
if A == '-' or A == '.' or B == '-' or B == '.':
continue
if A == B:
m += 1
else:
mm += 1
t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.