_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q13800 | _read_bam | train | def _read_bam(bam_fn, precursors):
"""
read bam file and perform realignment of hits
"""
mode = "r" if bam_fn.endswith("sam") else "rb"
handle = pysam.Samfile(bam_fn, mode)
reads = defaultdict(realign)
for line in handle:
chrom = handle.getrname(line.reference_id)
# print("%s... | python | {
"resource": ""
} |
q13801 | _collapse_fastq | train | def _collapse_fastq(in_fn):
"""
collapse reads into unique sequences
"""
args = argparse.Namespace()
args.fastq = in_fn
args.minimum = 1
args.out = op.dirname(in_fn)
return collapse_fastq(args) | python | {
"resource": ""
} |
q13802 | _read_pyMatch | train | def _read_pyMatch(fn, precursors):
"""
read pyMatch file and perform realignment of hits
"""
with open(fn) as handle:
reads = defaultdict(realign)
for line in handle:
query_name, seq, chrom, reference_start, end, mism, add = line.split()
reference_start = int(refe... | python | {
"resource": ""
} |
q13803 | _parse_mut | train | def _parse_mut(subs):
"""
Parse mutation tag from miraligner output
"""
if subs!="0":
subs = [[subs.replace(subs[-2:], ""),subs[-2], subs[-1]]]
return subs | python | {
"resource": ""
} |
q13804 | _read_miraligner | train | def _read_miraligner(fn):
"""Read ouput of miraligner and create compatible output."""
reads = defaultdict(realign)
with open(fn) as in_handle:
in_handle.next()
for line in in_handle:
cols = line.strip().split("\t")
iso = isomir()
query_name, seq = cols[1]... | python | {
"resource": ""
} |
q13805 | _cmd_miraligner | train | def _cmd_miraligner(fn, out_file, species, hairpin, out):
"""
Run miraligner for miRNA annotation
"""
tool = _get_miraligner()
path_db = op.dirname(op.abspath(hairpin))
cmd = "{tool} -freq -i {fn} -o {out_file} -s {species} -db {path_db} -sub 1 -trim 3 -add 3"
if not file_exists(out_file):
... | python | {
"resource": ""
} |
q13806 | _mirtop | train | def _mirtop(out_files, hairpin, gff3, species, out):
"""
Convert miraligner to mirtop format
"""
args = argparse.Namespace()
args.hairpin = hairpin
args.sps = species
args.gtf = gff3
args.add_extra = True
args.files = out_files
args.format = "seqbuster"
args.out_format = "gff... | python | {
"resource": ""
} |
q13807 | _merge | train | def _merge(dts):
"""
merge multiple samples in one matrix
"""
df = pd.concat(dts)
ma = df.pivot(index='isomir', columns='sample', values='counts')
ma_mirna = ma
ma = ma.fillna(0)
ma_mirna['mirna'] = [m.split(":")[0] for m in ma.index.values]
ma_mirna = ma_mirna.groupby(['mirna']).su... | python | {
"resource": ""
} |
q13808 | _create_counts | train | def _create_counts(out_dts, out_dir):
"""Summarize results into single files."""
ma, ma_mirna = _merge(out_dts)
out_ma = op.join(out_dir, "counts.tsv")
out_ma_mirna = op.join(out_dir, "counts_mirna.tsv")
ma.to_csv(out_ma, sep="\t")
ma_mirna.to_csv(out_ma_mirna, sep="\t")
return out_ma_mirna,... | python | {
"resource": ""
} |
q13809 | miraligner | train | def miraligner(args):
"""
Realign BAM hits to miRBAse to get better accuracy and annotation
"""
hairpin, mirna = _download_mirbase(args)
precursors = _read_precursor(args.hairpin, args.sps)
matures = _read_mature(args.mirna, args.sps)
gtf = _read_gtf(args.gtf)
out_dts = []
out_files ... | python | {
"resource": ""
} |
q13810 | chdir | train | def chdir(new_dir):
"""
stolen from bcbio.
Context manager to temporarily change to a new directory.
http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/
"""
cur_dir = os.getcwd()
_mkdir(new_dir)
os.chdir(new_dir)
try:
yield
finally:
os.... | python | {
"resource": ""
} |
q13811 | _get_flavor | train | def _get_flavor():
"""
Download flavor from github
"""
target = op.join("seqcluster", "flavor")
url = "https://github.com/lpantano/seqcluster.git"
if not os.path.exists(target):
# shutil.rmtree("seqcluster")
subprocess.check_call(["git", "clone","-b", "flavor", "--single-branch", u... | python | {
"resource": ""
} |
q13812 | _install | train | def _install(path, args):
"""
small helper for installation in case outside bcbio
"""
try:
from bcbio import install as bcb
except:
raise ImportError("It needs bcbio to do the quick installation.")
path_flavor = _get_flavor()
s = {"fabricrc_overrides": {"system_install": path... | python | {
"resource": ""
} |
q13813 | predictions | train | def predictions(args):
"""
Create predictions of clusters
"""
logger.info(args)
logger.info("reading sequeces")
out_file = os.path.abspath(os.path.splitext(args.json)[0] + "_prediction.json")
data = load_data(args.json)
out_dir = os.path.abspath(safe_dirs(os.path.join(args.out, "predict... | python | {
"resource": ""
} |
q13814 | sort_precursor | train | def sort_precursor(c, loci):
"""
Sort loci according to number of sequences mapped there.
"""
# Original Py 2.7 code
#data_loci = map(lambda (x): [x, loci[x].chr, int(loci[x].start), int(loci[x].end), loci[x].strand, len(c.loci2seq[x])], c.loci2seq.keys())
# 2to3 suggested Py 3 rewrite
data_... | python | {
"resource": ""
} |
q13815 | best_precursor | train | def best_precursor(clus, loci):
"""
Select best precursor asuming size around 100 nt
"""
data_loci = sort_precursor(clus, loci)
current_size = data_loci[0][5]
best = 0
for item, locus in enumerate(data_loci):
if locus[3] - locus[2] > 70:
if locus[5] > current_size * 0.8:
... | python | {
"resource": ""
} |
q13816 | _open_file | train | def _open_file(in_file):
"""From bcbio code"""
_, ext = os.path.splitext(in_file)
if ext == ".gz":
return gzip.open(in_file, 'rb')
if ext in [".fastq", ".fq"]:
return open(in_file, 'r')
# default to just opening it
return open(in_file, "r") | python | {
"resource": ""
} |
q13817 | select_snps | train | def select_snps(mirna, snp, out):
"""
Use bedtools to intersect coordinates
"""
with open(out, 'w') as out_handle:
print(_create_header(mirna, snp, out), file=out_handle, end="")
snp_in_mirna = pybedtools.BedTool(snp).intersect(pybedtools.BedTool(mirna), wo=True)
for single in sn... | python | {
"resource": ""
} |
q13818 | up_threshold | train | def up_threshold(x, s, p):
"""function to decide if similarity is
below cutoff"""
if 1.0 * x/s >= p:
return True
elif stat.binom_test(x, s, p) > 0.01:
return True
return False | python | {
"resource": ""
} |
q13819 | _scan | train | def _scan(positions):
"""get the region inside the vector with more expression"""
scores = []
for start in range(0, len(positions) - 17, 5):
end = start = 17
scores.add(_enrichment(positions[start:end], positions[:start], positions[end:])) | python | {
"resource": ""
} |
q13820 | _check_args | train | def _check_args(args):
"""
check arguments before starting analysis.
"""
logger.info("Checking parameters and files")
args.dir_out = args.out
args.samplename = "pro"
global decision_cluster
global similar
if not os.path.isdir(args.out):
logger.warning("the output folder doens... | python | {
"resource": ""
} |
q13821 | _total_counts | train | def _total_counts(seqs, seqL, aligned=False):
"""
Counts total seqs after each step
"""
total = Counter()
if isinstance(seqs, list):
if not aligned:
l = len([total.update(seqL[s].freq) for s in seqs])
else:
l = len([total.update(seqL[s].freq) for s in seqs if ... | python | {
"resource": ""
} |
q13822 | _get_annotation | train | def _get_annotation(c, loci):
"""get annotation of transcriptional units"""
data_ann_temp = {}
data_ann = []
counts = Counter()
for lid in c.loci2seq:
# original Py 2.7 code
#for dbi in loci[lid].db_ann.keys():
# data_ann_temp[dbi] = {dbi: map(lambda (x): loci[lid].db_ann[... | python | {
"resource": ""
} |
q13823 | _sum_by_samples | train | def _sum_by_samples(seqs_freq, samples_order):
"""
Sum sequences of a metacluster by samples.
"""
n = len(seqs_freq[seqs_freq.keys()[0]].freq.keys())
y = np.array([0] * n)
for s in seqs_freq:
x = seqs_freq[s].freq
exp = [seqs_freq[s].freq[sam] for sam in samples_order]
y ... | python | {
"resource": ""
} |
q13824 | _clean_alignment | train | def _clean_alignment(args):
"""
Prepare alignment for cluster detection.
"""
logger.info("Clean bam file with highly repetitive reads with low counts. sum(counts)/n_hits > 1%")
bam_file, seq_obj = clean_bam_file(args.afile, args.mask)
logger.info("Using %s file" % bam_file)
detect_complexity... | python | {
"resource": ""
} |
q13825 | _create_clusters | train | def _create_clusters(seqL, bam_file, args):
"""
Cluster sequences and
create metaclusters with multi-mappers.
"""
clus_obj = []
cluster_file = op.join(args.out, "cluster.bed")
if not os.path.exists(op.join(args.out, 'list_obj.pk')):
if not file_exists(cluster_file):
logge... | python | {
"resource": ""
} |
q13826 | _cleaning | train | def _cleaning(clusL, path):
"""
Load saved cluster and jump to next step
"""
backup = op.join(path, "list_obj_red.pk")
if not op.exists(backup):
clus_obj = reduceloci(clusL, path)
with open(backup, 'wb') as output:
pickle.dump(clus_obj, output, pickle.HIGHEST_PROTOCOL)
... | python | {
"resource": ""
} |
q13827 | explore | train | def explore(args):
"""Create mapping of sequences of two clusters
"""
logger.info("reading sequeces")
data = load_data(args.json)
logger.info("get sequences from json")
#get_sequences_from_cluster()
c1, c2 = args.names.split(",")
seqs, names = get_sequences_from_cluster(c1, c2, data[0])
... | python | {
"resource": ""
} |
q13828 | prepare | train | def prepare(args):
"""
Read all seq.fa files and create a matrix and unique fasta files.
The information is
:param args: options parsed from command line
:param con: logging messages going to console
:param log: logging messages going to console and file
:returns: files - matrix and fasta ... | python | {
"resource": ""
} |
q13829 | _create_matrix_uniq_seq | train | def _create_matrix_uniq_seq(sample_l, seq_l, maout, out, min_shared):
""" create matrix counts for each different sequence in all the fasta files
:param sample_l: :code:`list_s` is the output of :code:`_read_fasta_files`
:param seq_l: :code:`seq_s` is the output of :code:`_read_fasta_files`
:param maou... | python | {
"resource": ""
} |
q13830 | run_coral | train | def run_coral(clus_obj, out_dir, args):
"""
Run some CoRaL modules to predict small RNA function
"""
if not args.bed:
raise ValueError("This module needs the bed file output from cluster subcmd.")
workdir = op.abspath(op.join(args.out, 'coral'))
safe_dirs(workdir)
bam_in = op.abspath... | python | {
"resource": ""
} |
q13831 | is_tRNA | train | def is_tRNA(clus_obj, out_dir, args):
"""
Iterates through cluster precursors to predict sRNA types
"""
ref = os.path.abspath(args.reference)
utils.safe_dirs(out_dir)
for nc in clus_obj[0]:
c = clus_obj[0][nc]
loci = c['loci']
out_fa = "cluster_" + nc
if loci[0][3... | python | {
"resource": ""
} |
q13832 | _read_tRNA_scan | train | def _read_tRNA_scan(summary_file):
"""
Parse output from tRNA_Scan
"""
score = 0
if os.path.getsize(summary_file) == 0:
return 0
with open(summary_file) as in_handle:
# header = in_handle.next().strip().split()
for line in in_handle:
if not line.startswith("--... | python | {
"resource": ""
} |
q13833 | _run_tRNA_scan | train | def _run_tRNA_scan(fasta_file):
"""
Run tRNA-scan-SE to predict tRNA
"""
out_file = fasta_file + "_trnascan"
se_file = fasta_file + "_second_str"
cmd = "tRNAscan-SE -q -o {out_file} -f {se_file} {fasta_file}"
run(cmd.format(**locals()))
return out_file, se_file | python | {
"resource": ""
} |
q13834 | _parse_mut | train | def _parse_mut(mut):
"""
Parse mutation field to get position and nts.
"""
multiplier = 1
if mut.startswith("-"):
mut = mut[1:]
multiplier = -1
nt = mut.strip('0123456789')
pos = int(mut[:-2]) * multiplier
return nt, pos | python | {
"resource": ""
} |
q13835 | _get_reference_position | train | def _get_reference_position(isomir):
"""
Liftover from isomir to reference mature
"""
mut = isomir.split(":")[1]
if mut == "0":
return mut
nt, pos = _parse_mut(mut)
trim5 = isomir.split(":")[-2]
off = -1 * len(trim5)
if trim5.islower():
off = len(trim5)
if trim5 =... | python | {
"resource": ""
} |
q13836 | _get_pct | train | def _get_pct(isomirs, mirna):
"""
Get pct of variants respect to the reference
using reads and different sequences
"""
pass_pos = []
for isomir in isomirs.iterrows():
mir = isomir[1]["chrom"]
mut = isomir[1]["sv"]
mut_counts = isomir[1]["counts"]
total = mirna.loc... | python | {
"resource": ""
} |
q13837 | _print_header | train | def _print_header(data):
"""
Create vcf header to make
a valid vcf.
"""
print("##fileformat=VCFv4.2", file=STDOUT, end="")
print("##source=seqbuster2.3", file=STDOUT, end="")
print("##reference=mirbase", file=STDOUT, end="")
for pos in data:
print("##contig=<ID=%s>" % pos["chrom"... | python | {
"resource": ""
} |
q13838 | print_vcf | train | def print_vcf(data):
"""Print vcf line following rules."""
id_name = "."
qual = "."
chrom = data['chrom']
pos = data['pre_pos']
nt_ref = data['nt'][1]
nt_snp = data['nt'][0]
flt = "PASS"
info = "ID=%s" % data['mature']
frmt = "GT:NR:NS"
gntp = "%s:%s:%s" % (_genotype(data), d... | python | {
"resource": ""
} |
q13839 | liftover | train | def liftover(pass_pos, matures):
"""Make position at precursor scale"""
fixed_pos = []
_print_header(pass_pos)
for pos in pass_pos:
mir = pos["mature"]
db_pos = matures[pos["chrom"]]
mut = _parse_mut(pos["sv"])
print([db_pos[mir], mut, pos["sv"]])
pos['pre_pos'] =... | python | {
"resource": ""
} |
q13840 | create_vcf | train | def create_vcf(isomirs, matures, gtf, vcf_file=None):
"""
Create vcf file of changes for all samples.
PASS will be ones with > 3 isomiRs supporting the position
and > 30% of reads, otherwise LOW
"""
global STDOUT
isomirs['sv'] = [_get_reference_position(m) for m in isomirs["isomir"]]
... | python | {
"resource": ""
} |
q13841 | liftover_to_genome | train | def liftover_to_genome(pass_pos, gtf):
"""Liftover from precursor to genome"""
fixed_pos = []
for pos in pass_pos:
if pos["chrom"] not in gtf:
continue
db_pos = gtf[pos["chrom"]][0]
mut = _parse_mut(pos["sv"])
print([db_pos, pos])
if db_pos[3] == "+":
... | python | {
"resource": ""
} |
q13842 | _get_seqs_from_cluster | train | def _get_seqs_from_cluster(seqs, seen):
"""
Returns the sequences that are already part of the cluster
:param seqs: list of sequences ids
:param clus_id: dict of sequences ids that are part of a cluster
:returns:
* :code:`already_in`list of cluster id that contained some of the sequences
... | python | {
"resource": ""
} |
q13843 | _write_cluster | train | def _write_cluster(metacluster, cluster, loci, idx, path):
"""
For complex meta-clusters, write all the loci for further debug
"""
out_file = op.join(path, 'log', str(idx) + '.bed')
with utils.safe_run(out_file):
with open(out_file, 'w') as out_handle:
for idc in metacluster:
... | python | {
"resource": ""
} |
q13844 | _iter_loci | train | def _iter_loci(meta, clusters, s2p, filtered, n_cluster):
"""
Go through all locus and decide if they are part
of the same TU or not.
:param idx: int cluster id
:param s2p: dict with [loci].coverage[start] = # of sequences there
:param filtered: dict with clusters object
:param n_cluster: i... | python | {
"resource": ""
} |
q13845 | _convert_to_clusters | train | def _convert_to_clusters(c):
"""Return 1 cluster per loci"""
new_dict = {}
n_cluster = 0
logger.debug("_convert_to_cluster: loci %s" % c.loci2seq.keys())
for idl in c.loci2seq:
n_cluster += 1
new_c = cluster(n_cluster)
#new_c.id_prev = c.id
new_c.loci2seq[idl] = c.loc... | python | {
"resource": ""
} |
q13846 | _calculate_similarity | train | def _calculate_similarity(c):
"""Get a similarity matrix of % of shared sequence
:param c: cluster object
:return ma: similarity matrix
"""
ma = {}
for idc in c:
set1 = _get_seqs(c[idc])
[ma.update({(idc, idc2): _common(set1, _get_seqs(c[idc2]), idc, idc2)}) for idc2 in c if id... | python | {
"resource": ""
} |
q13847 | _get_seqs | train | def _get_seqs(list_idl):
"""get all sequences in a cluster knowing loci"""
seqs = set()
for idl in list_idl.loci2seq:
# logger.debug("_get_seqs_: loci %s" % idl)
[seqs.add(s) for s in list_idl.loci2seq[idl]]
# logger.debug("_get_seqs_: %s" % len(seqs))
return seqs | python | {
"resource": ""
} |
q13848 | _common | train | def _common(s1, s2, i1, i2):
"""calculate the common % percentage of sequences"""
c = len(set(s1).intersection(s2))
t = min(len(s1), len(s2))
pct = 1.0 * c / t * t
is_gt = up_threshold(pct, t * 1.0, parameters.similar)
logger.debug("_common: pct %s of clusters:%s %s = %s" % (1.0 * c / t, i1, i2,... | python | {
"resource": ""
} |
q13849 | _is_consistent | train | def _is_consistent(pairs, common, clus_seen, loci_similarity):
"""
Check if loci shared that match sequences with all
clusters seen until now.
"""
all_true1 = all([all([common and loci_similarity[(p, c)] > parameters.similar for p in pairs if (p, c) in loci_similarity]) for c in clus_seen])
all... | python | {
"resource": ""
} |
q13850 | _merge_similar | train | def _merge_similar(loci, loci_similarity):
"""
Internal function to reduce loci complexity
:param loci: class cluster
:param locilen_sorted: list of loci sorted by size
:return
c: updated class cluster
"""
n_cluster = 0
internal_cluster = {}
clus_seen = {}
loci_sorted = so... | python | {
"resource": ""
} |
q13851 | _merge_cluster | train | def _merge_cluster(old, new):
"""merge one cluster to another"""
logger.debug("_merge_cluster: %s to %s" % (old.id, new.id))
logger.debug("_merge_cluster: add idls %s" % old.loci2seq.keys())
for idl in old.loci2seq:
# if idl in new.loci2seq:
# new.loci2seq[idl] = list(set(new.loci2seq... | python | {
"resource": ""
} |
q13852 | _solve_conflict | train | def _solve_conflict(list_c, s2p, n_cluster):
"""
Make sure sequences are counts once.
Resolve by most-vote or exclussion
:params list_c: dict of objects cluster
:param s2p: dict of [loci].coverage = # num of seqs
:param n_cluster: number of clusters
return dict: new set of clusters
"""... | python | {
"resource": ""
} |
q13853 | _split_cluster | train | def _split_cluster(c, pairs, n):
"""split cluster by exclussion"""
old = c[p[0]]
new = c[p[1]]
new_c = cluster(n)
common = set(_get_seqs(old)).intersection(_get_seqs(new))
for idl in old.loci2seq:
in_common = list(set(common).intersection(old.loci2seq[idl]))
if len(in_common) > 0... | python | {
"resource": ""
} |
q13854 | _split_cluster_by_most_vote | train | def _split_cluster_by_most_vote(c, p):
"""split cluster by most-vote strategy"""
old, new = c[p[0]], c[p[1]]
old_size = _get_seqs(old)
new_size = _get_seqs(new)
logger.debug("_most_vote: size of %s with %s - %s with %s" % (old.id, len(old_size), new.id, len(new_size)))
if len(old_size) > len(new... | python | {
"resource": ""
} |
q13855 | _clean_cluster | train | def _clean_cluster(list_c):
"""
Remove cluster with less than 10 sequences and
loci with size smaller than 60%
"""
global REMOVED
init = len(list_c)
list_c = {k: v for k, v in list_c.iteritems() if len(_get_seqs(v)) > parameters.min_seqs}
logger.debug("_clean_cluster: number of clusters ... | python | {
"resource": ""
} |
q13856 | _select_loci | train | def _select_loci(c):
"""Select only loci with most abundant sequences"""
loci_len = {k: len(v) for k, v in c.loci2seq.iteritems()}
logger.debug("_select_loci: number of loci %s" % len(c.loci2seq.keys()))
loci_len_sort = sorted(loci_len.iteritems(), key=operator.itemgetter(1), reverse=True)
max_size ... | python | {
"resource": ""
} |
q13857 | _solve_loci_deprecated | train | def _solve_loci_deprecated(c, locilen_sorted, seen_seqs, filtered, maxseq, n_cluster):
"""internal function to reduce loci complexity
The function will read the all loci in a cluster of
sequences and will determine if all loci are part
of the same transcriptional unit(TU) by most-vote locus
or by e... | python | {
"resource": ""
} |
q13858 | _get_description | train | def _get_description(string):
"""
Parse annotation to get nice description
"""
ann = set()
if not string:
return "This cluster is inter-genic."
for item in string:
for db in item:
ann = ann.union(set(item[db]))
return "annotated as: %s ..." % ",".join(list(ann)[:3... | python | {
"resource": ""
} |
q13859 | _set_format | train | def _set_format(profile):
"""
Prepare dict to list of y values with same x
"""
x = set()
for sample in profile:
x = x.union(set(profile[sample].keys()))
if not x:
return ''
end, start = max(x), min(x)
x = range(start, end, 4)
scaled_profile = defaultdict(list)
for... | python | {
"resource": ""
} |
q13860 | _insert_data | train | def _insert_data(con, data):
"""
insert line for each cluster
"""
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS clusters;")
cur.execute("CREATE TABLE clusters(Id INT, Description TEXT, Locus TEXT, Annotation TEXT, Sequences TEXT, Profile TXT, Precursor TXT)")
... | python | {
"resource": ""
} |
q13861 | parse_align_file | train | def parse_align_file(file_in):
"""
Parse sam files with aligned sequences
"""
loc_id = 1
bedfile_clusters = ""
bamfile = pybedtools.BedTool(file_in)
bed = pybedtools.BedTool.bam_to_bed(bamfile)
for c, start, end, name, q, strand in bed:
loc_id += 1
bedfile_clusters += "%s... | python | {
"resource": ""
} |
q13862 | parse_ma_file | train | def parse_ma_file(seq_obj, in_file):
"""
read seqs.ma file and create dict with
sequence object
"""
name = ""
index = 1
total = defaultdict(int)
with open(in_file) as handle_in:
line = handle_in.readline().strip()
cols = line.split("\t")
samples = cols[2:]
... | python | {
"resource": ""
} |
q13863 | _position_in_feature | train | def _position_in_feature(pos_a, pos_b):
"""return distance to 3' and 5' end of the feature"""
strd = "-"
if pos_a[2] in pos_b[2]:
strd = "+"
if pos_a[2] in "+" and pos_b[2] in "+":
lento5 = pos_a[0] - pos_b[1] + 1
lento3 = pos_a[1] - pos_b[1] + 1
if pos_a[2] in "+" and pos_b[... | python | {
"resource": ""
} |
q13864 | anncluster | train | def anncluster(c, clus_obj, db, type_ann, feature_id="name"):
"""intersect transcription position with annotation files"""
id_sa, id_ea, id_id, id_idl, id_sta = 1, 2, 3, 4, 5
if type_ann == "bed":
id_sb = 7
id_eb = 8
id_stb = 11
id_tag = 9
ida = 0
clus_id = clus_obj.c... | python | {
"resource": ""
} |
q13865 | detect_complexity | train | def detect_complexity(bam_in, genome, out):
"""
genome coverage of small RNA
"""
if not genome:
logger.info("No genome given. skipping.")
return None
out_file = op.join(out, op.basename(bam_in) + "_cov.tsv")
if file_exists(out_file):
return None
fai = genome + ".fai"
... | python | {
"resource": ""
} |
q13866 | detect_clusters | train | def detect_clusters(c, current_seq, MIN_SEQ, non_un_gl=False):
"""
Parse the merge file of sequences position to create clusters that will have all
sequences that shared any position on the genome
:param c: file from bedtools with merge sequence positions
:param current_seq: list of sequences
:... | python | {
"resource": ""
} |
q13867 | peak_calling | train | def peak_calling(clus_obj):
"""
Run peak calling inside each cluster
"""
new_cluster = {}
for cid in clus_obj.clus:
cluster = clus_obj.clus[cid]
cluster.update()
logger.debug("peak calling for %s" % cid)
bigger = cluster.locimaxid
if bigger in clus_obj.loci:
... | python | {
"resource": ""
} |
q13868 | simulate | train | def simulate(args):
"""Main function that manage simulatin of small RNAs"""
if args.fasta:
name = None
seq = ""
reads = dict()
with open(args.fasta) as in_handle:
for line in in_handle:
if line.startswith(">"):
if name:
... | python | {
"resource": ""
} |
q13869 | _generate_reads | train | def _generate_reads(seq, name):
"""Main function that create reads from precursors"""
reads = dict()
if len(seq) < 130 and len(seq) > 70:
reads.update(_mature(seq[:40], 0, name))
reads.update(_mature(seq[-40:], len(seq) - 40, name))
reads.update(_noise(seq, name))
reads.updat... | python | {
"resource": ""
} |
q13870 | _write_reads | train | def _write_reads(reads, prefix):
"""
Write fasta file, ma file and real position
"""
out_ma = prefix + ".ma"
out_fasta = prefix + ".fasta"
out_real = prefix + ".txt"
with open(out_ma, 'w') as ma_handle:
print("id\tseq\tsample", file=ma_handle, end="")
with open(out_fasta, 'w'... | python | {
"resource": ""
} |
q13871 | stats | train | def stats(args):
"""Create stats from the analysis
"""
logger.info("Reading sequeces")
data = parse_ma_file(args.ma)
logger.info("Get sequences from sam")
is_align = _read_sam(args.sam)
is_json, is_db = _read_json(args.json)
res = _summarise_sam(data, is_align, is_json, is_db)
_write... | python | {
"resource": ""
} |
q13872 | _read_json | train | def _read_json(fn_json):
"""read json information"""
is_json = set()
is_db = {}
with open(fn_json) as handle:
data = json.load(handle)
# original Py 2.y core
#for item in data[0].values():
# seqs_name = map(lambda (x): x.keys(), item['seqs'])
# rewrite by 2to3
... | python | {
"resource": ""
} |
q13873 | _do_run | train | def _do_run(cmd, checks, log_stdout=False):
"""Perform running and check results, raising errors for issues.
"""
cmd, shell_arg, executable_arg = _normalize_cmd_args(cmd)
s = subprocess.Popen(cmd, shell=shell_arg, executable=executable_arg,
stdout=subprocess.PIPE,
... | python | {
"resource": ""
} |
q13874 | _normalize_seqs | train | def _normalize_seqs(s, t):
"""Normalize to RPM"""
for ids in s:
obj = s[ids]
[obj.norm_freq.update({sample: 1.0 * obj.freq[sample] / (t[sample]+1) * 1000000}) for sample in obj.norm_freq]
s[ids] = obj
return s | python | {
"resource": ""
} |
q13875 | prepare_bam | train | def prepare_bam(bam_in, precursors):
"""
Clean BAM file to keep only position inside the bigger cluster
"""
# use pybedtools to keep valid positions
# intersect option with -b bigger_cluster_loci
a = pybedtools.BedTool(bam_in)
b = pybedtools.BedTool(precursors)
c = a.intersect(b, u=True)... | python | {
"resource": ""
} |
q13876 | _reorder_columns | train | def _reorder_columns(bed_file):
"""
Reorder columns to be compatible with CoRaL
"""
new_bed = utils.splitext_plus(bed_file)[0] + '_order.bed'
with open(bed_file) as in_handle:
with open(new_bed, 'w') as out_handle:
for line in in_handle:
cols = line.strip().split(... | python | {
"resource": ""
} |
q13877 | detect_regions | train | def detect_regions(bam_in, bed_file, out_dir, prefix):
"""
Detect regions using first CoRaL module
"""
bed_file = _reorder_columns(bed_file)
counts_reads_cmd = ("coverageBed -s -counts -b {bam_in} "
"-a {bed_file} | sort -k4,4 "
"> {out_dir}/loci.cov")... | python | {
"resource": ""
} |
q13878 | _reads_per_position | train | def _reads_per_position(bam_in, loci_file, out_dir):
"""
Create input for compute entropy
"""
data = Counter()
a = pybedtools.BedTool(bam_in)
b = pybedtools.BedTool(loci_file)
c = a.intersect(b, s=True, bed=True, wo=True)
for line in c:
end = int(line[1]) + 1 + int(line[2]) if li... | python | {
"resource": ""
} |
q13879 | create_features | train | def create_features(bam_in, loci_file, reference, out_dir):
"""
Use feature extraction module from CoRaL
"""
lenvec_plus = op.join(out_dir, 'genomic_lenvec.plus')
lenvec_minus = op.join(out_dir, 'genomic_lenvec.minus')
compute_genomic_cmd = ("compute_genomic_lenvectors "
... | python | {
"resource": ""
} |
q13880 | report | train | def report(args):
"""
Create report in html format
"""
logger.info("reading sequeces")
data = load_data(args.json)
logger.info("create profile")
data = make_profile(data, os.path.join(args.out, "profiles"), args)
logger.info("create database")
make_database(data, "seqcluster.db", ar... | python | {
"resource": ""
} |
q13881 | _summarize_peaks | train | def _summarize_peaks(peaks):
"""
merge peaks position if closer than 10
"""
previous = peaks[0]
new_peaks = [previous]
for pos in peaks:
if pos > previous + 10:
new_peaks.add(pos)
previous = pos
return new_peaks | python | {
"resource": ""
} |
q13882 | find_mature | train | def find_mature(x, y, win=10):
"""
Window apprach to find hills in the expression profile
"""
previous = min(y)
peaks = []
intervals = range(x, y, win)
for pos in intervals:
if y[pos] > previous * 10:
previous = y[pos]
peaks.add(pos)
peaks = _summarize_pea... | python | {
"resource": ""
} |
q13883 | collapse | train | def collapse(in_file):
"""collapse identical sequences and keep Q"""
keep = Counter()
with open_fastq(in_file) as handle:
for line in handle:
if line.startswith("@"):
if line.find("UMI") > -1:
logger.info("Find UMI tags in read names, collapsing by UMI... | python | {
"resource": ""
} |
q13884 | collapse_umi | train | def collapse_umi(in_file):
"""collapse reads using UMI tags"""
keep = defaultdict(dict)
with open_fastq(in_file) as handle:
for line in handle:
if line.startswith("@"):
m = re.search('UMI_([ATGC]*)', line.strip())
umis = m.group(0)
seq = ha... | python | {
"resource": ""
} |
q13885 | open_fastq | train | def open_fastq(in_file):
""" open a fastq file, using gzip if it is gzipped
from bcbio package
"""
_, ext = os.path.splitext(in_file)
if ext == ".gz":
return gzip.open(in_file, 'rb')
if ext in [".fastq", ".fq", ".fasta", ".fa"]:
return open(in_file, 'r')
return ValueError("Fi... | python | {
"resource": ""
} |
q13886 | collapse_fastq | train | def collapse_fastq(args):
"""collapse fasq files after adapter trimming
"""
try:
umi_fn = args.fastq
if _is_umi(args.fastq):
umis = collapse(args.fastq)
umi_fn = os.path.join(args.out, splitext_plus(os.path.basename(args.fastq))[0] + "_umi_trimmed.fastq")
... | python | {
"resource": ""
} |
q13887 | filter_doctree_for_slides | train | def filter_doctree_for_slides(doctree):
"""Given a doctree, remove all non-slide related elements from it."""
current = 0
num_children = len(doctree.children)
while current < num_children:
child = doctree.children[current]
child.replace_self(
child.traverse(no_autoslides_fi... | python | {
"resource": ""
} |
q13888 | TransformNextSlides._make_title_node | train | def _make_title_node(self, node, increment=True):
"""Generate a new title node for ``node``.
``node`` is a ``nextslide`` node. The title will use the node's
parent's title, or the title specified as an argument.
"""
parent_title_node = node.parent.next_node(nodes.title)
... | python | {
"resource": ""
} |
q13889 | slideconf.apply | train | def apply(self, builder):
"""Apply the Slide Configuration to a Builder."""
if 'theme' in self.attributes:
builder.apply_theme(
self.attributes['theme'],
builder.theme_options,
) | python | {
"resource": ""
} |
q13890 | slideconf.get_conf | train | def get_conf(cls, builder, doctree=None):
"""Return a dictionary of slide configuration for this doctree."""
# set up the default conf
result = {
'theme': builder.config.slide_theme,
'autoslides': builder.config.autoslides,
'slide_classes': [],
}
... | python | {
"resource": ""
} |
q13891 | __fix_context | train | def __fix_context(context):
"""Return a new context dict based on original context.
The new context will be a copy of the original, and some mutable
members (such as script and css files) will also be copied to
prevent polluting shared context.
"""
COPY_LISTS = ('script_files', 'css_files',)
... | python | {
"resource": ""
} |
q13892 | SlideData.get_slide_context | train | def get_slide_context(self):
"""Return the context dict for rendering this slide."""
return {
'title': self.title,
'level': self.level,
'content': self.content,
'classes': self.classes,
'slide_classes': self._filter_classes(exclude='content-')... | python | {
"resource": ""
} |
q13893 | BaseSlideTranslator._add_slide_number | train | def _add_slide_number(self, slide_no):
"""Add the slide number to the output if enabled."""
if self.builder.config.slide_numbers:
self.body.append(
'\n<div class="slide-no">%s</div>\n' % (slide_no,),
) | python | {
"resource": ""
} |
q13894 | BaseSlideTranslator._add_slide_footer | train | def _add_slide_footer(self, slide_no):
"""Add the slide footer to the output if enabled."""
if self.builder.config.slide_footer:
self.body.append(
'\n<div class="slide-footer">%s</div>\n' % (
self.builder.config.slide_footer,
),
... | python | {
"resource": ""
} |
q13895 | inspect_config | train | def inspect_config(app):
"""Inspect the Sphinx configuration and update for slide-linking.
If links from HTML to slides are enabled, make sure the sidebar
configuration includes the template and add the necessary theme
directory as a loader so the sidebar template can be located.
If the sidebar co... | python | {
"resource": ""
} |
q13896 | add_link | train | def add_link(app, pagename, templatename, context, doctree):
"""Add the slides link to the HTML context."""
# we can only show the slidelink if we can resolve the filename
context['show_slidelink'] = (
app.config.slide_link_html_to_slides and
hasattr(app.builder, 'get_outfilename')
)
... | python | {
"resource": ""
} |
q13897 | AbstractSlideBuilder.apply_theme | train | def apply_theme(self, themename, themeoptions):
"""Apply a new theme to the document.
This will store the existing theme configuration and apply a new one.
"""
# push the existing values onto the Stack
self._theme_stack.append(
(self.theme, self.theme_options)
... | python | {
"resource": ""
} |
q13898 | AbstractSlideBuilder.post_process_images | train | def post_process_images(self, doctree):
"""Pick the best candidate for all image URIs."""
super(AbstractSlideBuilder, self).post_process_images(doctree)
# figure out where this doctree is in relation to the srcdir
relative_base = (
['..'] *
doctree.attributes.ge... | python | {
"resource": ""
} |
q13899 | parse_metadata | train | def parse_metadata(section):
"""Given the first part of a slide, returns metadata associated with it."""
metadata = {}
metadata_lines = section.split('\n')
for line in metadata_lines:
colon_index = line.find(':')
if colon_index != -1:
key = line[:colon_index].strip()
val = line[colon_index +... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.