code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if recursive:
new_args = [_apply_rules(arg, rules) for arg in self.args]
new_kwargs = {
key: _apply_rules(val, rules)
for (key, val) in self.kwargs.items()}
else:
new_args = self.args
new_kwargs = self.kwargs
... | def apply_rules(self, rules, recursive=True) | Rebuild the expression while applying a list of rules
The rules are applied against the instantiated expression, and any
sub-expressions if `recursive` is True. Rule application is best though
of as a pattern-based substitution. This is different from the
*automatic* rules that :meth:`c... | 2.611584 | 2.519082 | 1.036721 |
return self.apply_rules([(pattern, replacement)], recursive=recursive) | def apply_rule(self, pattern, replacement, recursive=True) | Apply a single rules to the expression
This is equivalent to :meth:`apply_rules` with
``rules=[(pattern, replacement)]``
Args:
pattern (.Pattern): A pattern containing one or more wildcards
replacement (callable): A callable that takes the wildcard names in
... | 6.015392 | 11.887781 | 0.506015 |
if self._free_symbols is None:
res = set.union(
set([]), # dummy arg (union fails without arguments)
*[_free_symbols(val) for val in self.kwargs.values()])
res.update(
set([]), # dummy arg (update fails without arguments)
... | def free_symbols(self) | Set of free SymPy symbols contained within the expression. | 4.47054 | 4.444913 | 1.005765 |
if self._bound_symbols is None:
res = set.union(
set([]), # dummy arg (union fails without arguments)
*[_bound_symbols(val) for val in self.kwargs.values()])
res.update(
set([]), # dummy arg (update fails without arguments)
... | def bound_symbols(self) | Set of bound SymPy symbols in the expression | 4.59003 | 4.592187 | 0.99953 |
if self._all_symbols is None:
self._all_symbols = self.free_symbols | self.bound_symbols
return self._all_symbols | def all_symbols(self) | Combination of :attr:`free_symbols` and :attr:`bound_symbols` | 3.747707 | 1.988101 | 1.885068 |
u = urllib.FancyURLopener()
logger.info("Downloading %s..." % url)
u.retrieve(url, dest)
logger.info('Done, see %s' % dest)
return dest | def download(url, dest) | Platform-agnostic downloader. | 3.701386 | 3.798639 | 0.974398 |
required_programs = [
('samtools',
'http://samtools.sourceforge.net/'),
('bedtools',
'http://bedtools.readthedocs.org/en/latest/'),
('bigWigToBedGraph',
'http://hgdownload.cse.ucsc.edu/admin/exe/linux.x86_64/'),
('bedGraphToBigWig',
'http://hg... | def requirements_check() | Ensure we have programs needed to download/manipulate the data | 1.9767 | 1.91111 | 1.03432 |
if os.path.exists(fn):
if hashlib.md5(open(fn).read()).hexdigest() == md5:
logger.info('md5sum match for %s' % fn)
return True
else:
logger.info('wrong md5sum for %s' % fn)
os.unlink(fn) | def _up_to_date(md5, fn) | Make sure md5sum(fn) == md5, and if not, delete `fn`. | 2.275074 | 2.055933 | 1.106589 |
"helper function to log a command and then run it"
logger.info(' '.join(cmds))
os.system(' '.join(cmds)) | def logged_command(cmds) | helper function to log a command and then run it | 5.908011 | 3.939447 | 1.499706 |
"Download cufflinks GTF files"
for size, md5, url in cufflinks:
cuff_gtf = os.path.join(args.data_dir, os.path.basename(url))
if not _up_to_date(md5, cuff_gtf):
download(url, cuff_gtf) | def get_cufflinks() | Download cufflinks GTF files | 4.44371 | 3.721149 | 1.194177 |
for size, md5, url in bams:
bam = os.path.join(
args.data_dir,
os.path.basename(url).replace('.bam', '_%s.bam' % CHROM))
if not _up_to_date(md5, bam):
logger.info(
'Downloading reads on chromosome %s from %s to %s'
% (CHROM, ur... | def get_bams() | Download BAM files if needed, extract only chr17 reads, and regenerate .bai | 2.96841 | 2.827073 | 1.049994 |
size, md5, url = GTF
full_gtf = os.path.join(args.data_dir, os.path.basename(url))
subset_gtf = os.path.join(
args.data_dir,
os.path.basename(url).replace('.gtf.gz', '_%s.gtf' % CHROM))
if not _up_to_date(md5, subset_gtf):
download(url, full_gtf)
cmds = [
... | def get_gtf() | Download GTF file from Ensembl, only keeping the chr17 entries. | 4.023224 | 3.776949 | 1.065205 |
size, md5, fn = DB
if not _up_to_date(md5, fn):
gffutils.create_db(fn.replace('.db', ''), fn, verbose=True, force=True) | def make_db() | Create gffutils database | 11.701991 | 8.737357 | 1.339306 |
for size, md5, fn in cufflinks_tables:
fn = os.path.join(args.data_dir, fn)
table = fn.replace('.gtf.gz', '.table')
if not _up_to_date(md5, table):
logger.info("Converting Cufflinks GTF %s to table" % fn)
fout = open(table, 'w')
fout.write('id\tscore\... | def cufflinks_conversion() | convert Cufflinks output GTF files into tables of score and FPKM. | 3.446242 | 3.096786 | 1.112845 |
if isinstance(feature, gffutils.Feature):
feature = asinterval(feature)
self.make_fig()
axes = []
for ax, method in self.panels():
feature = method(ax, feature)
axes.append(ax)
return axes | def plot(self, feature) | Spawns a new figure showing data for `feature`.
:param feature: A `pybedtools.Interval` object
Using the pybedtools.Interval `feature`, creates figure specified in
:meth:`BaseMiniBrowser.make_fig` and plots data on panels according to
`self.panels()`. | 8.301921 | 5.686191 | 1.460014 |
self.fig = plt.figure(figsize=(8, 4))
self._all_figures.append(self.fig) | def make_fig(self) | Figure constructor, called before `self.plot()` | 4.829088 | 4.008147 | 1.204818 |
txt = '%s:%s-%s' % (feature.chrom, feature.start, feature.stop)
ax.text(0.5, 0.5, txt, transform=ax.transAxes)
return feature | def example_panel(self, ax, feature) | A example panel that just prints the text of the feature. | 3.500277 | 3.419786 | 1.023537 |
from gffutils.contrib.plotting import Gene
extent = [feature.start, feature.stop]
nearby_genes = self.db.region(
(feature.chrom, feature.start, feature.stop), featuretype='gene')
ybase = 0
ngenes = 0
for nearby_gene in nearby_genes:
# TODO... | def genes_panel(self, ax, feature) | Plots gene models on an Axes.
Queries the database
:param ax: matplotlib.Axes object
:param feature: pybedtools.Interval | 3.375893 | 3.400316 | 0.992817 |
for gs, kwargs in zip(self.genomic_signal_objs, self.plotting_kwargs):
x, y = gs.local_coverage(feature, **self.local_coverage_kwargs)
ax.plot(x, y, **kwargs)
ax.axis('tight')
return feature | def signal_panel(self, ax, feature) | Plots each genomic signal as a line using the corresponding
plotting_kwargs | 5.853065 | 4.740845 | 1.234604 |
ax1 = self.fig.add_subplot(211)
ax2 = self.fig.add_subplot(212, sharex=ax1)
return (ax2, self.gene_panel), (ax1, self.signal_panel) | def panels(self) | Add 2 panels to the figure, top for signal and bottom for gene models | 3.525321 | 2.57142 | 1.370963 |
from gffutils.contrib.plotting import Gene
extent = [feature.start, feature.stop]
nearby_genes = self.db.region(
(feature.chrom, feature.start, feature.stop), featuretype='gene')
ybase = 0
ngenes = 0
for nearby_gene in nearby_genes:
ngenes... | def gene_panel(self, ax, feature) | Plots gene models on an Axes.
Queries the database
:param ax: matplotlib.Axes object
:param feature: pybedtools.Interval | 3.937604 | 3.999465 | 0.984533 |
MAX_VALUE = 100
# Create our test progress bar
bar = Bar(max_value=MAX_VALUE, fallback=True)
bar.cursor.clear_lines(2)
# Before beginning to draw our bars, we save the position
# of our cursor so we can restore back to this position before writing
# the next time.
bar.cursor.... | def simple() | Simple example using just the Bar class
This example is intended to show usage of the Bar class at the lowest
level. | 7.730708 | 7.569713 | 1.021268 |
#############
# Test data #
#############
# For this example, we're obviously going to be feeding fictitious data
# to ProgressTree, so here it is
leaf_values = [Value(0) for i in range(6)]
bd_defaults = dict(type=Bar, kwargs=dict(max_value=10))
test_d = {
"Warp Jump": ... | def tree() | Example showing tree progress view | 6.46455 | 6.317099 | 1.023342 |
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
line_kwargs = line_kwargs or {}
fill_kwargs = fill_kwargs or {}
m, lo, hi = ci(arr, conf)
ax.plot(x, m, **line_kwargs)
ax.fill_between(x, lo, hi, **fill_kwargs)
return ax | def ci_plot(x, arr, conf=0.95, ax=None, line_kwargs=None, fill_kwargs=None) | Plots the mean and 95% ci for the given array on the given axes
Parameters
----------
x : 1-D array-like
x values for the plot
arr : 2-D array-like
The array to calculate mean and std for
conf : float [.5 - 1]
Confidence interval to use
ax : matplotlib.Axes
Th... | 1.796436 | 2.044242 | 0.878779 |
_text_kwargs = dict(transform=ax.get_yaxis_transform())
if text_kwargs:
_text_kwargs.update(text_kwargs)
_hline_kwargs = dict(color='k')
if hline_kwargs:
_hline_kwargs.update(hline_kwargs)
pos = 0
for label in subset_order:
ind = subset_by == label
last_pos... | def add_labels_to_subsets(ax, subset_by, subset_order, text_kwargs=None,
add_hlines=True, hline_kwargs=None) | Helper function for adding labels to subsets within a heatmap.
Assumes that imshow() was called with `subsets` and `subset_order`.
Parameters
----------
ax : matplotlib.Axes
The axes to label. Generally you can use `fig.array_axes` attribute of
the Figure object returned by `metaseq.p... | 2.388782 | 2.483881 | 0.961714 |
if percentiles is not None:
for percentile in percentiles:
if not 0 <= percentile <= 100:
raise ValueError("percentile (%s) not between [0, 100]")
if method == 'global':
all_arrays = np.concatenate(
[i.ravel() for i in array_dict.itervalues()]
... | def calculate_limits(array_dict, method='global', percentiles=None, limit=()) | Calculate limits for a group of arrays in a flexible manner.
Returns a dictionary of calculated (vmin, vmax), with the same keys as
`array_dict`.
Useful for plotting heatmaps of multiple datasets, and the vmin/vmax values
of the colormaps need to be matched across all (or a subset) of heatmaps.
P... | 1.969229 | 1.845207 | 1.067213 |
m = arr.mean(axis=0)
n = len(arr)
se = arr.std(axis=0) / np.sqrt(n)
h = se * stats.t._ppf((1 + conf) / 2., n - 1)
return m, m - h, m + h | def ci(arr, conf=0.95) | Column-wise confidence interval.
Parameters
----------
arr : array-like
conf : float
Confidence interval
Returns
-------
m : array
column-wise mean
lower : array
lower column-wise confidence bound
upper : array
upper column-wise confidence bound | 2.058969 | 2.335972 | 0.881418 |
neg = x < 0
xi = np.log2(np.abs(x) + 1)
xi[neg] = -xi[neg]
return xi | def nice_log(x) | Uses a log scale but with negative numbers.
:param x: NumPy array | 4.10496 | 4.864846 | 0.843801 |
weighted = a * a.mean(axis=0)
scores = weighted.sum(axis=1)
zscores = (scores - scores.mean()) / scores.std()
return zscores | def tip_zscores(a) | Calculates the "target identification from profiles" (TIP) zscores
from Cheng et al. 2001, Bioinformatics 27(23):3221-3227.
:param a: NumPy array, where each row is the signal for a feature. | 3.363268 | 4.528318 | 0.742719 |
zscores = tip_zscores(a)
pvals = stats.norm.pdf(zscores)
rejected, fdrs = fdrcorrection(pvals)
return fdrs | def tip_fdr(a, alpha=0.05) | Returns adjusted TIP p-values for a particular `alpha`.
(see :func:`tip_zscores` for more info)
:param a: NumPy array, where each row is the signal for a feature
:param alpha: False discovery rate | 6.441838 | 6.989923 | 0.921589 |
xi = np.log2(x)
yi = np.log2(y)
xv = np.isfinite(xi)
yv = np.isfinite(yi)
global_min = min(xi[xv].min(), yi[yv].min())
global_max = max(xi[xv].max(), yi[yv].max())
xi[~xv] = global_min
yi[~yv] = global_min
return xi, yi | def prepare_logged(x, y) | Transform `x` and `y` to a log scale while dealing with zeros.
This function scales `x` and `y` such that the points that are zero in one
array are set to the min of the other array.
When plotting expression data, frequently one sample will have reads in
a particular feature but the other sample will ... | 2.060154 | 2.191262 | 0.940168 |
fig = plt.figure(figsize=figsize)
# Constants to keep track
if strip:
STRIP_COLS = 1
else:
STRIP_COLS = 0
ROWS = 4
COLS = 8 + STRIP_COLS
MAT_COLS = 7
MAT_ROWS = 3
LINE_ROWS = ROWS - MAT_ROWS
mat_ax = plt.subplot2grid(
shape=(ROWS, COLS),
loc... | def matrix_and_line_shell(figsize=(5, 12), strip=False) | Helper function to construct an empty figure that has space for a matrix,
a summary line plot directly below it, a colorbar axis, and an optional
"strip" axis that parallels the matrix (and shares its y-axis) where data
can be added to create callbacks.
Returns a tuple of (fig, matrix_ax, line_ax, stri... | 1.991013 | 1.969488 | 1.010929 |
try:
from sklearn.cluster import MiniBatchKMeans
except ImportError:
raise ImportError('please install scikits.learn for '
'clustering.')
# If integer, do it once and we're done
if isinstance(k, int):
best_k = k
else:
mean_dists = {}
... | def clustered_sortind(x, k=10, scorefunc=None) | Uses MiniBatch k-means clustering to cluster matrix into groups.
Each cluster of rows is then sorted by `scorefunc` -- by default, the max
peak height when all rows in a cluster are averaged, or
cluster.mean(axis=0).max().
Returns the index that will sort the rows of `x` and a list of "breaks".
`b... | 2.610831 | 2.548724 | 1.024368 |
try:
from sklearn.cluster import MiniBatchKMeans
except ImportError:
raise ImportError('please install scikits.learn for '
'clustering.')
# If integer, do it once and we're done
if isinstance(k, int):
best_k = k
else:
mean_dists = {}
... | def new_clustered_sortind(x, k=10, row_key=None, cluster_key=None) | Uses MiniBatch k-means clustering to cluster matrix into groups.
Each cluster of rows is then sorted by `scorefunc` -- by default, the max
peak height when all rows in a cluster are averaged, or
cluster.mean(axis=0).max().
Returns the index that will sort the rows of `x` and a list of "breaks".
`b... | 3.197321 | 3.132421 | 1.020719 |
d = orig.copy()
if keys is None:
keys = update_with.keys()
for k in keys:
if k in update_with:
if k in d and not override:
continue
d[k] = update_with[k]
return d | def _updatecopy(orig, update_with, keys=None, override=False) | Update a copy of dest with source. If `keys` is a list, then only update
with those keys. | 1.807121 | 1.877423 | 0.962554 |
axs = []
if xhists:
axs.extend(self.hxs)
if yhists:
axs.extend(self.hys)
if scatter:
axs.extend(self.ax)
for ax in axs:
ax.legend(**kwargs) | def add_legends(self, xhists=True, yhists=False, scatter=True, **kwargs) | Add legends to axes. | 2.716989 | 2.488873 | 1.091654 |
try:
klass = _registry[kind.lower()]
except KeyError:
raise ValueError(
'No support for %s format, choices are %s'
% (kind, _registry.keys()))
m = klass(fn)
m.kind = kind
return m | def genomic_signal(fn, kind) | Factory function that makes the right class for the file format.
Typically you'll only need this function to create a new genomic signal
object.
:param fn: Filename
:param kind:
String. Format of the file; see
metaseq.genomic_signal._registry.keys() | 4.686814 | 3.895133 | 1.203249 |
if processes is not None:
arrays = _array_parallel(
self.fn, self.__class__, features, processes=processes,
chunksize=chunksize, **kwargs)
else:
arrays = _array(self.fn, self.__class__, features, **kwargs)
if not ragged:
... | def array(self, features, processes=None, chunksize=1, ragged=False,
**kwargs) | Creates an MxN NumPy array of genomic signal for the region defined by
each feature in `features`, where M=len(features) and N=(bins or
feature length)
Parameters
----------
features : iterable of interval-like objects
An iterable of interval-like objects; see docstr... | 2.939791 | 3.470142 | 0.847168 |
# This gets the underlying pysam Samfile object
f = self.adapter.fileobj
d = {}
for ref, length in zip(f.references, f.lengths):
d[ref] = (0, length)
return d | def genome(self) | "genome" dictionary ready for pybedtools, based on the BAM header. | 7.414705 | 6.670112 | 1.111631 |
# Already run?
if self._readcount and not force:
return self._readcount
if os.path.exists(self.fn + '.mmr') and not force:
for line in open(self.fn + '.mmr'):
if line.startswith('#'):
continue
self._readcount =... | def mapped_read_count(self, force=False) | Counts total reads in a BAM file.
If a file self.bam + '.scale' exists, then just read the first line of
that file that doesn't start with a "#". If such a file doesn't exist,
then it will be created with the number of reads as the first and only
line in the file.
The result i... | 2.574238 | 2.492249 | 1.032898 |
grand = sum(table)
# Separate table into components and get row/col sums
t11, t12, t21, t22 = table
# Row sums, col sums, and grand total
r1 = t11 + t12
r2 = t21 + t22
c1 = t11 + t21
c2 = t12 + t22
# Re-cast everything as the appropriate format
t11, t12, t21, t22, c1, c2,... | def print_2x2_table(table, row_labels, col_labels, fmt="%d") | Prints a table used for Fisher's exact test. Adds row, column, and grand
totals.
:param table: The four cells of a 2x2 table: [r1c1, r1c2, r2c1, r2c2]
:param row_labels: A length-2 list of row names
:param col_labels: A length-2 list of column names | 2.394768 | 2.458696 | 0.973999 |
r1c1, r1c2, r2c1, r2c2 = map(float, table)
row1 = r1c1 + r1c2
row2 = r2c1 + r2c2
blocks = [
(r1c1, row1),
(r1c2, row1),
(r2c1, row2),
(r2c2, row2)]
new_table = []
for cell, row in blocks:
try:
x = cell / row
except ZeroDivisionE... | def print_row_perc_table(table, row_labels, col_labels) | given a table, print the percentages rather than the totals | 2.685057 | 2.625206 | 1.022799 |
r1c1, r1c2, r2c1, r2c2 = map(float, table)
col1 = r1c1 + r2c1
col2 = r1c2 + r2c2
blocks = [
(r1c1, col1),
(r1c2, col2),
(r2c1, col1),
(r2c2, col2)]
new_table = []
for cell, row in blocks:
try:
x = cell / row
except ZeroDivision... | def print_col_perc_table(table, row_labels, col_labels) | given a table, print the cols as percentages | 2.720413 | 2.65795 | 1.023501 |
table = [
sum(subset & ind1 & ind2),
sum(subset & ind1 & ~ind2),
sum(subset & ~ind1 & ind2),
sum(subset & ~ind1 & ~ind2)
]
print
print title
print '-' * len(title)
print print_2x2_table(table, row_labels=row_labels, col_labels=col_labels)
print print_row_... | def table_maker(subset, ind1, ind2, row_labels, col_labels, title) | `subset` provides a subsetted boolean of items to consider. If no subset,
you can use all with `np.ones_like(ind1) == 1`
`ind1` is used to subset rows, e.g., log2fc > 0. This is used for rows, so
row_label might be ['upregulated', 'others']
`ind2` is used to subset cols. For example, col_labels wou... | 2.510391 | 2.734617 | 0.918005 |
if save_cursor:
self.cursor.save()
tree = deepcopy(tree)
# TODO: Automatically collapse hierarchy so something
# will always be displayable (well, unless the top-level)
# contains too many to display
lines_required = self.lines_required(tree)
... | def draw(self, tree, bar_desc=None, save_cursor=True, flush=True) | Draw ``tree`` to the terminal
:type tree: dict
:param tree: ``tree`` should be a tree representing a hierarchy; each
key should be a string describing that hierarchy level and value
should also be ``dict`` except for leaves which should be
``BarDescriptors``. See ``... | 8.084009 | 7.584376 | 1.065877 |
lines_req = self.lines_required(tree)
self.cursor.clear_lines(lines_req) | def make_room(self, tree) | Clear lines in terminal below current cursor position as required
This is important to do before drawing to ensure sufficient
room at the bottom of your terminal.
:type tree: dict
:param tree: tree as described in ``BarDescriptor`` | 13.308574 | 10.251195 | 1.298246 |
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
return sum(self.lines_required(v, count=count)
for v in tree.values()) + 2
elif isinstance(tree, BarDescriptor):
if tree.get("kwargs", {}).get("title_p... | def lines_required(self, tree, count=0) | Calculate number of lines required to draw ``tree`` | 4.977871 | 4.216009 | 1.180707 |
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
# Calculate value and max_value
max_val = 0
value = 0
for k in tree:
# Get descriptor by recursing
bar_desc = self._calculate_... | def _calculate_values(self, tree, bar_d) | Calculate values for drawing bars of non-leafs in ``tree``
Recurses through ``tree``, replaces ``dict``s with
``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use
the ``BarDescriptor``s to draw the tree | 4.532437 | 4.272228 | 1.060907 |
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
for k, v in sorted(tree.items()):
bar_desc, subdict = v[0], v[1]
args = [self.cursor.term] + bar_desc.get("args", [])
kwargs = dict(title_pos="ab... | def _draw(self, tree, indent=0) | Recurse through ``tree`` and draw all nodes | 5.341496 | 5.205362 | 1.026153 |
assert isinstance(dicts, list) and all(isinstance(d, dict) for d in dicts)
return dict(chain(*[copy.deepcopy(d).items() if deepcopy else d.items()
for d in dicts])) | def merge_dicts(dicts, deepcopy=False) | Merges dicts
In case of key conflicts, the value kept will be from the latter
dictionary in the list of dictionaries
:param dicts: [dict, ...]
:param deepcopy: deepcopy items within dicts | 2.718863 | 3.100376 | 0.876946 |
features = pybedtools.BedTool(prefix + '.features')
arrays = np.load(prefix + '.npz', mmap_mode=mmap_mode)
return features, arrays | def load_features_and_arrays(prefix, mmap_mode='r') | Returns the features and NumPy arrays that were saved with
save_features_and_arrays.
Parameters
----------
prefix : str
Path to where data are saved
mmap_mode : {None, 'r+', 'r', 'w+', 'c'}
Mode in which to memory-map the file. See np.load for details. | 3.300551 | 4.731552 | 0.697562 |
if link_features:
if isinstance(features, pybedtools.BedTool):
assert isinstance(features.fn, basestring)
features_filename = features.fn
else:
assert isinstance(features, basestring)
features_filename = features
if overwrite:
... | def save_features_and_arrays(features, arrays, prefix, compressed=False,
link_features=False, overwrite=False) | Saves NumPy arrays of processed data, along with the features that
correspond to each row, to files for later use.
Two files will be saved, both starting with `prefix`:
prefix.features : a file of features. If GFF features were provided,
this will be in GFF format, if BED features were provid... | 2.621991 | 2.32062 | 1.129866 |
devices = fritz.get_devices()
for device in devices:
print('#' * 30)
print('name=%s' % device.name)
print(' ain=%s' % device.ain)
print(' id=%s' % device.identifier)
print(' productname=%s' % device.productname)
print(' manufacturer=%s' % device.manufact... | def list_all(fritz, args) | Command that prints all device information. | 1.989846 | 1.989691 | 1.000078 |
stats = fritz.get_device_statistics(args.ain)
print(stats) | def device_statistics(fritz, args) | Command that prints the device statistics. | 4.566358 | 5.294729 | 0.862435 |
parser = argparse.ArgumentParser(
description='Fritz!Box Smarthome CLI tool.')
parser.add_argument('-v', action='store_true', dest='verbose',
help='be more verbose')
parser.add_argument('-f', '--fritzbox', type=str, dest='host',
help='Fritz!Box IP... | def main(args=None) | The main function. | 1.641831 | 1.63273 | 1.005574 |
f = iter(f)
x = []
while 1:
if len(x) < n:
try:
x.append(f.next())
except StopIteration:
if len(x) > 0:
yield tuple(x)
break
else:
yield tuple(x)
x = [] | def chunker(f, n) | Utility function to split iterable `f` into `n` chunks | 2.266164 | 2.178978 | 1.040012 |
fn = os.path.join(data_dir(), fn)
if not os.path.exists(fn):
raise ValueError("%s does not exist" % fn)
return fn | def example_filename(fn) | Return a bed file from the pybedtools examples directory. Use
:func:`list_example_files` to see a list of files that are included. | 2.474564 | 3.049702 | 0.811412 |
if not isinstance(n, int):
raise ValueError('n must be an integer')
orig_feature = copy(f)
step = (f.stop - f.start) / n
for i in range(f.start, f.stop, step):
f = copy(orig_feature)
start = i
stop = min(i + step, orig_feature.stop)
f.start = start
f.... | def split_feature(f, n) | Split an interval into `n` roughly equal portions | 2.496293 | 2.417053 | 1.032784 |
if isinstance(s, basestring):
m = coord_re.search(s)
if m.group('strand'):
return pybedtools.create_interval_from_list([
m.group('chrom'),
m.group('start'),
m.group('stop'),
'.',
'0',
m.g... | def tointerval(s) | If string, then convert to an interval; otherwise just return the input | 2.363665 | 2.306241 | 1.0249 |
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' or '%'")
if unit == "c":
ensure(value <= self.columns, ValueError,
"Terminal only has {} columns, cannot d... | def max_width(self) | Get maximum width of progress bar
:rtype: int
:returns: Maximum column width of progress bar | 4.715811 | 5.042142 | 0.935279 |
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start_char),
self.max_width, # Progress bar
len(self.end_char),
1, # Space betwee... | def full_line_width(self) | Find actual length of bar_str
e.g., Progress [ | ] 10/10 | 6.193728 | 5.096157 | 1.215372 |
for color in colors:
try:
if isinstance(color, str):
req_colors = 16 if "bright" in color else 8
ensure(term.number_of_colors >= req_colors,
ColorUnsupportedError,
"{} is unsupporte... | def _supports_colors(term, raise_err, colors) | Check if ``term`` supports ``colors``
:raises ColorUnsupportedError: This is raised if ``raise_err``
is ``False`` and a color in ``colors`` is unsupported by ``term``
:type raise_err: bool
:param raise_err: Set to ``False`` to return a ``bool`` indicating
color support r... | 3.04471 | 2.829831 | 1.075934 |
if isinstance(color, str):
ensure(
any(isinstance(back_color, t) for t in [str, type(None)]),
TypeError,
"back_color must be a str or NoneType"
)
if back_color:
return getattr(term, "_".join(
... | def _get_format_callable(term, color, back_color) | Get string-coloring callable
Get callable for string output using ``color`` on ``back_color``
on ``term``
:param term: blessings.Terminal instance
:param color: Color that callable will color the string it's passed
:param back_color: Back color for the string
:retur... | 3.478745 | 3.386831 | 1.027139 |
if not ignore_overflow:
s_length = len(s) if s_length is None else s_length
if err_msg is None:
err_msg = (
"Terminal has {} columns; attempted to write "
"a string {} of length {}.".format(
self.col... | def _write(self, s, s_length=None, flush=False, ignore_overflow=False,
err_msg=None) | Write ``s``
:type s: str|unicode
:param s: String to write
:param s_length: Custom length of ``s``
:param flush: Set this to flush the terminal stream after writing
:param ignore_overflow: Set this to ignore if s will exceed
the terminal's width
:param err_m... | 3.279802 | 3.060866 | 1.071528 |
# This is essentially winch-handling without having
# to do winch-handling; cleanly redrawing on winch is difficult
# and out of the intended scope of this class; we *can*
# however, adjust the next draw to be proper by re-measuring
# the terminal since the code ... | def draw(self, value, newline=True, flush=True) | Draw the progress bar
:type value: int
:param value: Progress value relative to ``self.max_value``
:type newline: bool
:param newline: If this is set, a newline will be written after drawing | 4.456317 | 4.511413 | 0.987787 |
if method is None:
method = 'summarize'
# We may be dividing by zero in some cases, which raises a warning in
# NumPy based on the IEEE 754 standard (see
# http://docs.scipy.org/doc/numpy/reference/generated/
# numpy.seterr.html)
#
# T... | def summarize(self, interval, bins=None, method='summarize',
function='mean', zero_inf=True, zero_nan=True) | Parameters
----------
interval : object
Object with chrom (str), start (int) and stop (int) attributes.
bins : int or None
Number of bins; if None, bins will be the length of the interval
method : summarize | ucsc_summarize | get_as_array
"summarize... | 2.725733 | 2.446742 | 1.114026 |
value = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
value.append(node.data)
return ''.join(value) | def get_text(nodelist) | Get the value from a text node. | 1.819893 | 1.725161 | 1.054912 |
rsp = self._session.get(url, params=params, timeout=timeout)
rsp.raise_for_status()
return rsp.text.strip() | def _request(self, url, params=None, timeout=10) | Send a request with parameters. | 2.885059 | 2.915548 | 0.989543 |
url = 'http://' + self._host + '/login_sid.lua'
params = {}
if username:
params['username'] = username
if secret:
params['response'] = secret
plain = self._request(url, params)
dom = xml.dom.minidom.parseString(plain)
sid = get_te... | def _login_request(self, username=None, secret=None) | Send a login request with paramerters. | 3.315875 | 3.230265 | 1.026503 |
_LOGGER.debug('logout')
url = 'http://' + self._host + '/login_sid.lua'
params = {
'security:command/logout': '1',
'sid': self._sid
}
self._request(url, params) | def _logout_request(self) | Send a logout request. | 7.154141 | 6.325424 | 1.131014 |
to_hash = (challenge + '-' + password).encode('UTF-16LE')
hashed = hashlib.md5(to_hash).hexdigest()
return '{0}-{1}'.format(challenge, hashed) | def _create_login_secret(challenge, password) | Create a login secret. | 3.521724 | 3.202604 | 1.099644 |
url = 'http://' + self._host + '/webservices/homeautoswitch.lua'
params = {
'switchcmd': cmd,
'sid': self._sid
}
if param:
params['param'] = param
if ain:
params['ain'] = ain
plain = self._request(url, params)
... | def _aha_request(self, cmd, ain=None, param=None, rf=str) | Send an AHA request. | 3.771642 | 3.674861 | 1.026336 |
try:
(sid, challenge) = self._login_request()
if sid == '0000000000000000':
secret = self._create_login_secret(challenge, self._password)
(sid2, challenge) = self._login_request(username=self._user,
... | def login(self) | Login and get a valid session ID. | 3.170273 | 2.984688 | 1.062179 |
plain = self._aha_request('getdevicelistinfos')
dom = xml.dom.minidom.parseString(plain)
_LOGGER.debug(dom)
return dom.getElementsByTagName("device") | def get_device_elements(self) | Get the DOM elements for the device list. | 9.842856 | 8.071904 | 1.219397 |
elements = self.get_device_elements()
for element in elements:
if element.getAttribute('identifier') == ain:
return element
return None | def get_device_element(self, ain) | Get the DOM element for the specified device. | 3.395174 | 2.956723 | 1.148289 |
devices = []
for element in self.get_device_elements():
device = FritzhomeDevice(self, node=element)
devices.append(device)
return devices | def get_devices(self) | Get the list of all known devices. | 4.994475 | 4.449293 | 1.122532 |
devices = self.get_devices()
for device in devices:
if device.ain == ain:
return device | def get_device_by_ain(self, ain) | Returns a device specified by the AIN. | 2.672435 | 2.354948 | 1.134817 |
param = 16 + ((float(temperature) - 8) * 2)
if param < min(range(16, 56)):
param = 253
elif param > max(range(16, 56)):
param = 254
self._aha_request('sethkrtsoll', ain=ain, param=int(param)) | def set_target_temperature(self, ain, temperature) | Set the thermostate target temperature. | 7.085337 | 7.199584 | 0.984131 |
node = self._fritz.get_device_element(self.ain)
self._update_from_node(node) | def update(self) | Update the device values. | 13.416434 | 9.933553 | 1.350618 |
self.update()
try:
return {
126.5: 'off',
127.0: 'on',
self.eco_temperature: 'eco',
self.comfort_temperature: 'comfort'
}[self.target_temperature]
except KeyError:
return 'manual' | def get_hkr_state(self) | Get the thermostate state. | 5.088747 | 4.740094 | 1.073554 |
try:
value = {
'off': 0,
'on': 100,
'eco': self.eco_temperature,
'comfort': self.comfort_temperature
}[state]
except KeyError:
return
self.set_target_temperature(value) | def set_hkr_state(self, state) | Set the state of the thermostat.
Possible values for state are: 'on', 'off', 'comfort', 'eco'. | 3.74997 | 3.190882 | 1.175214 |
should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != "True"
if should_write_s:
self._stream.write(s) | def write(self, s) | Writes ``s`` to the terminal output stream
Writes can be disabled by setting the environment variable
`PROGRESSIVE_NOWRITE` to `'True'` | 10.029104 | 4.737062 | 2.117157 |
self.write(self.term.save)
self._saved = True | def save(self) | Saves current cursor position, so that it can be restored later | 18.393562 | 13.728794 | 1.33978 |
self.write(self.term.move_down)
self.write(self.term.clear_bol) | def newline(self) | Effects a newline by moving the cursor down and clearing | 7.97287 | 6.278212 | 1.269927 |
# first go from white to color_high
orig_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
'test', ['#FFFFFF', color_high], N=2048)
# For example, say vmin=-3 and vmax=9. If vmin were positive, what would
# its color be?
vmin = float(vmin)
vmax = float(vmax)
mx = max... | def smart_colormap(vmin, vmax, color_high='#b11902', hue_low=0.6) | Creates a "smart" colormap that is centered on zero, and accounts for
asymmetrical vmin and vmax by matching saturation/value of high and low
colors.
It works by first creating a colormap from white to `color_high`. Setting
this color to the max(abs([vmin, vmax])), it then determines what the color
... | 3.14963 | 3.096077 | 1.017297 |
if a < 0.:
return cmap
cdict = copy.copy(cmap._segmentdata)
fn = lambda x: (x[0] ** a, x[1], x[2])
for key in ('red', 'green', 'blue'):
cdict[key] = map(fn, cdict[key])
cdict[key].sort()
assert (cdict[key][0] < 0 or cdict[key][-1] > 1), \
"Resulting indic... | def cmap_powerlaw_adjust(cmap, a) | Returns a new colormap based on the one given
but adjusted via power-law, `newcmap = oldcmap**a`.
:param cmap: colormap instance (e.g., cm.jet)
:param a: power | 3.031342 | 3.449455 | 0.878789 |
if not (0. < center_ratio) & (center_ratio < 1.):
return cmap
a = math.log(center_ratio) / math.log(0.5)
return cmap_powerlaw_adjust(cmap, a) | def cmap_center_adjust(cmap, center_ratio) | Returns a new colormap based on the one given
but adjusted so that the old center point higher
(>0.5) or lower (<0.5)
:param cmap: colormap instance (e.g., cm.jet)
:param center_ratio: | 4.089925 | 5.372629 | 0.761252 |
if not ((range[0] < center) and (center < range[1])):
return cmap
return cmap_center_adjust(
cmap,
abs(center - range[0]) / abs(range[1] - range[0])) | def cmap_center_point_adjust(cmap, range, center) | Converts center to a ratio between 0 and 1 of the
range given and calls cmap_center_adjust(). returns
a new adjusted colormap accordingly
:param cmap: colormap instance
:param range: Tuple of (min, max)
:param center: New cmap center | 3.74892 | 4.210064 | 0.890466 |
if db is not None:
if isinstance(db, basestring):
db = gffutils.FeatureDB(db)
if not isinstance(db, gffutils.FeatureDB):
raise ValueError(
"`db` must be a filename or a gffutils.FeatureDB")
self._kwargs['db'] = db
... | def attach_db(self, db) | Attach a gffutils.FeatureDB for access to features.
Useful if you want to attach a db after this instance has already been
created.
Parameters
----------
db : gffutils.FeatureDB | 3.213867 | 3.060151 | 1.050232 |
if not self.db:
raise ValueError("Please attach a gffutils.FeatureDB")
for i in self.data.index:
try:
yield gffutils.helpers.asinterval(self.db[i])
except gffutils.FeatureNotFoundError:
if ignore_unknown:
co... | def features(self, ignore_unknown=False) | Generator of features.
If a gffutils.FeatureDB is attached, returns a pybedtools.Interval for
every feature in the dataframe's index.
Parameters
----------
ignore_unknown : bool
If True, silently ignores features that are not found in the db. | 4.390605 | 2.848083 | 1.5416 |
names = [i[attribute] for i in x]
new = self.copy()
new.data = new.data.reindex(names)
return new | def reindex_to(self, x, attribute="Name") | Returns a copy that only has rows corresponding to feature names in x.
Parameters
----------
x : str or pybedtools.BedTool
BED, GFF, GTF, or VCF where the "Name" field (that is, the value
returned by feature['Name']) or any arbitrary attribute
attribute : str
... | 3.791894 | 6.490642 | 0.584209 |
return pybedtools.BedTool(self.features())\
.each(featurefuncs.five_prime, upstream, downstream)\
.saveas() | def five_prime(self, upstream=1, downstream=0) | Creates a BED/GFF file of the 5' end of each feature represented in the
table and returns the resulting pybedtools.BedTool object. Needs an
attached database.
Parameters
----------
upstream, downstream : int
Number of basepairs up and downstream to include | 8.614138 | 8.063087 | 1.068342 |
return self.__class__(self.data.reindex_like(other), **self._kwargs) | def align_with(self, other) | Align the dataframe's index with another. | 8.008922 | 5.572841 | 1.437135 |
if not self.db:
return self
ind = []
for i, gene_id in enumerate(self.data.index):
try:
self.db[gene_id]
ind.append(i)
except gffutils.FeatureNotFoundError:
pass
ind = np.array(ind)
retur... | def strip_unknown_features(self) | Remove features not found in the `gffutils.FeatureDB`. This will
typically include 'ambiguous', 'no_feature', etc, but can also be
useful if the database was created from a different one than was used
to create the table. | 3.765829 | 3.106214 | 1.212354 |
def _transform_func(x):
result = transform_func(x)
if isinstance(result, pybedtools.Interval):
result = [result]
for i in result:
if i:
yield result
intersect_kwargs = intersect_kwargs or {}
... | def genes_with_peak(self, peaks, transform_func=None, split=False,
intersect_kwargs=None, id_attribute='ID', *args,
**kwargs) | Returns a boolean index of genes that have a peak nearby.
Parameters
----------
peaks : string or pybedtools.BedTool
If string, then assume it's a filename to a BED/GFF/GTF file of
intervals; otherwise use the pybedtools.BedTool object directly.
transform_func :... | 3.066919 | 2.860927 | 1.072002 |
ind = self.data[self.pval_column] <= thresh
if idx:
return ind
return self[ind] | def changed(self, thresh=0.05, idx=True) | Changed features.
{threshdoc} | 7.315021 | 8.276198 | 0.883862 |
ind = (
(self.data[self.pval_column] > thresh)
| np.isnan(self.data[self.pval_column])
)
if idx:
return ind
return self[ind] | def unchanged(self, thresh=0.05, idx=True) | Changed features.
{threshdoc} | 3.723694 | 3.978678 | 0.935912 |
return self.upregulated(thresh=thresh, idx=idx) | def enriched(self, thresh=0.05, idx=True) | Enriched features.
{threshdoc} | 7.876655 | 11.600345 | 0.679002 |
ind = (
(self.data[self.pval_column] <= thresh)
& (self.data[self.lfc_column] > 0)
)
if idx:
return ind
return self[ind] | def upregulated(self, thresh=0.05, idx=True) | Upregulated features.
{threshdoc} | 3.829214 | 4.309879 | 0.888474 |
return self.downregulated(thresh=thresh, idx=idx) | def disenriched(self, thresh=0.05, idx=True) | Disenriched features.
{threshdoc} | 8.527742 | 11.835507 | 0.720522 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.