text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(cls, name, ncpus=None): """Create a Moap instance based on the predictor name. Parameters name : str ncpus : int, optional Number of threads. Default ...
try: return cls._predictors[name.lower()](ncpus=ncpus) except KeyError: raise Exception("Unknown class")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_predictor(cls, name): """Register method to keep list of predictors."""
def decorator(subclass): """Register as decorator function.""" cls._predictors[name.lower()] = subclass subclass.name = name.lower() return subclass return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_classification_predictors(self): """List available classification predictors."""
preds = [self.create(x) for x in self._predictors.keys()] return [x.name for x in preds if x.ptype == "classification"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _activate(self): """Activates the stream."""
if six.callable(self.streamer): # If it's a function, create the stream. self.stream_ = self.streamer(*(self.args), **(self.kwargs)) else: # If it's iterable, use it directly. self.stream_ = iter(self.streamer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def iterate(self, max_iter=None): '''Instantiate an iterator. Parameters ---------- max_iter : None or int > 0 Maximum number of iterations to yield. If ``None``, exhaust the stream. Yields ------ obj : Objects yielded by the streamer pro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def cycle(self, max_iter=None): '''Iterate from the streamer infinitely. This function will force an infinite stream, restarting the streamer even if a StopIteration is raised. Parameters ---------- max_iter : None or int > 0 Maximum number of iterations to ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rank_motifs(stats, metrics=("roc_auc", "recall_at_fdr")): """Determine mean rank of motifs based on metrics."""
rank = {} combined_metrics = [] motif_ids = stats.keys() background = list(stats.values())[0].keys() for metric in metrics: mean_metric_stats = [np.mean( [stats[m][bg][metric] for bg in background]) for m in motif_ids] ranked_metric_stats = rankdata(mean_metric_stats) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_stats(stats, fname, header=None): """write motif statistics to text file."""
# Write stats output to file for bg in list(stats.values())[0].keys(): f = open(fname.format(bg), "w") if header: f.write(header) stat_keys = sorted(list(list(stats.values())[0].values())[0].keys()) f.write("{}\t{}\n".format("Motif", "\t".join(stat_keys))) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_roc_values(motif, fg_file, bg_file): """Calculate ROC AUC values for ROC plots."""
#print(calc_stats(motif, fg_file, bg_file, stats=["roc_values"], ncpus=1)) #["roc_values"]) try: # fg_result = motif.pwm_scan_score(Fasta(fg_file), cutoff=0.0, nreport=1) # fg_vals = [sorted(x)[-1] for x in fg_result.values()] # # bg_result = motif.pwm_scan_score(Fasta(bg_file), c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_roc_plots(pwmfile, fgfa, background, outdir): """Make ROC plots for all motifs."""
motifs = read_motifs(pwmfile, fmt="pwm", as_dict=True) ncpus = int(MotifConfig().get_default_params()['ncpus']) pool = Pool(processes=ncpus) jobs = {} for bg,fname in background.items(): for m_id, m in motifs.items(): k = "{}_{}".format(str(m), bg) jobs[k] = pool.ap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_text_report(inputfile, motifs, closest_match, stats, outdir): """Create text report of motifs with statistics and database match."""
my_stats = {} for motif in motifs: match = closest_match[motif.id] my_stats[str(motif)] = {} for bg in list(stats.values())[0].keys(): if str(motif) not in stats: logger.error("####") logger.error("{} not found".format(str(motif))) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def axes_off(ax): """Get rid of all axis ticks, lines, etc. """
ax.set_frame_on(False) ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def motif_tree_plot(outfile, tree, data, circle=True, vmin=None, vmax=None, dpi=300): """ Plot a "phylogenetic" tree """
try: from ete3 import Tree, faces, AttrFace, TreeStyle, NodeStyle except ImportError: print("Please install ete3 to use this functionality") sys.exit(1) # Define the tree t, ts = _get_motif_tree(tree, data, circle, vmin, vmax) # Save image t.render(outfile, tree_st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_bed_file(fname): """ Check if the inputfile is a valid bed-file """
if not os.path.exists(fname): logger.error("Inputfile %s does not exist!", fname) sys.exit(1) for i, line in enumerate(open(fname)): if line.startswith("#") or line.startswith("track") or line.startswith("browser"): # comment or BED specific stuff pass e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_denovo_input(inputfile, params): """ Check if an input file is valid, which means BED, narrowPeak or FASTA """
background = params["background"] input_type = determine_file_type(inputfile) if input_type == "fasta": valid_bg = FA_VALID_BGS elif input_type in ["bed", "narrowpeak"]: genome = params["genome"] valid_bg = BED_VALID_BGS if "genomic" in background or "g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_to_best_match(fname, motifs, ncpus=None, genome=None, score=False): """Scan a FASTA file with motifs. Scan a FASTA file and return a dictionary with the...
# Initialize scanner s = Scanner(ncpus=ncpus) s.set_motifs(motifs) s.set_threshold(threshold=0.0) if genome: s.set_genome(genome) if isinstance(motifs, six.string_types): motifs = read_motifs(motifs) logger.debug("scanning %s...", fname) result = dict([(m.id, []) f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_background(self, fname=None, genome=None, length=200, nseq=10000): """Set the background to use for FPR and z-score calculations. Background can be speci...
length = int(length) if genome and fname: raise ValueError("Need either genome or filename for background.") if fname: if not os.path.exists(fname): raise IOError("Background file {} does not exist!".format(fname)) self.background = Fasta(f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_threshold(self, fpr=None, threshold=None): """Set motif scanning threshold based on background sequences. Parameters fpr : float, optional Desired FPR, b...
if threshold and fpr: raise ValueError("Need either fpr or threshold.") if fpr: fpr = float(fpr) if not (0.0 < fpr < 1.0): raise ValueError("Parameter fpr should be between 0 and 1") if not self.motifs: raise ValueErro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def best_score(self, seqs, scan_rc=True, normalize=False): """ give the score of the best match of each motif in each sequence returns an iterator of lists conta...
self.set_threshold(threshold=0.0) if normalize and len(self.meanstd) == 0: self.set_meanstd() means = np.array([self.meanstd[m][0] for m in self.motif_ids]) stds = np.array([self.meanstd[m][1] for m in self.motif_ids]) for matches in self.scan(seqs, 1, scan_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roc(args): """ Calculate ROC_AUC and other metrics and optionally plot ROC curve."""
outputfile = args.outfile # Default extension for image if outputfile and not outputfile.endswith(".png"): outputfile += ".png" motifs = read_motifs(args.pwmfile, fmt="pwm") ids = [] if args.ids: ids = args.ids.split(",") else: ids = [m.id for m in motifs] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def seqcor(m1, m2, seq=None): """Calculates motif similarity based on Pearson correlation of scores. Based on Kielbasa (2015) and Grau (2015). Scores are calcula...
l1 = len(m1) l2 = len(m2) l = max(l1, l2) if seq is None: seq = RCDB L = len(seq) # Scan RC de Bruijn sequence result1 = pfmscan(seq, m1.pwm, m1.pwm_min_score(), len(seq), False, True) result2 = pfmscan(seq, m2.pwm, m2.pwm_min_score(), len(seq), False, True) # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_motifs(self, m1, m2, match="total", metric="wic", combine="mean", pval=False): """Compare two motifs. The similarity metric can be any of seqcor, pcc...
if metric == "seqcor": return seqcor(m1, m2) elif match == "partial": if pval: return self.pvalue(m1, m2, "total", metric, combine, self.max_partial(m1.pwm, m2.pwm, metric, combine)) elif metric in ["pcc", "ed", "distance", "wic", "chisq", "ssd"]: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_scores(self, motifs, dbmotifs, match, metric, combine, pval=False, parallel=True, trim=None, ncpus=None): """Pairwise comparison of a set of motifs c...
# trim motifs first, if specified if trim: for m in motifs: m.trim(trim) for m in dbmotifs: m.trim(trim) # hash of result scores scores = {} if parallel: # Divide the job into big chunks, t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_closest_match(self, motifs, dbmotifs=None, match="partial", metric="wic",combine="mean", parallel=True, ncpus=None): """Return best match in database for...
if dbmotifs is None: pwm = self.config.get_default_params()["motif_db"] pwmdir = self.config.get_motif_dir() dbmotifs = os.path.join(pwmdir, pwm) motifs = parse_motifs(motifs) dbmotifs = parse_motifs(dbmotifs) dbmotif_lookup = dict([(m.id, m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_regions(service): """ List regions for the service """
for region in service.regions(): print '%(name)s: %(endpoint)s' % { 'name': region.name, 'endpoint': region.endpoint, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def elb_table(balancers): """ Print nice looking table of information from list of load balancers """
t = prettytable.PrettyTable(['Name', 'DNS', 'Ports', 'Zones', 'Created']) t.align = 'l' for b in balancers: ports = ['%s: %s -> %s' % (l[2], l[0], l[1]) for l in b.listeners] ports = '\n'.join(ports) zones = '\n'.join(b.availability_zones) t.add_row([b.name, b.dns_name, port...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ec2_table(instances): """ Print nice looking table of information from list of instances """
t = prettytable.PrettyTable(['ID', 'State', 'Monitored', 'Image', 'Name', 'Type', 'SSH key', 'DNS']) t.align = 'l' for i in instances: name = i.tags.get('Name', '') t.add_row([i.id, i.state, i.monitored, i.image_id, name, i.instance_type, i.key_name, i.dns_name]) return t
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ec2_image_table(images): """ Print nice looking table of information from images """
t = prettytable.PrettyTable(['ID', 'State', 'Name', 'Owner', 'Root device', 'Is public', 'Description']) t.align = 'l' for i in images: t.add_row([i.id, i.state, i.name, i.ownerId, i.root_device_type, i.is_public, i.description]) return t
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ec2_fab(service, args): """ Run Fabric commands against EC2 instances """
instance_ids = args.instances instances = service.list(elb=args.elb, instance_ids=instance_ids) hosts = service.resolve_hosts(instances) fab.env.hosts = hosts fab.env.key_filename = settings.get('SSH', 'KEY_FILE') fab.env.user = settings.get('SSH', 'USER', getpass.getuser()) fab.env.parall...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def buffer_stream(stream, buffer_size, partial=False, axis=None): '''Buffer "data" from an stream into one data object. Parameters ---------- stream : stream The stream to buffer buffer_size : int > 0 The number of examples to retain per batch. partial : bool, default=False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tuples(stream, *keys): """Reformat data as tuples. Parameters stream : iterable Stream of data objects. *keys : strings Keys to use for ordering data. Yields...
if not keys: raise PescadorError('Unable to generate tuples from ' 'an empty item set') for data in stream: try: yield tuple(data[key] for key in keys) except TypeError: raise DataError("Malformed data stream: {}".format(data))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keras_tuples(stream, inputs=None, outputs=None): """Reformat data objects as keras-compatible tuples. For more detail: https://keras.io/models/model/#fit Par...
flatten_inputs, flatten_outputs = False, False if inputs and isinstance(inputs, six.string_types): inputs = [inputs] flatten_inputs = True if outputs and isinstance(outputs, six.string_types): outputs = [outputs] flatten_outputs = True inputs, outputs = (inputs or []), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def location(args): """ Creates histrogram of motif location. Parameters args : argparse object Command line arguments. """
fastafile = args.fastafile pwmfile = args.pwmfile lwidth = args.width if not lwidth: f = Fasta(fastafile) lwidth = len(f.items()[0][1]) f = None jobs = [] motifs = pwmfile_to_motifs(pwmfile) ids = [motif.id for motif in motifs] if args.ids: ids = args.i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def which(fname): """Find location of executable."""
if "PATH" not in os.environ or not os.environ["PATH"]: path = os.defpath else: path = os.environ["PATH"] for p in [fname] + [os.path.join(x, fname) for x in path.split(os.pathsep)]: p = os.path.abspath(p) if os.access(p, os.X_OK) and not os.path.isdir(p): return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by_ext(dirname, ext): """Find all files in a directory by extension."""
# Get all fasta-files try: files = os.listdir(dirname) except OSError: if os.path.exists(dirname): cmd = "find {0} -maxdepth 1 -name \"*\"".format(dirname) p = sp.Popen(cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE) stdout, _stderr = p.communicate...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_motifs(): """Return list of Motif instances from default motif database."""
config = MotifConfig() d = config.get_motif_dir() m = config.get_default_params()['motif_db'] if not d or not m: raise ValueError("default motif database not configured") fname = os.path.join(d, m) with open(fname) as f: motifs = read_motifs(f) return motifs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def motif_from_align(align): """Convert alignment to motif. Converts a list with sequences to a motif. Sequences should be the same length. Parameters align : li...
width = len(align[0]) nucs = {"A":0,"C":1,"G":2,"T":3} pfm = [[0 for _ in range(4)] for _ in range(width)] for row in align: for i in range(len(row)): pfm[i][nucs[row[i]]] += 1 m = Motif(pfm) m.align = align[:] return m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def motif_from_consensus(cons, n=12): """Convert consensus sequence to motif. Converts a consensus sequences using the nucleotide IUPAC alphabet to a motif. Para...
width = len(cons) nucs = {"A":0,"C":1,"G":2,"T":3} pfm = [[0 for _ in range(4)] for _ in range(width)] m = Motif() for i,char in enumerate(cons): for nuc in m.iupac[char.upper()]: pfm[i][nucs[nuc]] = n / len(m.iupac[char.upper()]) m = Motif(pfm) m.id = cons return m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_motifs(motifs): """Parse motifs in a variety of formats to return a list of motifs. Parameters motifs : list or str Filename of motif, list of motifs o...
if isinstance(motifs, six.string_types): with open(motifs) as f: if motifs.endswith("pwm") or motifs.endswith("pfm"): motifs = read_motifs(f, fmt="pwm") elif motifs.endswith("transfac"): motifs = read_motifs(f, fmt="transfac") else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_motifs(infile=None, fmt="pwm", as_dict=False): """ Read motifs from a file or stream or file-like object. Parameters infile : string or file-like object...
if infile is None or isinstance(infile, six.string_types): infile = pwmfile_location(infile) with open(infile) as f: motifs = _read_motifs_from_filehandle(f, fmt) else: motifs = _read_motifs_from_filehandle(infile, fmt) if as_dict: motifs = {m.id:m for m in mot...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def information_content(self): """Return the total information content of the motif. Return ------ ic : float Motif information content. """
ic = 0 for row in self.pwm: ic += 2.0 + np.sum([row[x] * log(row[x])/log(2) for x in range(4) if row[x] > 0]) return ic
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pwm_min_score(self): """Return the minimum PWM score. Returns ------- score : float Minimum PWM score. """
if self.min_score is None: score = 0 for row in self.pwm: score += log(min(row) / 0.25 + 0.01) self.min_score = score return self.min_score
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pwm_max_score(self): """Return the maximum PWM score. Returns ------- score : float Maximum PWM score. """
if self.max_score is None: score = 0 for row in self.pwm: score += log(max(row) / 0.25 + 0.01) self.max_score = score return self.max_score
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def score_kmer(self, kmer): """Calculate the log-odds score for a specific k-mer. Parameters kmer : str String representing a kmer. Should be the same length as ...
if len(kmer) != len(self.pwm): raise Exception("incorrect k-mer length") score = 0.0 d = {"A":0, "C":1, "G":2, "T":3} for nuc, row in zip(kmer.upper(), self.pwm): score += log(row[d[nuc]] / 0.25 + 0.01) return score
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pfm_to_pwm(self, pfm, pseudo=0.001): """Convert PFM with counts to a PFM with fractions. Parameters pfm : list 2-dimensional list with counts. pseudo : float...
return [[(x + pseudo)/(float(np.sum(row)) + pseudo * 4) for x in row] for row in pfm]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ic_pos(self, row1, row2=None): """Calculate the information content of one position. Returns ------- score : float Information content. """
if row2 is None: row2 = [0.25,0.25,0.25,0.25] score = 0 for a,b in zip(row1, row2): if a > 0: score += a * log(a / b) / log(2) return score
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pcc_pos(self, row1, row2): """Calculate the Pearson correlation coefficient of one position compared to another position. Returns ------- score : float Pears...
mean1 = np.mean(row1) mean2 = np.mean(row2) a = 0 x = 0 y = 0 for n1, n2 in zip(row1, row2): a += (n1 - mean1) * (n2 - mean2) x += (n1 - mean1) ** 2 y += (n2 - mean2) ** 2 if a == 0: return 0 else:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rc(self): """Return the reverse complemented motif. Returns ------- m : Motif instance New Motif instance with the reverse complement of the input motif. """
m = Motif() m.pfm = [row[::-1] for row in self.pfm[::-1]] m.pwm = [row[::-1] for row in self.pwm[::-1]] m.id = self.id + "_revcomp" return m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trim(self, edge_ic_cutoff=0.4): """Trim positions with an information content lower than the threshold. The default threshold is set to 0.4. The Motif will b...
pwm = self.pwm[:] while len(pwm) > 0 and self.ic_pos(pwm[0]) < edge_ic_cutoff: pwm = pwm[1:] self.pwm = self.pwm[1:] self.pfm = self.pfm[1:] while len(pwm) > 0 and self.ic_pos(pwm[-1]) < edge_ic_cutoff: pwm = pwm[:-1] self.pwm = self.p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consensus_scan(self, fa): """Scan FASTA with the motif as a consensus sequence. Parameters fa : Fasta object Fasta object to scan Returns ------- matches : d...
regexp = "".join(["[" + "".join(self.iupac[x.upper()]) + "]" for x in self.to_consensusv2()]) p = re.compile(regexp) matches = {} for name,seq in fa.items(): matches[name] = [] for match in p.finditer(seq): middle = (match.span()[1] + match.span(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pwm_scan_to_gff(self, fa, gfffile, cutoff=0.9, nreport=50, scan_rc=True, append=False): """Scan sequences with this motif and save to a GFF file. Scan sequen...
if append: out = open(gfffile, "a") else: out = open(gfffile, "w") c = self.pwm_min_score() + (self.pwm_max_score() - self.pwm_min_score()) * cutoff pwm = self.pwm strandmap = {-1:"-","-1":"-","-":"-","1":"+",1:"+","+":"+"} gff_line ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def average_motifs(self, other, pos, orientation, include_bg=False): """Return the average of two motifs. Combine this motif with another motif and return the av...
# xxCATGYT # GGCTTGYx # pos = -2 pfm1 = self.pfm[:] pfm2 = other.pfm[:] if orientation < 0: pfm2 = [row[::-1] for row in pfm2[::-1]] pfm1_count = float(np.sum(pfm1[0])) pfm2_count = float(np.sum(pfm2[0])) if include_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pwm_to_str(self, precision=4): """Return string representation of pwm. Parameters precision : int, optional, default 4 Floating-point precision. Returns ---...
if not self.pwm: return "" fmt = "{{:.{:d}f}}".format(precision) return "\n".join( ["\t".join([fmt.format(p) for p in row]) for row in self.pwm] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_pwm(self, precision=4, extra_str=""): """Return pwm as string. Parameters precision : int, optional, default 4 Floating-point precision. extra_str |: str,...
motif_id = self.id if extra_str: motif_id += "_%s" % extra_str if not self.pwm: self.pwm = [self.iupac_pwm[char]for char in self.consensus.upper()] return ">%s\n%s" % ( motif_id, self._pwm_to_str(precision) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_img(self, fname, fmt="PNG", add_left=0, seqlogo=None, height=6): """Create a sequence logo using seqlogo. Create a sequence logo and save it to a file. Va...
if not seqlogo: seqlogo = self.seqlogo if not seqlogo: raise ValueError("seqlogo not specified or configured") #TODO: split to_align function VALID_FORMATS = ["EPS", "GIF", "PDF", "PNG"] N = 1000 fmt = fmt.upper() if not ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def randomize(self): """Create a new motif with shuffled positions. Shuffle the positions of this motif and return a new Motif instance. Returns ------- m : Moti...
random_pfm = [[c for c in row] for row in self.pfm] random.shuffle(random_pfm) m = Motif(pfm=random_pfm) m.id = "random" return m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maelstrom(args): """Run the maelstrom method."""
infile = args.inputfile genome = args.genome outdir = args.outdir pwmfile = args.pwmfile methods = args.methods ncpus = args.ncpus if not os.path.exists(infile): raise ValueError("file {} does not exist".format(infile)) if methods: methods = [x.strip() for x in met...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zmq_recv_data(socket, flags=0, copy=True, track=False): """Receive data over a socket."""
data = dict() msg = socket.recv_multipart(flags=flags, copy=copy, track=track) headers = json.loads(msg[0].decode('ascii')) if len(headers) == 0: raise StopIteration for header, payload in zip(headers, msg[1:]): data[header['key']] = np.frombuffer(buffer(payload), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hardmask(self): """ Mask all lowercase nucleotides with N's """
p = re.compile("a|c|g|t|n") for seq_id in self.fasta_dict.keys(): self.fasta_dict[seq_id] = p.sub("N", self.fasta_dict[seq_id]) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_random(self, n, l=None): """ Return n random sequences from this Fasta object """
random_f = Fasta() if l: ids = self.ids[:] random.shuffle(ids) i = 0 while (i < n) and (len(ids) > 0): seq_id = ids.pop() if (len(self[seq_id]) >= l): start = random.randint(0, len(self[seq_id]) - l) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writefasta(self, fname): """ Write sequences to FASTA formatted file"""
f = open(fname, "w") fa_str = "\n".join([">%s\n%s" % (id, self._format_seq(seq)) for id, seq in self.items()]) f.write(fa_str) f.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def batch_length(batch): '''Determine the number of samples in a batch. Parameters ---------- batch : dict A batch dictionary. Each value must implement `len`. All values must have the same `len`. Returns ------- n : int >= 0 or None The number of samples in this b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _activate(self): """Activates a number of streams"""
self.distribution_ = 1. / self.n_streams * np.ones(self.n_streams) self.valid_streams_ = np.ones(self.n_streams, dtype=bool) self.streams_ = [None] * self.k self.stream_weights_ = np.zeros(self.k) self.stream_counts_ = np.zeros(self.k, dtype=int) # Array of pointers in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterate(self, max_iter=None): """Yields items from the mux, and handles stream exhaustion and replacement. """
if max_iter is None: max_iter = np.inf # Calls Streamer's __enter__, which calls activate() with self as active_mux: # Main sampling loop n = 0 while n < max_iter and active_mux._streamers_available(): # Pick a stream from the ac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _next_sample_index(self): """StochasticMux chooses its next sample stream randomly"""
return self.rng.choice(self.n_active, p=(self.stream_weights_ / self.weight_norm_))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _activate(self): """ShuffledMux's activate is similar to StochasticMux, but there is no 'n_active', since all the streams are always available. """
self.streams_ = [None] * self.n_streams # Weights of the active streams. # Once a stream is exhausted, it is set to 0. # Upon activation, this is just a copy of self.weights. self.stream_weights_ = np.array(self.weights, dtype=float) # How many samples have been drawn f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _next_sample_index(self): """ShuffledMux chooses its next sample stream randomly, conditioned on the stream weights. """
return self.rng.choice(self.n_streams, p=(self.stream_weights_ / self.weight_norm_))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _next_sample_index(self): """Rotates through each active sampler by incrementing the index"""
# Return the next streamer index where the streamer is not None, # wrapping around. idx = self.active_index_ self.active_index_ += 1 if self.active_index_ >= len(self.streams_): self.active_index_ = 0 # Continue to increment if this streamer is exhausted (N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _new_stream(self, idx): """Activate a new stream, given the index into the stream pool. BaseMux's _new_stream simply chooses a new stream and activates it. F...
# Get the stream index from the candidate pool stream_index = self.stream_idxs_[idx] # Activate the Streamer, and get the weights self.streams_[idx] = self.streamers[stream_index].iterate() # Reset the sample count to zero self.stream_counts_[idx] = 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _new_stream(self): '''Grab the next stream from the input streamers, and start it. Raises ------ StopIteration When the input list or generator of streamers is complete, will raise a StopIteration. If `mode == cycle`, it will instead restart itera...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def npz_generator(npz_path): """Generate data from an npz file."""
npz_data = np.load(npz_path) X = npz_data['X'] # Y is a binary maxtrix with shape=(n, k), each y will have shape=(k,) y = npz_data['Y'] n = X.shape[0] while True: i = np.random.randint(0, n) yield {'X': X[i], 'Y': y[i]}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def phyper(k, good, bad, N): """ Current hypergeometric implementation in scipy is broken, so here's the correct version """
pvalues = [phyper_single(x, good, bad, N) for x in range(k + 1, N + 1)] return np.sum(pvalues)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_motif_enrichment(sample, background, mtc=None, len_sample=None, len_back=None): """Calculate enrichment based on hypergeometric distribution"""
INF = "Inf" if mtc not in [None, "Bonferroni", "Benjamini-Hochberg", "None"]: raise RuntimeError("Unknown correction: %s" % mtc) sig = {} p_value = {} n_sample = {} n_back = {} if not(len_sample): len_sample = sample.seqn() if not(len_back): len_bac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_cutoff(motifs, cutoff, default=0.9): """ Provide either a file with one cutoff per motif or a single cutoff returns a hash with motif id as key and cut...
cutoffs = {} if os.path.isfile(str(cutoff)): for i,line in enumerate(open(cutoff)): if line != "Motif\tScore\tCutoff\n": try: motif,_,c = line.strip().split("\t") c = float(c) cutoffs[motif] = c ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_file_type(fname): """ Detect file type. The following file types are supported: BED, narrowPeak, FASTA, list of chr:start-end regions If the extens...
if not (isinstance(fname, str) or isinstance(fname, unicode)): raise ValueError("{} is not a file name!", fname) if not os.path.isfile(fname): raise ValueError("{} is not a file!", fname) ext = os.path.splitext(fname)[1].lower() if ext in ["bed"]: return "bed" elif ext in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_checksum(fname): """Return md5 checksum of file. Note: only works for files < 4GB. Parameters filename : str File used to calculate checksum. Returns --...
size = os.path.getsize(fname) with open(fname, "r+") as f: checksum = hashlib.md5(mmap.mmap(f.fileno(), size)).hexdigest() return checksum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_annotation(genomebuild, gene_file): """ Download gene annotation from UCSC based on genomebuild. Will check UCSC, Ensembl and RefSeq annotation. Par...
pred_bin = "genePredToBed" pred = find_executable(pred_bin) if not pred: sys.stderr.write("{} not found in path!\n".format(pred_bin)) sys.exit(1) tmp = NamedTemporaryFile(delete=False, suffix=".gz") anno = [] f = urlopen(UCSC_GENE_URL.format(genomebuild)) p = re.compile(r'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_index(self, fasta, index): """ Index a single, one-sequence fasta-file"""
out = open(index, "wb") f = open(fasta) # Skip first line of fasta-file line = f.readline() offset = f.tell() line = f.readline() while line: out.write(pack(self.pack_char, offset)) offset = f.tell() line = f.readline() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_index_file(self): """read the param_file, index_dir should already be set """
param_file = os.path.join(self.index_dir, self.param_file) with open(param_file) as f: for line in f.readlines(): (name, fasta_file, index_file, line_size, total_size) = line.strip().split("\t") self.size[name] = int(total_size) self.fasta_fil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_seq_from_fasta(self, fasta, offset, nr_lines): """ retrieve a number of lines from a fasta file-object, starting at offset"""
fasta.seek(offset) lines = [fasta.readline().strip() for _ in range(nr_lines)] return "".join(lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sequence(self, chrom, start, end, strand=None): """ Retrieve a sequence """
# Check if we have an index_dir if not self.index_dir: print("Index dir is not defined!") sys.exit() # retrieve all information for this specific sequence fasta_file = self.fasta_file[chrom] index_file = self.index_file[chrom] line_size = sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_size(self, chrom=None): """ Return the sizes of all sequences in the index, or the size of chrom if specified as an optional argument """
if len(self.size) == 0: raise LookupError("no chromosomes in index, is the index correct?") if chrom: if chrom in self.size: return self.size[chrom] else: raise KeyError("chromosome {} not in index".format(chrom)) total = 0 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_tool(name): """ Returns an instance of a specific tool. Parameters name : str Name of the tool (case-insensitive). Returns ------- tool : MotifProgram in...
tool = name.lower() if tool not in __tools__: raise ValueError("Tool {0} not found!\n".format(name)) t = __tools__[tool]() if not t.is_installed(): sys.stderr.write("Tool {0} not installed!\n".format(tool)) if not t.is_configured(): sys.stderr.write("Tool {0} not configur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def locate_tool(name, verbose=True): """ Returns the binary of a tool. Parameters name : str Name of the tool (case-insensitive). Returns ------- tool_bin : str ...
m = get_tool(name) tool_bin = which(m.cmd) if tool_bin: if verbose: print("Found {} in {}".format(m.name, tool_bin)) return tool_bin else: print("Couldn't find {}".format(m.name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bin(self): """ Get the command used to run the tool. Returns ------- command : str The tool system command. """
if self.local_bin: return self.local_bin else: return self.config.bin(self.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, fastafile, params=None, tmp=None): """ Run the tool and predict motifs from a FASTA file. Parameters fastafile : str Name of the FASTA input file. ...
if not self.is_configured(): raise ValueError("%s is not configured" % self.name) if not self.is_installed(): raise ValueError("%s is not installed or not correctly configured" % self.name) self.tmpdir = mkdtemp(prefix="{0}.".format(self.name), dir=tmp) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run XXmotif and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool. fas...
params = self._parse_params(params) outfile = os.path.join( self.tmpdir, os.path.basename(fastafile.replace(".fa", ".pwm"))) stdout = "" stderr = "" cmd = "%s %s %s --localization --batch %s %s" % ( bin, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run Homer and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool. fasta...
params = self._parse_params(params) outfile = NamedTemporaryFile( mode="w", dir=self.tmpdir, prefix= "homer_w{}.".format(params["width"]) ).name cmd = "%s denovo -i %s -b %s -len %s -S %s %s -o %s -p 8" % ( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run HMS and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool. fastafi...
params = self._parse_params(params) default_params = {"width":10} if params is not None: default_params.update(params) fgfile, summitfile, outfile = self._prepare_files(fastafile) current_path = os.getcwd() os.chdir(self.tm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run AMD and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool. fastafi...
params = self._parse_params(params) fgfile = os.path.join(self.tmpdir, "AMD.in.fa") outfile = fgfile + ".Matrix" shutil.copy(fastafile, fgfile) current_path = os.getcwd() os.chdir(self.tmpdir) stdout = "" stderr = "" cm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run Trawler and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool. fas...
params = self._parse_params(params) tmp = NamedTemporaryFile(mode="w", dir=self.tmpdir, delete=False) shutil.copy(fastafile, tmp.name) fastafile = tmp.name current_path = os.getcwd() os.chdir(self.dir()) motifs = [] stdout = "" stde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin,fastafile, params=None): """ Run Weeder and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool. fasta...
params = self._parse_params(params) organism = params["organism"] weeder_organisms = { "hg18":"HS", "hg19":"HS", "hg38":"HS", "mm9":"MM", "mm10":"MM", "dm3":"DM", "dm5":"DM", "dm6":"DM", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run MotifSampler and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool...
params = self._parse_params(params) # TODO: test organism #cmd = "%s -f %s -b %s -m %s -w %s -n %s -o %s -s %s > /dev/null 2>&1" % ( cmd = "%s -f %s -b %s -m %s -w %s -n %s -o %s -s %s" % ( bin, fastafile, params["background_model"], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run MDmodule and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool. fa...
default_params = {"width":10, "number":10} if params is not None: default_params.update(params) new_file = os.path.join(self.tmpdir, "mdmodule_in.fa") shutil.copy(fastafile, new_file) fastafile = new_file pwmfile = fastafile + ".out" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run ChIPMunk and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool. fa...
params = self._parse_params(params) basename = "munk_in.fa" new_file = os.path.join(self.tmpdir, basename) out = open(new_file, "w") f = Fasta(fastafile) for seq in f.seqs: header = len(seq) // 2 out.write(">%s\n" % header) out.write(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run Posmo and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool. fasta...
default_params = {} if params is not None: default_params.update(params) width = params.get("width", 8) basename = "posmo_in.fa" new_file = os.path.join(self.tmpdir, basename) shutil.copy(fastafile, new_file) fastafile = new_file ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Get enriched JASPAR motifs in a FASTA file. Parameters bin : str Command used to run the tool. fastafile...
fname = os.path.join(self.config.get_motif_dir(), "JASPAR2010_vertebrate.pwm") motifs = read_motifs(fname, fmt="pwm") for motif in motifs: motif.id = "JASPAR_%s" % motif.id return motifs, "", ""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_program(self, bin, fastafile, params=None): """ Run MEME and predict motifs from a FASTA file. Parameters bin : str Command used to run the tool. fastaf...
default_params = {"width":10, "single":False, "number":10} if params is not None: default_params.update(params) tmp = NamedTemporaryFile(dir=self.tmpdir) tmpname = tmp.name strand = "-revcomp" width = default_params["width"] number = de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_to_table(input_table, genome, scoring, pwmfile=None, ncpus=None): """Scan regions in input table with motifs. Parameters input_table : str Filename of i...
config = MotifConfig() if pwmfile is None: pwmfile = config.get_default_params().get("motif_db", None) if pwmfile is not None: pwmfile = os.path.join(config.get_motif_dir(), pwmfile) if pwmfile is None: raise ValueError("no pwmfile given and no default database spe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_args(parser): """ Converts arguments extracted from a parser to a dict, and will dismiss arguments which default to NOT_SET. :param parser: an ``argparse...
args = vars(parser.parse_args()).items() return {key: val for key, val in args if not isinstance(val, NotSet)}