text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
⌀
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def properties_for_args(cls, arg_names='_arg_names'): """For a class with an attribute `arg_names` containing a list of names, add a property for every name in that list. It is assumed that there is an instance attribute ``self._<arg_name>``, which is returned by the `arg_name` property. The decorator also adds a class attribute :attr:`_has_properties_for_args` that may be used to ensure that a class is decorated. """
from qnet.algebra.core.scalar_algebra import Scalar scalar_args = False if hasattr(cls, '_scalar_args'): scalar_args = cls._scalar_args for arg_name in getattr(cls, arg_names): def get_arg(self, name): val = getattr(self, "_%s" % name) if scalar_args: assert isinstance(val, Scalar) return val prop = property(partial(get_arg, name=arg_name)) doc = "The `%s` argument" % arg_name if scalar_args: doc += ", as a :class:`.Scalar` instance." else: doc += "." prop.__doc__ = doc setattr(cls, arg_name, prop) cls._has_properties_for_args = True return cls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_category(self, slug): """ Get the category object """
try: return get_category_for_slug(slug) except ObjectDoesNotExist as e: raise Http404(str(e))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_unique_slug(self, cleaned_data): """ Test whether the slug is unique within a given time period. """
date_kwargs = {} error_msg = _("The slug is not unique") # The /year/month/slug/ URL determines when a slug can be unique. pubdate = cleaned_data['publication_date'] or now() if '{year}' in appsettings.FLUENT_BLOGS_ENTRY_LINK_STYLE: date_kwargs['year'] = pubdate.year error_msg = _("The slug is not unique within it's publication year.") if '{month}' in appsettings.FLUENT_BLOGS_ENTRY_LINK_STYLE: date_kwargs['month'] = pubdate.month error_msg = _("The slug is not unique within it's publication month.") if '{day}' in appsettings.FLUENT_BLOGS_ENTRY_LINK_STYLE: date_kwargs['day'] = pubdate.day error_msg = _("The slug is not unique within it's publication day.") date_range = get_date_range(**date_kwargs) # Base filters are configurable for translation support. dup_filters = self.get_unique_slug_filters(cleaned_data) if date_range: dup_filters['publication_date__range'] = date_range dup_qs = EntryModel.objects.filter(**dup_filters) if self.instance and self.instance.pk: dup_qs = dup_qs.exclude(pk=self.instance.pk) # Test whether the slug is unique in the current month # Note: doesn't take changes to FLUENT_BLOGS_ENTRY_LINK_STYLE into account. if dup_qs.exists(): raise ValidationError(error_msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_rules_no_recurse(expr, rules): """Non-recursively match expr again all rules"""
try: # `rules` is an OrderedDict key => (pattern, replacement) items = rules.items() except AttributeError: # `rules` is a list of (pattern, replacement) tuples items = enumerate(rules) for key, (pat, replacement) in items: matched = pat.match(expr) if matched: try: return replacement(**matched) except CannotSimplify: pass return expr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(cls, *args, **kwargs): """Instantiate while applying automatic simplifications Instead of directly instantiating `cls`, it is recommended to use :meth:`create`, which applies simplifications to the args and keyword arguments according to the :attr:`simplifications` class attribute, and returns an appropriate object (which may or may not be an instance of the original `cls`). Two simplifications of particular importance are :func:`.match_replace` and :func:`.match_replace_binary` which apply rule-based simplifications. The :func:`.temporary_rules` context manager may be used to allow temporary modification of the automatic simplifications that :meth:`create` uses, in particular the rules for :func:`.match_replace` and :func:`.match_replace_binary`. Inside the managed context, the :attr:`simplifications` class attribute may be modified and rules can be managed with :meth:`add_rule` and :meth:`del_rules`. """
global LEVEL if LOG: logger = logging.getLogger('QNET.create') logger.debug( "%s%s.create(*args, **kwargs); args = %s, kwargs = %s", (" " * LEVEL), cls.__name__, args, kwargs) LEVEL += 1 key = cls._get_instance_key(args, kwargs) try: if cls.instance_caching: instance = cls._instances[key] if LOG: LEVEL -= 1 logger.debug("%s(cached)-> %s", (" " * LEVEL), instance) return instance except KeyError: pass for i, simplification in enumerate(cls.simplifications): if LOG: try: simpl_name = simplification.__name__ except AttributeError: simpl_name = "simpl%d" % i simplified = simplification(cls, args, kwargs) try: args, kwargs = simplified if LOG: logger.debug( "%s(%s)-> args = %s, kwargs = %s", (" " * LEVEL), simpl_name, args, kwargs) except (TypeError, ValueError): # We assume that if the simplification didn't return a tuple, # the result is a fully instantiated object if cls.instance_caching: cls._instances[key] = simplified if cls._create_idempotent and cls.instance_caching: try: key2 = simplified._instance_key if key2 != key: cls._instances[key2] = simplified # simplified key except AttributeError: # simplified might e.g. be a scalar and not have # _instance_key pass if LOG: LEVEL -= 1 logger.debug( "%s(%s)-> %s", (" " * LEVEL), simpl_name, simplified) return simplified if len(kwargs) > 0: cls._has_kwargs = True instance = cls(*args, **kwargs) if cls.instance_caching: cls._instances[key] = instance if cls._create_idempotent and cls.instance_caching: key2 = cls._get_instance_key(args, kwargs) if key2 != key: cls._instances[key2] = instance # instantiated key if LOG: LEVEL -= 1 logger.debug("%s -> %s", (" " * LEVEL), instance) return instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kwargs(self): """The dictionary of keyword-only arguments for the instantiation of the Expression"""
# Subclasses must override this property if and only if they define # keyword-only arguments in their __init__ method if hasattr(self, '_has_kwargs') and self._has_kwargs: raise NotImplementedError( "Class %s does not provide a kwargs property" % str(self.__class__.__name__)) return {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def substitute(self, var_map): """Substitute sub-expressions Args: var_map (dict): Dictionary with entries of the form ``{expr: substitution}`` """
if self in var_map: return var_map[self] return self._substitute(var_map)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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:`create` uses (see :meth:`add_rule`), which are applied *before* expressions are instantiated. Args: rules (list or ~collections.OrderedDict): List of rules or dictionary mapping names to rules, where each rule is a tuple (:class:`Pattern`, replacement callable), cf. :meth:`apply_rule` recursive (bool): If true (default), apply rules to all arguments and keyword arguments of the expression. Otherwise, only the expression itself will be re-instantiated. If `rules` is a dictionary, the keys (rules names) are used only for debug logging, to allow an analysis of which rules lead to the final form of an expression. """
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 simplified = self.create(*new_args, **new_kwargs) return _apply_rules_no_recurse(simplified, rules)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 `pattern` as keyword arguments, and returns a replacement for any expression that `pattern` matches. Example: Consider the following Heisenberg Hamiltonian:: '- (∑_{i,j ∈ ℌₛ} J_ij σ̂_i^(s) σ̂_j^(s))' We can transform this into a classical Hamiltonian by replacing the operators with scalars:: '- (∑_{i,j ∈ ℌₛ} J_ij σ_i σ_j)' """
return self.apply_rules([(pattern, replacement)], recursive=recursive)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bound_symbols(self): """Set of bound SymPy symbols in the expression"""
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) *[_bound_symbols(arg) for arg in self.args]) self._bound_symbols = res return self._bound_symbols
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(url, dest): """ Platform-agnostic downloader. """
u = urllib.FancyURLopener() logger.info("Downloading %s..." % url) u.retrieve(url, dest) logger.info('Done, see %s' % dest) return dest
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def logged_command(cmds): "helper function to log a command and then run it" logger.info(' '.join(cmds)) os.system(' '.join(cmds))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_cufflinks(): "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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_bams(): """ Download BAM files if needed, extract only chr17 reads, and regenerate .bai """
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, url, bam)) cmds = ['samtools', 'view', '-b', url, COORD, '>', bam] logged_command(cmds) bai = bam + '.bai' if not os.path.exists(bai): logger.info('indexing %s' % bam) logger.info(' '.join(cmds)) cmds = [ 'samtools', 'index', bam] logged_command(cmds) if os.path.exists(os.path.basename(url) + '.bai'): os.unlink(os.path.basename(url) + '.bai') for size, md5, fn in bais: if not _up_to_date(md5, fn): cmds = [ 'samtools', 'index', bai.replace('.bai', '')] logged_command(cmds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_gtf(): """ Download GTF file from Ensembl, only keeping the chr17 entries. """
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 = [ 'zcat', '<', full_gtf, '|', 'awk -F "\\t" \'{if ($1 == "%s") print $0}\'' % CHROM.replace('chr', ''), '|', 'awk \'{print "chr"$0}\'', '>', subset_gtf] logged_command(cmds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_db(): """ Create gffutils database """
size, md5, fn = DB if not _up_to_date(md5, fn): gffutils.create_db(fn.replace('.db', ''), fn, verbose=True, force=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cufflinks_conversion(): """ convert Cufflinks output GTF files into tables of score and FPKM. """
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\tfpkm\n') x = pybedtools.BedTool(fn) seen = set() for i in x: accession = i['transcript_id'].split('.')[0] if accession not in seen: seen.update([accession]) fout.write( '\t'.join([accession, i.score, i['FPKM']]) + '\n') fout.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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()`. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example_panel(self, ax, feature): """ A example panel that just prints the text of the feature. """
txt = '%s:%s-%s' % (feature.chrom, feature.start, feature.stop) ax.text(0.5, 0.5, txt, transform=ax.transAxes) return feature
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signal_panel(self, ax, feature): """ Plots each genomic signal as a line using the corresponding plotting_kwargs """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def panels(self): """ Add 2 panels to the figure, top for signal and bottom for gene models """
ax1 = self.fig.add_subplot(211) ax2 = self.fig.add_subplot(212, sharex=ax1) return (ax2, self.gene_panel), (ax1, self.signal_panel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple(): """Simple example using just the Bar class This example is intended to show usage of the Bar class at the lowest level. """
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.save() for i in range(MAX_VALUE + 1): sleep(0.1 * random.random()) # We restore the cursor to saved position before writing bar.cursor.restore() # Now we draw the bar bar.draw(value=i)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tree(): """Example showing tree progress view"""
############# # 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": { "1) Prepare fuel": { "Load Tanks": { "Tank 1": BarDescriptor(value=leaf_values[0], **bd_defaults), "Tank 2": BarDescriptor(value=leaf_values[1], **bd_defaults), }, "Refine tylium ore": BarDescriptor( value=leaf_values[2], **bd_defaults ), }, "2) Calculate jump co-ordinates": { "Resolve common name to co-ordinates": { "Querying resolution from baseship": BarDescriptor( value=leaf_values[3], **bd_defaults ), }, }, "3) Perform jump": { "Check FTL drive readiness": BarDescriptor( value=leaf_values[4], **bd_defaults ), "Juuuuuump!": BarDescriptor(value=leaf_values[5], **bd_defaults) } } } # We'll use this function to bump up the leaf values def incr_value(obj): for val in leaf_values: if val.value < 10: val.value += 1 break # And this to check if we're to stop drawing def are_we_done(obj): return all(val.value == 10 for val in leaf_values) ################### # The actual code # ################### # Create blessings.Terminal instance t = Terminal() # Initialize a ProgressTree instance n = ProgressTree(term=t) # We'll use the make_room method to make sure the terminal # is filled out with all the room we need n.make_room(test_d) while not are_we_done(test_d): sleep(0.2 * random.random()) # After the cursor position is first saved (in the first draw call) # this will restore the cursor back to the top so we can draw again n.cursor.restore() # We use our incr_value method to bump the fake numbers incr_value(test_d) # Actually draw out the bars n.draw(test_d, BarDescriptor(bd_defaults))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 The axes object on which to plot line_kwargs : dict Additional kwargs passed to Axes.plot fill_kwargs : dict Additiona kwargs passed to Axes.fill_between """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.plotutils.imshow`. subset_by, subset_order : array, list See `metaseq.plotutils.imshow()` docstring; these should be the same `subsets` and `subset_order` that were provided to that function. """
_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 = pos pos += sum(ind) if add_hlines: ax.axhline(pos, **_hline_kwargs) ax.text( 1.1, last_pos + (pos - last_pos)/2.0, label, **_text_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. Parameters array_dict : dict of np.arrays method : {'global', 'independent', callable} If method="global", then use the global min/max values across all arrays in array_dict. If method="independent", then each array will have its own min/max calcuated. If a callable, then it will be used to group the keys of `array_dict`, and each group will have its own group-wise min/max calculated. percentiles : None or list If not None, a list of (lower, upper) percentiles in the range [0,100]. """
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()] ) if percentiles: vmin = mlab.prctile( all_arrays, percentiles[0]) vmax = mlab.prctile( all_arrays, percentiles[1]) else: vmin = all_arrays.min() vmax = all_arrays.max() d = dict([(i, (vmin, vmax)) for i in array_dict.keys()]) elif method == 'independent': d = {} for k, v in array_dict.iteritems(): d[k] = (v.min(), v.max()) elif hasattr(method, '__call__'): d = {} sorted_keys = sorted(array_dict.keys(), key=method) for group, keys in itertools.groupby(sorted_keys, method): keys = list(keys) all_arrays = np.concatenate([array_dict[i] for i in keys]) if percentiles: vmin = mlab.prctile( all_arrays, percentiles[0]) vmax = mlab.prctile( all_arrays, percentiles[1]) else: vmin = all_arrays.min() vmax = all_arrays.max() for key in keys: d[key] = (vmin, vmax) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nice_log(x): """ Uses a log scale but with negative numbers. :param x: NumPy array """
neg = x < 0 xi = np.log2(np.abs(x) + 1) xi[neg] = -xi[neg] return xi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
zscores = tip_zscores(a) pvals = stats.norm.pdf(zscores) rejected, fdrs = fdrcorrection(pvals) return fdrs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 not. Expression data also tends to look better on a log scale, but log(0) is undefined and therefore cannot be shown on a plot. This function allows these points to be shown, piled up along one side of the plot. :param x,y: NumPy arrays """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, x, y, scatter_kwargs, hist_kwargs=None, xhist_kwargs=None, yhist_kwargs=None, num_ticks=3, labels=None, hist_share=False, marginal_histograms=True): """ Adds a new scatter to self.scatter_ax as well as marginal histograms for the same data, borrowing addtional room from the axes. Parameters x, y : array-like Data to be plotted scatter_kwargs : dict Keyword arguments that are passed directly to scatter(). hist_kwargs : dict Keyword arguments that are passed directly to hist(), for both the top and side histograms. xhist_kwargs, yhist_kwargs : dict Additional, margin-specific kwargs for the x or y histograms respectively. These are used to update `hist_kwargs` num_ticks : int How many tick marks to use in each histogram's y-axis labels : array-like Optional NumPy array of labels that will be set on the collection so that they can be accessed by a callback function. hist_share : bool If True, then all histograms will share the same frequency axes. Useful for showing relative heights if you don't want to use the hist_kwarg `normed=True` marginal_histograms : bool Set to False in order to disable marginal histograms and just use as a normal scatterplot. """
scatter_kwargs = scatter_kwargs or {} hist_kwargs = hist_kwargs or {} xhist_kwargs = xhist_kwargs or {} yhist_kwargs = yhist_kwargs or {} yhist_kwargs.update(dict(orientation='horizontal')) # Plot the scatter coll = self.scatter_ax.scatter(x, y, **scatter_kwargs) coll.labels = labels if not marginal_histograms: return xhk = _updatecopy(hist_kwargs, xhist_kwargs) yhk = _updatecopy(hist_kwargs, yhist_kwargs) axhistx = self.divider.append_axes( 'top', size=self.hist_size, pad=self.pad, sharex=self.scatter_ax, sharey=self.xfirst_ax) axhisty = self.divider.append_axes( 'right', size=self.hist_size, pad=self.pad, sharey=self.scatter_ax, sharex=self.yfirst_ax) axhistx.yaxis.set_major_locator( MaxNLocator(nbins=num_ticks, prune='both')) axhisty.xaxis.set_major_locator( MaxNLocator(nbins=num_ticks, prune='both')) if not self.xfirst_ax and hist_share: self.xfirst_ax = axhistx if not self.yfirst_ax and hist_share: self.yfirst_ax = axhisty # Keep track of which axes are which, because looking into fig.axes # list will get awkward.... self.top_hists.append(axhistx) self.right_hists.append(axhisty) # Scatter will deal with NaN, but hist will not. So clean the data # here. hx = _clean(x) hy = _clean(y) self.hxs.append(hx) self.hys.append(hy) # Only plot hists if there's valid data if len(hx) > 0: if len(hx) == 1: _xhk = _updatecopy(orig=xhk, update_with=dict(bins=[hx[0], hx[0]]), keys=['bins']) axhistx.hist(hx, **_xhk) else: axhistx.hist(hx, **xhk) if len(hy) > 0: if len(hy) == 1: _yhk = _updatecopy(orig=yhk, update_with=dict(bins=[hy[0], hy[0]]), keys=['bins']) axhisty.hist(hy, **_yhk) else: axhisty.hist(hy, **yhk) # Turn off unnecessary labels -- for these, use the scatter's axes # labels for txt in axhisty.get_yticklabels() + axhistx.get_xticklabels(): txt.set_visible(False) for txt in axhisty.get_xticklabels(): txt.set_rotation(-90)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_legends(self, xhists=True, yhists=False, scatter=True, **kwargs): """ Add legends to axes. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genome(self): """ "genome" dictionary ready for pybedtools, based on the BAM header. """
# 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 is also stored in self._readcount so that the time-consuming part only runs once; use force=True to force re-count. Parameters force : bool If True, then force a re-count; otherwise use cached data if available. """
# 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 = float(line.strip()) return self._readcount cmds = ['samtools', 'view', '-c', '-F', '0x4', self.fn] p = subprocess.Popen( cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if stderr: sys.stderr.write('samtools says: %s' % stderr) return None mapped_reads = int(stdout) # write to file so the next time you need the lib size you can access # it quickly if not os.path.exists(self.fn + '.mmr'): fout = open(self.fn + '.mmr', 'w') fout.write(str(mapped_reads) + '\n') fout.close() self._readcount = mapped_reads return self._readcount
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
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, r1, r2, grand = [ fmt % i for i in [t11, t12, t21, t22, c1, c2, r1, r2, grand]] # Construct rows and columns the long way... rows = [ [""] + col_labels + ['total'], [row_labels[0], t11, t12, r1], [row_labels[1], t21, t22, r2], ['total', c1, c2, grand], ] cols = [ [row[0] for row in rows], [col_labels[0], t11, t21, c1], [col_labels[1], t12, t22, c2], ['total', r1, r2, grand], ] # Get max column width for each column; need this for nice justification widths = [] for col in cols: widths.append(max(len(i) for i in col)) # ReST-formatted header sep = ['=' * i for i in widths] # Construct the table one row at a time with nice justification s = [] s.append(' '.join(sep)) s.append(' '.join(i.ljust(j) for i, j in zip(rows[0], widths))) s.append(' '.join(sep)) for row in rows[1:]: s.append(' '.join(i.ljust(j) for i, j in zip(row, widths))) s.append(' '.join(sep) + '\n') return "\n".join(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_row_perc_table(table, row_labels, col_labels): """ given a table, print the percentages rather than the totals """
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 ZeroDivisionError: x = 0 new_table.append(x) s = print_2x2_table(new_table, row_labels, col_labels, fmt="%.2f") s = s.splitlines(True) del s[5] return ''.join(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_col_perc_table(table, row_labels, col_labels): """ given a table, print the cols as percentages """
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 ZeroDivisionError: x = 0 new_table.append(x) s = print_2x2_table(new_table, row_labels, col_labels, fmt="%.2f") s = s.splitlines(False) last_space = s[0].rindex(" ") new_s = [i[:last_space] for i in s] return '\n'.join(new_s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ``BarDescriptor`` for a tree example. :type bar_desc: BarDescriptor|NoneType :param bar_desc: For describing non-leaf bars in that will be drawn from ``tree``; certain attributes such as ``value`` and ``kwargs["max_value"]`` will of course be overridden if provided. :type flush: bool :param flush: If this is set, output written will be flushed :type save_cursor: bool :param save_cursor: If this is set, cursor location will be saved before drawing; this will OVERWRITE a previous save, so be sure to set this accordingly (to your needs). """
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) ensure(lines_required <= self.cursor.term.height, LengthOverflowError, "Terminal is not long ({} rows) enough to fit all bars " "({} rows).".format(self.cursor.term.height, lines_required)) bar_desc = BarDescriptor(type=Bar) if not bar_desc else bar_desc self._calculate_values(tree, bar_desc) self._draw(tree) if flush: self.cursor.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_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`` """
lines_req = self.lines_required(tree) self.cursor.clear_lines(lines_req)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lines_required(self, tree, count=0): """Calculate number of lines required to draw ``tree``"""
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_pos") in ["left", "right"]: return 1 else: return 2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
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_values(tree[k], bar_d) # Reassign to tuple of (new descriptor, tree below) tree[k] = (bar_desc, tree[k]) value += bar_desc["value"].value max_val += bar_desc.get("kwargs", {}).get("max_value", 100) # Merge in values from ``bar_d`` before returning descriptor kwargs = merge_dicts( [bar_d.get("kwargs", {}), dict(max_value=max_val)], deepcopy=True ) ret_d = merge_dicts( [bar_d, dict(value=Value(floor(value)), kwargs=kwargs)], deepcopy=True ) return BarDescriptor(ret_d) elif isinstance(tree, BarDescriptor): return tree else: raise TypeError("Unexpected type {}".format(type(tree)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _draw(self, tree, indent=0): """Recurse through ``tree`` and draw all nodes"""
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="above", indent=indent, title=k) kwargs.update(bar_desc.get("kwargs", {})) b = Bar(*args, **kwargs) b.draw(value=bar_desc["value"].value, flush=False) self._draw(subdict, indent=indent + self.indent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
features = pybedtools.BedTool(prefix + '.features') arrays = np.load(prefix + '.npz', mmap_mode=mmap_mode) return features, arrays
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 provided it will be in BED format, and so on. prefix.npz : A NumPy .npz file. Parameters arrays : dict of NumPy arrays Rows in each array should correspond to `features`. This dictionary is passed to np.savez features : iterable of Feature-like objects This is usually the same features that were used to create the array in the first place. link_features : bool If True, then assume that `features` is either a pybedtools.BedTool pointing to a file, or a filename. In this case, instead of making a copy, a symlink will be created to the original features. This helps save disk space. prefix : str Path to where data will be saved. compressed : bool If True, saves arrays using np.savez_compressed rather than np.savez. This will save disk space, but will be slower when accessing the data later. """
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: force_flag = '-f' else: force_flag = '' cmds = [ 'ln', '-s', force_flag, os.path.abspath(features_filename), prefix + '.features'] os.system(' '.join(cmds)) else: pybedtools.BedTool(features).saveas(prefix + '.features') if compressed: np.savez_compressed( prefix, **arrays) else: np.savez(prefix, **arrays)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_all(fritz, args): """Command that prints all device information."""
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.manufacturer) print(" present=%s" % device.present) print(" lock=%s" % device.lock) print(" devicelock=%s" % device.device_lock) if device.present is False: continue if device.has_switch: print(" Switch:") print(" switch_state=%s" % device.switch_state) if device.has_switch: print(" Powermeter:") print(" power=%s" % device.power) print(" energy=%s" % device.energy) print(" voltage=%s" % device.voltage) if device.has_temperature_sensor: print(" Temperature:") print(" temperature=%s" % device.temperature) print(" offset=%s" % device.offset) if device.has_thermostat: print(" Thermostat:") print(" battery_low=%s" % device.battery_low) print(" battery_level=%s" % device.battery_level) print(" actual=%s" % device.actual_temperature) print(" target=%s" % device.target_temperature) print(" comfort=%s" % device.comfort_temperature) print(" eco=%s" % device.eco_temperature) print(" window=%s" % device.window_open) print(" summer=%s" % device.summer_active) print(" holiday=%s" % device.holiday_active) if device.has_alarm: print(" Alert:") print(" alert=%s" % device.alert_state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def device_statistics(fritz, args): """Command that prints the device statistics."""
stats = fritz.get_device_statistics(args.ain) print(stats)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunker(f, n): """ Utility function to split iterable `f` into `n` chunks """
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 = []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_feature(f, n): """ Split an interval into `n` roughly equal portions """
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.stop = stop yield f if stop == orig_feature.stop: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tointerval(s): """ If string, then convert to an interval; otherwise just return the input """
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.group('strand')]) else: return pybedtools.create_interval_from_list([ m.group('chrom'), m.group('start'), m.group('stop'), ]) return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_width(self): """Get maximum width of progress bar :rtype: int :returns: Maximum column width of progress bar """
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 draw " "bar of size {}.".format(self.columns, value)) retval = value else: # unit == "%" ensure(0 < value <= 100, ValueError, "value=={} does not satisfy 0 < value <= 100".format(value)) dec = value / 100 retval = dec * self.columns return floor(retval)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_line_width(self): """Find actual length of bar_str e.g., Progress [ | ] 10/10 """
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 between end_char and amount_complete_str len(str(self.max_value)) * 2 + 1 # 100/100 ]) return bar_str_len
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 rather than raising ColorUnsupportedError """
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 unsupported by your terminal.".format(color)) elif isinstance(color, int): ensure(term.number_of_colors >= color, ColorUnsupportedError, "{} is unsupported by your terminal.".format(color)) except ColorUnsupportedError as e: if raise_err: raise e else: return False else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 :returns: callable(s: str) -> str """
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( [color, "on", back_color] )) elif back_color is None: return getattr(term, color) elif isinstance(color, int): return term.on_color(color) else: raise TypeError("Invalid type {} for color".format( type(color) ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
# 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 is mostly written dynamically # and many attributes and dynamically calculated properties. self._measure_terminal() # To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0 amount_complete = 1.0 if self.max_value == 0 else value / self.max_value fill_amount = int(floor(amount_complete * self.max_width)) empty_amount = self.max_width - fill_amount # e.g., '10/20' if 'fraction' or '50%' if 'percentage' amount_complete_str = ( u"{}/{}".format(value, self.max_value) if self._num_rep == "fraction" else u"{}%".format(int(floor(amount_complete * 100))) ) # Write title if supposed to be above if self._title_pos == "above": title_str = u"{}{}\n".format( " " * self._indent, self.title, ) self._write(title_str, ignore_overflow=True) # Construct just the progress bar bar_str = u''.join([ u(self.filled(self._filled_char * fill_amount)), u(self.empty(self._empty_char * empty_amount)), ]) # Wrap with start and end character bar_str = u"{}{}{}".format(self.start_char, bar_str, self.end_char) # Add on title if supposed to be on left or right if self._title_pos == "left": bar_str = u"{} {}".format(self.title, bar_str) elif self._title_pos == "right": bar_str = u"{} {}".format(bar_str, self.title) # Add indent bar_str = u''.join([" " * self._indent, bar_str]) # Add complete percentage or fraction bar_str = u"{} {}".format(bar_str, amount_complete_str) # Set back to normal after printing bar_str = u"{}{}".format(bar_str, self.term.normal) # Finally, write the completed bar_str self._write(bar_str, s_length=self.full_line_width) # Write title if supposed to be below if self._title_pos == "below": title_str = u"\n{}{}".format( " " * self._indent, self.title, ) self._write(title_str, ignore_overflow=True) # Newline to wrap up if newline: self.cursor.newline() if flush: self.cursor.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_text(nodelist): """Get the value from a text node."""
value = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: value.append(node.data) return ''.join(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _request(self, url, params=None, timeout=10): """Send a request with parameters."""
rsp = self._session.get(url, params=params, timeout=timeout) rsp.raise_for_status() return rsp.text.strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _login_request(self, username=None, secret=None): """Send a login request with paramerters."""
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_text(dom.getElementsByTagName('SID')[0].childNodes) challenge = get_text( dom.getElementsByTagName('Challenge')[0].childNodes) return (sid, challenge)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _logout_request(self): """Send a logout request."""
_LOGGER.debug('logout') url = 'http://' + self._host + '/login_sid.lua' params = { 'security:command/logout': '1', 'sid': self._sid } self._request(url, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_login_secret(challenge, password): """Create a login secret."""
to_hash = (challenge + '-' + password).encode('UTF-16LE') hashed = hashlib.md5(to_hash).hexdigest() return '{0}-{1}'.format(challenge, hashed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _aha_request(self, cmd, ain=None, param=None, rf=str): """Send an AHA request."""
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) if plain == 'inval': raise InvalidError if rf == bool: return bool(int(plain)) return rf(plain)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login(self): """Login and get a valid session ID."""
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, secret=secret) if sid2 == '0000000000000000': _LOGGER.warning("login failed %s", sid2) raise LoginError(self._user) self._sid = sid2 except xml.parsers.expat.ExpatError: raise LoginError(self._user)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_device_elements(self): """Get the DOM elements for the device list."""
plain = self._aha_request('getdevicelistinfos') dom = xml.dom.minidom.parseString(plain) _LOGGER.debug(dom) return dom.getElementsByTagName("device")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_device_element(self, ain): """Get the DOM element for the specified device."""
elements = self.get_device_elements() for element in elements: if element.getAttribute('identifier') == ain: return element return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_devices(self): """Get the list of all known devices."""
devices = [] for element in self.get_device_elements(): device = FritzhomeDevice(self, node=element) devices.append(device) return devices
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_device_by_ain(self, ain): """Returns a device specified by the AIN."""
devices = self.get_devices() for device in devices: if device.ain == ain: return device
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_target_temperature(self, ain, temperature): """Set the thermostate target temperature."""
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """Update the device values."""
node = self._fritz.get_device_element(self.ain) self._update_from_node(node)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_hkr_state(self): """Get the thermostate state."""
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'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_hkr_state(self, state): """Set the state of the thermostat. Possible values for state are: 'on', 'off', 'comfort', 'eco'. """
try: value = { 'off': 0, 'on': 100, 'eco': self.eco_temperature, 'comfort': self.comfort_temperature }[state] except KeyError: return self.set_target_temperature(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, s): """Writes ``s`` to the terminal output stream Writes can be disabled by setting the environment variable `PROGRESSIVE_NOWRITE` to `'True'` """
should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != "True" if should_write_s: self._stream.write(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self): """Saves current cursor position, so that it can be restored later"""
self.write(self.term.save) self._saved = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newline(self): """Effects a newline by moving the cursor down and clearing"""
self.write(self.term.move_down) self.write(self.term.clear_bol)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
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 self.db = db
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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: continue else: raise gffutils.FeatureNotFoundError('%s not found' % i)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 Attribute containing the name of the feature to use as the index. """
names = [i[attribute] for i in x] new = self.copy() new.data = new.data.reindex(names) return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def align_with(self, other): """ Align the dataframe's index with another. """
return self.__class__(self.data.reindex_like(other), **self._kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def radviz(self, column_names, transforms=dict(), **kwargs): """ Radviz plot. Useful for exploratory visualization, a radviz plot can show multivariate data in 2D. Conceptually, the variables (here, specified in `column_names`) are distributed evenly around the unit circle. Then each point (here, each row in the dataframe) is attached to each variable by a spring, where the stiffness of the spring is proportional to the value of corresponding variable. The final position of a point represents the equilibrium position with all springs pulling on it. In practice, each variable is normalized to 0-1 (by subtracting the mean and dividing by the range). This is a very exploratory plot. The order of `column_names` will affect the results, so it's best to try a couple different orderings. For other caveats, see [1]. Additional kwargs are passed to self.scatter, so subsetting, callbacks, and other configuration can be performed using options for that method (e.g., `genes_to_highlight` is particularly useful). Parameters column_names : list Which columns of the dataframe to consider. The columns provided should only include numeric data, and they should not contain any NaN, inf, or -inf values. transforms : dict Dictionary mapping column names to transformations that will be applied just for the radviz plot. For example, np.log1p is a useful function. If a column name is not in this dictionary, it will be used as-is. ax : matplotlib.Axes If not None, then plot the radviz on this axes. If None, then a new figure will be created. kwargs : dict Additional arguments are passed to self.scatter. Note that not all possible kwargs for self.scatter are necessarily useful for a radviz plot (for example, margninal histograms would not be meaningful). Notes ----- This method adds two new variables to self.data: "radviz_x" and "radviz_y". It then calls the self.scatter method, using these new variables. The data transformation was adapted from the pandas.tools.plotting.radviz function. References [1] Hoffman,P.E. et al. (1997) DNA visual and analytic data mining. In the Proceedings of the IEEE Visualization. Phoenix, AZ, pp. 437-441. [2] http://www.agocg.ac.uk/reports/visual/casestud/brunsdon/radviz.htm [3] http://pandas.pydata.org/pandas-docs/stable/visualization.html\ #radviz """
# make a copy of data x = self.data[column_names].copy() for k, v in transforms.items(): x[k] = v(x[k]) def normalize(series): mn = min(series) mx = max(series) return (series - mn) / (mx - mn) df = x.apply(normalize) to_plot = [] n = len(column_names) s = np.array([(np.cos(t), np.sin(t)) for t in [2.0 * np.pi * (i / float(n)) for i in range(n)]]) for i in range(len(x)): row = df.irow(i).values row_ = np.repeat(np.expand_dims(row, axis=1), 2, axis=1) to_plot.append((s * row_).sum(axis=0) / row.sum()) x_, y_ = zip(*to_plot) self.data['radviz_x'] = x_ self.data['radviz_y'] = y_ ax = self.scatter('radviz_x', 'radviz_y', **kwargs) ax.add_patch(patches.Circle((0.0, 0.0), radius=1.0, facecolor='none')) for xy, name in zip(s, column_names): ax.add_patch(patches.Circle(xy, radius=0.025, facecolor='gray')) if xy[0] < 0.0 and xy[1] < 0.0: ax.text(xy[0] - 0.025, xy[1] - 0.025, name, ha='right', va='top', size='small') elif xy[0] < 0.0 and xy[1] >= 0.0: ax.text(xy[0] - 0.025, xy[1] + 0.025, name, ha='right', va='bottom', size='small') elif xy[0] >= 0.0 and xy[1] < 0.0: ax.text(xy[0] + 0.025, xy[1] - 0.025, name, ha='left', va='top', size='small') elif xy[0] >= 0.0 and xy[1] >= 0.0: ax.text(xy[0] + 0.025, xy[1] + 0.025, name, ha='left', va='bottom', size='small') ax.axis('equal') return ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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) return self.__class__(self.data.ix[ind], **self._kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 : callable This function will be applied to each gene object returned by self.features(). Additional args and kwargs are passed to `transform_func`. For example, if you're looking for peaks within 1kb upstream of TSSs, then pybedtools.featurefuncs.TSS would be a useful `transform_func`, and you could supply additional kwargs of `upstream=1000` and `downstream=0`. This function can return iterables of features, too. For example, you might want to look for peaks falling within the exons of a gene. In this case, `transform_func` should return an iterable of pybedtools.Interval objects. The only requirement is that the `name` field of any feature matches the index of the dataframe. intersect_kwargs : dict kwargs passed to pybedtools.BedTool.intersect. id_attribute : str The attribute in the GTF or GFF file that contains the id of the gene. For meaningful results to be returned, a gene's ID be also found in the index of the dataframe. For GFF files, typically you'd use `id_attribute="ID"`. For GTF files, you'd typically use `id_attribute="gene_id"`. """
def _transform_func(x): """ In order to support transform funcs that return a single feature or an iterable of features, we need to wrap it """ result = transform_func(x) if isinstance(result, pybedtools.Interval): result = [result] for i in result: if i: yield result intersect_kwargs = intersect_kwargs or {} if not self._cached_features: self._cached_features = pybedtools\ .BedTool(self.features())\ .saveas() if transform_func: if split: features = self._cached_features\ .split(_transform_func, *args, **kwargs) else: features = self._cached_features\ .each(transform_func, *args, **kwargs) else: features = self._cached_features hits = list(set([i[id_attribute] for i in features.intersect( peaks, **intersect_kwargs)])) return self.data.index.isin(hits)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enriched(self, thresh=0.05, idx=True): """ Enriched features. {threshdoc} """
return self.upregulated(thresh=thresh, idx=idx)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upregulated(self, thresh=0.05, idx=True): """ Upregulated features. {threshdoc} """
ind = ( (self.data[self.pval_column] <= thresh) & (self.data[self.lfc_column] > 0) ) if idx: return ind return self[ind]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disenriched(self, thresh=0.05, idx=True): """ Disenriched features. {threshdoc} """
return self.downregulated(thresh=thresh, idx=idx)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colormapped_bedfile(self, genome, cmap=None): """ Create a BED file with padj encoded as color Features will be colored according to adjusted pval (phred transformed). Downregulated features have the sign flipped. Parameters cmap : matplotlib colormap Default is matplotlib.cm.RdBu_r Notes ----- Requires a FeatureDB to be attached. """
if self.db is None: raise ValueError("FeatureDB required") db = gffutils.FeatureDB(self.db) def scored_feature_generator(d): for i in range(len(d)): try: feature = db[d.ix[i]] except gffutils.FeatureNotFoundError: raise gffutils.FeatureNotFoundError(d.ix[i]) score = -10 * np.log10(d.padj[i]) lfc = d.log2FoldChange[i] if np.isnan(lfc): score = 0 if lfc < 0: score *= -1 feature.score = str(score) feature = extend_fields( gff2bed(gffutils.helpers.asinterval(feature)), 9) fields = feature.fields[:] fields[6] = fields[1] fields[7] = fields[2] fields.append(str(d.padj[i])) fields.append(str(d.pval[i])) fields.append('%.3f' % d.log2FoldChange[i]) fields.append('%.3f' % d.baseMeanB[i]) fields.append('%.3f' % d.baseMeanB[i]) yield pybedtools.create_interval_from_list(fields) x = pybedtools.BedTool(scored_feature_generator(self)).saveas() norm = x.colormap_normalize() if cmap is None: cmap = cm.RdBu_r cmap = colormap_adjust.cmap_center_point_adjust( cmap, [norm.vmin, norm.vmax], 0) def score_zeroer(f): f.score = '0' return f return x.each(add_color, cmap=cmap, norm=norm)\ .sort()\ .each(score_zeroer)\ .truncate_to_chrom(genome)\ .saveas()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _array_parallel(fn, cls, genelist, chunksize=250, processes=1, **kwargs): """ Returns an array of genes in `genelist`, using `bins` bins. `genelist` is a list of pybedtools.Interval objects Splits `genelist` into pieces of size `chunksize`, creating an array for each chunk and merging ret A chunksize of 25-100 seems to work well on 8 cores. """
pool = multiprocessing.Pool(processes) chunks = list(chunker(genelist, chunksize)) # pool.map can only pass a single argument to the mapped function, so you # need this trick for passing multiple arguments; idea from # http://stackoverflow.com/questions/5442910/ # python-multiprocessing-pool-map-for-multiple-arguments # results = pool.map( func=_array_star, iterable=itertools.izip( itertools.repeat(fn), itertools.repeat(cls), chunks, itertools.repeat(kwargs))) pool.close() pool.join() return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _array_star(args): """ Unpacks the tuple `args` and calls _array. Needed to pass multiple args to a pool.map-ed function """
fn, cls, genelist, kwargs = args return _array(fn, cls, genelist, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_npz(self, bigwig, metric='mean0', outdir=None): """ Bin data for bigwig and save to disk. The .npz file will have the pattern {outdir}/{bigwig}.{chrom}.{windowsize}.{metric}.npz and will have two arrays, x (genomic coordinates of midpoints of each window) and y (metric for each window). It can be loaded like this:: d = np.load(filename, mmap_mode='r') bigwig : str or BigWigSignal object BigWig data that will be used to create the array metric : 'covered', 'sum', 'mean0', 'mean' Metric to store in array, as reported by bigWigAverageOverBed: * "covered": the number of bases covered by the bigWig. * "sum": sum of values over all bases covered * "mean0": average over bases with non-covered bases counted as zeros * mean: average over just the covered bases outdir : str or None Where to store output filenames. If None, store the file in the same directory as the bigwig file. """
if isinstance(bigwig, _genomic_signal.BigWigSignal): bigwig = bigwig.fn if outdir is None: outdir = os.path.dirname(bigwig) basename = os.path.basename(bigwig) windowsize = self.windowsize outfiles = [] for chrom in self.chroms: tmp_output = pybedtools.BedTool._tmp() windows = self.make_windows(chrom) outfile = os.path.join( outdir, '{basename}.{chrom}.{windowsize}.{metric}'.format(**locals()) + '.npz') cmds = [ 'bigWigAverageOverBed', bigwig, windows, tmp_output] os.system(' '.join(cmds)) names = ['name', 'size', 'covered', 'sum', 'mean0', 'mean'] df = pandas.read_table(tmp_output, names=names) x = df.size.cumsum() - df.size / 2 y = df[metric] np.savez(outfile, x=x, y=y) outfiles.append(outfile) del x, y, df return outfiles
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(signal1, signal2, features, outfn, comparefunc=np.subtract, batchsize=5000, array_kwargs=None, verbose=False): """ Compares two genomic signal objects and outputs results as a bedGraph file. Can be used for entire genome-wide comparisons due to its parallel nature. Typical usage would be to create genome-wide windows of equal size to provide as `features`:: windowsize = 10000 features = pybedtools.BedTool().window_maker( genome='hg19', w=windowsize) You will usually want to choose bins for the array based on the final resolution you would like. Say you would like 10-bp bins in the final bedGraph; using the example above you would use array_kwargs={'bins': windowsize/10}. Or, for single-bp resolution (beware: file will be large), use {'bins': windowsize}. Here's how it works. This function: * Takes `batchsize` features at a time from `features` * Constructs normalized (RPMMR) arrays in parallel for each input genomic signal object for those `batchsize` features * Applies `comparefunc` (np.subtract by default) to the arrays to get a "compared" (e.g., difference matrix by default) for the `batchsize` features. * For each row in this matrix, it outputs each nonzero column as a bedGraph format line in `outfn` `comparefunc` is a function with the signature:: def f(x, y): return z where `x` and `y` will be arrays for `signal1` and `signal2` (normalized to RPMMR) and `z` is a new array. By default this is np.subtract, but another common `comparefunc` might be a log2-fold-change function:: def lfc(x, y): return np.log2(x / y) :param signal1: A genomic_signal object :param signal2: Another genomic_signal object :param features: An iterable of pybedtools.Interval objects. A list will be created for every `batchsize` features, so you need enough memory for this. :param comparefunc: Function to use to compare arrays (default is np.subtract) :param outfn: String filename to write bedGraph file :param batchsize: Number of features (each with length `windowsize` bp) to process at a time :param array_kwargs: Kwargs passed directly to genomic_signal.array. Needs `processes` and `chunksize` if you want parallel processing :param verbose: Be noisy """
fout = open(outfn, 'w') fout.write('track type=bedGraph\n') i = 0 this_batch = [] for feature in features: if i <= batchsize: this_batch.append(feature) i += 1 continue if verbose: print 'working on batch of %s' % batchsize sys.stdout.flush() arr1 = signal1.array(this_batch, **array_kwargs).astype(float) arr2 = signal2.array(this_batch, **array_kwargs).astype(float) arr1 /= signal1.million_mapped_reads() arr2 /= signal2.million_mapped_reads() compared = comparefunc(arr1, arr2) for feature, row in itertools.izip(this_batch, compared): start = feature.start bins = len(row) binsize = len(feature) / len(row) # Quickly move on if nothing here. speed increase prob best for # sparse data if sum(row) == 0: continue for j in range(0, len(row)): score = row[j] stop = start + binsize if score != 0: fout.write('\t'.join([ feature.chrom, str(start), str(stop), str(score)]) + '\n') start = start + binsize this_batch = [] i = 0 fout.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_next_prime(N): """Find next prime >= N"""
def is_prime(n): if n % 2 == 0: return False i = 3 while i * i <= n: if n % i: i += 2 else: return False return True if N < 3: return 2 if N % 2 == 0: N += 1 for n in range(N, 2*N, 2): if is_prime(n): return n raise AssertionError("Failed to find a prime number between {0} and {1}...".format(N, 2*N))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def File(name, mode='a', chunk_cache_mem_size=1024**2, w0=0.75, n_cache_chunks=None, **kwds): """Create h5py File object with cache specification This function is basically just a wrapper around the usual h5py.File constructor, but accepts two additional keywords: Parameters name : str mode : str **kwds : dict (as keywords) Standard h5py.File arguments, passed to its constructor chunk_cache_mem_size : int Number of bytes to use for the chunk cache. Defaults to 1024**2 (1MB), which is also the default for h5py.File -- though it cannot be changed through the standard interface. w0 : float between 0.0 and 1.0 Eviction parameter. Defaults to 0.75. "If the application will access the same data more than once, w0 should be set closer to 0, and if the application does not, w0 should be set closer to 1." --- <https://www.hdfgroup.org/HDF5/doc/Advanced/Chunking/> n_cache_chunks : int Number of chunks to be kept in cache at a time. Defaults to the (smallest integer greater than) the square root of the number of elements that can fit into memory. This is just used for the number of slots (nslots) maintained in the cache metadata, so it can be set larger than needed with little cost. """
import sys import numpy as np import h5py name = name.encode(sys.getfilesystemencoding()) open(name, mode).close() # Just make sure the file exists if mode in [m+b for m in ['w', 'w+', 'r+', 'a', 'a+'] for b in ['', 'b']]: mode = h5py.h5f.ACC_RDWR else: mode = h5py.h5f.ACC_RDONLY if 'dtype' in kwds: bytes_per_object = np.dtype(kwds['dtype']).itemsize else: bytes_per_object = np.dtype(np.float).itemsize # assume float as most likely if not n_cache_chunks: n_cache_chunks = int(np.ceil(np.sqrt(chunk_cache_mem_size / bytes_per_object))) nslots = _find_next_prime(100 * n_cache_chunks) propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS) settings = list(propfaid.get_cache()) settings[1:] = (nslots, chunk_cache_mem_size, w0) propfaid.set_cache(*settings) return h5py.File(h5py.h5f.open(name, flags=mode, fapl=propfaid), **kwds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(c, prefix, relative_paths=True): """ Save data from a Chipseq object. Parameters c : Chipseq object Chipseq object, most likely after calling the `diffed_array` method prefix : str Prefix, including any leading directory paths, to save the data. relative_paths : bool If True (default), then the path names in the `prefix.info` file will be relative to `prefix`. Otherwise, they will be absolute. The following files will be created: :prefix.intervals: A BED file (or GFF, GTF, or VCF as appropriate) of the features used for the array :prefix.info: A YAML-format file indicating the IP and control BAM files, any array kwargs, the database filename, and any minibrowser local coverage args. These are all needed to reconstruct a new Chipseq object. Path names will be relative to `prefix`. :prefix.npz: A NumPy .npz file with keys 'diffed_array', 'ip_array', and 'control_array' """
dirname = os.path.dirname(prefix) pybedtools.BedTool(c.features).saveas(prefix + '.intervals') def usepath(f): if relative_paths: return os.path.relpath(f, start=dirname) else: return os.path.abspath(f) with open(prefix + '.info', 'w') as fout: info = { 'ip_bam': usepath(c.ip.fn), 'control_bam': usepath(c.control.fn), 'array_kwargs': c.array_kwargs, 'dbfn': usepath(c.dbfn), 'browser_local_coverage_kwargs': c.browser_local_coverage_kwargs, 'relative_paths': relative_paths, } fout.write(yaml.dump(info, default_flow_style=False)) np.savez( prefix, diffed_array=c.diffed_array, ip_array=c.ip_array, control_array=c.control_array )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xcorr(x, y, maxlags): """ Streamlined version of matplotlib's `xcorr`, without the plots. :param x, y: NumPy arrays to cross-correlate :param maxlags: Max number of lags; result will be `2*maxlags+1` in length """
xlen = len(x) ylen = len(y) assert xlen == ylen c = np.correlate(x, y, mode=2) # normalize c /= np.sqrt(np.dot(x, x) * np.dot(y, y)) lags = np.arange(-maxlags, maxlags + 1) c = c[xlen - 1 - maxlags:xlen + maxlags] return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot(self, x, row_order=None, imshow_kwargs=None, strip=True): """ Plot the scaled ChIP-seq data. :param x: X-axis to use (e.g, for TSS +/- 1kb with 100 bins, this would be `np.linspace(-1000, 1000, 100)`) :param row_order: Array-like object containing row order -- typically the result of an `np.argsort` call. :param strip: Include axes along the left side with points that can be clicked to spawn a minibrowser for that feature. """
nrows = self.diffed_array.shape[0] if row_order is None: row_order = np.arange(nrows) extent = (min(x), max(x), 0, nrows) axes_info = metaseq.plotutils.matrix_and_line_shell(strip=strip) fig, matrix_ax, line_ax, strip_ax, cbar_ax = axes_info _imshow_kwargs = dict( aspect='auto', extent=extent, interpolation='nearest') if imshow_kwargs: _imshow_kwargs.update(imshow_kwargs) if 'cmap' not in _imshow_kwargs: _imshow_kwargs['cmap'] = metaseq.colormap_adjust.smart_colormap( self.diffed_array.min(), self.diffed_array.max() ) mappable = matrix_ax.imshow( self.diffed_array[row_order], **_imshow_kwargs) plt.colorbar(mappable, cbar_ax) line_ax.plot(x, self.diffed_array.mean(axis=0)) if strip_ax: line, = strip_ax.plot(np.zeros((nrows,)), np.arange(nrows) + 0.5, **self._strip_kwargs) line.features = self.features line.ind = row_order matrix_ax.axis('tight') if strip_ax: strip_ax.xaxis.set_visible(False) matrix_ax.yaxis.set_visible(False) matrix_ax.xaxis.set_visible(False) if self.db: self.minibrowser = GeneChipseqMiniBrowser( [self.ip, self.control], db=self.db, plotting_kwargs=self.browser_plotting_kwargs, local_coverage_kwargs=self.browser_local_coverage_kwargs) else: self.minibrowser = SignalChipseqMiniBrowser( [self.ip, self.control], plotting_kwargs=self.browser_plotting_kwargs, local_coverage_kwargs=self.browser_local_coverage_kwargs) fig.canvas.mpl_connect('pick_event', self.callback) self.fig = fig self.axes = { 'matrix_ax': matrix_ax, 'strip_ax': strip_ax, 'line_ax': line_ax, 'cbar_ax': cbar_ax }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def callback(self, event): """ Callback function to spawn a mini-browser when a feature is clicked. """
artist = event.artist ind = artist.ind limit = 5 browser = True if len(event.ind) > limit: print "more than %s genes selected; not spawning browsers" % limit browser = False for i in event.ind: feature = artist.features[ind[i]] print feature, if browser: self.minibrowser.plot(feature)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, event=None): """ Remove all the registered observers for the given event name. Arguments: event (str): event name to remove. """
observers = self._pool.get(event) if observers: self._pool[event] = []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trigger(self, event, *args, **kw): """ Triggers event observers for the given event name, passing custom variadic arguments. """
observers = self._pool.get(event) # If no observers registered for the event, do no-op if not observers or len(observers) == 0: return None # Trigger observers coroutines in FIFO sequentially for fn in observers: # Review: perhaps this should not wait yield from fn(*args, **kw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def until(coro, coro_test, assert_coro=None, *args, **kw): """ Repeatedly call `coro` coroutine function until `coro_test` returns `True`. This function is the inverse of `paco.whilst()`. This function is a coroutine. Arguments: coro (coroutinefunction): coroutine function to execute. coro_test (coroutinefunction): coroutine function to test. assert_coro (coroutinefunction): optional assertion coroutine used to determine if the test passed or not. *args (mixed): optional variadic arguments to pass to `coro` function. Raises: TypeError: if input arguments are invalid. Returns: list: result values returned by `coro`. Usage:: calls = 0 async def task(): nonlocal calls calls += 1 return calls async def calls_gt_4(): return calls > 4 await paco.until(task, calls_gt_4) # => [1, 2, 3, 4, 5] """
@asyncio.coroutine def assert_coro(value): return not value return (yield from whilst(coro, coro_test, assert_coro=assert_coro, *args, **kw))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def curry(arity_or_fn=None, ignore_kwargs=False, evaluator=None, *args, **kw): """ Creates a function that accepts one or more arguments of a function and either invokes func returning its result if at least arity number of arguments have been provided, or returns a function that accepts the remaining function arguments until the function arity is satisfied. This function is overloaded: you can pass a function or coroutine function as first argument or an `int` indicating the explicit function arity. Function arity can be inferred via function signature or explicitly passed via `arity_or_fn` param. You can optionally ignore keyword based arguments as well passsing the `ignore_kwargs` param with `True` value. This function can be used as decorator. Arguments: arity_or_fn (int|function|coroutinefunction): function arity to curry or function to curry. ignore_kwargs (bool): ignore keyword arguments as arity to satisfy during curry. evaluator (function): use a custom arity evaluator function. *args (mixed): mixed variadic arguments for partial function application. *kwargs (mixed): keyword variadic arguments for partial function application. Raises: TypeError: if function is not a function or a coroutine function. Returns: function or coroutinefunction: function will be returned until all the function arity is satisfied, where a coroutine function will be returned instead. Usage:: # Function signature inferred function arity @paco.curry async def task(x, y, z=0): return x * y + z await task(4)(4)(z=8) # => 24 # User defined function arity @paco.curry(4) async def task(x, y, *args, **kw): return x * y + args[0] * args[1] await task(4)(4)(8)(8) # => 80 # Ignore keyword arguments from arity @paco.curry(ignore_kwargs=True) async def task(x, y, z=0): return x * y await task(4)(4) # => 16 """
def isvalidarg(x): return all([ x.kind != x.VAR_KEYWORD, x.kind != x.VAR_POSITIONAL, any([ not ignore_kwargs, ignore_kwargs and x.default == x.empty ]) ]) def params(fn): return inspect.signature(fn).parameters.values() def infer_arity(fn): return len([x for x in params(fn) if isvalidarg(x)]) def merge_args(acc, args, kw): _args, _kw = acc _args = _args + args _kw = _kw or {} _kw.update(kw) return _args, _kw def currier(arity, acc, fn, *args, **kw): """ Function either continues curring of the arguments or executes function if desired arguments have being collected. If function curried is variadic then execution without arguments will finish curring and trigger the function """ # Merge call arguments with accumulated ones _args, _kw = merge_args(acc, args, kw) # Get current function call accumulated arity current_arity = len(args) # Count keyword params as arity to satisfy, if required if not ignore_kwargs: current_arity += len(kw) # Decrease function arity to satisfy arity -= current_arity # Use user-defined custom arity evaluator strategy, if present currify = evaluator and evaluator(acc, fn) # If arity is not satisfied, return recursive partial function if currify is not False and arity > 0: return functools.partial(currier, arity, (_args, _kw), fn) # If arity is satisfied, instanciate coroutine and return it return fn(*_args, **_kw) def wrapper(fn, *args, **kw): if not iscallable(fn): raise TypeError('paco: first argument must a coroutine function, ' 'a function or a method.') # Infer function arity, if required arity = (arity_or_fn if isinstance(arity_or_fn, int) else infer_arity(fn)) # Wraps function as coroutine function, if needed. fn = wraps(fn) if isfunc(fn) else fn # Otherwise return recursive currier function return currier(arity, (args, kw), fn, *args, **kw) if arity > 0 else fn # Return currier function or decorator wrapper return (wrapper(arity_or_fn, *args, **kw) if iscallable(arity_or_fn) else wrapper)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compose(*coros): """ Creates a coroutine function based on the composition of the passed coroutine functions. Each function consumes the yielded result of the coroutine that follows. Composing coroutine functions f(), g(), and h() would produce the result of f(g(h())). Arguments: *coros (coroutinefunction): variadic coroutine functions to compose. Raises: RuntimeError: if cannot execute a coroutine function. Returns: coroutinefunction Usage:: async def sum_1(num): return num + 1 async def mul_2(num): return num * 2 coro = paco.compose(sum_1, mul_2, sum_1) await coro(2) # => 7 """
# Make list to inherit built-in type methods coros = list(coros) @asyncio.coroutine def reducer(acc, coro): return (yield from coro(acc)) @asyncio.coroutine def wrapper(acc): return (yield from reduce(reducer, coros, initializer=acc, right=True)) return wrapper