INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Runs the Geweke diagnostic on the supplied chains. | def geweke(self, chain=None, first=0.1, last=0.5, threshold=0.05):
""" Runs the Geweke diagnostic on the supplied chains.
Parameters
----------
chain : int|str, optional
Which chain to run the diagnostic on. By default, this is `None`,
which will run the diagnost... |
Generates a LaTeX table from parameter summaries. | def get_latex_table(self, parameters=None, transpose=False, caption=None,
label="tab:model_params", hlines=True, blank_fill="--"): # pragma: no cover
""" Generates a LaTeX table from parameter summaries.
Parameters
----------
parameters : list[str], optional
... |
Gets a summary of the marginalised parameter distributions. | def get_summary(self, squeeze=True, parameters=None, chains=None):
""" Gets a summary of the marginalised parameter distributions.
Parameters
----------
squeeze : bool, optional
Squeeze the summaries. If you only have one chain, squeeze will not return
a length ... |
Gets the maximum posterior point in parameter space from the passed parameters. Requires the chains to have set posterior values. | def get_max_posteriors(self, parameters=None, squeeze=True, chains=None):
""" Gets the maximum posterior point in parameter space from the passed parameters.
Requires the chains to have set `posterior` values.
Parameters
----------
parameters : str|list[str]
... |
Takes a chain and returns the correlation between chain parameters. | def get_correlations(self, chain=0, parameters=None):
"""
Takes a chain and returns the correlation between chain parameters.
Parameters
----------
chain : int|str, optional
The chain index or name. Defaults to first chain.
parameters : list[str], optional
... |
Takes a chain and returns the covariance between chain parameters. | def get_covariance(self, chain=0, parameters=None):
"""
Takes a chain and returns the covariance between chain parameters.
Parameters
----------
chain : int|str, optional
The chain index or name. Defaults to first chain.
parameters : list[str], optional
... |
Gets a LaTeX table of parameter correlations. | def get_correlation_table(self, chain=0, parameters=None, caption="Parameter Correlations",
label="tab:parameter_correlations"):
"""
Gets a LaTeX table of parameter correlations.
Parameters
----------
chain : int|str, optional
The chain ... |
Gets a LaTeX table of parameter covariance. | def get_covariance_table(self, chain=0, parameters=None, caption="Parameter Covariance",
label="tab:parameter_covariance"):
"""
Gets a LaTeX table of parameter covariance.
Parameters
----------
chain : int|str, optional
The chain index o... |
Generates LaTeX appropriate text from marginalised parameter bounds. | def get_parameter_text(self, lower, maximum, upper, wrap=False):
""" Generates LaTeX appropriate text from marginalised parameter bounds.
Parameters
----------
lower : float
The lower bound on the parameter
maximum : float
The value of the parameter with ... |
Add a chain to the consumer. | def add_chain(self, chain, parameters=None, name=None, weights=None, posterior=None, walkers=None,
grid=False, num_eff_data_points=None, num_free_params=None, color=None, linewidth=None,
linestyle=None, kde=None, shade=None, shade_alpha=None, power=None, marker_style=None, marker_siz... |
Removes a chain from ChainConsumer. Calling this will require any configurations set to be redone! | def remove_chain(self, chain=-1):
"""
Removes a chain from ChainConsumer. Calling this will require any configurations set to be redone!
Parameters
----------
chain : int|str, list[str|int]
The chain(s) to remove. You can pass in either the chain index, or the chain ... |
r Configure the general plotting parameters common across the bar and contour plots. | def configure(self, statistics="max", max_ticks=5, plot_hists=True, flip=True,
serif=True, sigma2d=False, sigmas=None, summary=None, bins=None, rainbow=None,
colors=None, linestyles=None, linewidths=None, kde=False, smooth=None,
cloud=None, shade=None, shade_alpha=N... |
Configure the arguments passed to the axvline and axhline methods when plotting truth values. | def configure_truth(self, **kwargs): # pragma: no cover
""" Configure the arguments passed to the ``axvline`` and ``axhline``
methods when plotting truth values.
If you do not call this explicitly, the :func:`plot` method will
invoke this method automatically.
Recommended to s... |
Returns a ChainConsumer instance containing all the walks of a given chain as individual chains themselves. | def divide_chain(self, chain=0):
"""
Returns a ChainConsumer instance containing all the walks of a given chain
as individual chains themselves.
This method might be useful if, for example, your chain was made using
MCMC with 4 walkers. To check the sampling of all 4 walkers agr... |
Calculate motif score threshold for a given FPR. | def threshold(args):
"""Calculate motif score threshold for a given FPR."""
if args.fpr < 0 or args.fpr > 1:
print("Please specify a FPR between 0 and 1")
sys.exit(1)
motifs = read_motifs(args.pwmfile)
s = Scanner()
s.set_motifs(args.pwmfile)
s.set_threshold(args.fpr, filen... |
Convert two arrays of values to an array of labels and an array of scores. | def values_to_labels(fg_vals, bg_vals):
"""
Convert two arrays of values to an array of labels and an array of scores.
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
Returns
... |
Computes the recall at a specific FDR ( default 10% ). | def recall_at_fdr(fg_vals, bg_vals, fdr_cutoff=0.1):
"""
Computes the recall at a specific FDR (default 10%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fdr : float, ... |
Computes the hypergeometric p - value at a specific FPR ( default 1% ). | def matches_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
Computes the hypergeometric p-value at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr... |
Computes the hypergeometric p - value at a specific FPR ( default 1% ). | def phyper_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
Computes the hypergeometric p-value at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr ... |
Computes the fraction positives at a specific FPR ( default 1% ). | def fraction_fpr(fg_vals, bg_vals, fpr=0.01):
"""
Computes the fraction positives at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr : flo... |
Returns the motif score at a specific FPR ( default 1% ). | def score_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
Returns the motif score at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr : float, opti... |
Computes the enrichment at a specific FPR ( default 1% ). | def enr_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
Computes the enrichment at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr : float, option... |
Computes the maximum enrichment. | def max_enrichment(fg_vals, bg_vals, minbg=2):
"""
Computes the maximum enrichment.
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
minbg : int, optional
Minimum n... |
Computes the Mean Normalized Conditional Probability ( MNCP ). | def mncp(fg_vals, bg_vals):
"""
Computes the Mean Normalized Conditional Probability (MNCP).
MNCP is described in Clarke & Granek, Bioinformatics, 2003.
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of val... |
Computes the Precision - Recall Area Under Curve ( PR AUC ) | def pr_auc(fg_vals, bg_vals):
"""
Computes the Precision-Recall Area Under Curve (PR AUC)
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
Returns
-------
score : float
PR AU... |
Computes the ROC Area Under Curve ( ROC AUC ) | def roc_auc(fg_vals, bg_vals):
"""
Computes the ROC Area Under Curve (ROC AUC)
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
Returns
-------
score : float
ROC AUC score
... |
Computes the ROC Area Under Curve until a certain FPR value. | def roc_auc_xlim(x_bla, y_bla, xlim=0.1):
"""
Computes the ROC Area Under Curve until a certain FPR value.
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
xlim : float, optional
FPR val... |
Return fpr ( x ) and tpr ( y ) of the ROC curve. | def roc_values(fg_vals, bg_vals):
"""
Return fpr (x) and tpr (y) of the ROC curve.
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
Returns
-------
fpr : array
... |
Computes the maximum F - measure. | def max_fmeasure(fg_vals, bg_vals):
"""
Computes the maximum F-measure.
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
Returns
-------
f : float
Maximum f... |
Computes the Kolmogorov - Smirnov p - value of position distribution. | def ks_pvalue(fg_pos, bg_pos=None):
"""
Computes the Kolmogorov-Smirnov p-value of position distribution.
Parameters
----------
fg_pos : array_like
The list of values for the positive set.
bg_pos : array_like, optional
The list of values for the negative set.
Returns
... |
Computes the - log10 of Kolmogorov - Smirnov p - value of position distribution. | def ks_significance(fg_pos, bg_pos=None):
"""
Computes the -log10 of Kolmogorov-Smirnov p-value of position distribution.
Parameters
----------
fg_pos : array_like
The list of values for the positive set.
bg_pos : array_like, optional
The list of values for the negative set.
... |
Load and shape data for training with Keras + Pescador. | def setup_data():
"""Load and shape data for training with Keras + Pescador.
Returns
-------
input_shape : tuple, len=3
Shape of each sample; adapts to channel configuration of Keras.
X_train, y_train : np.ndarrays
Images and labels for training.
X_test, y_test : np.ndarrays
... |
Create a compiled Keras model. | def build_model(input_shape):
"""Create a compiled Keras model.
Parameters
----------
input_shape : tuple, len=3
Shape of each image sample.
Returns
-------
model : keras.Model
Constructed model.
"""
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),... |
A basic generator for sampling data. | def sampler(X, y):
'''A basic generator for sampling data.
Parameters
----------
X : np.ndarray, len=n_samples, ndim=4
Image data.
y : np.ndarray, len=n_samples, ndim=2
One-hot encoded class vectors.
Yields
------
data : dict
Single image sample, like {X: np.nd... |
Add noise to a data stream. | def additive_noise(stream, key='X', scale=1e-1):
'''Add noise to a data stream.
Parameters
----------
stream : iterable
A stream that yields data objects.
key : string, default='X'
Name of the field to add noise.
scale : float, default=0.1
Scale factor for gaussian noi... |
Return default GimmeMotifs parameters. | def parse_denovo_params(user_params=None):
"""Return default GimmeMotifs parameters.
Defaults will be replaced with parameters defined in user_params.
Parameters
----------
user_params : dict, optional
User-defined parameters.
Returns
-------
params : dict
"""
config ... |
Return aggregated ranks as implemented in the RobustRankAgg R package. | def rankagg_R(df, method="stuart"):
"""Return aggregated ranks as implemented in the RobustRankAgg R package.
This function is now deprecated.
References:
Kolde et al., 2012, DOI: 10.1093/bioinformatics/btr709
Stuart et al., 2003, DOI: 10.1126/science.1087447
Parameters
--------... |
Return aggregated ranks. | def rankagg(df, method="stuart"):
"""Return aggregated ranks.
Implementation is ported from the RobustRankAggreg R package
References:
Kolde et al., 2012, DOI: 10.1093/bioinformatics/btr709
Stuart et al., 2003, DOI: 10.1126/science.1087447
Parameters
----------
df : pand... |
Yield data while optionally burning compute cycles. | def data_gen(n_ops=100):
"""Yield data, while optionally burning compute cycles.
Parameters
----------
n_ops : int, default=100
Number of operations to run between yielding data.
Returns
-------
data : dict
A object which looks like it might come from some
machine l... |
Parallel calculation of motif statistics. | def mp_calc_stats(motifs, fg_fa, bg_fa, bg_name=None):
"""Parallel calculation of motif statistics."""
try:
stats = calc_stats(motifs, fg_fa, bg_fa, ncpus=1)
except Exception as e:
raise
sys.stderr.write("ERROR: {}\n".format(str(e)))
stats = {}
if not bg_name:
bg... |
Parallel motif prediction. | def _run_tool(job_name, t, fastafile, params):
"""Parallel motif prediction."""
try:
result = t.run(fastafile, params, mytmpdir())
except Exception as e:
result = ([], "", "{} failed to run: {}".format(job_name, e))
return job_name, result |
Parallel prediction of motifs. | def pp_predict_motifs(fastafile, outfile, analysis="small", organism="hg18", single=False, background="", tools=None, job_server=None, ncpus=8, max_time=-1, stats_fg=None, stats_bg=None):
"""Parallel prediction of motifs.
Utility function for gimmemotifs.denovo.gimme_motifs. Probably better to
use that, i... |
Predict motifs input is a FASTA - file | def predict_motifs(infile, bgfile, outfile, params=None, stats_fg=None, stats_bg=None):
""" Predict motifs, input is a FASTA-file"""
# Parse parameters
required_params = ["tools", "available_tools", "analysis",
"genome", "use_strand", "max_time"]
if params is None:
... |
Add motifs to the result object. | def add_motifs(self, args):
"""Add motifs to the result object."""
self.lock.acquire()
# Callback function for motif programs
if args is None or len(args) != 2 or len(args[1]) != 3:
try:
job = args[0]
logger.warn("job %s failed", job)
... |
Make sure all jobs are finished. | def wait_for_stats(self):
"""Make sure all jobs are finished."""
logging.debug("waiting for statistics to finish")
for job in self.stat_jobs:
job.get()
sleep(2) |
Callback to add motif statistics. | def add_stats(self, args):
"""Callback to add motif statistics."""
bg_name, stats = args
logger.debug("Stats: %s %s", bg_name, stats)
for motif_id in stats.keys():
if motif_id not in self.stats:
self.stats[motif_id] = {}
self.stat... |
Prepare a narrowPeak file for de novo motif prediction. | def prepare_denovo_input_narrowpeak(inputfile, params, outdir):
"""Prepare a narrowPeak file for de novo motif prediction.
All regions to same size; split in test and validation set;
converted to FASTA.
Parameters
----------
inputfile : str
BED file with input regions.
params : di... |
Prepare a BED file for de novo motif prediction. | def prepare_denovo_input_bed(inputfile, params, outdir):
"""Prepare a BED file for de novo motif prediction.
All regions to same size; split in test and validation set;
converted to FASTA.
Parameters
----------
inputfile : str
BED file with input regions.
params : dict
Dic... |
Create all the FASTA files for de novo motif prediction and validation. Parameters ---------- | def prepare_denovo_input_fa(inputfile, params, outdir):
"""Create all the FASTA files for de novo motif prediction and validation.
Parameters
----------
"""
fraction = float(params["fraction"])
abs_max = int(params["abs_max"])
logger.info("preparing input (FASTA)")
pred_fa = os.pa... |
Create background of a specific type. | def create_background(bg_type, fafile, outfile, genome="hg18", width=200, nr_times=10, custom_background=None):
"""Create background of a specific type.
Parameters
----------
bg_type : str
Name of background type.
fafile : str
Name of input FASTA file.
outfile : str
Na... |
Create different backgrounds for motif prediction and validation. | def create_backgrounds(outdir, background=None, genome="hg38", width=200, custom_background=None):
"""Create different backgrounds for motif prediction and validation.
Parameters
----------
outdir : str
Directory to save results.
background : list, optional
Background types to ... |
Filter significant motifs based on several statistics. Parameters ---------- stats: dict Statistics disctionary object. | def _is_significant(stats, metrics=None):
"""Filter significant motifs based on several statistics.
Parameters
----------
stats : dict
Statistics disctionary object.
metrics : sequence
Metric with associated minimum values. The default is
(("max_enrichment", 3), ("roc_a... |
Filter significant motifs based on several statistics. | def filter_significant_motifs(fname, result, bg, metrics=None):
"""Filter significant motifs based on several statistics.
Parameters
----------
fname : str
Filename of output file were significant motifs will be saved.
result : PredictionResult instance
Contains motifs and associat... |
Return the best motif per cluster for a clustering results. | def best_motif_in_cluster(single_pwm, clus_pwm, clusters, fg_fa, background, stats=None, metrics=("roc_auc", "recall_at_fdr")):
"""Return the best motif per cluster for a clustering results.
The motif can be either the average motif or one of the clustered motifs.
Parameters
----------
single_pwm ... |
Rename motifs to GimmeMotifs_1.. GimmeMotifs_N. If stats object is passed stats will be copied. | 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... |
De novo motif prediction based on an ensemble of different tools. | 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
... |
Register method to keep list of dbs. | 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 |
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 hypergeom lasso lightningclassification lightningregr... | 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... |
Create a Moap instance based on the predictor name. | 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... |
Register method to keep list of predictors. | 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... |
List available classification predictors. | 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"] |
Activates the stream. | 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... |
Instantiate an iterator. | 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... |
Iterate from the streamer infinitely. | 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 ... |
Calculate motif enrichment metrics. | 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. | 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
... |
Determine mean rank of motifs based on metrics. | 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... |
write motif statistics to text file. | 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())[... |
Calculate ROC AUC values for ROC plots. | 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)[... |
Make ROC plots for all motifs. | 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... |
Create text report of motifs with statistics and database match. | 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 main gimme_motifs output html report. | 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 text and graphical (. html ) motif reports. | 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... |
Get rid of all axis ticks lines etc. | 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) |
Plot list of motifs with database match and p - value param plotdata: list of ( motif dbmotif pval ) | 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 a phylogenetic tree | 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)
... |
Check if the inputfile is a valid bed - file | 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 an input file is valid which means BED narrowPeak or FASTA | 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 ["... |
Scan a FASTA file with motifs. | 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
... |
Set the background to use for FPR and z - score calculations. | 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 motif scanning threshold based on background sequences. | 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... |
count the number of matches above the cutoff returns an iterator of lists containing integer counts | 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 | 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... |
give the score of the best match of each motif in each sequence returns an iterator of lists containing floats | 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 best match of each motif in each sequence returns an iterator of nested lists containing tuples: ( score position strand ) | 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):
... |
scan a set of regions/ sequences | 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"
)
... |
Calculate ROC_AUC and other metrics and optionally plot ROC curve. | 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... |
Calculates motif position similarity based on sum of squared distances. Parameters ---------- p1: list Motif position 1. p2: list Motif position 2. Returns ------- score: float | 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 similarity based on Pearson correlation of scores. | 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... |
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 only the matching psotiions are used to calculate the sco... | 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, ... |
Pairwise comparison of a set of motifs compared to reference motifs. | 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... |
Return best match in database for motifs. | 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... |
List regions for the service | 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,
} |
Print nice looking table of information from list of load balancers | 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 instances | 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 images | 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... |
Run Fabric commands against EC2 instances | 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... |
AWS support script s main method | 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... |
Buffer data from an stream into one data object. | 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
... |
Reformat data as tuples. | 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
-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.