Ejemplo n.º 1
0
def atacseq_summary(config, input, output, Cutadapt, Qualimap,
                    MarkDuplicates, InsertMetrics, AlignmentMetrics):
    """Make atacseq summary"""
    # Dictionary of figures
    d = {}
    Cutadapt.read_aggregate_data()
    d.update({'cutadapt': {'fig': Cutadapt.plot('cutadapt')[0]}})

    Qualimap.read_aggregate_data()
    d.update({'qualimap': {'fig': {'globals': Qualimap.plot("Globals")[0],
                                   'coverage_per_contig': Qualimap.plot("Coverage_per_contig")[0]}}})
    
    InsertMetrics.read_aggregate_data()
    plist = [InsertMetrics.plot('metrics')[0]] + [x for sublist in InsertMetrics.plot("hist")[0].children for x in sublist]
    gp = gridplot([plist[i:i+3] for i in range(0, len(plist), 3)])
    d.update({'picard': {'InsertMetrics': {'atacseq' : {'fig': gp}}}})

    MarkDuplicates.read_aggregate_data()
    d['picard'].update({'DuplicationMetrics': {'atacseq':
                                               {'fig':
                                                gridplot([[MarkDuplicates.plot('metrics')[0],
                                                           MarkDuplicates.plot('hist')[0]]])}}})

    d.update({'rulegraph' : {'fig' : input.rulegraph, 'uri': data_uri(input.rulegraph),
                             'target' : 'atacseq_all'}})

    # Write the resulting html
    tp = Env.get_template('workflow_atacseq_qc.html')
    with open(output.html, "w") as fh:
        fh.write(static_html(tp, template_variables=d, css_raw=css_files))
Ejemplo n.º 2
0
def plot_LP_YP(file, outfile='Lx-P.html',
      title='L-P Relation for Radio Halo Clusters',
      categories = ["Limit+SZ", "Limit-SZ", "RHclusters"],
      colors=['#462066', '#00AAA0', '#FF7A5A'],
      label_font_size='10pt', title_font_size='12pt',
      x_axis_type="log", y_axis_type="log",
      legend=["Upper limits on RH power, with SZ",
        "Upper limits on RH power, no SZ", "RH detections"],
      TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,hover,hover,hover,previewsave",
      withSZ=False, withLP=True, withLineEq=False):

    clusters = filter_clusters(file)
    output_file(outfile, title=title)


    if withSZ == True and withLP == True:
        p1 = plot_LP(clusters, withLineEq=withLineEq, ysize=375)
        p2 = plot_YP(clusters, withLineEq=withLineEq, ysize=375)
        p2.y_range = p1.y_range
        p = gridplot([[p1],[p2]], toolbar_location='above')
        show(p)
    elif withLP != True and withSZ == True:
        p2 = plot_YP(clusters, withLineEq=withLineEq)
        show(p2)
    elif withLP == True and withSZ != True:
        p1 = plot_LP(clusters, withLineEq=withLineEq)
        show(p1)
Ejemplo n.º 3
0
def render_basic(
    itmdt: Intermediate,
    yscale: str,
    plot_width: int,
    plot_height: int,
) -> Box:
    """
    Render plots from plot(df)
    """
    figs = list()
    for col, dtype, data in itmdt["data"]:
        if dtype == DType.Categorical:
            df, total_grps, miss_pct = data
            fig = bar_viz(
                df[:-1],
                total_grps,
                miss_pct,
                col,
                yscale,
                plot_width,
                plot_height,
                False,
            )
            figs.append(fig)
        elif dtype == DType.Numerical:
            df, miss_pct = data
            fig = hist_viz(df, miss_pct, col, yscale, plot_width, plot_height,
                           False)
            figs.append(fig)
    return gridplot(
        children=figs,
        sizing_mode=None,
        toolbar_location=None,
        ncols=3,
    )
Ejemplo n.º 4
0
def plot_LP_YP(
        file,
        outfile='Lx-P.html',
        title='L-P Relation for Radio Halo Clusters',
        categories=["Limit+SZ", "Limit-SZ", "RHclusters"],
        colors=['#462066', '#00AAA0', '#FF7A5A'],
        label_font_size='10pt',
        title_font_size='12pt',
        x_axis_type="log",
        y_axis_type="log",
        legend=[
            "Upper limits on RH power, with SZ",
            "Upper limits on RH power, no SZ", "RH detections"
        ],
        TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,hover,hover,hover,previewsave",
        withSZ=False,
        withLP=True,
        withLineEq=False):

    clusters = filter_clusters(file)
    output_file(outfile, title=title)

    if withSZ == True and withLP == True:
        p1 = plot_LP(clusters, withLineEq=withLineEq, ysize=375)
        p2 = plot_YP(clusters, withLineEq=withLineEq, ysize=375)
        p2.y_range = p1.y_range
        p = gridplot([[p1], [p2]], toolbar_location='above')
        show(p)
    elif withLP != True and withSZ == True:
        p2 = plot_YP(clusters, withLineEq=withLineEq)
        show(p2)
    elif withLP == True and withSZ != True:
        p1 = plot_LP(clusters, withLineEq=withLineEq)
        show(p1)
Ejemplo n.º 5
0
def fig1(xs, g, P_sb, P_sc, I, R=8.4/2):
    """Compute y-values, and lay out Fig. 1 plots."""

    kwargs = {}

    ys_1a        = [g(x, 8.4) for x in xs]
    ys_1a_dashed = [g(x, R)   for x in xs]
    fig1a, data_1a = curve(xs, ys_1a, ys_1a_dashed, y_range=[-0.5, 15],
                           title='Child growth curve', **kwargs)
    fig1a.xaxis.axis_label = "Age (month)"
    fig1a.yaxis.axis_label = "Head radius R (cm)"

    ys_1b        = [P_sb(x, 8.4) for x in xs]
    ys_1b_dashed = [P_sb(x, R)   for x in xs]
    fig1b, data_1b = curve(xs, ys_1b, ys_1b_dashed, y_range=[-0.05, 1.05],
                           title='Birth survival curve', **kwargs)
    fig1b.xaxis.axis_label = "Birth Age T (month)"
    fig1b.yaxis.axis_label = "P(survive birth)"

    ys_1c        = [P_sc(x, I(8.4)) for x in xs]
    ys_1c_dashed = [P_sc(x, I(R))   for x in xs]
    fig1c, data_1c = curve(xs, ys_1c, ys_1c_dashed, y_range=[-0.05, 1.05],
                           title='Childhood survival curve', **kwargs)
    fig1c.xaxis.axis_label = "Time until maturity M (month)"
    fig1c.yaxis.axis_label = "P(survive childhood)"


    fig = bkp.gridplot([[fig1a, fig1b, fig1c]])
    # fig.toolbar.location = None

    handle = bkp.show(fig, notebook_handle=True)
    return handle, (data_1a, data_1b, data_1c)
Ejemplo n.º 6
0
def plot_bokeh_correlations(filepath, nonan=1):
    from bokeh.plotting import figure, gridplot
    head, data, nresp = read_mml_evaldb_nd(filepath, nonan=nonan)

    # create xy scatter plots
    y = data[:, -nresp]
    sort = np.argsort(y)
    y = y[sort]

    keys = head[:-nresp]
    colors = ('blue', 'green', 'red', 'cyan',
              'maroon', 'yellow', 'black', 'white')

    ylabel = r"{0}".format(head[-1])
    plots = []
    for i, key in enumerate(keys):
        x = data[:, i][sort]
        m2, m, b = np.polyfit(x, y, 2)
        m2, (m, b) = 0, np.polyfit(x, y, 1)
        TOOLS = "pan,wheel_zoom,box_zoom,reset,save,resize"
        y_axis_label = ylabel if not i else None
        p = figure(tools=TOOLS, x_axis_label=r'{0}'.format(key),
                   y_axis_label=y_axis_label)
        p.scatter(x, y, color=colors[i])
        p.line(x, m2 * x * x + m * x + b, color='black')
        plots.append(p)
    return gridplot([plots])
Ejemplo n.º 7
0
def bokeh_linked():
    """these are taken EXACTLY from
    http://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html

    """
    # prepare some data
    N = 100
    x = np.linspace(0, 4*np.pi, N)
    y0 = np.sin(x)
    y1 = np.cos(x)
    y2 = np.sin(x) + np.cos(x)

    # create a new plot
    s1 = bkp.figure(width=250, plot_height=250, title=None)
    s1.circle(x, y0, size=10, color="navy", alpha=0.5)

    # NEW: create a new plot and share both ranges
    s2 = bkp.figure(
        x_range=s1.x_range, y_range=s1.y_range, width=250, plot_height=250,
        title=None
    )
    s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5)

    # NEW: create a new plot and share only one range
    s3 = bkp.figure(x_range=s1.x_range, width=250, plot_height=250, title=None)
    s3.square(x, y2, size=10, color="olive", alpha=0.5)

    # NEW: put the subplots in a gridplot
    p = bkp.gridplot([[s1, s2, s3]], toolbar_location=None)

    return bke.components(p)
Ejemplo n.º 8
0
def bokeh_brushed():
    """these are taken EXACTLY from
    http://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html

    """
    # prepare some date
    N = 300
    x = np.linspace(0, 4*np.pi, N)
    y0 = np.sin(x)
    y1 = np.cos(x)

    # NEW: create a column data source for the plots to share
    source = bkm.ColumnDataSource(data=dict(x=x, y0=y0, y1=y1))

    # create a new plot and add a renderer
    left = bkp.figure(tools=BOKEH_TOOLS, width=350, height=350, title=None)
    left.circle('x', 'y0', source=source)

    # create another new plot and add a renderer
    right = bkp.figure(tools=BOKEH_TOOLS, width=350, height=350, title=None)
    right.circle('x', 'y1', source=source)

    # put the subplots in a gridplot
    p = bkp.gridplot([[left, right]])

    return bke.components(p)
Ejemplo n.º 9
0
def bokeh_plot(df):
    tooltip = """
        <div>
            <div>
                <img
                src="@image_files" height="60" alt="image"
                style="float: left; margin: 0px 15px 15px 0px; image-rendering: pixelated;"
                border="2"
                ></img>
            </div>
            <div>
                <span style="font-size: 17px;">@source_filenames</span>
            </div>
        </div>
              """
    filenames = b64_image_files(df['images'])
    df['image_files'] = filenames
    colors_raw = cm.viridis((df['time'] - df['time'].min()) /
                            (df['time'].max() - df['time'].min()), bytes=True)
    colors_str = ['#%02x%02x%02x' % tuple(c[:3]) for c in colors_raw]
    df['color'] = colors_str
    source = ColumnDataSource(df)
    bplot.output_file('plot.html')
    hover0 = HoverTool(tooltips=tooltip)
    hover1 = HoverTool(tooltips=tooltip)
    tools0 = [t() for t in TOOLS] + [hover0]
    tools1 = [t() for t in TOOLS] + [hover1]
    pca = bplot.figure(tools=tools0)
    pca.circle('PC1', 'PC2', color='color', source=source)
    tsne = bplot.figure(tools=tools1)
    tsne.circle('tSNE-0', 'tSNE-1', color='color', source=source)
    p = bplot.gridplot([[pca, tsne]])
    bplot.show(p)
Ejemplo n.º 10
0
def plot_bias_variance(N=8, random_seed=42, err=0.5):
    np.random.seed(random_seed)
    x = 10 ** np.linspace(-2, 0, N)
    y = test_func(x)
    xfit = np.linspace(-0.2, 1.2, 1000)
    titles = ['d = 1 (under-fit; high bias)',
              'd = 2',
              'd = 6 (over-fit; high variance)']
    degrees = [1, 2, 6]
    
    row = []
    for i, d in enumerate(degrees):
        fig = bk.figure(plot_width=240, plot_height=240,
                        title=titles[i], x_range=(-0.2, 1.2), y_range=(0, 12))
        fig.title_text_font_size = '11pt'
        fig.xaxis.axis_label_text_font_size = '9pt'
        fig.yaxis.axis_label_text_font_size = '9pt'
        fig.x(x, y, color='black', size=12)
        
        p = np.polyfit(x, y, d)
        yfit = np.polyval(p, xfit)
        fig.line(xfit, yfit, line_color='blue')
        
        fig.xaxis.axis_label = 'house size'
        fig.xaxis.axis_label_text_font_size = '9pt'
        if i == 0:
            fig.yaxis.axis_label = 'price'
        row.append(fig)

    gp = bk.gridplot([row], border_space=0)
    bk.show(gp)
Ejemplo n.º 11
0
def bokeh_brushed():
    """these are taken EXACTLY from
    http://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html

    """
    # prepare some date
    N = 300
    x = np.linspace(0, 4 * np.pi, N)
    y0 = np.sin(x)
    y1 = np.cos(x)

    # NEW: create a column data source for the plots to share
    source = bkm.ColumnDataSource(data=dict(x=x, y0=y0, y1=y1))

    # create a new plot and add a renderer
    left = bkp.figure(tools=BOKEH_TOOLS, width=350, height=350, title=None)
    left.circle('x', 'y0', source=source)

    # create another new plot and add a renderer
    right = bkp.figure(tools=BOKEH_TOOLS, width=350, height=350, title=None)
    right.circle('x', 'y1', source=source)

    # put the subplots in a gridplot
    p = bkp.gridplot([[left, right]])

    return bke.components(p)
Ejemplo n.º 12
0
def bokeh_linked():
    """these are taken EXACTLY from
    http://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html

    """
    # prepare some data
    N = 100
    x = np.linspace(0, 4 * np.pi, N)
    y0 = np.sin(x)
    y1 = np.cos(x)
    y2 = np.sin(x) + np.cos(x)

    # create a new plot
    s1 = bkp.figure(width=250, plot_height=250, title=None)
    s1.circle(x, y0, size=10, color="navy", alpha=0.5)

    # NEW: create a new plot and share both ranges
    s2 = bkp.figure(x_range=s1.x_range,
                    y_range=s1.y_range,
                    width=250,
                    plot_height=250,
                    title=None)
    s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5)

    # NEW: create a new plot and share only one range
    s3 = bkp.figure(x_range=s1.x_range, width=250, plot_height=250, title=None)
    s3.square(x, y2, size=10, color="olive", alpha=0.5)

    # NEW: put the subplots in a gridplot
    p = bkp.gridplot([[s1, s2, s3]], toolbar_location=None)

    return bke.components(p)
Ejemplo n.º 13
0
def plot_cohort_employment(dataf):
    dataf = dataf.copy()

    plts = []
    subset_dict = {
        'male_west': [0, 0],
        'male_east': [0, 1],
        'female_west': [1, 0],
        'female_east': [1, 1],
    }

    for name, vals in subset_dict.items():
        data = data_cohort_employment(dataf, vals)
        cols = data.columns.tolist()
        cols.remove("age")
        p = figure(title=name)

        for ind, var in enumerate(cols):
            p.line(y=data[var],
                   x=data['age'],
                   legend_label=var,
                   color=Spectral6[ind],
                   line_width=2)
        plts.append(p)

    p = gridplot([[plts[0], plts[1]], [plts[2], plts[3]]])
    return p
Ejemplo n.º 14
0
def plot_stepdb(df) -> None:
    """plot step distribution

    Parameters
    ----------
    df : DataFrame
        outcome of cal_stepinfo with duration, ap_ptp, ml_ptp, balance, LR
    """

    f_amp = figure(width=300,
                   height=300,
                   title='Step Duration vs Amplitude',
                   x_axis_label='Duration [s]',
                   y_axis_label='ptp Magnitude [g]')
    f_amp.circle(df.duration, df.ap_ptp, color=df.LR)
    f_bal = figure(width=300,
                   height=300,
                   title='Balance Check',
                   x_axis_label='Duration Right [s]',
                   y_axis_label='Duration Left [s]')
    f_bal.circle(df.duration.loc[df.balance > 0],
                 df.duration.loc[df.balance <= 0],
                 color='black')
    f_bal.line([df.duration.min(), df.duration.max()],
               [df.duration.min(), df.duration.max()])

    fig = gridplot([f_amp, f_bal], ncols=2)

    show(fig)

    export_png(fig, filename='steps_info.png')
Ejemplo n.º 15
0
def plot_bias_variance(N=8, random_seed=42, err=0.5):
    np.random.seed(random_seed)
    x = 10**np.linspace(-2, 0, N)
    y = test_func(x)
    xfit = np.linspace(-0.2, 1.2, 1000)
    titles = [
        'd = 1 (under-fit; high bias)', 'd = 2',
        'd = 6 (over-fit; high variance)'
    ]
    degrees = [1, 2, 6]

    row = []
    for i, d in enumerate(degrees):
        fig = bk.figure(plot_width=240,
                        plot_height=240,
                        title=titles[i],
                        x_range=(-0.2, 1.2),
                        y_range=(0, 12))
        fig.title_text_font_size = '11pt'
        fig.xaxis.axis_label_text_font_size = '9pt'
        fig.yaxis.axis_label_text_font_size = '9pt'
        fig.x(x, y, color='black', size=12)

        p = np.polyfit(x, y, d)
        yfit = np.polyval(p, xfit)
        fig.line(xfit, yfit, line_color='blue')

        fig.xaxis.axis_label = 'house size'
        fig.xaxis.axis_label_text_font_size = '9pt'
        if i == 0:
            fig.yaxis.axis_label = 'price'
        row.append(fig)

    gp = bk.gridplot([row], border_space=0)
    bk.show(gp)
Ejemplo n.º 16
0
def bokeh_plot(df):
    tooltip = """
        <div>
            <div>
                <img
                src="@image_files" height="60" alt="image"
                style="float: left; margin: 0px 15px 15px 0px; image-rendering: pixelated;"
                border="2"
                ></img>
            </div>
            <div>
                <span style="font-size: 17px;">@source_filenames</span>
            </div>
        </div>
              """
    filenames = b64_image_files(df['images'])
    df['image_files'] = filenames
    colors_raw = cm.viridis((df['time'] - df['time'].min()) /
                            (df['time'].max() - df['time'].min()),
                            bytes=True)
    colors_str = ['#%02x%02x%02x' % tuple(c[:3]) for c in colors_raw]
    df['color'] = colors_str
    source = ColumnDataSource(df)
    bplot.output_file('plot.html')
    hover0 = HoverTool(tooltips=tooltip)
    hover1 = HoverTool(tooltips=tooltip)
    tools0 = [t() for t in TOOLS] + [hover0]
    tools1 = [t() for t in TOOLS] + [hover1]
    pca = bplot.figure(tools=tools0)
    pca.circle('PC1', 'PC2', color='color', source=source)
    tsne = bplot.figure(tools=tools1)
    tsne.circle('tSNE-0', 'tSNE-1', color='color', source=source)
    p = bplot.gridplot([[pca, tsne]])
    bplot.show(p)
Ejemplo n.º 17
0
def plot_bokeh_correlations(filepath, nonan=1):
    from bokeh.plotting import figure, gridplot
    head, data, nresp = read_mml_evaldb_nd(filepath, nonan=nonan)

    # create xy scatter plots
    y = data[:, -nresp]
    sort = np.argsort(y)
    y = y[sort]

    keys = head[:-nresp]
    colors = ('blue', 'green', 'red', 'cyan', 'maroon', 'yellow', 'black',
              'white')

    ylabel = r"{0}".format(head[-1])
    plots = []
    for i, key in enumerate(keys):
        x = data[:, i][sort]
        m2, m, b = np.polyfit(x, y, 2)
        m2, (m, b) = 0, np.polyfit(x, y, 1)
        TOOLS = "pan,wheel_zoom,box_zoom,reset,save,resize"
        y_axis_label = ylabel if not i else None
        p = figure(tools=TOOLS,
                   x_axis_label=r'{0}'.format(key),
                   y_axis_label=y_axis_label)
        p.scatter(x, y, color=colors[i])
        p.line(x, m2 * x * x + m * x + b, color='black')
        plots.append(p)
    return gridplot([plots])
def plot_comparaison_bokeh(df_probs, rep_visualisation):
    """
    courbe pour comparer les dc_0, dc_0.5
                             dh_0, dh_0.5
                             correl_dc_dh_0, correl_dc_dh_0.5
    """
    for k_erreur in df_probs["k_erreur"].unique():
        df_k = df_probs[df_probs["k_erreur"] == k_erreur]
        df_k.fillna(-5, inplace=True)
        df_k['graph_number'] = np.arange(1, df_k.shape[0] + 1)

        output_file(rep_visualisation + "/" +
                    "comparaison_dashboard_p0_p05_k_" + str(k_erreur) +
                    ".html")
        #dc
        dcs = ["dc_0", "dc_0.5"]
        p_dc = plot_compa_cols_k(df_k, dcs, k_erreur)
        #dh
        dhs = ["dh_0", "dh_0.5"]
        p_dh = plot_compa_cols_k(df_k, dhs, k_erreur)
        #correl
        correls = ["correl_dc_dh_0", "correl_dc_dh_0.5"]
        p_correl = plot_compa_cols_k(df_k, correls, k_erreur)
        #runtime
        runtimes = ["runtime_0", "runtime_0.5"]
        p_runtime = plot_compa_cols_k(df_k, runtimes, k_erreur)

        p = gridplot([[p_dc, p_dh, p_correl, p_runtime]],
                     toolbar_location='above')
        show(p)
def make_plot(title1, plot1, title2, plot2, title3, plot3, title4, plot4,
              title5, plot5, sample_df):
    plot1.title = title1
    plot2.title = title2
    plot3.title = title3
    plot4.title = title4
    plot5.title = title5
    plot1.yaxis.axis_label = data_dict['DO']['title']
    plot1.yaxis.axis_label_text_font_style = "italic"
    plot2.yaxis.axis_label = data_dict['Ammonium']['title']
    plot2.yaxis.axis_label_text_font_style = "italic"
    plot3.yaxis.axis_label = data_dict['pH']['name']
    plot3.yaxis.axis_label_text_font_style = "italic"
    plot4.yaxis.axis_label = data_dict['N2 Mass Flow Controller']['title']
    plot4.yaxis.axis_label_text_font_style = "italic"
    plot5.yaxis.axis_label = data_dict['Air Mass Flow Controller']['title']
    plot5.yaxis.axis_label_text_font_style = "italic"
    plot1.line(x=sample_df.index, y=sample_df[title1], color="navy")
    plot2.line(x=sample_df.index, y=sample_df[title2], color="firebrick")
    plot3.line(x=sample_df.index,
               y=sample_df[title3],
               color="#28D0B4",
               line_width=2)
    plot4.line(x=sample_df.index, y=sample_df[title4], color="orange")
    plot5.line(x=sample_df.index, y=sample_df[title5], color="black")
    p = gridplot([[plot1, plot2, plot3], [plot4, plot5, None]])
    return p
Ejemplo n.º 20
0
def create_plot(team="LAA", year=2012):
    expr = bz.by(db.Salaries.teamID,
                 avg=db.Salaries.salary.mean(),
                 max=db.Salaries.salary.max(),
                 ratio=db.Salaries.salary.max() / db.Salaries.salary.min())
    expr = expr.sort('ratio', ascending=False)

    df_salary_gb = into(pd.DataFrame, expr)
    source1 = into(ColumnDataSource, df_salary_gb[["teamID", "avg"]])

    plot1 = plt.figure(title="Salary ratio by team", x_range=list(df_salary_gb["teamID"]))
    plot1.scatter(x="teamID", y="avg", source=source1, size=20)
    plot1.xaxis.major_label_orientation = np.pi/3

    df = into(pd.DataFrame, db.Salaries)
    df = df[df["teamID"] == team]
    df = df[df["yearID"] == year]

    df = df[["playerID","salary"]].sort('salary')
    source_team = into(ColumnDataSource, df)
    p_team = plt.figure(title="Salary of players for %s during %s" % (team, year),
                        x_range=list(df["playerID"]))#, tools=TOOLS)
    p_team.scatter(x="playerID", y="salary", source=source_team, size=20)
    p_team.xaxis.major_label_orientation = np.pi/3

    p = plt.gridplot([[plot1, p_team]])
    return p
Ejemplo n.º 21
0
def make_rseqc_summary_plots(rd_file, gc_file, do_qc=True, min_exonmap=60.0, max_three_prime_map=10.0):
    """Make rseqc summary plots"""
    df_rd = pd.read_csv(rd_file, index_col=0)
    df_gc = pd.read_csv(gc_file, index_col=0)
    samples = list(df_gc.index)
    # Use tags for formula 
    df = df_rd.pivot_table(columns=["Group"], values=["Tag_count"], index="sample")
    df['Tag_count', "ExonMap"] = 100.0 * (df['Tag_count', "CDS_Exons"] + df['Tag_count', "3'UTR_Exons"] + df['Tag_count', "5'UTR_Exons"]) / df['Tag_count', "Total_Assigned_Tags"]

    df.columns = df.columns.droplevel()
    df['i'] = list(range(0, len(df.index)))
    df['samples'] = samples
    df_gc["three_prime_map"] = 100.0 * df_gc.loc[:, "91":"100"].sum(axis=1) / df_gc.loc[:, "1":"100"].sum(axis=1)
    df = pd.concat([df, df_gc], axis=1)

    colors = brewer["PiYG"][3]
    colormap = {'False' : colors[0], 'True' : colors[2]}
    columns = [
        TableColumn(field="samples", title="Sample"),
        TableColumn(field="ExonMap", title="Tags mapping to exons (%)"),
        TableColumn(field="3' Map", title="Tags mapping to 3' end (%)"),
    ]
    source = ColumnDataSource(df)

    # Default tools, plot_config and tooltips
    TOOLS="pan,box_zoom,box_select,lasso_select,reset,save,hover"
    plot_config=dict(plot_width=300, plot_height=300, 
                     tools=TOOLS, title_text_font_size='12pt',
                     x_range=[0, len(samples)], y_range=[0, 105],
                     x_axis_type=None, y_axis_type="linear", 
                     xaxis={'axis_label' : "sample", 'major_label_orientation' : np.pi/3, 'axis_label_text_font_size' : '10pt'}, 
                     yaxis={'axis_label' : "percent (%)", 'major_label_orientation' : 1, 'axis_label_text_font_size' : '10pt'})

    # Exonmap plot
    qc = QCArgs(x=[0,len(samples)], 
                y=[min_exonmap, min_exonmap], 
                line_dash=[2,4]) if do_qc else None
    c1 = list(map(lambda x: colormap[str(x)], 
                  df['ExonMap'] < min_exonmap)) if do_qc else colors[0]
    p1 = scatterplot(x='i', y='ExonMap', 
                     source=source, color=c1, qc=qc, 
                     tooltips = [{'type':HoverTool, 'tips' : [
                         ('Sample', '@samples'),('ExonMap', '@ExonMap'),]}], 
                     title="Tags mapping to exons", **plot_config)
    # Fraction reads mapping to the 10% right-most end
    qc = QCArgs(x=[0,len(samples)], 
                y=[max_three_prime_map, max_three_prime_map], 
                line_dash=[2,4]) if do_qc else None
    c2 = list(map(lambda x: colormap[str(x)], 
                  df['three_prime_map'] > max_three_prime_map)) if do_qc else colors[0]
    p2 = scatterplot(x = 'i', y = 'three_prime_map', 
                     color = c2, source = source, 
                     qc=qc,
                     tooltips = [{'type':HoverTool, 'tips' : [
                         ('Sample', '@samples'),('ExonMap', '@ExonMap'),]}], 
                     title="Reads mapping to 3' end", **plot_config)

    return {'fig' : gridplot([[p1, p2]]),
            'uri' : [data_uri(rd_file), data_uri(gc_file)],
            'file' : [rd_file, gc_file]}
Ejemplo n.º 22
0
def simple_chart(request):
    plot = figure()
    import numpy as np
    # x = np.arange(-10,10,0.1)
    # y = np.arange(-10,10,0.1)
    # plot.circle([1,2], [3,4])
    script, div = components(plot, CDN)


    tp, hp = np.loadtxt('/Users/sebastian/phd/data/phenEOB-data/phenP/hp.dat').T
    tc, hc = np.loadtxt('/Users/sebastian/phd/data/phenEOB-data/phenP/hc.dat').T

    # select the tools we want
    # TOOLS="reset,pan,wheel_zoom,box_zoom,save"


    # p1 = figure(tools=TOOLS, plot_width=300*2, plot_height=300)
    p1 = figure(plot_width=300*2, plot_height=300)
    p1.line(tp, hp, color="red", alpha=0.5)

    # p2 = figure(tools=TOOLS, plot_width=300*2, plot_height=300, x_range=p1.x_range, y_range=p1.y_range,)
    p2 = figure(plot_width=300*2, plot_height=300, x_range=p1.x_range, y_range=p1.y_range,)
    p2.line(tc, hc, color="blue", alpha=0.5)
    from bokeh.plotting import gridplot
    p = gridplot([[p1],[p2]])

    # plots = {'Red': p1, 'Blue': p2}

    # script, div = components(plots)
    script, div = components(p)

    return render(request, "bokplot/simple_chart.html", {"the_script": script, "the_div": div})
Ejemplo n.º 23
0
def plot_LP_YP(file, outfile='Lx-P.html',
      title='L-P Relation for Radio Halo Clusters',
      categories = ["Limit+SZ", "Limit-SZ", "RHclusters"],
      colors=['#462066', '#00AAA0', '#FF7A5A'],
      xaxis_label='0.1-2.4 keV X-ray Luminosity (x 1E+44 erg/s)',
      yaxis_label='1.4 GHz Radio Halo Power (x 1E+24 W/Hz)',
      label_font_size='14pt', title_font_size='16pt',
      x_range=[1, 50], y_range=[0.1,100], xsize=600, ysize=600,
      x_axis_type="log", y_axis_type="log",
      legend=["Upper limits on RH power, with SZ",
        "Upper limits on RH power, no SZ", "RH detections"],
      TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,hover,hover,hover,previewsave",
      withSZ=False, withLP=True):

    clusters = filter_clusters(file)
    output_file(outfile, title=title)


    if withSZ == True and withLP == True:
        p1 = plot_LP(clusters)
        p2 = plot_YP(clusters)
        p2.y_range = p1.y_range
        p = gridplot([[p1,p2]], toolbar_location='above')
        show(p)
    elif withLP != True and withSZ == True:
        p2 = plot_YP(clusters)
        show(p2)
    elif withLP == True and withSZ != True:
        p1 = plot_LP(clusters)
        show(p1)
Ejemplo n.º 24
0
    def apply(self, func, **kwargs):

        # create a figure with specified layout
        d = [[] for _ in range(len(self.layout))]

        for i, row in enumerate(self.layout):

            is_bottom = ((i + 1) == len(self.layout))

            for j, seqid in enumerate(row):

                is_left = (j == 0)

                if seqid is not None:

                    contig_size = len(self.genome[seqid])
                    px = int(contig_size * 1e-6 * self.plot_width_per_mb)
                    px += self.min_border_left
                    px += self.min_border_right

                    try:
                        yrange = s1.y_range
                    except NameError:
                        yrange = None

                    s1 = figure(width=px,
                                plot_height=self.figheight,
                                min_border_left=self.min_border_left,
                                min_border_right=self.min_border_right,
                                tools=self.tools,
                                title=self.chrom_label_func(seqid),
                                y_range=yrange,
                                x_range=(1, contig_size))

                    s1.xaxis.ticker = FixedTicker(
                        ticks=np.arange(0, contig_size, self.major_tick_dist))
                    s1.xaxis[0].formatter = NumeralTickFormatter(format="0a.0")

                    # handle general plot things specific to genome not data
                    if self.pfunc is not None:
                        self.pfunc(seqid, s1)

                    # function lives here
                    func(self.genome[seqid],
                         s1,
                         is_left=is_left,
                         is_bottom=is_bottom,
                         **kwargs)
                    d[i].append(s1)

                else:
                    d[i].append(None)

        # put the subplots in a grid plot
        p = gridplot(d,
                     toolbar_location="left",
                     sizing_mode='fixed',
                     plot_width=None)

        show(p)
Ejemplo n.º 25
0
def plot_candlestick(inputDf: pd.DataFrame, dateStart: str = "19000101", ma1Period: int = 0, ma2Period: int = 0, 
                     stochPeriod: int = 10, 
                     close: str = "<CLOSE>", open: str = "<OPEN>", high: str = "<HIGH>", low: str = "<LOW>",
                     ticker: str = "<TICKER>", vol: str = "<VOL>") -> None:
    df = inputDf.copy()
    w = 12*60*60*1000 # half day in ms
    if ma1Period > 0:
        df['MA_'+str(ma1Period)] = df[close].rolling(ma1Period).mean()
    if ma2Period > 0:
        df['MA_'+str(ma2Period)] = df[close].rolling(ma2Period).mean()
    
    df = df.loc[df.index >= dateStart]
    inc = df[close] > df[open]
    dec = df[open] > df[close]
    TOOLS = "crosshair,pan,wheel_zoom,box_zoom,reset,save"

    df["%K"] = (100 
                * (df[close] - df[close].rolling(stochPeriod).min()) 
                / (df[close].rolling(stochPeriod).max() - df[close].rolling(stochPeriod).min()))
    df["%D"] = df["%K"].rolling(3).mean()
    df["%D-slow"] = df["%D"].rolling(2).mean()
    
    pp = figure(x_axis_type="datetime", tools=TOOLS, plot_width=1000, title = df[ticker].values[0])
    ppv = figure(x_axis_type="datetime", x_range=pp.x_range, tools=TOOLS, 
                 plot_width=1000, plot_height=200, title="VOLUME")
    ppstoch = figure(x_axis_type="datetime", x_range=pp.x_range, tools=TOOLS, 
                     plot_width=1000, plot_height=200, title="STOCH")
    
    pp.xaxis.major_label_orientation = pi/4
    pp.xaxis.ticker.desired_num_ticks = 60
    pp.yaxis.ticker.desired_num_ticks = 20
    pp.grid.grid_line_alpha=0.3
    
    ppv.xaxis.major_label_orientation = pi/4
    ppv.xaxis.ticker.desired_num_ticks = 60
    ppv.yaxis.ticker.desired_num_ticks = 5
    ppv.grid.grid_line_alpha=0.3
    
    ppstoch.xaxis.major_label_orientation = pi/4
    ppstoch.xaxis.ticker.desired_num_ticks = 60
    ppstoch.yaxis.ticker.desired_num_ticks = 5
    ppstoch.grid.grid_line_alpha=0.3

    pp.segment(df.index, df[high], df.index, df[low], color="black")
    pp.vbar(df.index[inc], w, df[open][inc], df[close][inc], fill_color="#D5E1DD", line_color="black")
    pp.vbar(df.index[dec], w, df[open][dec], df[close][dec], fill_color="#F2583E", line_color="black")
    pp.add_tools(HoverTool(tooltips=[( 'price',  '$y')]))
    if ma1Period > 0:
        pp.line(df.index, df['MA_'+str(ma1Period)], color="blue")
    if ma2Period > 0:
        pp.line(df.index, df['MA_'+str(ma2Period)], color="red")
    ppv.vbar(df.index, w, 0, df[vol], fill_color="#F2583E", line_color="black")
    
    ppstoch.line(df.index, df['%D'], color="red")
    ppstoch.line(df.index, df['%D-slow'], color="green")
    
    gg = gridplot([[pp], [ppv], [ppstoch]])
    
    show(gg)  # open a browser
def plot_errors(filepath, pred_errors, baseline_errors, show_plot=True):
    """Create a plot to evaluate the model against the baseline.

    This function uses the Bokeh plotting library to create an html document
    comparing model performance to baseline for each cohort.

    Args:
        filepath (string): The file and path of the html document.
        pred_errors (pandas.DataFrame): The model outputs from `estimate_cohort_rates`.
        baseline_errors (pandas.Series): The absolute difference between the actual
            conversion rates for each cohort and a global conversionrate (across all
            cohorts).
        show_plot (bool): If True, open the html document in the browser. If False,
            just output the Bokeh plot object.

    Returns:
        bokeh.plotting.figure.Figure: If show_plot is False, return the plot object.
        Otherwise, return nothing.

    """

    if show_plot:
        output_file(filepath)

    # create one plot for each cohort group (defined by trial date)
    grid_list = []
    for trial_date in pred_errors.index:
        baseline = baseline_errors[trial_date]
        days = pred_errors['fold_1'].columns.tolist()
        baselines = [baseline for d in days]

        plot = figure(plot_width=250,
                      plot_height=200,
                      x_axis_label='day from ' +
                      trial_date.strftime('%Y-%m-%d'),
                      y_axis_label='error',
                      y_range=[0.0, 0.075],
                      toolbar_location=None)

        # plot one gray line for each fold of the model validation
        for fold in [
                l for l in pred_errors.columns.get_level_values(0).unique()
                if 'fold' in l
        ]:
            plot.line(days,
                      pred_errors.loc[trial_date, fold].tolist(),
                      line_width=1,
                      line_color='grey')

        # add a black line for the baseline
        plot.line(days, baselines, line_width=1, line_color='black')
        grid_list.append(plot)

    gp = gridplot(grid_list, ncols=3, toolbar_location=None)

    if show_plot:
        show(gp)
    else:
        return gp
def renderPlot(s1, s2, s3):
    p = gridplot(([[s1, s2, s3]]))
    output_file(
        "C:\\Users\\SROY\\Desktop\\Courses\\CS513\\Project\\DTM_Scatter.html",
        title="Digital Terrain Model")
    print("Opening Browser")
    show(p)  # open a browser
    return 0
Ejemplo n.º 28
0
def show(grid):
    """Display graphs, accepts a list of list of figures.

    The postures(), goals() and effects() functions display their
    graphs automatically unless the keyword argument `show` is set
    to False.
    """
    bkp.show(bkp.gridplot(grid))
Ejemplo n.º 29
0
def show(grid):
    """Display graphs, accepts a list of list of figures.

    The postures(), goals() and effects() functions display their
    graphs automatically unless the keyword argument `show` is set
    to False.
    """
    bkp.show(bkp.gridplot(grid))
Ejemplo n.º 30
0
def plot_layer(data, title, dim, layer_plot_directory):
    bplt.output_file(os.path.join(layer_plot_directory, title + ".html"))
    data = data.detach().cpu().numpy()
    if dim == 2:
        data1 = data[:, 0]
        data2 = data[:, 1]
        p1 = bplt.figure(title=title + "_1")
        p1.line(np.arange(len(data1)), data1)
        p1.xaxis.axis_label = "frames"
        p1.yaxis.axis_label = "features range and mean: " + str(np.min(data1)) + ", " + str(np.max(data1)) + \
                              ", " + str(np.mean(data1))
        p2 = bplt.figure(title=title + "_2")
        p2.line(np.arange(len(data2)), data2)
        p2.xaxis.axis_label = "frames"
        p2.yaxis.axis_label = "features range and mean: " + str(np.min(data2)) + ", " + str(np.max(data2)) + \
                              ", " + str(np.mean(data2))
        bplt.save(bplt.gridplot([p1], [p2]))
    if dim == 3:
        data1 = data[:, 0, :]
        data2 = data[:, 1, :]
        p1 = bplt.figure(x_range=(0, data1.shape[0]),
                         y_range=(0, data1.shape[1]),
                         title=title + "_1")
        p1.image(image=[np.log(data1 + np.abs(np.min(data1)) + 1e-10).T],
                 x=[0],
                 y=[0],
                 dw=[data1.shape[0]],
                 dh=[data1.shape[1]],
                 palette='Greys256')
        p1.xaxis.axis_label = "frames"
        p1.yaxis.axis_label = "features range and mean: " + str(np.min(data1)) + ", " + str(np.max(data1)) + \
                              ", " + str(np.mean(data1))
        p2 = bplt.figure(x_range=(0, data2.shape[0]),
                         y_range=(0, data2.shape[1]),
                         title=title + "_2")
        p2.image(image=[np.log(data2 + np.abs(np.min(data2)) + 1e-10).T],
                 x=[0],
                 y=[0],
                 dw=[data2.shape[0]],
                 dh=[data2.shape[1]],
                 palette='Greys256')
        p2.xaxis.axis_label = "frames"
        p2.yaxis.axis_label = "features range and mean: " + str(np.min(data2)) + ", " + str(np.max(data2)) + \
                              ", " + str(np.mean(data2))
        bplt.save(bplt.gridplot([p1], [p2]))
Ejemplo n.º 31
0
def bokeh_plot(u, t, legends, u_e, t_e, I, w, t_range, filename):
    """
    Make plots for u vs t using the Bokeh library.
    u and t are lists (several experiments can be compared).
    legends contain legend strings for the various u,t pairs.
    Each plot has u vs t and the exact solution u_e vs t_e.
    """
    import numpy as np
    import bokeh.plotting as plt
    plt.output_file(filename, mode='cdn', title='Comparison')
    # Assume that all t arrays have the same range
    t_fine = np.linspace(0, t[0][-1], 1001)  # fine mesh for u_e
    tools = 'pan,wheel_zoom,box_zoom,reset,'\
            'save,box_select,lasso_select'
    u_range = [-1.2 * I, 1.2 * I]
    font_size = '8pt'
    p = []  # list of all individual plots
    p_ = plt.figure(width=300,
                    plot_height=250,
                    title=legends[0],
                    x_axis_label='t',
                    y_axis_label='u',
                    x_range=t_range,
                    y_range=u_range,
                    tools=tools,
                    title_text_font_size=font_size)
    p_.xaxis.axis_label_text_font_size = font_size
    p_.yaxis.axis_label_text_font_size = font_size
    p_.line(t[0], u[0], line_color='blue')
    p_.line(t_e, u_e, line_color='red', line_dash='4 4')
    p.append(p_)
    for i in range(1, len(t)):
        p_ = plt.figure(width=300,
                        plot_height=250,
                        title=legends[i],
                        x_axis_label='t',
                        y_axis_label='u',
                        x_range=p[0].x_range,
                        y_range=p[0].y_range,
                        tools=tools,
                        title_text_font_size=font_size)
        p_.xaxis.axis_label_text_font_size = font_size
        p_.yaxis.axis_label_text_font_size = font_size
        p_.line(t[i], u[i], line_color='blue')
        p_.line(t_e, u_e, line_color='red', line_dash='4 4')
        p.append(p_)

    # Arrange in grid with 3 plots per row
    grid = [[]]
    for i, p_ in enumerate(p):
        grid[-1].append(p_)
        if (i + 1) % 3 == 0:
            # New row
            grid.append([])
    plot = plt.gridplot(grid, toolbar_location='left')
    plt.save(plot)
    plt.show(plot)
Ejemplo n.º 32
0
    def _make_document(self, doc: Document) -> None:
        doc.title = "Train Tracker"
        # for _, plot in self._plots.items():
        #     doc.add_root(plot.fig)
        figs = [plot.fig for _, plot in self._plots.items()]
        grid = [figs[i:i + 3] for i in range(0, len(figs), 3)]
        doc.add_root(gridplot(grid))

        doc.add_periodic_callback(lambda: self._update_plots(doc), TIMEOUT)
Ejemplo n.º 33
0
def facet_grid(fig, x, y, df=None, source=None, groups=None, ncol=3,
               share_x_range=False, share_y_range=False, **kwargs):
    """
    facet_grid - generate a simple gridplot from a figure

    Args:
      fig (:py:class:`~bokeh.plotting.Plot`): bokeh Plot object
      x (str): string for x component
      y (str, list): string or list of strings for y component
      df (:py:class:`~pandas.DataFrame`): pandas DataFram
      groups (str, list(str)): groups to group by
      ncol (int): number of columns to use in gridplot
      share_x_range (bool): share x range across plots
      share_y_range (bool): share y range across plots
      kwargs: keyword arguments to pass to figure

    Returns:
      :class:~bokeh.models.GridPlot` object
    """
    if not groups:
        smllogger.warning("no groups defined; returning without modifying figure")
        return
    try:
        grouped = df.groupby(groups)
    except:
        raise
    flist = []
    gr = fig.select(GlyphRenderer)
    lgd = fig.select(Legend)
    if len(gr) == 0:
        smllogger.warning("no glyph renderer defined for plot; aborting")
        return
    j = 0
    for name, group in grouped:
        subfig = figure(title=str(name), **kwargs)
        for glyph, yy in zip(gr, y):
            plotfn = str(glyph.glyph).split(", ")[0].lower()
            kw = glyph.glyph.properties_with_values()
            kw.pop('x', None)
            kw.pop('y', None)
            kw.pop('xs', None)
            kw.pop('ys', None)
            source = ColumnDataSource(group)
            kw['legend'] = str(yy) if len(lgd) > 0 else None
            if plotfn == "multiline":
                plotfn = "line"
                getattr(subfig, plotfn)(x=x, y=yy, source=source, **kw)
            else:
                getattr(subfig, plotfn)(x=x, y=yy, source=source, **kw)
        if j > 0:
            if share_x_range:
                subfig.x_range = flist[0].x_range
            if share_y_range:
                subfig.y_range = flist[0].y_range
        j = j + 1
        flist.append(subfig)
    return gridplot([flist[i:i+ncol] for i in range(0, len(flist), ncol)])
Ejemplo n.º 34
0
def readTempData():
    attacks = ['190C', '200C', '210C', '220C', '230C']
    # Create a dictionary to store each figure in
    p = {}
    legendColors = ['navy', 'olive', 'firebrick', 'orange', 'purple']
    titles = [
        'Lowered to 190C', 'Lowered to 200C', 'Control - 210C',
        'Raised to 220C', 'Raised to 230C'
    ]
    i = int(1)
    # Iterate through all 5 temperature attacks (190C-230C)
    for x in attacks:
        # Format the Bokeh plots for the temperature graphs
        p[x] = figure(width=900,
                      plot_height=600,
                      title=titles[i - 1],
                      x_axis_label='Strain',
                      y_axis_label='Stress (MPa)',
                      x_range=(0, 0.0225),
                      y_range=(0, 34))
        output_file("Attack_5_" + x + ".html")
        p[x].title.text_font = 'Segoe UI'
        p[x].title.text_font_size = '26pt'
        p[x].title.align = 'center'
        p[x].xaxis.axis_label_text_font_size = '26pt'
        p[x].xaxis.major_label_text_font_size = '24pt'
        p[x].yaxis.axis_label_text_font_size = '26pt'
        p[x].yaxis.major_label_text_font_size = '24pt'
        p[x].min_border = 35
        # Load the mat file for each temperature
        mat = sio.loadmat('Attack_5_' + x + '.mat')
        # Iterate through all five specimens
        for specimen in range(5):
            # print("Specmimen:",specimen+1)
            # Assign values for stress and strain from the MAT file
            stress = mat['Temp_Test_Batch_' + str(i) + '_' +
                         x]['stress'][0][0][:, specimen]
            strain = mat['Temp_Test_Batch_' + str(i) + '_' +
                         x]['strain'][0][0][:, specimen]
            p[x].line(strain,
                      stress,
                      legend=None,
                      line_width=1,
                      line_color=legendColors[specimen])
        i = i + 1
        # Write output files
        outputWrite = 'Plot_' + x + '.png'
        # export_png(p,filename=outputWrite)
        print("Finished Writing File: " + outputWrite)
        reset_output()
    # Debugging
    # l=gridplot([[p['190C']],[p['200C']],[p['210C']],[p['220C']],[p['230C']]])   # Vertical
    l = gridplot([[p['190C'], p['200C']], [p['210C'], None],
                  [p['220C'], p['230C']]])  # Horizontal
    # export_png(l,filename='Gridplot.png')
    show(l)
Ejemplo n.º 35
0
def generate_grid_scatter_plot(data_frame):
    y = data_frame['Diabetes_Pct'].values
    x1 = data_frame['Black_Pct'].values
    x2 = data_frame['Hispanic_Pct'].values
    x3 = data_frame['LowAccess_Pct'].values
    x4 = data_frame['HouseholdIncome'].values

    source = ColumnDataSource(data=dict(y=y, x1=x1, x2=x2, x3=x3, x4=x4))

    TOOLS = "crosshair,wheel_zoom,reset,tap,pan,box_select"

    p1 = figure(tools=TOOLS,
                width=300,
                plot_height=250,
                x_range=(-.04, 1.08),
                y_range=(0, 0.21))
    p1.scatter('x1', 'y', source=source, fill_alpha=0.8, line_color=None)
    p1.xaxis.axis_label = 'Percent Black'
    p1.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")
    p1.xaxis[0].formatter = NumeralTickFormatter(format="0.0%")

    p2 = figure(tools=TOOLS,
                toolbar_location="right",
                width=300,
                plot_height=250,
                x_range=(-.04, 1.08),
                y_range=(0, 0.21))
    p2.scatter('x2', 'y', source=source, fill_alpha=0.8, line_color=None)
    p2.xaxis.axis_label = 'Percent Hispanic'
    p2.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")
    p2.xaxis[0].formatter = NumeralTickFormatter(format="0.0%")

    p3 = figure(tools=TOOLS,
                width=300,
                plot_height=250,
                x_range=(-.04, 1.08),
                y_range=(0, 0.21))
    p3.scatter('x3', 'y', source=source, fill_alpha=0.8, line_color=None)
    p3.xaxis.axis_label = 'Low Access Population'
    p3.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")
    p3.xaxis[0].formatter = NumeralTickFormatter(format="0.0%")

    p4 = figure(tools=TOOLS,
                width=300,
                plot_height=250,
                x_range=(9.8, 11.8),
                y_range=(0, 0.21))
    p4.scatter('x4', 'y', source=source, fill_alpha=0.8, line_color=None)
    p4.xaxis.axis_label = 'Median Household Income (log scale)'
    p4.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")

    plot_quad = gridplot([[p1, p2], [p3, p4]])

    script, dev = components(plot_quad)
    return script, dev
Ejemplo n.º 36
0
    def stop(self):

        pdb.set_trace()

        x_range = [self.datetime[0], self.datetime[-1]]

        # equity/cash diagram
        y_range1 = [0.95 * min(min(self.equity), min(self.cash)),
                    1.05 * max(max(self.equity), max(self.cash))]

        equity_figure = bp.figure(x_range=x_range, y_range=y_range1, x_axis_type="datetime",
                                  plot_width=self.p.plot_w, plot_height=self.p.plot_h,
                                  title = 'Equity Curve, $')
        # equity filled area
        equity_figure.patch(self.datetime+[self.datetime[-1], self.datetime[0]],
                            self.equity+[0.0, 0.0], alpha=0.75, line_width=1.0, color='green')
        # margin/position size
        equity_figure.patch(self.datetime+self.datetime[::-1], self.equity+self.cash[::-1],
                            alpha=0.75, line_width=1.0, color='lightblue')
        # equity curve
        equity_figure.line(self.datetime, self.equity, color='darkgreen', line_width=2.0)

        # money drawdown diagram
        y_range2 = [1.05 * self.maxddd[-1], 0]

        ddd_figure = bp.figure(x_range=equity_figure.x_range, y_range=y_range2,
                              plot_width=self.p.plot_w, plot_height=int(self.p.plot_h/2.5),
                              x_axis_type="datetime", title = 'Drawdown, $')
        # money drawdown filled area
        ddd_figure.patch(self.datetime+[self.datetime[-1], self.datetime[0]],
                         self.ddd+[0.0, 0.0], alpha=0.25, line_width=1.0, color='red')
        # money drawdown curve
        ddd_figure.line(self.datetime, self.ddd, color='red', line_width=2.0)
        # max money drawdown curve
        ddd_figure.line(self.datetime, self.maxddd,
                        color='black', line_width=1.0, line_dash='dashed')

        # percent drawdown diagram
        y_range3 = [1.05 * self.maxddp[-1], 0]

        ddp_figure = bp.figure(x_range=equity_figure.x_range, y_range=y_range3,
                              plot_width=self.p.plot_w, plot_height=int(self.p.plot_h/2.5),
                              x_axis_type="datetime", title = 'Drawdown, %')
        # percent drawdown filled area
        ddp_figure.patch(self.datetime+[self.datetime[-1], self.datetime[0]],
                         self.ddp+[0.0, 0.0], alpha=0.25, line_width=1.0, color='red')
        # percent drawdown curve
        ddp_figure.line(self.datetime, self.ddp, color='red', line_width=2.0)
        # max percent drawdown curve
        ddp_figure.line(self.datetime, self.maxddp,
                        color='black', line_width=1.0, line_dash='dashed')

        bp.output_file(self.p.html_name, title=self.p.html_title)
        bp.show(bp.gridplot([equity_figure, ddd_figure, ddp_figure], ncols=1))
Ejemplo n.º 37
0
def generate_seir_charts(options, results):
    output_file("all-series.html")
    all_plots = []
    plot = generate_seir_chart(options, results.global_series)
    all_plots.append([plot])

    for s in results.series:
        plot = generate_seir_chart(options, s)
        all_plots.append(([plot]))

    p = gridplot(all_plots)
    show(p)
def diagnostics(resid_, date_, lag_ ):
    resid_, date_ = resid_[lag_:], date_[lag_:]
    source = ColumnDataSource(data=dict(
    resid_ = resid_,
    qqplot_x = norm.ppf((np.arange(1,len(resid_) + 1) - 0.5)/len(resid_)),
    qqplot_y = np.sort(resid_),
    date_ = date_,
    date_label = [str(d)[:7] for d in date_[np.argsort(resid_)]],
    ind_sort = np.arange(0, len(resid_))[np.argsort(resid_)],
    ind = np.arange(0, len(resid_))
    ))

    
    s1 = figure(x_axis_type="datetime", plot_width = 400, plot_height = 400, title = "TS plot for residuals",
               tooltips = [("index","@ind")])
    s1.line(x = "date_", y = "resid_",source = source)
    s1.xaxis.axis_label = "Date"
    s1.yaxis.axis_label = "Residuals"

    hist, edges = np.histogram(resid_, density=True)
    
    s2 = figure(plot_width = 400, plot_height = 400, title = "Histagram for residuals")
    s2.quad(top = hist, bottom = 0,left=edges[:-1], right=edges[1:],
           fill_color="navy", line_color="white", alpha=0.5)
    s2.xaxis.axis_label = "Residuals"
    s2.yaxis.axis_label = "Frequency"
    
    acf, ci = ts_tool.acf(resid_, alpha = 0.05)
    s3 = figure(plot_width = 400, plot_height = 400, title = "ACF plot of residuals")
    s3.vbar(x = list(range(1,41)), width = 0.5, bottom = 0,
       top = acf[1:], color="firebrick")
    s3.line(x = list(range(1,41)), y = 2/(len(resid_))**0.5)
    s3.line(x = list(range(1,41)), y = -2/(len(resid_))**0.5)
    s3.xaxis.axis_label = "Lag"
    s3.yaxis.axis_label = "ACF"
    
    s4 = figure(plot_width = 400, plot_height = 400, title = "Q-Q plot of residuals",tooltips = [("date", "@date_label"),("index","@ind_sort")])
    s4.circle(x = "qqplot_x", y = "qqplot_y", source = source)
    y_,x_  = np.quantile(resid_, [0.25, 0.75]), norm.ppf([0.25, 0.75])
    slope = (y_[0] - y_[1])/(x_[0] - x_[1])
    intercept = y_[0] - slope*x_[0]
    line_ = norm.ppf((np.arange(1,len(resid_) + 1) - 0.5)/len(resid_))*slope + intercept
    s4.line(x = norm.ppf((np.arange(1,len(resid_) + 1) - 0.5)/len(resid_)), y = line_)
    s4.xaxis.axis_label = "Theoretical Quantile"
    s4.yaxis.axis_label = "Sample Quantile"
    
    p = gridplot([[s1, s2], [s3, s4]])
    # print("Shapiro Test for normality has p-value:",shapiro(resid_).pvalue)
    # output_file("%s.html"%("diagnostics"))
    # show(p)
    # reset_output()
    # output_notebook()
    return p, shapiro(resid_).pvalue
Ejemplo n.º 39
0
def visualize(profilers, file_path=None, show=True, save=True, **kwargs):
    """Visualize the results of profiling in a bokeh plot.

    If multiple profilers are passed in, the plots are stacked vertically.

    Parameters
    ----------
    profilers : profiler or list
        Profiler or list of profilers.
    file_path : string, optional
        Name of the plot output file.
    show : boolean, optional
        If True (default), the plot is opened in a browser.
    save : boolean, optional
        If True (default), the plot is saved to disk.
    **kwargs
        Other keyword arguments, passed to bokeh.figure. These will override
        all defaults set by visualize.

    Returns
    -------
    The completed bokeh plot object.
    """
    if not _state._notebook:
        file_path = file_path or "profile.html"
        bp.output_file(file_path)

    if not isinstance(profilers, list):
        profilers = [profilers]
    figs = [prof._plot(**kwargs) for prof in profilers]
    # Stack the plots
    if len(figs) == 1:
        p = figs[0]
    else:
        top = figs[0]
        for f in figs[1:]:
            f.x_range = top.x_range
            f.title = None
            f.min_border_top -= 30
            f.plot_height -= 30
        for f in figs[:-1]:
            f.xaxis.axis_label = None
            f.min_border_bottom -= 30
            f.plot_height -= 30
        for f in figs:
            f.min_border_left = 75
            f.min_border_right = 75
        p = bp.gridplot([[f] for f in figs])
    if show:
        bp.show(p)
    if file_path and save:
        bp.save(p)
    return p
Ejemplo n.º 40
0
def visualize(profilers, file_path=None, show=True, save=True, **kwargs):
    """Visualize the results of profiling in a bokeh plot.

    If multiple profilers are passed in, the plots are stacked vertically.

    Parameters
    ----------
    profilers : profiler or list
        Profiler or list of profilers.
    file_path : string, optional
        Name of the plot output file.
    show : boolean, optional
        If True (default), the plot is opened in a browser.
    save : boolean, optional
        If True (default), the plot is saved to disk.
    **kwargs
        Other keyword arguments, passed to bokeh.figure. These will override
        all defaults set by visualize.

    Returns
    -------
    The completed bokeh plot object.
    """
    if not _state._notebook:
        file_path = file_path or "profile.html"
        bp.output_file(file_path)

    if not isinstance(profilers, list):
        profilers = [profilers]
    figs = [prof._plot(**kwargs) for prof in profilers]
    # Stack the plots
    if len(figs) == 1:
        p = figs[0]
    else:
        top = figs[0]
        for f in figs[1:]:
            f.x_range = top.x_range
            f.title = None
            f.min_border_top = 20
            f.plot_height -= 30
        for f in figs[:-1]:
            f.xaxis.axis_label = None
            f.min_border_bottom = 20
            f.plot_height -= 30
        for f in figs:
            f.min_border_left = 75
            f.min_border_right = 75
        p = bp.gridplot([[f] for f in figs])
    if show:
        bp.show(p)
    if file_path and save:
        bp.save(p)
    return p
Ejemplo n.º 41
0
    def _make_multiplot(self):

        self._make_datasource()


        self._make_hovertool_string()
        figs = [self._make_patch_plot(title) for title in self.plot_params['plot_titles']]

        for fig_i in figs[1:]:
            fig_i.x_range = figs[0].x_range
            fig_i.y_range = figs[0].y_range

        for i, fig in enumerate(figs):
            fig.title_text_color = 'black'
            fig.axis.axis_label_text_color = 'black'
            fig.axis.major_label_text_color = '#B3B3B3'
            fig.title_text_font_size = '18pt'
            fig.axis.axis_label_text_font_size = '12pt'
            fig.axis.major_label_text_font_size= '9pt'
            fig.axis.minor_tick_line_color = None
            fig.axis.major_tick_in = -2
            fig.axis.major_tick_out = 8
            fig.axis.major_tick_line_color = '#B3B3B3'
            fig.axis.major_tick_line_width = 2
            fig.axis.major_tick_line_cap = 'butt'
            fig.xaxis.axis_label = self.plot_params['x_label']
            fig.yaxis.axis_label = self.plot_params['y_label']
            fig.outline_line_width = 0.5
            fig.outline_line_color = 'black'
            if not self.logvals:
                fig.xaxis[0].formatter = PrintfTickFormatter(format="%0.1e")
                fig.yaxis[0].formatter = PrintfTickFormatter(format="%0.1e")
            hover = fig.select_one(HoverTool)
            hover.point_policy = "follow_mouse"
            hover.tooltips = self._hovertool_html[i]

        n_cols = self.plot_params['n_cols']
        n_figs = len(figs)
        figs = [figs[i*n_cols:(i+1)*n_cols] for i in range((n_figs//n_cols)+1)]
        if n_figs % n_cols == 0:
            figs=figs[:-1]
        fig = gridplot(figs)

        save_string = self.plot_params['save_string']

        if not save_string:
            output_notebook()
            show(fig)
        elif save_string == 'return':
            return(fig)
        elif save_string.endswith('.html'):
            output_file(save_string)
            save(fig)
Ejemplo n.º 42
0
def _facet_grid(df, return_source, glyph, colormap, facet, **kwargs):
    groups = df.groupby(facet)
    flist = []
    ncol = kwargs.pop('ncol')
    x = kwargs.pop('x')
    y = kwargs.pop('y')
    plot_height = kwargs.pop('plot_height')
    plot_width = kwargs.pop('plot_width')
    j = 0
    source_dict = {}
    for name, group in groups:
        name = str(name)
        kwfig = utils.fig_args(kwargs)
        subfig = utils.create_bokeh_fig(plot_height=plot_height,
                                        plot_width=plot_width,
                                        name = name,
                                        **kwfig)
        fig_props = set(subfig.properties())
        kwfig = utils.fig_args(kwargs, fig_props)
        subfig.set(**kwfig)
        source = ColumnDataSource(group)
        kw = {'legend': name,
              'x': x,
              'y': y}

        getattr(subfig, glyph)(source=source, **kw)
        source_dict[name] = source 
        if j > 0:
            if kwargs.get('share_x_range', None):
                subfig.x_range = flist[0].x_range
            if kwargs.get('share_y_range', None):
                subfig.y_range = flist[0].y_range
        j = j + 1
        flist.append(subfig)

    if return_source:
        return gridplot([flist[i:i+ncol] for i in range(0, len(flist), ncol)]), source_dict
    else:
        return gridplot([flist[i:i+ncol] for i in range(0, len(flist), ncol)]), None
def create_grid(graphs, columns=6, **kwargs):
    grid = []
    current_row = []
    i = 1
    for graph in graphs:
        current_row.append(graph)
        if i % columns == 0:
            grid.append(current_row)
            current_row = []
        i += 1
    if len(current_row) > 0:
        grid.append(current_row)
    return gridplot(grid, **kwargs)
Ejemplo n.º 44
0
 def __exit__(self, *args):
     global _figures, _figsize
     if len(_figures) > 1 or len(_figures[0]) > 0:
         f = _bplt.gridplot(_figures, merge_tools=False)
         if _static_images:
             _show_static_images(f)
         else:
             _process_canvas([])
             _bplt.show(f)
             _process_canvas(
                 [item for sublist in _figures for item in sublist])
     _figures = None
     _figsize = self.ofigsize
Ejemplo n.º 45
0
def plot_map(perf_map, res, title='performance map', colors=BLUE_COLORS, show=True, scale='default'):
    ps = list(perf_map.values())
    p_min, p_max = np.min(ps), np.max(ps)
    if scale == 'log':
        c_min, c_max = -math.log(-p_min+EPSILON), -math.log(-p_max+EPSILON)
    else:
        c_min, c_max = p_min, p_max

    img = np.zeros((res, res), dtype=np.uint32)
    view = img.view(dtype=np.uint8).reshape(img.shape + (4,))

    for (i, j), p in perf_map.items():
        if scale == 'log':
            p = -math.log(-p+EPSILON)
        c_idx = int(np.floor((len(colors)-1)*(p - c_min)/(c_max-c_min)))
        r, g, b = colors[c_idx]
        view[j, i, 0] = r
        view[j, i, 1] = g
        view[j, i, 2] = b
        view[j, i, 3] = 255

    plot = bkp.figure(width=SIZE, height=SIZE, x_range=(-0.7, 0.7), y_range=(-0.7, 0.7),
                           title=title, title_text_font_size='12pt',
                           tools = "pan,box_zoom,reset,save")
    plot.image_rgba([img], x=[-0.7],  y=[-0.7], dh=[1.4], dw=[1.4])



    if scale == 'log':
        cbar = colorbar(colors, inversed=True)
        cb_plot = bkp.figure(width=100, height=SIZE, x_range=(0, 1.0), y_axis_type="log", y_range=(-p_max, -p_min))
        cb_plot.image_rgba([cbar], x=[0.0],  y=[-p_max], dw=[1.0], dh=[p_max-p_min])
    else:
        cbar = colorbar(colors)
        cb_plot = bkp.figure(width=100, height=SIZE, x_range=(0, 1.0), y_range=(p_min, p_max))
        cb_plot.image_rgba([cbar], x=[0.0],  y=[p_min], dw=[1.0], dh=[p_max-p_min])

    cb_plot.min_border_right = 25
    cb_plot.xgrid.grid_line_color = None
    cb_plot.xaxis.minor_tick_line_color = None
    cb_plot.xaxis.major_tick_line_color = None
    cb_plot.xaxis.axis_line_color = None
    cb_plot.xaxis[0].formatter = PrintfTickFormatter(format="")
    if scale == 'log':
        cb_plot.yaxis.formatter = PrintfTickFormatter(format="-%1.0e")

    if show:
        bkp.show(bkp.gridplot([[plot, cb_plot]]))
    return [plot, cb_plot]
Ejemplo n.º 46
0
def bokeh_plot(u, t, legends, u_e, t_e, I, w, t_range, filename):
    """
    Make plots for u vs t using the Bokeh library.
    u and t are lists (several experiments can be compared).
    legends contain legend strings for the various u,t pairs.
    Each plot has u vs t and the exact solution u_e vs t_e.
    """
    import numpy as np
    import bokeh.plotting as plt
    plt.output_file(filename, mode='cdn', title='Comparison')
    # Assume that all t arrays have the same range
    t_fine = np.linspace(0, t[0][-1], 1001)  # fine mesh for u_e
    tools = 'pan,wheel_zoom,box_zoom,reset,'\
            'save,box_select,lasso_select'
    u_range = [-1.2*I, 1.2*I]
    font_size = '8pt'
    p = []
    p_ = plt.figure(
        width=300, plot_height=250, title=legends[0],
        x_axis_label='t', y_axis_label='u',
        x_range=t_range, y_range=u_range, tools=tools,
        title_text_font_size=font_size)
    p_.xaxis.axis_label_text_font_size=font_size
    p_.yaxis.axis_label_text_font_size=font_size
    p_.line(t[0], u[0], line_color='blue')
    p_.line(t_e, u_e, line_color='red', line_dash='4 4')
    p.append(p_)
    for i in range(1, len(t)):
        p_ = plt.figure(
            width=300, plot_height=250, title=legends[i],
            x_axis_label='t', y_axis_label='u',
            x_range=p[0].x_range, y_range=p[0].y_range, tools=tools,
            title_text_font_size=font_size)
        p_.xaxis.axis_label_text_font_size=font_size
        p_.yaxis.axis_label_text_font_size=font_size
        p_.line(t[i], u[i], line_color='blue')
        p_.line(t_e, u_e, line_color='red', line_dash='4 4')
        p.append(p_)

    # Arrange in grid with 3 plots per row
    grid = [[]]
    for i, p_ in enumerate(p):
        grid[-1].append(p_)
        if (i+1) % 3 == 0:
            # New row
            grid.append([])
    plot = plt.gridplot(grid, toolbar_location='left')
    plt.save(plot)
    plt.show(plot)
Ejemplo n.º 47
0
def atacseq_qualimap_plot_globals(df, **kwargs):
    """Plot qualimap global statistics.

    Args:
      df(:class:`~pandas.DataFrame`): data frame holding summary of qualimap results. The summary is provided by  :meth:`snakemakelib.odo.qualimap.resource_genome_results`.
      kwargs(dict): keyword arguments

    Returns:
      (:class:`bokeh.plotting.gridplot`): bokeh gridplot

    Examples:

    .. bokeh-plot::
        :source-position: above

        import pandas as pd
        from bokeh.plotting import show
        from snakemakelib_workflows.atacseq.app import atacseq_qualimap_plot_globals

        df = pd.DataFrame([['S1', 'number of reads', 80, 100],
                           ['S1', 'number of mapped reads', 20, 25],
                           ['S1', 'number of duplicated reads', 10, 25],
                           ['S1', 'number of unique reads', 10, 12.5]],
                          columns=['SM','statistic','value', 'percent'])
        p = atacseq_qualimap_plot_globals(df, height=200, width=200)
        show(p)


    """
    READ_ROWS = ["number of reads",
                 "number of mapped reads",
                 "number of duplicated reads",
                 "number of unique reads"]
    df.set_index(['statistic', 'SM'], inplace=True)
    df.sortlevel(inplace=True)
    df = df.loc[pd.IndexSlice[READ_ROWS, :]].reset_index()
    df["value"] = [log10(x) for x in df["value"]]
    df["SM"] = df["SM"].astype(str)
    p1 = Scatter(df, x="SM", y="value", color="statistic",
                 legend="top_right", ylabel="log10(count)",
                 title="Qualimap read summary",
                 height=kwargs.get("height", 400),
                 width=kwargs.get("width", 400))
    p2 = Scatter(df, x="SM", y="percent",
                 color="statistic", legend="top_right",
                 title="Qualimap read summary, percent",
                 height=kwargs.get("height", 400),
                 width=kwargs.get("width", 400))
    return gridplot([[p1, p2]])
Ejemplo n.º 48
0
    def get_figure(self):
        canvases = list(self._collect_unique_canvas())
        n_cols = 3
        n_rows = (len(canvases)-1)//3 + 1

        # set correct size of figure
        for c in canvases:
            c.plot_width  = self.fig_width//n_cols
            c.plot_height = self.fig_height//n_rows

        # get figures
        grid = []
        for row in range(n_rows):
            grid.append(canvases[n_cols*row:n_cols*(row+1)])

        return gridplot(grid)
Ejemplo n.º 49
0
def basic_bokeh(out_fn="estuary_out.html"):
    """ Basic 3-panel plot of output using Bokeh """

    if os.path.exists(out_fn):
        os.remove(out_fn)
    output_file(out_fn)

    # Construct Bokeh plot
    source = ColumnDataSource(result)
    day_range = Range1d(0, result.iloc[-1]["day"])

    # colors = sns.cycle([rgb_to_hex(c) for c in sns.color_palette('Dark2', 3)])
    colors = ["MediumSeaGreen", "OrangeRed", "DarkViolet"]

    TOOLS = "box_zoom,reset"

    # Create a new plot and add a renderer
    top = figure(tools=TOOLS, width=1000, height=300, title=None, x_range=day_range)
    top.line("day", "S", source=source, line_color=colors[0], line_width=3, line_cap="round")
    top.y_range = Range1d(0, 1.05 * result["S"].max())
    top.yaxis.axis_label = "Salinity (g/kg)"

    mid = figure(tools=TOOLS, width=1000, height=300, title=None, x_range=top.x_range)
    mid.line("day", "N", source=source, line_color=colors[1], line_width=3, line_cap="round")
    mid.y_range = Range1d(0, 1.05 * result["N"].max())
    mid.yaxis.axis_label = "Nitrate (mu mol/L)"

    bot = figure(tools=TOOLS, width=1000, height=300, title=None, x_range=top.x_range)
    bot.line("day", "O", source=source, line_color=colors[2], line_width=3, line_cap="round")
    bot.y_range = Range1d(0, 1.05 * result["O"].max())
    bot.yaxis.axis_label = "Oxygen (mu mol/L)"

    # Set plot aesthetics
    for p in [top, mid, bot]:
        p.xgrid.grid_line_color = None
        p.ygrid.grid_line_alpha = 0.5

        p.xaxis.axis_label = "Day"

        # Add spin-up annotation box
        spin_up_box = BoxAnnotation(plot=p, left=0, right=2, fill_alpha=0.75, fill_color="grey")
        p.renderers.extend([spin_up_box])

    # Generate multi-panel plot and display
    p = gridplot([[top], [mid], [bot]], toolbar_location="above")
    show(p)
Ejemplo n.º 50
0
def atacseq_qualimap_plot_globals(df, **kwargs):
    READ_ROWS = ["number of reads", "number of mapped reads", "number of duplicated reads", "number of unique reads"]
    df.set_index(["statistic", "SM"], inplace=True)
    df.sortlevel(inplace=True)
    df = df.loc[pd.IndexSlice[READ_ROWS, :]].reset_index()
    df["value"] = [log10(x) for x in df["value"]]
    df["SM"] = df["SM"].astype(str)
    p1 = Scatter(
        df,
        x="SM",
        y="value",
        color="statistic",
        legend="top_right",
        ylabel="log10(count)",
        title="Qualimap read summary",
    )
    p2 = Scatter(df, x="SM", y="percent", color="statistic", legend="top_right", title="Qualimap read summary, percent")
    return gridplot([[p1, p2]])
Ejemplo n.º 51
0
def make_figure():
    top = figure(tools=TOOLS, width=600, height=400,
                 x_axis_label='x',
                 y_axis_label='f(x)')

    top.line('x', 'y1', source=source, line_width=2)
    top.scatter('x', 'y1', source=source, size=0)

    bottom = figure(tools=TOOLS, width=600, height=400,
                    x_axis_label='x',
                    y_axis_label="f(x)'")
    bottom.line('x', 'y2', source=source, alpha=1, line_width=2)
    bottom.scatter('x', 'y2', source=source, size=0)

    plot = gridplot([[top], [bottom]])

    show(plot)
    return plot
Ejemplo n.º 52
0
	def plot_data(self):
		
		
		
		output_file(self.name+'_'+self.choice+'.html',title=self.name)
		tools = "pan,wheel_zoom,box_zoom,reset,save"
		
		fig1=figure(title=self.name+'_'+self.choice,title_text_align='center',y_axis_label='I',x_range=self.plot_limits[0],y_range=self.plot_limits[1],min_border_left=50,min_border_bottom=10,tools=tools,width=800,plot_height=380)

		T=np.arange(self.models[0][1][0]-3*self.models[0][1][1],self.models[0][1][0]+3*self.models[0][1][1],0.01)
		
		fig1.line(T,18-2.5*np.log10(self.lightcurve_model(T)),line_width=0.7,color='red')
		
		for i in xrange(len(self.telescopes)):

			
			
			#fig1.scatter(self.aligned_lightcurves[i][:,2],self.aligned_lightcurves[i][:,0],fill_color='#'+self.colors[self.telescopes[i][0]],line_color=None,legend=self.telescopes[i][1],size=5/10**np.abs(self.aligned_lightcurves[i][:,1]))
			fig1.segment(self.aligned_lightcurves[i][:,2],self.aligned_lightcurves[i][:,0]+np.abs(self.aligned_lightcurves[i][:,1]),self.aligned_lightcurves[i][:,2],self.aligned_lightcurves[i][:,0]-np.abs(self.aligned_lightcurves[i][:,1]),color='#'+self.colors[self.telescopes[i][0]],line_alpha=0.3)
			
			fig1.scatter(self.aligned_lightcurves[i][:,2],self.aligned_lightcurves[i][:,0],fill_color='#'+self.colors[self.telescopes[i][0]],line_color=None,legend=self.telescopes[i][1],size=4)
		
		
		fig1.xaxis.minor_tick_line_color=None
		fig1.xaxis.major_tick_line_color=None
		fig1.xaxis.major_label_text_font_size='0pt'
		fig1.legend.label_width=190
		fig1.legend.label_width=50
		fig1.legend.background_fill_alpha=0.5
		fig1.legend.label_text_alpha=0.5
		
		fig2=figure(width=800,plot_height=120,x_range=fig1.x_range,y_range=(-0.5,0.5),x_axis_label='HJD-2450000',y_axis_label='Delta_I',min_border_left=70,min_border_top=10)
		for i in xrange(len(self.telescopes)):
			
			residuals=self.residuals(i)
			
			fig2.segment(self.lightcurves[i][:,2],residuals+np.abs(self.lightcurves[i][:,1]),self.lightcurves[i][:,2],residuals-np.abs(self.lightcurves[i][:,1]),color='#'+self.colors[self.telescopes[i][0]],line_alpha=0.3)
			fig2.scatter(self.lightcurves[i][:,2],residuals,fill_color='#'+self.colors[self.telescopes[i][0]],line_color=None,size=4)
		fig2.xaxis.minor_tick_line_color=None
		p=gridplot([[fig1],[fig2]],toolbar_location="right")	
		
		show(p)
    def create_grid_images(self, img_list, name, n_cols=3):
        # Create a list with the image figures and image data sources
        p_images = []
        data_sources = []
        for i in xrange(len(img_list)):
            p_img, data_img = self.create_figure_image(img_list[i], name=name + str(i))
            p_images.append(p_img)
            data_sources.append(data_img)

        # Add the needed Nones so we can transform in a square matrix
        for i in xrange(n_cols - len(img_list) % n_cols):
            p_images.append(None)

        # Reshape as a matrix (List format)
        p_images = np.asarray(p_images).reshape(-1, 3).tolist()

        # Plot the images
        p = gridplot(p_images)

        # return the grid
        return p, data_sources
Ejemplo n.º 54
0
def create_plot(N, func1, func2, color):
    N = 300
    x = np.linspace(0, 4*np.pi, N)
    y1 = np.sin(x)
    y2 = np.cos(x)

    source = ColumnDataSource()
    source.add(data=x, name='x')
    source.add(data=y1, name='y1')
    source.add(data=y2, name='y2')

    TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select,lasso_select"

    s1 = plt.figure(tools=TOOLS, plot_width=350, plot_height=350)
    s1.scatter('x', 'y1', source=source, fill_color=color)

    s2 = plt.figure(tools=TOOLS, plot_width=350, plot_height=350)
    s2.scatter('x', 'y2', source=source, fill_color=color)

    p = plt.gridplot([[s1,s2]])
    return p
Ejemplo n.º 55
0
def make_picard_summary_plots(inputfiles, ncol=4):
    d = {}
    TOOLS = "pan,box_zoom,wheel_zoom,box_select,lasso_select,resize,reset,save,hover"
    for (metrics_file, hist_file) in zip(inputfiles[0::2], inputfiles[1::2]):
        df_met = _read_metrics(metrics_file)
        df_hist = _read_metrics(hist_file)
        p1 = df_met.plot_metrics(tools=TOOLS)
        key = os.path.splitext(metrics_file)[0]
        if df_met.label not in d:
            d[df_met.label] = {}
            d[df_met.label][key] = {}
            d[df_met.label][key]['uri'] = [data_uri(metrics_file)]
            d[df_met.label][key]['file'] = [metrics_file]
        if df_hist is not None:
            p2 = df_hist.plot_hist(tools=TOOLS)
            d[df_met.label][key]['uri'].append(data_uri(hist_file))
            d[df_met.label][key]['file'].append(hist_file)
        else:
            p2 = []
        plist = p1 + p2
        gp = gridplot([plist[i:i+ncol] for i in range(0, len(plist), ncol)])
        d[df_met.label][key]['fig'] = gp
    return d
Ejemplo n.º 56
0
def list(s1):
    s=int(s1)
    print("Exercise n: ", s)
    #output_file("home.html")
    exercise = list_exercises[s]
    T = exercise.X.shape[1]
    t = np.arange(T)/100
    plot = figure(width=350, plot_height=250, title="Droit Acceleration X")
    plot.line(t,exercise.get_signal("DAX")[0])
    plot2=figure(width=350, plot_height=250, title="Droit Acceleration Y")
    plot2.line(t,exercise.get_signal("DAY")[0])
    plot3=figure(width=350, plot_height=250, title="Droit Acceleration Z")
    plot3.line(t,exercise.get_signal("DAZ")[0])
    plot4=figure(width=350, plot_height=250, title="Droit Rotation X")
    plot4.line(t,exercise.get_signal("DRX")[0])
    plot5=figure(width=350, plot_height=250, title="Droit Rotation X")
    plot5.line(t,exercise.get_signal("DRY")[0])
    plot6=figure(width=350, plot_height=250, title="Droit Rotation X")
    plot6.line(t,exercise.get_signal("DRZ")[0])
    #p = hplot(plot, plot2)
    p = gridplot([[plot, plot2, plot3], [plot4, plot5, plot6]])
    html = file_html(p, CDN, "home")
    return html
Ejemplo n.º 57
0
def make_plot(title1, plot1, title2, plot2, title3, plot3, title4, plot4, title5, plot5, sample_df):
    plot1.title = title1
    plot2.title = title2
    plot3.title = title3
    plot4.title = title4
    plot5.title = title5
    plot1.yaxis.axis_label = data_dict['DO']['title']
    plot1.yaxis.axis_label_text_font_style = "italic"
    plot2.yaxis.axis_label = data_dict['Ammonium']['title']
    plot2.yaxis.axis_label_text_font_style = "italic"
    plot3.yaxis.axis_label = data_dict['pH']['name']
    plot3.yaxis.axis_label_text_font_style = "italic"
    plot4.yaxis.axis_label = data_dict['N2 Mass Flow Controller']['title']
    plot4.yaxis.axis_label_text_font_style = "italic"
    plot5.yaxis.axis_label = data_dict['Air Mass Flow Controller']['title']
    plot5.yaxis.axis_label_text_font_style = "italic"
    plot1.line(x=sample_df.index, y=sample_df[title1], color="navy")
    plot2.line(x=sample_df.index, y=sample_df[title2], color="firebrick")
    plot3.line(x=sample_df.index, y=sample_df[title3], color="#28D0B4", line_width=2)
    plot4.line(x=sample_df.index, y=sample_df[title4], color="orange")
    plot5.line(x=sample_df.index, y=sample_df[title5], color="black")
    p = gridplot([[plot1, plot2, plot3], [plot4, plot5, None]])
    return p
Ejemplo n.º 58
0
    def make_figure():
#%% Create Time Series Graph
        #Create Time Series plot area
        time_plot = figure(plot_height= 400, plot_width= 800, title="", x_axis_label ='Time', 
                    tools='', y_axis_label = 'l1013aspv', toolbar_location="left",
                    x_axis_type="datetime",
                    y_range=(min(data_source.data["y1"]) -min(data_source.data["y1"]*0.1 ),
                             max(data_source.data["y1"]) + max(data_source.data["y1"]*0.1)))
                       
        #modify the BoxSelectTool 
        #dimensions = specify the dimension in which the box selection is free in
        #select_every_mousemove = select points as box moves over
        time_plot.add_tools(BoxSelectTool(dimensions = ["width"], select_every_mousemove = True))

        #add anther axis
        time_plot.extra_y_ranges = {"foo": Range1d(start = min(data_source.data["y2"]) 
                                                        - min(data_source.data["y1"]*0.1),
                                                  end = max(data_source.data["y2"]) + max(data_source.data["y1"]*0.1))}
                                                  
        #add data to scatter plot (data points on time plot)
        time_scat = time_plot.scatter("x", "y1", source = data_source,size = 1, color = "green")
        time_scat2 = time_plot.scatter("x", "y2", source = data_source,size= 1, color = "blue", y_range_name = "foo")
           
        #add time series line
        time_plot.line("x","y1",source=data_source,color = time_scat.glyph.fill_color,
                                   alpha=0.5)
                                   
        time_plot.line("x","y2",source=data_source,color= time_scat2.glyph.fill_color,
                                    alpha=0.5,y_range_name="foo")
                                    
        #Customize time_plot grid lines
        time_plot.xgrid.grid_line_color = None
        time_plot.ygrid.grid_line_alpha = 0.2
        #First axes styling
        time_plot.yaxis.axis_line_color = time_scat.glyph.fill_color
        time_plot.yaxis.minor_tick_line_color = time_scat.glyph.fill_color
        time_plot.yaxis.major_tick_line_color = time_scat.glyph.fill_color
        time_plot.yaxis.axis_label_text_color = time_scat.glyph.fill_color
        time_plot.yaxis.major_label_text_color = time_scat.glyph.fill_color
                                    
        #add second axis to time_plot and styling
        time_plot.add_layout(LinearAxis(y_range_name = "foo",
                                        axis_line_color = str(time_scat2.glyph.fill_color),
                                        major_label_text_color = str(time_scat2.glyph.fill_color), 
                                        axis_label_text_color = str(time_scat2.glyph.fill_color),
                                        major_tick_line_color = str(time_scat2.glyph.fill_color),
                                        minor_tick_line_color = str(time_scat2.glyph.fill_color),
                                        axis_label= "l1015asop"), "left")
                                    
#%% Create Marginal Histogram and KDE
       #Create marginal histogram for y-axis data density
        #set up figure
        hist_plot = figure(plot_height = 400, plot_width = 200, y_range = time_plot.y_range)
        
        #add second axis to histogram
        hist_plot.extra_y_ranges = {"foo": 
            Range1d(start = min(data_source.data["y2"]) - min(data_source.data["y1"]*0.1),
                    end = max(data_source.data["y2"]) + max(data_source.data["y1"]*0.1))}
        
        #Customize hist_plot grid lines
        hist_plot.xgrid.grid_line_alpha = 0.2
        hist_plot.ygrid.grid_line_alpha = 0.5
                
        #get histogram data 
        hist, edges = histogram(data_source.data["y1"], density = True, bins = 20)
        hist2, edges2 = histogram(data_source.data["y2"], density = True, bins = 20)
        
        #styleing histograms axises              
        hist_plot.xaxis.axis_label = ""
        hist_plot.yaxis.axis_label = ""
        hist_plot.xaxis.visible = None
                    
        #add gaussian kernel density estomator
        y_span = linspace(min(data_source.data["y1"]),
                             max(data_source.data["y1"]), size(data_source.data["y1"]))
        kde = gkde(data_source.data["y1"]).evaluate(y_span)
        
        y_span2 = linspace(min(data_source.data["y2"]),
                             max(data_source.data["y2"]), size(data_source.data["y2"]))
        kde2 = gkde(data_source.data["y2"]).evaluate(y_span2)                             
                                    
                                    
        #Histogram First axes styling
        hist_plot.yaxis.axis_line_color = time_scat.glyph.fill_color
        hist_plot.yaxis.minor_tick_line_color = time_scat.glyph.fill_color
        hist_plot.yaxis.major_tick_line_color = time_scat.glyph.fill_color
        hist_plot.yaxis.axis_label_text_color = time_scat.glyph.fill_color
        hist_plot.yaxis.major_label_text_color = time_scat.glyph.fill_color        
        #Histogram second axes styling
        hist_plot.add_layout(LinearAxis(y_range_name = "foo",
                                        axis_line_color = str(time_scat2.glyph.fill_color),
                                        major_label_text_color = str(time_scat2.glyph.fill_color), 
                                        axis_label_text_color = str(time_scat2.glyph.fill_color),
                                        major_tick_line_color = str(time_scat2.glyph.fill_color),
                                        minor_tick_line_color = str(time_scat2.glyph.fill_color)), "left")
                                        
#%% Create Scatter Graph       
        scat_plot = figure(plot_height = 400, plot_width = 400, title = "", x_axis_label = 'l1015asop', 
                    y_axis_label = 'l1013aspv')
        
        #scatter plot axis cutomization
        scat_plot.yaxis.axis_line_color = time_scat.glyph.fill_color
        scat_plot.yaxis.minor_tick_line_color = time_scat.glyph.fill_color
        scat_plot.yaxis.major_tick_line_color = time_scat.glyph.fill_color
        scat_plot.yaxis.axis_label_text_color = time_scat.glyph.fill_color
        scat_plot.yaxis.major_label_text_color = time_scat.glyph.fill_color
        
        scat_plot.xaxis.axis_line_color = time_scat2.glyph.fill_color
        scat_plot.xaxis.minor_tick_line_color = time_scat2.glyph.fill_color
        scat_plot.xaxis.major_tick_line_color = time_scat2.glyph.fill_color
        scat_plot.xaxis.axis_label_text_color = time_scat2.glyph.fill_color
        scat_plot.xaxis.major_label_text_color = time_scat2.glyph.fill_color 
                
        
#%% Add data to Histogram and scatter plot (this data is updated in callback fuction)       
        #Create updateable plots
        u_hist_source = ColumnDataSource(data=dict(top=edges[1:],bottom=edges[:-1],left=zeros_like(edges),right=hist))
        u_hist_source2 = ColumnDataSource(data=dict(top=edges2[1:],bottom=edges2[:-1],left=zeros_like(edges2),right=hist2))
        u_kde_source = ColumnDataSource(data=dict(x = kde, y = y_span))
        u_kde_source2 = ColumnDataSource(data=dict(x = kde2, y = y_span2))
        scat_data = ColumnDataSource(data=dict(x=[0],y=[0]))

        #Updateble histogram
        hist_plot.quad(top = 'top', bottom = 'bottom', left = 'left', right = 'right', source = u_hist_source,
                                fill_color = time_scat.glyph.fill_color, alpha = 0.5)
                                
        hist_plot.quad(top = 'top', bottom = 'bottom', left = 'left', right = 'right', source = u_hist_source2,
                                fill_color = time_scat2.glyph.fill_color, alpha = 0.3, y_range_name = "foo")
        #Updateble kde line
        hist_plot.line('x', 'y', source=u_kde_source ,line_color = "#008000")
        hist_plot.line('x', 'y', source=u_kde_source2 ,line_color = "#000099", y_range_name = "foo")
        
        
        
        #Updateble scatter plot 
        scat_plot.scatter('x', 'y', source=scat_data,size=2, alpha=0.3)

#%% Updating fuction            
        data_source.callback = CustomJS(args=dict(hist_data=u_hist_source, hist_data2=u_hist_source2,
                                        kde_d = u_kde_source, kde_d2 = u_kde_source2, sc=scat_data),
                                code="""
                            Update_ALL_Figures(cb_obj, hist_data, hist_data2, kde_d, kde_d2, sc)
                                    """)
#%% create plot layout
                                    
        layout = gridplot([[time_plot, hist_plot], [scat_plot, None]])
        return layout #need to return the layout