Making plots of time vs read length, time vs quality and cumulative yield.
494528
def time_plots(df, path, title=None, color="#4CB391", figformat="png",
               log_length=False, plot_settings=None):
    """"""
    dfs = check_valid_time_and_sort(df, "start_time")
    logging.info("Nanoplotter: Creating timeplots using {} reads.".format(len(dfs)))
    cumyields = cumulative_yield(dfs=dfs.set_index("start_time"),
                                 path=path,
                                 figformat=figformat,
                                 title=title,
                                 color=color)
    reads_pores_over_time = plot_over_time(dfs=dfs.set_index("start_time"),
                                           path=path,
                                           figformat=figformat,
                                           title=title,
                                           color=color)
    violins = violin_plots_over_time(dfs=dfs,
                                     path=path,
                                     figformat=figformat,
                                     title=title,
                                     log_length=log_length,
                                     plot_settings=plot_settings)
    return cumyields + reads_pores_over_time + violins
760669
def plot_data():
    '''

    '''

    var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM']
    # colorbar limits for each property
    lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2], [0, 9]])  # reasonable values
    # lims = np.array([[20,36], [26,33], [1.5,5.6], [0,4], [0,9], [0,1.5]]) # values to show colormaps

    for fname in fnames:
        fig, axes = plt.subplots(nrows=4, ncols=2)
        fig.set_size_inches(20, 10)
        fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.0, hspace=0.07)
        i = 0
        for ax, Var, cmap in zip(axes.flat, var, cmaps):  # loop through data to plot up

            # get variable data
            lat, lon, z, data = test.read(Var, fname)

            map1 = ax.scatter(lat, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=lims[i, 0], vmax=lims[i, 1])
            # no stupid offset
            y_formatter = mpl.ticker.ScalarFormatter(useOffset=False)
            ax.xaxis.set_major_formatter(y_formatter)
            if i == 6:
                ax.set_xlabel('Latitude [degrees]')
                ax.set_ylabel('Depth [m]')
            else:
                ax.set_xticklabels([])
                ax.set_yticklabels([])
            ax.set_ylim(-z.max(), 0)
            ax.set_xlim(lat.min(), lat.max())
            cb = plt.colorbar(map1, ax=ax, pad=0.02)
            cb.set_label(cmap.name + ' [' + '$' + cmap.units + '$]')
            i += 1

        fig.savefig('figures/' + fname.split('.')[0] + '.png', bbox_inches='tight')
1030683
def stats(args):
    
    p = OptionParser(stats.__doc__)
    p.set_outfile()
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    folder, = args
    statsfiles = iglob(folder, "*.stats")
    after_equal = lambda x: x.split("=")[-1]
    header = "Library Assembled_reads Contigs".split()
    contents = []
    # label=M0096 total=7443 cnts=948 mean=7.851 std=35.96
    for statsfile in statsfiles:
        fp = open(statsfile)
        for row in fp:
            if row.startswith("label="):
                break
        label, total, cnts = row.split()[:3]
        label = after_equal(label)
        reads = int(after_equal(total))
        contigs = int(after_equal(cnts))
        contents.append((label, reads, contigs))

    all_labels, all_reads, all_contigs = zip(*contents)
    contents.append(("SUM", sum(all_reads), sum(all_contigs)))
    contents.append(("AVERAGE (per sample)", \
                    int(np.mean(all_reads)), int(np.mean(all_contigs))))
    contents.append(("MEDIAN (per sample)", \
                    int(np.median(all_reads)), int(np.median(all_contigs))))
    write_csv(header, contents, filename=opts.outfile)
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')
1150091
def aggregate_metrics(latencies_ms, duration_ms, num_bucket):
    """"""
    overall_op_count = 0
    op_counts = {operation : len(latency) for operation,
                 latency in latencies_ms.iteritems()}
    overall_op_count = sum([op_count for op_count in op_counts.itervalues()])

    print('[OVERALL], RunTime(ms), %f' % duration_ms)
    print('[OVERALL], Throughput(ops/sec), %f' % (float(overall_op_count) /
                                                duration_ms * 1000.0))

    for operation in op_counts.keys():
        operation_upper = operation.upper()
        print('[%s], Operations, %d' % (operation_upper, op_counts[operation]))
        print('[%s], AverageLatency(us), %f' % (
            operation_upper, numpy.average(latencies_ms[operation]) * 1000.0))
        print('[%s], LatencyVariance(us), %f' % (
            operation_upper, numpy.var(latencies_ms[operation]) * 1000.0))
        print('[%s], MinLatency(us), %f' % (
            operation_upper, min(latencies_ms[operation]) * 1000.0))
        print('[%s], MaxLatency(us), %f' % (
            operation_upper, max(latencies_ms[operation]) * 1000.0))
        print('[%s], 95thPercentileLatency(us), %f' % (
            operation_upper,
            numpy.percentile(latencies_ms[operation], 95.0) * 1000.0))
        print('[%s], 99thPercentileLatency(us), %f' % (
            operation_upper,
            numpy.percentile(latencies_ms[operation], 99.0) * 1000.0))
        print('[%s], 99.9thPercentileLatency(us), %f' % (
            operation_upper,
            numpy.percentile(latencies_ms[operation], 99.9) * 1000.0))
        print('[%s], Return=OK, %d' % (operation_upper, op_counts[operation]))
        latency_array = numpy.array(latencies_ms[operation])
        for j in range(num_bucket):
            print('[%s], %d, %d' % (
                operation_upper, j,
                ((j <= latency_array) & (latency_array < (j + 1))).sum()))
        print('[%s], >%d, %d' % (operation_upper, num_bucket,
                                 (num_bucket <= latency_array).sum()))
267254
def plot_profile(ribo_counts, transcript_name, transcript_length,
                 start_stops, read_lengths=None, read_offsets=None, rna_counts=None,
                 color_scheme='default', html_file='index.html', output_path='output'):
    
    colors = get_color_palette(scheme=color_scheme)
    gs = gridspec.GridSpec(3, 1, height_ratios=[6, 1.3, 0.5], hspace=0.35)
    font_axis = {'family': 'sans-serif', 'color': colors['color'], 'weight': 'bold', 'size': 7}

    # riboseq bar plots
    gs2 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs[0])
    ax2 = plt.subplot(gs2[0])
    label = 'Ribo-Seq count'

    if read_lengths:
        if len(read_lengths) > 1:
            label = 'Ribo-Seq count ({}-mers)'.format(', '.join('{}'.format(item) for item in read_lengths))
        else:
            label = 'Ribo-Seq count ({}-mer)'.format('{}'.format(read_lengths[0]))

    ax2.set_ylabel(label, fontdict=font_axis, labelpad=10)

    # rna coverage if available
    ax_rna = None
    if rna_counts:
        ax_rna = ax2.twinx()
        ax_rna.set_ylabel('RNA-Seq count', fontdict=font_axis, labelpad=10)
        ax_rna.bar(rna_counts.keys(), rna_counts.values(), facecolor=colors['rna'],
                   edgecolor=colors['rna'], label='RNA')
        ax_rna.set_zorder(1)

    frame_counts = {1: {}, 2: {}, 3: {}}
    for k, v in ribo_counts.iteritems():
        for fr in (1, 2, 3):
            if v[fr] > 0:
                frame_counts[fr][k] = v[fr]
                break

    cnts = []
    [cnts.extend(item.values()) for item in frame_counts.values()]
    y_max = float(max(cnts) * 1.25)
    ax2.set_ylim(0.0, y_max)
    ax2.set_zorder(2)
    ax2.patch.set_facecolor('none')

    for frame in (1, 2, 3):
        color = colors['frames'][frame - 1]
        x_vals = frame_counts[frame].keys()
        ax2.bar(x_vals, frame_counts[frame].values(), color=color, facecolor=color, edgecolor=color)

    # ORF architecture
    gs3 = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=gs[1], hspace=0.1)
    if color_scheme == 'greyorfs':
        axisbg = [colors['grey'] for i in range(3)]
    else:
        axisbg = colors['frames']

    ax4 = plt.subplot(gs3[0], sharex=ax2, axisbg=axisbg[0])
    ax5 = plt.subplot(gs3[1], sharex=ax2, axisbg=axisbg[1])
    ax6 = plt.subplot(gs3[2], sharex=ax2, axisbg=axisbg[2])
    ax6.set_xlabel('Transcript length ({} nt)'.format(transcript_length), fontdict=font_axis, labelpad=6)

    # Legend
    gs4 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs[2], hspace=0.1)
    ax7 = plt.subplot(gs4[0], axisbg=colors['background'])
    set_axis_color(ax7, colors['background'])

    ax7.text(0.02, 0.1, "AUG", size=5, ha="center", va="center", color=colors['color'],
             bbox=dict(boxstyle="square", facecolor=colors['start'], edgecolor=colors['color'], linewidth=0.3))
    ax7.text(0.06, 0.1, "STOP", size=5, ha="center", va="center", color='white',
             bbox=dict(boxstyle="square", color=colors['stop']))
    ax7.text(0.13, 0.1, "Frames", size=5, ha='center', va='center', color=colors['color'],
             fontdict={'weight': 'bold'})
    ax7.text(0.17, 0.1, "1", size=5, ha="center", va="center", color='white',
             bbox=dict(boxstyle="square", color=colors['frames'][0]))
    ax7.text(0.19, 0.1, "2", size=5, ha="center", va="center", color='white',
             bbox=dict(boxstyle="square", color=colors['frames'][1]))
    ax7.text(0.21, 0.1, "3", size=5, ha="center", va="center", color='white',
             bbox=dict(boxstyle="square", color=colors['frames'][2]))

    # No ticks or labels for ORF 1, 2 and Legend
    for axis in (ax4, ax5, ax7):
        axis.tick_params(top=False, left=False, right=False, bottom=False, labeltop=False,
                         labelleft=False, labelright=False, labelbottom=False)

    axes = [ax2]
    if ax_rna:
        axes.append(ax_rna)

    fp = FontProperties(size='5')
    for axis in axes:
        set_axis_color(axis, colors['axis'])
        axis.tick_params(colors=colors['ticks'])
        for item in (axis.get_xticklabels() + axis.get_yticklabels()):
            item.set_fontproperties(fp)
            item.set_color(colors['color'])

    for axis, frame in ((ax4, 1), (ax5, 2), (ax6, 3)):
        if color_scheme == 'greyorfs':
            color = colors['grey']
        else:
            color = colors['frames'][frame - 1]
        set_axis_color(axis, color, alpha=0.05)
        axis.patch.set_alpha(0.3)  # opacity of ORF architecture
        for item in (axis.get_xticklabels()):
            item.set_fontproperties(fp)
            item.set_color(colors['color'])
        axis.set_ylim(0, 0.2)
        axis.set_xlim(0, transcript_length)
        starts = [(item, 1) for item in start_stops[frame]['starts']]
        stops = [(item, 1) for item in start_stops[frame]['stops']]
        start_colors = [colors['start'] for item in starts]
        axis.broken_barh(starts, (0.11, 0.2), facecolors=start_colors,
                         edgecolors=start_colors, label='start', zorder=5)
        stop_colors = [colors['stop'] for item in stops]
        axis.broken_barh(stops, (0, 0.2), facecolors=stop_colors,
                         edgecolors=stop_colors, label='stop', zorder=5)
        axis.set_ylabel('{}'.format(frame),
                        fontdict={'family': 'sans-serif', 'color': colors['color'],
                                  'weight': 'normal', 'size': '6'},
                        rotation='horizontal', labelpad=10, verticalalignment='center')
        axis.tick_params(top=False, left=False, right=False, labeltop=False,
                         labelleft=False, labelright=False, direction='out', colors=colors['ticks'])
    plt.title('{}'.format(transcript_name),
              fontdict={'family': 'sans-serif', 'color': colors['color'],
                        'weight': 'bold', 'size': 8, 'y': 20})
    if not os.path.exists(output_path):
        os.mkdir(output_path)
    plt.savefig(os.path.join(output_path, 'riboplot.svg'), facecolor=colors['background'])
    plt.savefig(os.path.join(output_path, 'riboplot.png'), dpi=600, facecolor=colors['background'])

    with open(os.path.join(CONFIG.PKG_DATA_DIR, 'riboplot.html')) as g, open(os.path.join(output_path, html_file), 'w') as h:
        h.write(g.read().format(transcript_name=transcript_name))

    css_dir = os.path.join(output_path, 'css')
    if not os.path.exists(css_dir):
        os.mkdir(css_dir)

    css_data_dir = os.path.join(CONFIG.PKG_DATA_DIR, 'css')
    for fname in os.listdir(css_data_dir):
        shutil.copy(os.path.join(css_data_dir, fname), os.path.join(output_path, 'css', fname))
651450
def gen_time_intervals(start, end, delta):
    
    curr = start
    while curr < end:
        yield curr
        curr += delta
445309
def timeseries_subplot(X,
                       time=None,
                       color=None,
                       var_names=(),
                       highlightsX=(),
                       xlabel='',
                       ylabel='gene expression',
                       yticks=None,
                       xlim=None,
                       legend=True,
                       palette=None,
                       color_map='viridis'):
    

    if color is not None:
        use_color_map = isinstance(color[0], float) or isinstance(color[0], np.float32)
    palette = default_palette(palette)
    x_range = np.arange(X.shape[0]) if time is None else time
    if X.ndim == 1: X = X[:, None]
    if X.shape[1] > 1:
        colors = palette[:X.shape[1]].by_key()['color']
        subsets = [(x_range, X[:, i]) for i in range(X.shape[1])]
    elif use_color_map:
        colors = [color]
        subsets = [(x_range, X[:, 0])]
    else:
        levels, _ = np.unique(color, return_inverse=True)
        colors = np.array(palette[:len(levels)].by_key()['color'])
        subsets = [(x_range[color == l], X[color == l, :]) for l in levels]

    for i, (x, y) in enumerate(subsets):
        pl.scatter(
            x, y,
            marker='.',
            edgecolor='face',
            s=rcParams['lines.markersize'],
            c=colors[i],
            label=var_names[i] if len(var_names) > 0 else '',
            cmap=color_map,
            rasterized=settings._vector_friendly)
    ylim = pl.ylim()
    for ih, h in enumerate(highlightsX):
        pl.plot([h, h], [ylim[0], ylim[1]], '--', color='black')
    pl.ylim(ylim)
    if xlim is not None:
        pl.xlim(xlim)
    pl.xlabel(xlabel)
    pl.ylabel(ylabel)
    if yticks is not None:
        pl.yticks(yticks)
    if len(var_names) > 0 and legend:
        pl.legend(frameon=False)
390687
def timeseries_as_heatmap(X, var_names=None, highlightsX=None, color_map=None):
    
    if highlightsX is None:
        highlightsX = []
    if var_names is None:
        var_names = []
    if len(var_names) == 0:
        var_names = np.arange(X.shape[1])
    if var_names.ndim == 2:
        var_names = var_names[:, 0]

    # transpose X
    X = X.T
    minX = np.min(X)

    # insert space into X
    if False:
        # generate new array with highlightsX
        space = 10  # integer
        Xnew = np.zeros((X.shape[0], X.shape[1] + space*len(highlightsX)))
        hold = 0
        _hold = 0
        space_sum = 0
        for ih, h in enumerate(highlightsX):
            _h = h + space_sum
            Xnew[:, _hold:_h] = X[:, hold:h]
            Xnew[:, _h:_h+space] = minX * np.ones((X.shape[0], space))
            # update variables
            space_sum += space
            _hold = _h + space
            hold = h
        Xnew[:, _hold:] = X[:, hold:]

    fig = pl.figure(figsize=(1.5*4, 2*4))
    im = pl.imshow(np.array(X, dtype=np.float_), aspect='auto',
                   interpolation='nearest', cmap=color_map)
    pl.colorbar(shrink=0.5)
    pl.yticks(range(X.shape[0]), var_names)
    for ih, h in enumerate(highlightsX):
        pl.plot([h, h], [0, X.shape[0]], '--', color='black')
    pl.xlim([0, X.shape[1]-1])
    pl.ylim([0, X.shape[0]-1])
724447
def main():
    
    args = get_args()
    args.start = date_parser.parse(args.start)
    args.end = date_parser.parse(args.end)
    args.step = timedelta(args.step)
    config = Config(args.config)

    times = [args.start + i * args.step for i in range(int((args.end - args.start) / args.step))]

    for i, time in enumerate(times):
        make_plot(time, config, args.step)
57761
def plot_results(fout_png, goea_results, *args, **kws):
    """"""
    if "{NS}" not in fout_png:
        plt_goea_results(fout_png, goea_results, *args, **kws)
    else:
        # Plot separately by NS: BP, MF, CC
        ns2goea_results = cx.defaultdict(list)
        for rec in goea_results:
            ns2goea_results[rec.NS].append(rec)
        for ns_name, ns_res in ns2goea_results.items():
            png = fout_png.format(NS=ns_name)
            plt_goea_results(png, ns_res, *args, **kws)
478140
def simulation(n_obs=300, n_vars=None, alpha=None, beta=None, gamma=None, alpha_=None, t_max=None,
               noise_model='normal', noise_level=1, switches=None):
    
    from .tools.dynamical_model_utils import unspliced, spliced, vectorize

    def draw_poisson(n):
        from random import uniform  # draw from poisson
        t = np.cumsum([- .1 * np.log(uniform(0, 1)) for _ in range(n - 1)])
        return np.insert(t, 0, 0)  # prepend t0=0

    def simulate_dynamics(tau, alpha, beta, gamma, u0, s0, noise_model, noise_level):
        ut = unspliced(tau, u0, alpha, beta)
        st = spliced(tau, s0, u0, alpha, beta, gamma)

        if noise_model is 'normal':  # add noise
            ut += np.random.normal(scale=noise_level * np.percentile(ut, 99) / 10, size=len(ut))
            st += np.random.normal(scale=noise_level * np.percentile(st, 99) / 10, size=len(st))
        ut, st = np.clip(ut, 0, None), np.clip(st, 0, None)
        return ut, st

    def simulate_gillespie(alpha, beta, gamma):
        # update rules: transcription (u+1,s), splicing (u-1,s+1), degradation (u,s-1), nothing (u,s)
        update_rule = np.array([[1, 0], [-1, 1], [0, -1], [0, 0]])

        def update(props):
            if np.sum(props) > 0:
                props /= np.sum(props)
            p_cumsum = props.cumsum()
            p = np.random.rand()
            i = 0
            while p > p_cumsum[i]:
                i += 1
            return update_rule[i]

        u, s = np.zeros(len(alpha)), np.zeros(len(alpha))
        for i, alpha_i in enumerate(alpha):
            u_, s_ = (u[i - 1], s[i - 1]) if i > 0 else (0, 0)
            du, ds = update(props=np.array([alpha_i, beta * u_, gamma * s_]))
            u[i], s[i] = (u_ + du, s_ + ds)
        return u, s

    alpha = 5 if alpha is None else alpha
    beta = .5 if beta is None else beta
    gamma = .3 if gamma is None else gamma
    alpha_ = 0 if alpha_ is None else alpha_

    t = draw_poisson(n_obs)
    if t_max is not None:
        t *= t_max / np.max(t)
    t_max = np.max(t)

    def cycle(array, n_vars=None):
        if isinstance(array, (list, tuple)):
            return array if n_vars is None else array * int(np.ceil(n_vars / len(array)))
        else:
            return [array] if n_vars is None else [array] * n_vars

    # switching time point obtained as fraction of t_max rounded down
    switches = cycle([.4, .7, 1, .1], n_vars) if switches is None else cycle(switches, n_vars)
    t_ = np.array([np.max(t[t < t_i * t_max]) for t_i in switches])

    noise_level = cycle(noise_level, len(switches) if n_vars is None else n_vars)

    n_vars = max(len(switches), len(noise_level))
    U = np.zeros(shape=(len(t), n_vars))
    S = np.zeros(shape=(len(t), n_vars))
    for i in range(n_vars):
        alpha_i = alpha[i] if isinstance(alpha, (tuple, list, np.ndarray)) else alpha
        beta_i = beta[i] if isinstance(beta, (tuple, list, np.ndarray)) else beta
        gamma_i = gamma[i] if isinstance(gamma, (tuple, list, np.ndarray)) else gamma
        tau, alpha_vec, u0_vec, s0_vec = vectorize(t, t_[i], alpha_i, beta_i, gamma_i, alpha_=alpha_, u0=0, s0=0)
        beta_i
        if noise_model is 'gillespie':
            U[:, i], S[:, i] = simulate_gillespie(alpha_vec, beta, gamma)
        else:
            U[:, i], S[:, i] = simulate_dynamics(tau, alpha_vec, beta_i, gamma_i,
                                                 u0_vec, s0_vec, noise_model, noise_level[i])

    obs = {'true_t': t.round(2)}
    var = {'true_t_': t_[:n_vars],
           'true_alpha': np.ones(n_vars) * alpha,
           'true_beta': np.ones(n_vars) * beta,
           'true_gamma': np.ones(n_vars) * gamma,
           'true_scaling': np.ones(n_vars)}
    layers = {'unspliced': U, 'spliced': S}

    return AnnData(S, obs, var, layers=layers)
706485
def plot_accuracy(data, output_dir_path='.', output_filename='accuracy.png',
                  width=10, height=8):
    
    output_path = os.path.join(output_dir_path, output_filename)

    max_val_data = get_epoch_max_val_acc(data)
    max_val_label = round(max_val_data['acc'].values[0], 4)

    # max_val_epoch = max_val_data['epoch'].values[0]
    max_epoch_data = data[data['epoch'] == data['epoch'].max()]

    plot = ggplot(data, aes('epoch', 'acc', color='factor(data)')) + \
        geom_line(size=1, show_legend=False) + \
        geom_vline(aes(xintercept='epoch', color='data'),
                   data=max_val_data, alpha=0.5, show_legend=False) + \
        geom_label(aes('epoch', 'acc'), data=max_val_data,
                   label=max_val_label, nudge_y=-0.02, va='top', label_size=0,
                   show_legend=False) + \
        geom_text(aes('epoch', 'acc', label='data'), data=max_epoch_data,
                  nudge_x=2, ha='center', show_legend=False) + \
        geom_point(aes('epoch', 'acc'), data=max_val_data,
                   show_legend=False) + \
        labs(y='Accuracy', x='Epochs') + \
        theme_bw(base_family='Arial', base_size=15) + \
        scale_color_manual(['#ef8a62', '#67a9cf', "#f7f7f7"])

    plot.save(output_path, width=width, height=height)
504476
function TimeseriesHistogram( canvas, width, height, left, top ) {
		var graph, data, histogram, edges, axes, annotations, title, text, means;

		// [1] Instantiate a new graph generator and configure:
		graph = xfig.graph( canvas )
			.width( width )
			.height( height )
			.position({
				'left': left,
				'top': top
			})
			.xMin( 0 )
			.xMax( 1 );

		// Create the graph:
		graph.create( 'timeseries-histogram' );

		// Get data:
		d3.json( 'data/timeseries-histogram.data.json', function ( error, json ) {

			// [2] Instantiate a new data generator and configure:
			data = xfig.data( json )
				.accessors( 'x', function ( d ) {
					return d[ 0 ];
				})
				.accessors( 'y', function ( d ) {
					return d[ 1 ];
				});

			// Create edges to define our histogram bins:
			edges = xfig.vector.linspace( -0.025, 1.025, 0.05 );
			
			// Format the data and extract the data to histogram:
			data.format( [ 'x', 'y' ] )
				.extract( function ( d ) {
					return d[ 1 ];
				});

			// Calculate each dataset's mean value and sort the datasets based on their means:
			means = data.mean( function ( d ) {
				return d;
			});
			means = means.map( function ( d, i ) {
				return [ d, i ];
			});
			means.sort( function ( a, b ) {
				return a[0] < b[0] ? -1 : ( a[0] > b[0] ? 1 : 0 );
			});
			means = means.map( function ( d ) {
				return d[ 1 ];
			});

			// Calculate the histogram:
			data.reorder( means )
				.histc( function ( d ) { return d; }, edges );

			// Bind the data instance to the graph:
			graph.data( data )
				.yMin( 0 )
				.yMax( data.size()[0] )
				.zMin( 0 )
				.zMax( data.max( function ( d ) {
					return d[ 1 ];
				}))
				.zRange( ['#ffffff', '#000000'] );

			// [3] Instantiate a new histogram generator and configure:
			histogram = xfig.timeserieshistogram( graph );

			// Create the histogram:
			histogram.create();

			// [4] Instantiate a new axes generator and configure:
			axes = xfig.axes( graph )
				.xLabel( 'percent' )
				.yLabel( 'index' );

			// Create the axes:
			axes.create();

			// [5] Instantiate a new annotations generator and configure:
			annotations = xfig.annotations( graph );

			// Create the annotations element:
			annotations.create();

			// [5.1] Instantiate a new title instance and configure:
			title = annotations.title()
				.top( -30 )
				.left( 0 );

			// Add a (sub)title:
			title.create( 'Subtitle' );

		});

	}
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()
283085
def main():
    
    # Getting and checking the options
    args = parseArgs()
    checkArgs(args)

    # Reads the population file
    populations = readPopulations(args.population_file)

    # Acquire the data
    theData, theLabels = extractData(args.file, populations)
    theOrders = range(len(theLabels))
    theColors = [(0.215686275, 0.000494118, 0.721568627),
                 (0.301960784, 0.68627451, 0.290196078),
                 (0.596078431, 0.305882353, 0.639215686),
                 (0.894117647, 0.101960784, 0.109803922),
                 (0.596078431, 0.305882353, 0.639215686)]
    theSizes = [12, 12, 12, 8, 12]
    theMarkers = [".", ".", ".", "+", "D"]

    # Plot the data
    plotMDS(theData, theOrders, theLabels, theColors, theSizes, theMarkers,
            args)
366681
def autocorrelation_plot(time)
      r = autocorrelation time
      start = @times[:repeat].first
      ende = (start + r.size)
      (start...ende).to_a.zip(r)
    end