sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def rename_motifs(motifs, stats=None):
"""Rename motifs to GimmeMotifs_1..GimmeMotifs_N.
If stats object is passed, stats will be copied."""
final_motifs = []
for i, motif in enumerate(motifs):
old = str(motif)
motif.id = "GimmeMotifs_{}".format(i + 1)
final_motifs.append(mo... | Rename motifs to GimmeMotifs_1..GimmeMotifs_N.
If stats object is passed, stats will be copied. | entailment |
def gimme_motifs(inputfile, outdir, params=None, filter_significant=True, cluster=True, create_report=True):
"""De novo motif prediction based on an ensemble of different tools.
Parameters
----------
inputfile : str
Filename of input. Can be either BED, narrowPeak or FASTA.
outdir : str
... | De novo motif prediction based on an ensemble of different tools.
Parameters
----------
inputfile : str
Filename of input. Can be either BED, narrowPeak or FASTA.
outdir : str
Name of output directory.
params : dict, optional
Optional parameters.
filter_significant : ... | entailment |
def register_db(cls, dbname):
"""Register method to keep list of dbs."""
def decorator(subclass):
"""Register as decorator function."""
cls._dbs[dbname] = subclass
subclass.name = dbname
return subclass
return decorator | Register method to keep list of dbs. | entailment |
def moap(inputfile, method="hypergeom", scoring=None, outfile=None, motiffile=None, pwmfile=None, genome=None, fpr=0.01, ncpus=None,
subsample=None):
"""Run a single motif activity prediction algorithm.
Parameters
----------
inputfile : str
:1File with regions (chr:start-end) in fir... | Run a single motif activity prediction algorithm.
Parameters
----------
inputfile : str
:1File with regions (chr:start-end) in first column and either cluster
name in second column or a table with values.
method : str, optional
Motif activity method to use. Any of 'hyp... | entailment |
def create(cls, name, ncpus=None):
"""Create a Moap instance based on the predictor name.
Parameters
----------
name : str
Name of the predictor (eg. Xgboost, BayesianRidge, ...)
ncpus : int, optional
Number of threads. Default is the number spec... | Create a Moap instance based on the predictor name.
Parameters
----------
name : str
Name of the predictor (eg. Xgboost, BayesianRidge, ...)
ncpus : int, optional
Number of threads. Default is the number specified in the config.
Returns
... | entailment |
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 decorat... | Register method to keep list of predictors. | entailment |
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"] | List available classification predictors. | entailment |
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(se... | Activates the stream. | entailment |
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... | 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 provided on init.
See Also
----... | entailment |
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 ... | 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 yield.
If `None`, iterate indef... | entailment |
def calc_stats_iterator(motifs, fg_file, bg_file, genome=None, stats=None, ncpus=None):
"""Calculate motif enrichment metrics.
Parameters
----------
motifs : str, list or Motif instance
A file with motifs in pwm format, a list of Motif instances or a
single Motif instance.
fg_file... | Calculate motif enrichment metrics.
Parameters
----------
motifs : str, list or Motif instance
A file with motifs in pwm format, a list of Motif instances or a
single Motif instance.
fg_file : str
Filename of a FASTA, BED or region file with positive sequences.
bg_file : ... | entailment |
def calc_stats(motifs, fg_file, bg_file, genome=None, stats=None, ncpus=None):
"""Calculate motif enrichment metrics.
Parameters
----------
motifs : str, list or Motif instance
A file with motifs in pwm format, a list of Motif instances or a
single Motif instance.
fg_file : str
... | Calculate motif enrichment metrics.
Parameters
----------
motifs : str, list or Motif instance
A file with motifs in pwm format, a list of Motif instances or a
single Motif instance.
fg_file : str
Filename of a FASTA, BED or region file with positive sequences.
bg_file : ... | entailment |
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... | Determine mean rank of motifs based on metrics. | entailment |
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())[... | write motif statistics to text file. | entailment |
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)[... | Calculate ROC AUC values for ROC plots. | entailment |
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_i... | Make ROC plots for all motifs. | entailment |
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():
... | Create text report of motifs with statistics and database match. | entailment |
def _create_graphical_report(inputfile, pwm, background, closest_match, outdir, stats, best_id=None):
"""Create main gimme_motifs output html report."""
if best_id is None:
best_id = {}
logger.debug("Creating graphical report")
class ReportMotif(object):
"""Placeholder for motif st... | Create main gimme_motifs output html report. | entailment |
def create_denovo_motif_report(inputfile, pwmfile, fgfa, background, locfa, outdir, params, stats=None):
"""Create text and graphical (.html) motif reports."""
logger.info("creating reports")
motifs = read_motifs(pwmfile, fmt="pwm")
# ROC plots
create_roc_plots(pwmfile, fgfa, background, outdi... | Create text and graphical (.html) motif reports. | entailment |
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) | Get rid of all axis ticks, lines, etc. | entailment |
def match_plot(plotdata, outfile):
"""Plot list of motifs with database match and p-value
"param plotdata: list of (motif, dbmotif, pval)
"""
fig_h = 2
fig_w = 7
nrows = len(plotdata)
ncols = 2
fig = plt.figure(figsize=(fig_w, nrows * fig_h))
for i, (motif, dbmotif, pval) in e... | Plot list of motifs with database match and p-value
"param plotdata: list of (motif, dbmotif, pval) | entailment |
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)
... | Plot a "phylogenetic" tree | entailment |
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("... | Check if the inputfile is a valid bed-file | entailment |
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 ["... | Check if an input file is valid, which means BED, narrowPeak or FASTA | entailment |
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 best match per motif.
Parameters
----------
fname : str
Filename of a sequence file in FASTA format.
motifs : list
... | Scan a FASTA file with motifs.
Scan a FASTA file and return a dictionary with the best match per motif.
Parameters
----------
fname : str
Filename of a sequence file in FASTA format.
motifs : list
List of motif instances.
Returns
-------
result : dict
Dictiona... | entailment |
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 specified either as a genome name or as the
name of a FASTA file.
Parameters
----------
fname : str, opti... | Set the background to use for FPR and z-score calculations.
Background can be specified either as a genome name or as the
name of a FASTA file.
Parameters
----------
fname : str, optional
Name of FASTA file to use as background.
genome : str, optio... | entailment |
def set_threshold(self, fpr=None, threshold=None):
"""Set motif scanning threshold based on background sequences.
Parameters
----------
fpr : float, optional
Desired FPR, between 0.0 and 1.0.
threshold : float or str, optional
Desired motif threshold, ex... | Set motif scanning threshold based on background sequences.
Parameters
----------
fpr : float, optional
Desired FPR, between 0.0 and 1.0.
threshold : float or str, optional
Desired motif threshold, expressed as the fraction of the
difference between... | entailment |
def count(self, seqs, nreport=100, scan_rc=True):
"""
count the number of matches above the cutoff
returns an iterator of lists containing integer counts
"""
for matches in self.scan(seqs, nreport, scan_rc):
counts = [len(m) for m in matches]
yield counts | count the number of matches above the cutoff
returns an iterator of lists containing integer counts | entailment |
def total_count(self, seqs, nreport=100, scan_rc=True):
"""
count the number of matches above the cutoff
returns an iterator of lists containing integer counts
"""
count_table = [counts for counts in self.count(seqs, nreport, scan_rc)]
return np.sum(np.array(coun... | count the number of matches above the cutoff
returns an iterator of lists containing integer counts | entailment |
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 containing floats
"""
self.set_threshold(threshold=0.0)
if normalize and len(self.meanstd) == 0:
self.se... | give the score of the best match of each motif in each sequence
returns an iterator of lists containing floats | entailment |
def best_match(self, seqs, scan_rc=True):
"""
give the best match of each motif in each sequence
returns an iterator of nested lists containing tuples:
(score, position, strand)
"""
self.set_threshold(threshold=0.0)
for matches in self.scan(seqs, 1, scan_rc):
... | give the best match of each motif in each sequence
returns an iterator of nested lists containing tuples:
(score, position, strand) | entailment |
def scan(self, seqs, nreport=100, scan_rc=True, normalize=False):
"""
scan a set of regions / sequences
"""
if not self.threshold:
sys.stderr.write(
"Using default threshold of 0.95. "
"This is likely not optimal!\n"
)
... | scan a set of regions / sequences | entailment |
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 arg... | Calculate ROC_AUC and other metrics and optionally plot ROC curve. | entailment |
def ssd(p1, p2):
"""Calculates motif position similarity based on sum of squared distances.
Parameters
----------
p1 : list
Motif position 1.
p2 : list
Motif position 2.
Returns
-------
score : float
"""
return 2 - np.sum([(a-b)**2 for a,b in zip(p1... | Calculates motif position similarity based on sum of squared distances.
Parameters
----------
p1 : list
Motif position 1.
p2 : list
Motif position 2.
Returns
-------
score : float | entailment |
def seqcor(m1, m2, seq=None):
"""Calculates motif similarity based on Pearson correlation of scores.
Based on Kielbasa (2015) and Grau (2015).
Scores are calculated based on scanning a de Bruijn sequence of 7-mers.
This sequence is taken from ShortCAKE (Orenstein & Shamir, 2015).
Optionally anothe... | Calculates motif similarity based on Pearson correlation of scores.
Based on Kielbasa (2015) and Grau (2015).
Scores are calculated based on scanning a de Bruijn sequence of 7-mers.
This sequence is taken from ShortCAKE (Orenstein & Shamir, 2015).
Optionally another sequence can be given as an argumen... | entailment |
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, ed, distance, wic,
chisq, akl or ssd. If match is 'total' the similarity score is
calculated for the whole match, ... | Compare two motifs.
The similarity metric can be any of seqcor, pcc, ed, distance, wic,
chisq, akl or ssd. If match is 'total' the similarity score is
calculated for the whole match, including positions that are not
present in both motifs. If match is partial or subtotal, onl... | entailment |
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 compared to reference motifs.
Parameters
----------
motifs : list
List of Motif instan... | Pairwise comparison of a set of motifs compared to reference motifs.
Parameters
----------
motifs : list
List of Motif instances.
dbmotifs : list
List of Motif instances.
match : str
Match can be "partial", "subtotal" or "total". Not all met... | entailment |
def get_closest_match(self, motifs, dbmotifs=None, match="partial", metric="wic",combine="mean", parallel=True, ncpus=None):
"""Return best match in database for motifs.
Parameters
----------
motifs : list or str
Filename of motifs or list of motifs.
dbmotifs : list... | Return best match in database for motifs.
Parameters
----------
motifs : list or str
Filename of motifs or list of motifs.
dbmotifs : list or str, optional
Database motifs, default will be used if not specified.
match : str, optional
metric : s... | entailment |
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,
} | List regions for the service | entailment |
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]
por... | Print nice looking table of information from list of load balancers | entailment |
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... | Print nice looking table of information from list of instances | entailment |
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... | Print nice looking table of information from images | entailment |
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_FI... | Run Fabric commands against EC2 instances | entailment |
def main():
"""
AWS support script's main method
"""
p = argparse.ArgumentParser(description='Manage Amazon AWS services',
prog='aws',
version=__version__)
subparsers = p.add_subparsers(help='Select Amazon AWS service to use')
# Au... | AWS support script's main method | entailment |
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
... | 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
If True, yield a final partial batch on under-run.
axis : int ... | entailment |
def tuples(stream, *keys):
"""Reformat data as tuples.
Parameters
----------
stream : iterable
Stream of data objects.
*keys : strings
Keys to use for ordering data.
Yields
------
items : tuple of np.ndarrays
Data object reformated as a tuple.
Raises
-... | Reformat data as tuples.
Parameters
----------
stream : iterable
Stream of data objects.
*keys : strings
Keys to use for ordering data.
Yields
------
items : tuple of np.ndarrays
Data object reformated as a tuple.
Raises
------
DataError
If the... | entailment |
def keras_tuples(stream, inputs=None, outputs=None):
"""Reformat data objects as keras-compatible tuples.
For more detail: https://keras.io/models/model/#fit
Parameters
----------
stream : iterable
Stream of data objects.
inputs : string or iterable of strings, None
Keys to us... | Reformat data objects as keras-compatible tuples.
For more detail: https://keras.io/models/model/#fit
Parameters
----------
stream : iterable
Stream of data objects.
inputs : string or iterable of strings, None
Keys to use for ordered input data.
If not specified, returns ... | entailment |
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(... | Creates histrogram of motif location.
Parameters
----------
args : argparse object
Command line arguments. | entailment |
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(... | Find location of executable. | entailment |
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, shel... | Find all files in a directory by extension. | entailment |
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)
... | Return list of Motif instances from default motif database. | entailment |
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 : list
List with sequences (A,C,G,T).
Returns
-------
m : Motif instance
Motif created from ... | Convert alignment to motif.
Converts a list with sequences to a motif. Sequences should be the same
length.
Parameters
----------
align : list
List with sequences (A,C,G,T).
Returns
-------
m : Motif instance
Motif created from the aligned sequences. | entailment |
def motif_from_consensus(cons, n=12):
"""Convert consensus sequence to motif.
Converts a consensus sequences using the nucleotide IUPAC alphabet to a
motif.
Parameters
----------
cons : str
Consensus sequence using the IUPAC alphabet.
n : int , optional
Count used to conv... | Convert consensus sequence to motif.
Converts a consensus sequences using the nucleotide IUPAC alphabet to a
motif.
Parameters
----------
cons : str
Consensus sequence using the IUPAC alphabet.
n : int , optional
Count used to convert the sequence to a PFM.
Returns
... | entailment |
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 or single Motif instance.
Returns
-------
motifs : list
List of Motif instances.
"""
if isin... | Parse motifs in a variety of formats to return a list of motifs.
Parameters
----------
motifs : list or str
Filename of motif, list of motifs or single Motif instance.
Returns
-------
motifs : list
List of Motif instances. | entailment |
def _read_motifs_from_filehandle(handle, fmt):
"""
Read motifs from a file-like object.
Parameters
----------
handle : file-like object
Motifs.
fmt : string, optional
Motif format, can be 'pwm', 'transfac', 'xxmotif', 'jaspar' or 'align'.
Returns
-------
motifs... | Read motifs from a file-like object.
Parameters
----------
handle : file-like object
Motifs.
fmt : string, optional
Motif format, can be 'pwm', 'transfac', 'xxmotif', 'jaspar' or 'align'.
Returns
-------
motifs : list
List of Motif instances. | entailment |
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, optional
Motif database, filename of motif file or file-like object. If infile
is not specified the default... | Read motifs from a file or stream or file-like object.
Parameters
----------
infile : string or file-like object, optional
Motif database, filename of motif file or file-like object. If infile
is not specified the default motifs as specified in the config file
will be returned.
... | entailment |
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 r... | Return the total information content of the motif.
Return
------
ic : float
Motif information content. | entailment |
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)
s... | Return the minimum PWM score.
Returns
-------
score : float
Minimum PWM score. | entailment |
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)
s... | Return the maximum PWM score.
Returns
-------
score : float
Maximum PWM score. | entailment |
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 the motif.
Returns
-------
score : float
Log-odd score.
... | Calculate the log-odds score for a specific k-mer.
Parameters
----------
kmer : str
String representing a kmer. Should be the same length as the motif.
Returns
-------
score : float
Log-odd score. | entailment |
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
Pseudocount used in conversion.
Returns
-------
p... | Convert PFM with counts to a PFM with fractions.
Parameters
----------
pfm : list
2-dimensional list with counts.
pseudo : float
Pseudocount used in conversion.
Returns
-------
pwm : list
2-dimensional list with fracti... | entailment |
def to_motevo(self):
"""Return motif formatted in MotEvo (TRANSFAC-like) format
Returns
-------
m : str
String of motif in MotEvo format.
"""
m = "//\n"
m += "NA {}\n".format(self.id)
m += "P0\tA\tC\tG\tT\n"
for i, row in enume... | Return motif formatted in MotEvo (TRANSFAC-like) format
Returns
-------
m : str
String of motif in MotEvo format. | entailment |
def to_transfac(self):
"""Return motif formatted in TRANSFAC format
Returns
-------
m : str
String of motif in TRANSFAC format.
"""
m = "%s\t%s\t%s\n" % ("DE", self.id, "unknown")
for i, (row, cons) in enumerate(zip(self.pfm, self.to_consensus... | Return motif formatted in TRANSFAC format
Returns
-------
m : str
String of motif in TRANSFAC format. | entailment |
def to_meme(self):
"""Return motif formatted in MEME format
Returns
-------
m : str
String of motif in MEME format.
"""
motif_id = self.id.replace(" ", "_")
m = "MOTIF %s\n" % motif_id
m += "BL MOTIF %s width=0 seqs=0\n"% motif_id
... | Return motif formatted in MEME format
Returns
-------
m : str
String of motif in MEME format. | entailment |
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):
... | Calculate the information content of one position.
Returns
-------
score : float
Information content. | entailment |
def pcc_pos(self, row1, row2):
"""Calculate the Pearson correlation coefficient of one position
compared to another position.
Returns
-------
score : float
Pearson correlation coefficient.
"""
mean1 = np.mean(row1)
mean2 = np.mean(row2)
... | Calculate the Pearson correlation coefficient of one position
compared to another position.
Returns
-------
score : float
Pearson correlation coefficient. | entailment |
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 ... | Return the reverse complemented motif.
Returns
-------
m : Motif instance
New Motif instance with the reverse complement of the input motif. | entailment |
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 be changed in-place.
Parameters
----------
edge_ic_cutoff : float, optional
Information content threshold.... | Trim positions with an information content lower than the threshold.
The default threshold is set to 0.4. The Motif will be changed in-place.
Parameters
----------
edge_ic_cutoff : float, optional
Information content threshold. All motif positions at the flanks
... | entailment |
def consensus_scan(self, fa):
"""Scan FASTA with the motif as a consensus sequence.
Parameters
----------
fa : Fasta object
Fasta object to scan
Returns
-------
matches : dict
Dictionaru with matches.
"""
regexp = ... | Scan FASTA with the motif as a consensus sequence.
Parameters
----------
fa : Fasta object
Fasta object to scan
Returns
-------
matches : dict
Dictionaru with matches. | entailment |
def pwm_scan(self, fa, cutoff=0.9, nreport=50, scan_rc=True):
"""Scan sequences with this motif.
Scan sequences from a FASTA object with this motif. Less efficient
than using a Scanner object. By setting the cutoff to 0.0 and
nreport to 1, the best match for every sequence will be ret... | Scan sequences with this motif.
Scan sequences from a FASTA object with this motif. Less efficient
than using a Scanner object. By setting the cutoff to 0.0 and
nreport to 1, the best match for every sequence will be returned.
Only the position of the matches is returned.
Par... | entailment |
def pwm_scan_all(self, fa, cutoff=0.9, nreport=50, scan_rc=True):
"""Scan sequences with this motif.
Scan sequences from a FASTA object with this motif. Less efficient
than using a Scanner object. By setting the cutoff to 0.0 and
nreport to 1, the best match for every sequence will be... | Scan sequences with this motif.
Scan sequences from a FASTA object with this motif. Less efficient
than using a Scanner object. By setting the cutoff to 0.0 and
nreport to 1, the best match for every sequence will be returned.
The score, position and strand for every match is returned... | entailment |
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 sequences from a FASTA object with this motif. Less efficient
than using a Scanner object. By setting the cutoff to 0.0 and
nrepor... | Scan sequences with this motif and save to a GFF file.
Scan sequences from a FASTA object with this motif. Less efficient
than using a Scanner object. By setting the cutoff to 0.0 and
nreport to 1, the best match for every sequence will be returned.
The output is save to a file in GFF... | entailment |
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 average as a new
Motif object. The position and orientatien need to be supplied. The pos
parameter is the position of the second... | Return the average of two motifs.
Combine this motif with another motif and return the average as a new
Motif object. The position and orientatien need to be supplied. The pos
parameter is the position of the second motif relative to this motif.
For example, take the following ... | entailment |
def _pwm_to_str(self, precision=4):
"""Return string representation of pwm.
Parameters
----------
precision : int, optional, default 4
Floating-point precision.
Returns
-------
pwm_string : str
"""
if not self.pwm:
return ... | Return string representation of pwm.
Parameters
----------
precision : int, optional, default 4
Floating-point precision.
Returns
-------
pwm_string : str | entailment |
def to_pwm(self, precision=4, extra_str=""):
"""Return pwm as string.
Parameters
----------
precision : int, optional, default 4
Floating-point precision.
extra_str |: str, optional
Extra text to include with motif id line.
Retur... | Return pwm as string.
Parameters
----------
precision : int, optional, default 4
Floating-point precision.
extra_str |: str, optional
Extra text to include with motif id line.
Returns
-------
motif_str : str
M... | entailment |
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. Valid formats are: PNG,
EPS, GIF and PDF.
Parameters
----------
fname : str
Output filename.
... | Create a sequence logo using seqlogo.
Create a sequence logo and save it to a file. Valid formats are: PNG,
EPS, GIF and PDF.
Parameters
----------
fname : str
Output filename.
fmt : str , optional
Output format (case-insensitive). Valid format... | entailment |
def randomize(self):
"""Create a new motif with shuffled positions.
Shuffle the positions of this motif and return a new Motif instance.
Returns
-------
m : Motif instance
Motif instance with shuffled positions.
"""
random_pfm = [[c for c in row] for... | Create a new motif with shuffled positions.
Shuffle the positions of this motif and return a new Motif instance.
Returns
-------
m : Motif instance
Motif instance with shuffled positions. | entailment |
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))
... | Run the maelstrom method. | entailment |
def zmq_send_data(socket, data, flags=0, copy=True, track=False):
"""Send data, e.g. {key: np.ndarray}, with metadata"""
header, payload = [], []
for key in sorted(data.keys()):
arr = data[key]
if not isinstance(arr, np.ndarray):
raise DataError('Only ndarray types can be seri... | Send data, e.g. {key: np.ndarray}, with metadata | entailment |
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 ... | Receive data over a socket. | entailment |
def iterate(self, max_iter=None):
"""
Note: A ZMQStreamer does not activate its stream,
but allows the zmq_worker to do that.
Yields
------
data : dict
Data drawn from `streamer(max_iter)`.
"""
context = zmq.Context()
if six.PY2:
... | Note: A ZMQStreamer does not activate its stream,
but allows the zmq_worker to do that.
Yields
------
data : dict
Data drawn from `streamer(max_iter)`. | entailment |
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 | Mask all lowercase nucleotides with N's | entailment |
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 (... | Return n random sequences from this Fasta object | entailment |
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() | Write sequences to FASTA formatted file | entailment |
def cluster_motifs(motifs, match="total", metric="wic", combine="mean", pval=True, threshold=0.95, trim_edges=False, edge_ic_cutoff=0.2, include_bg=True, progress=True, ncpus=None):
"""
Clusters a set of sequence motifs. Required arg 'motifs' is a file containing
positional frequency matrices or an array w... | Clusters a set of sequence motifs. Required arg 'motifs' is a file containing
positional frequency matrices or an array with motifs.
Optional args:
'match', 'metric' and 'combine' specify the method used to compare and score
the motifs. By default the WIC score is used (metric='wic'), using the the
... | entailment |
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... | 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 batch.
If the batch has n... | entailment |
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_coun... | Activates a number of streams | entailment |
def _new_stream(self, idx):
'''Randomly select and create a stream.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace
'''
# instantiate
if self.rate is not None:
n_stream = 1 + self.rng.poisson(lam=self.rate)
... | Randomly select and create a stream.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace | entailment |
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... | Yields items from the mux, and handles stream exhaustion and
replacement. | entailment |
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_)) | StochasticMux chooses its next sample stream randomly | entailment |
def _activate_stream(self, idx):
'''Randomly select and create a stream.
StochasticMux adds mode handling to _activate_stream, making it so that
if we're not sampling "with_replacement", the distribution for this
chosen streamer is set to 0, causing the streamer not to be available
... | Randomly select and create a stream.
StochasticMux adds mode handling to _activate_stream, making it so that
if we're not sampling "with_replacement", the distribution for this
chosen streamer is set to 0, causing the streamer not to be available
until it is exhausted.
Paramete... | entailment |
def _new_stream(self, idx):
'''Randomly select and create a new stream.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace
'''
# Choose the stream index from the candidate pool
self.stream_idxs_[idx] = self.rng.choice(
... | Randomly select and create a new stream.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace | entailment |
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.
... | ShuffledMux's activate is similar to StochasticMux,
but there is no 'n_active', since all the streams are always available. | entailment |
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_)) | ShuffledMux chooses its next sample stream randomly,
conditioned on the stream weights. | entailment |
def _new_stream(self, idx):
'''Randomly select and create a new stream.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace
'''
# Don't activate the stream if the weight is 0 or None
if self.stream_weights_[idx]:
... | Randomly select and create a new stream.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace | entailment |
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.stream... | Rotates through each active sampler by incrementing the index | entailment |
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.
For special behavior (ie Weighted streams), you must override this
in a child class.
Parameters
----------
... | Activate a new stream, given the index into the stream pool.
BaseMux's _new_stream simply chooses a new stream and activates it.
For special behavior (ie Weighted streams), you must override this
in a child class.
Parameters
----------
idx : int, [0:n_streams - 1]
... | entailment |
def _replace_stream(self, idx=None):
"""Called by `BaseMux`'s iterate() when a stream is exhausted.
Set the stream to None so it is ignored once exhausted.
Parameters
----------
idx : int or None
Raises
------
StopIteration
If all streams are... | Called by `BaseMux`'s iterate() when a stream is exhausted.
Set the stream to None so it is ignored once exhausted.
Parameters
----------
idx : int or None
Raises
------
StopIteration
If all streams are consumed, and `mode`=="exahustive" | entailment |
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... | 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 iterating from the beginning of the seq... | entailment |
def split_and_save_datasets(X, Y, paths):
"""Shuffle X and Y into n / len(paths) datasets, and save them
to disk at the locations provided in paths.
"""
shuffled_idxs = np.random.permutation(np.arange(len(X)))
for i in range(len(paths)):
# Take every len(paths) item, starting at i.
... | Shuffle X and Y into n / len(paths) datasets, and save them
to disk at the locations provided in paths. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.