Plot a bargraph showing the strandedness of alignments
199006
def strand_barplot(self):
        
        # Plot bar graph of groups
        keys = [ 'End 1 Sense', 'End 1 Antisense', 'End 2 Sense', 'End 2 Antisense' ]
        # Config for the plot
        pconfig = {
            'id': 'rna_seqc_strandedness_plot',
            'title': 'RNA-SeQC: Strand Specificity',
            'ylab': '% Reads',
            'cpswitch_counts_label': '# Reads',
            'cpswitch_percent_label': '% Reads',
            'ymin': 0,
            'cpswitch_c_active': False
        }
        self.add_section (
            name = 'Strand Specificity',
            anchor = 'rna_seqc_strand_specificity',
            helptext = 'End 1/2 Sense are the number of End 1 or 2 reads that were sequenced in the sense direction. '
                       'Similarly, End 1/2 Antisense are the number of End 1 or 2 reads that were sequenced in the '
                       'antisense direction',
            plot = bargraph.plot(self.rna_seqc_metrics, keys, pconfig)
        )
992393
def reshape_bar_plot(df, x, y, bars):
    
    idx = [bars, x]
    if df.duplicated(idx).any():
        warnings.warn('Duplicated index found.')
        df = df.drop_duplicates(idx, keep='last')
    df = df.set_index(idx)[y].unstack(x).T
    return df
346754
def _plot_ulims(
    ax, x, y, xerr, color, capsize=5, height_fraction=0.25, elinewidth=2
):
    
    ax.errorbar(
        x, y, xerr=xerr, ls="", color=color, elinewidth=elinewidth, capsize=0
    )

    from distutils.version import LooseVersion
    import matplotlib

    mpl_version = LooseVersion(matplotlib.__version__)
    if mpl_version >= LooseVersion("1.4.0"):
        ax.errorbar(
            x,
            y,
            yerr=height_fraction * y,
            ls="",
            uplims=True,
            color=color,
            elinewidth=elinewidth,
            capsize=capsize,
            zorder=10,
        )
    else:
        ax.errorbar(
            x,
            (1 - height_fraction) * y,
            yerr=height_fraction * y,
            ls="",
            lolims=True,
            color=color,
            elinewidth=elinewidth,
            capsize=capsize,
            zorder=10,
        )
628363
def barplot(bars, title='', upColor='blue', downColor='red'):
    
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D
    from matplotlib.patches import Rectangle

    if isinstance(bars, pd.DataFrame):
        ohlcTups = [
            tuple(v) for v in bars[['open', 'high', 'low', 'close']].values]
    elif bars and hasattr(bars[0], 'open_'):
        ohlcTups = [(b.open_, b.high, b.low, b.close) for b in bars]
    else:
        ohlcTups = [(b.open, b.high, b.low, b.close) for b in bars]

    fig, ax = plt.subplots()
    ax.set_title(title)
    ax.grid(True)
    fig.set_size_inches(10, 6)
    for n, (open_, high, low, close) in enumerate(ohlcTups):
        if close >= open_:
            color = upColor
            bodyHi, bodyLo = close, open_
        else:
            color = downColor
            bodyHi, bodyLo = open_, close
        line = Line2D(
            xdata=(n, n),
            ydata=(low, bodyLo),
            color=color,
            linewidth=1)
        ax.add_line(line)
        line = Line2D(
            xdata=(n, n),
            ydata=(high, bodyHi),
            color=color,
            linewidth=1)
        ax.add_line(line)
        rect = Rectangle(
            xy=(n - 0.3, bodyLo),
            width=0.6,
            height=bodyHi - bodyLo,
            edgecolor=color,
            facecolor=color,
            alpha=0.4,
            antialiased=True
        )
        ax.add_patch(rect)

    ax.autoscale_view()
    return fig
245146
def strand(s1, s2):
    
    return "".join(map(lambda x,y:chr(ord(x)&ord(y)), s1, s2))
948906
def _plot_completeness(ax, comw, start_time, end_time):
    '''
    
    '''
    comw = np.array(comw)
    comp = np.column_stack([np.hstack([end_time, comw[:, 0], start_time]),
                            np.hstack([comw[0, 1], comw[:, 1], comw[-1, 1]])])
    ax.step(comp[:-1, 0], comp[1:, 1], linestyle='-',
            where="post", linewidth=3, color='brown')
843960
def viterbi_alignment(es, fs, t, a):
    '''
    
    '''
    max_a = collections.defaultdict(float)
    l_e = len(es)
    l_f = len(fs)
    for (j, e) in enumerate(es, 1):
        current_max = (0, -1)
        for (i, f) in enumerate(fs, 1):
            val = t[(e, f)] * a[(i, j, l_e, l_f)]
            # select the first one among the maximum candidates
            if current_max[1] < val:
                current_max = (i, val)
        max_a[j] = current_max[0]
    return max_a
989325
def B(u, v, dfs_data):
    """Bu(v) = {wx | w is in S*(v)}"""
    if a(v, dfs_data) != u:
        return None

    return list(set([edge_id for w in S_star(v, dfs_data) for edge_id in dfs_data['graph'].get_node(w)['edges']]))
780414
def plot_bargraph (self, data, cats=None, pconfig=None):
        
        from multiqc.plots import bargraph
        if pconfig is None:
            pconfig = {}
        return bargraph.plot(data, cats, pconfig)
521266
def graph_repr(self):
        """"""

        # Replace any floating point numbers in the expression
        # with their scientific notation
        final = re.sub(r"[-+]?\d*\.\d+",
                       lambda x: format(float(x.group(0)), '.2E'),
                       self._expr)
        # Graphviz interprets `\l` as "divide label into lines, left-justified"
        return "Expression:\\l  {}\\l".format(
            final,
        )
255389
def trimmomatic_barplot (self):
        

        # Specify the order of the different possible categories
        keys = OrderedDict()
        keys['surviving'] =              { 'color': '#437bb1', 'name': 'Surviving Reads' }
        keys['both_surviving'] =         { 'color': '#f7a35c', 'name': 'Both Surviving' }
        keys['forward_only_surviving'] = { 'color': '#e63491', 'name': 'Forward Only Surviving' }
        keys['reverse_only_surviving'] = { 'color': '#b1084c', 'name': 'Reverse Only Surviving' }
        keys['dropped'] =                { 'color': '#7f0000', 'name': 'Dropped' }

        # Config for the plot
        pconfig = {
            'id': 'trimmomatic_plot',
            'title': 'Trimmomatic: Surviving Reads',
            'ylab': '# Reads',
            'cpswitch_counts_label': 'Number of Reads'
        }

        self.add_section( plot = bargraph.plot(self.trimmomatic, keys, pconfig) )
666654
def nx_contracted_nodes(G, u, v, self_loops=True, inplace=False):
    
    import itertools as it
    if G.is_directed():
        in_edges = ((w, u, d) for w, x, d in G.in_edges(v, data=True)
                    if self_loops or w != u)
        out_edges = ((u, w, d) for x, w, d in G.out_edges(v, data=True)
                     if self_loops or w != u)
        new_edges = it.chain(in_edges, out_edges)
    else:
        new_edges = ((u, w, d) for x, w, d in G.edges(v, data=True)
                     if self_loops or w != u)
    if inplace:
        H = G
        new_edges = list(new_edges)
    else:
        H = G.copy()
    node_dict = nx_node_dict(H)
    v_data = node_dict[v]
    H.remove_node(v)
    H.add_edges_from(new_edges)
    if 'contraction' in node_dict[u]:
        node_dict[u]['contraction'][v] = v_data
    else:
        node_dict[u]['contraction'] = {v: v_data}
    return H
579221
def plot_result(filt, full, prntres=True):
    """
    # Check matplotlib (soft dependency)
    if not plt:
        print(plt_msg)
        return

    if prntres:
        print_result(filt, full)

    # Get spacing and shift values from full output of brute
    spacing = full[2][0, :, 0]
    shift = full[2][1, 0, :]

    # Get minimum field values from full output of brute
    minfield = np.squeeze(full[3])

    plt.figure("Brute force result", figsize=(9.5, 4.5))
    plt.subplots_adjust(wspace=.4, bottom=0.2)

    # Figure 1: Only if more than 1 spacing or more than 1 shift
    # Figure of minfield, depending if spacing/shift are vectors or floats
    if spacing.size > 1 or shift.size > 1:
        plt.subplot(121)
        if full[4] == 0:  # Min amp
            plt.title("Minimal recovered fields")
            ylabel = 'Minimal recovered amplitude (log10)'
            field = np.log10(minfield)
            cmap = plt.cm.viridis
        else:  # Max r
            plt.title("Maximum recovered r")
            ylabel = 'Maximum recovered r'
            field = 1/minfield
            cmap = plt.cm.viridis_r

        if shift.size == 1:    # (a) if only one shift value,
            plt.plot(spacing, field)
            plt.xlabel('Spacing')
            plt.ylabel(ylabel)

        elif spacing.size == 1:  # (b) if only one spacing value
            plt.plot(shift, field)
            plt.xlabel('Shift')
            plt.ylabel(ylabel)

        else:   # (c) if several spacing and several shift values
            field = np.ma.masked_where(np.isinf(minfield), field)
            plt.pcolormesh(shift, spacing, field, cmap=cmap)
            plt.ylabel('Spacing')
            plt.xlabel('Shift')
            plt.colorbar()

    # Figure 2: Filter values
    if spacing.size > 1 or shift.size > 1:
        plt.subplot(122)
    plt.title('Filter values of best filter')
    for attr in ['j0', 'j1', 'sin', 'cos']:
        if hasattr(filt, attr):
            plt.plot(np.log10(filt.base),
                     np.log10(np.abs(getattr(filt, attr))), '.-', lw=.5,
                     label='abs('+attr+')')
            plt.plot(np.log10(filt.base), np.log10(-getattr(filt, attr)), '.',
                     color='k', ms=4)
    plt.plot(np.inf, 0, '.', color='k', ms=4, label='Neg. values')
    plt.xlabel('Base (log10)')
    plt.ylabel('Abs(Amplitude) (log10)')
    plt.legend(loc='best')
    plt.gcf().canvas.draw()  # To force draw in notebook while running
    plt.show()
545599
def bismark_alignment_chart (self):
        

        # Specify the order of the different possible categories
        keys = OrderedDict()
        keys['aligned_reads']   = { 'color': '#2f7ed8', 'name': 'Aligned Uniquely' }
        keys['ambig_reads']     = { 'color': '#492970', 'name': 'Aligned Ambiguously' }
        keys['no_alignments']   = { 'color': '#0d233a', 'name': 'Did Not Align' }
        keys['discarded_reads'] = { 'color': '#f28f43', 'name': 'No Genomic Sequence' }

        # Config for the plot
        config = {
            'id': 'bismark_alignment',
            'title': 'Bismark: Alignment Scores',
            'ylab': '# Reads',
            'cpswitch_counts_label': 'Number of Reads'
        }

        self.add_section (
            name = 'Alignment Rates',
            anchor = 'bismark-alignment',
            plot = bargraph.plot(self.bismark_data['alignment'], keys, config)
        )
339091
def align_subplots(N,M,xlim=None, ylim=None):
    """"""
    #find sensible xlim,ylim
    if xlim is None:
        xlim = [np.inf,-np.inf]
        for i in range(N*M):
            plt.subplot(N,M,i+1)
            xlim[0] = min(xlim[0],plt.xlim()[0])
            xlim[1] = max(xlim[1],plt.xlim()[1])
    if ylim is None:
        ylim = [np.inf,-np.inf]
        for i in range(N*M):
            plt.subplot(N,M,i+1)
            ylim[0] = min(ylim[0],plt.ylim()[0])
            ylim[1] = max(ylim[1],plt.ylim()[1])

    for i in range(N*M):
        plt.subplot(N,M,i+1)
        plt.xlim(xlim)
        plt.ylim(ylim)
        if (i)%M:
            plt.yticks([])
        else:
            removeRightTicks()
        if i<(M*(N-1)):
            plt.xticks([])
        else:
            removeUpperTicks()
1338557
def t_string_NGRAPH(t):
    "
    global __STRING

    P = {' ': 0, "'": 2, '.': 8, ':': 10}
    N = {' ': 0, "'": 1, '.': 4, ':': 5}

    __STRING += chr(128 + P[t.value[1]] + N[t.value[2]])
708261
def _compute_ticks(self, element, edges, widths, lims):
        
        if self.xticks is None or not isinstance(self.xticks, int):
            return None
        if self.cyclic:
            x0, x1, _, _ = lims
            xvals = np.linspace(x0, x1, self.xticks)
            labels = ["%.0f" % np.rad2deg(x) + '\N{DEGREE SIGN}' for x in xvals]
        elif self.xticks:
            dim = element.get_dimension(0)
            inds = np.linspace(0, len(edges), self.xticks, dtype=np.int)
            edges = list(edges) + [edges[-1] + widths[-1]]
            xvals = [edges[i] for i in inds]
            labels = [dim.pprint_value(v) for v in xvals]
        return [xvals, labels]