Ejemplo n.º 1
0
def make_tpf_figure_elements(tpf,
                             tpf_source,
                             pedestal=None,
                             fiducial_frame=None,
                             plot_width=370,
                             plot_height=340,
                             scale='log',
                             vmin=None,
                             vmax=None,
                             cmap='Viridis256',
                             tools='tap,box_select,wheel_zoom,reset'):
    """Returns the lightcurve figure elements.

    Parameters
    ----------
    tpf : TargetPixelFile
        TPF to show.
    tpf_source : bokeh.plotting.ColumnDataSource
        TPF data source.
    pedestal: float
        A scalar value to be added to the TPF flux values, often to avoid
        taking the log of a negative number in colorbars.
        Defaults to `-min(tpf.flux) + 1`
    fiducial_frame: int
        The tpf slice to start with by default, it is assumed the WCS
        is exact for this frame.
    scale: str
        Color scale for tpf figure. Default is 'log'
    vmin: int [optional]
        Minimum color scale for tpf figure
    vmax: int [optional]
        Maximum color scale for tpf figure
    cmap: str
        Colormap to use for tpf plot. Default is 'Viridis256'
    tools: str
        Bokeh tool list
    Returns
    -------
    fig, stretch_slider : bokeh.plotting.figure.Figure, RangeSlider
    """
    if pedestal is None:
        pedestal = -np.nanmin(tpf.flux.value) + 1
    if scale == 'linear':
        pedestal = 0

    if tpf.mission in ['Kepler', 'K2']:
        title = 'Pixel data (CCD {}.{})'.format(tpf.module, tpf.output)
    elif tpf.mission == 'TESS':
        title = 'Pixel data (Camera {}.{})'.format(tpf.camera, tpf.ccd)
    else:
        title = "Pixel data"

    # We subtract 0.5 from the range below because pixel coordinates refer to
    # the middle of a pixel, e.g. (col, row) = (10.0, 20.0) is a pixel center.
    fig = figure(plot_width=plot_width,
                 plot_height=plot_height,
                 x_range=(tpf.column - 0.5, tpf.column + tpf.shape[2] - 0.5),
                 y_range=(tpf.row - 0.5, tpf.row + tpf.shape[1] - 0.5),
                 title=title,
                 tools=tools,
                 toolbar_location="below",
                 border_fill_color="whitesmoke")

    fig.yaxis.axis_label = 'Pixel Row Number'
    fig.xaxis.axis_label = 'Pixel Column Number'

    vlo, lo, hi, vhi = np.nanpercentile(tpf.flux.value + pedestal,
                                        [0.2, 1, 95, 99.8])
    if vmin is not None:
        vlo, lo = vmin, vmin
    if vmax is not None:
        vhi, hi = vmax, vmax

    if scale == 'log':
        vstep = (np.log10(vhi) -
                 np.log10(vlo)) / 300.0  # assumes counts >> 1.0!
    if scale == 'linear':
        vstep = (vhi - vlo) / 300.0  # assumes counts >> 1.0!

    if scale == 'log':
        color_mapper = LogColorMapper(palette=cmap, low=lo, high=hi)
    elif scale == 'linear':
        color_mapper = LinearColorMapper(palette=cmap, low=lo, high=hi)
    else:
        raise ValueError(
            'Please specify either `linear` or `log` scale for color.')

    fig.image([tpf.flux.value[fiducial_frame, :, :] + pedestal],
              x=tpf.column - 0.5,
              y=tpf.row - 0.5,
              dw=tpf.shape[2],
              dh=tpf.shape[1],
              dilate=True,
              color_mapper=color_mapper,
              name="tpfimg")

    # The colorbar will update with the screen stretch slider
    # The colorbar margin increases as the length of the tick labels grows.
    # This colorbar share of the plot window grows, shrinking plot area.
    # This effect is known, some workarounds might work to fix the plot area:
    # https://github.com/bokeh/bokeh/issues/5186

    if scale == 'log':
        ticker = LogTicker(desired_num_ticks=8)
    elif scale == 'linear':
        ticker = BasicTicker(desired_num_ticks=8)

    color_bar = ColorBar(color_mapper=color_mapper,
                         ticker=ticker,
                         label_standoff=-10,
                         border_line_color=None,
                         location=(0, 0),
                         background_fill_color='whitesmoke',
                         major_label_text_align='left',
                         major_label_text_baseline='middle',
                         title='e/s',
                         margin=0)
    fig.add_layout(color_bar, 'right')

    color_bar.formatter = PrintfTickFormatter(format="%14i")

    if tpf_source is not None:
        fig.rect('xx',
                 'yy',
                 1,
                 1,
                 source=tpf_source,
                 fill_color='gray',
                 fill_alpha=0.4,
                 line_color='white')

    # Configure the stretch slider and its callback function
    if scale == 'log':
        start, end = np.log10(vlo), np.log10(vhi)
        values = (np.log10(lo), np.log10(hi))
    elif scale == 'linear':
        start, end = vlo, vhi
        values = (lo, hi)

    stretch_slider = RangeSlider(start=start,
                                 end=end,
                                 step=vstep,
                                 title='Screen Stretch ({})'.format(scale),
                                 value=values,
                                 orientation='horizontal',
                                 width=200,
                                 direction='ltr',
                                 show_value=True,
                                 sizing_mode='fixed',
                                 height=15,
                                 name='tpfstretch')

    def stretch_change_callback_log(attr, old, new):
        """TPF stretch slider callback."""
        fig.select('tpfimg')[0].glyph.color_mapper.high = 10**new[1]
        fig.select('tpfimg')[0].glyph.color_mapper.low = 10**new[0]

    def stretch_change_callback_linear(attr, old, new):
        """TPF stretch slider callback."""
        fig.select('tpfimg')[0].glyph.color_mapper.high = new[1]
        fig.select('tpfimg')[0].glyph.color_mapper.low = new[0]

    if scale == 'log':
        stretch_slider.on_change('value', stretch_change_callback_log)
    if scale == 'linear':
        stretch_slider.on_change('value', stretch_change_callback_linear)

    return fig, stretch_slider
Ejemplo n.º 2
0
def make_tpf_figure_elements(tpf,
                             tpf_source,
                             pedestal=None,
                             fiducial_frame=None,
                             plot_width=370,
                             plot_height=340):
    """Returns the lightcurve figure elements.

    Parameters
    ----------
    tpf : TargetPixelFile
        TPF to show.
    tpf_source : bokeh.plotting.ColumnDataSource
        TPF data source.
    pedestal: float
        A scalar value to be added to the TPF flux values, often to avoid
        taking the log of a negative number in colorbars.
        Defaults to `-min(tpf.flux) + 1`
    fiducial_frame: int
        The tpf slice to start with by default, it is assumed the WCS
        is exact for this frame.

    Returns
    -------
    fig, stretch_slider : bokeh.plotting.figure.Figure, RangeSlider
    """
    if pedestal is None:
        pedestal = -np.nanmin(tpf.flux) + 1

    if tpf.mission in ['Kepler', 'K2']:
        title = 'Pixel data (CCD {}.{})'.format(tpf.module, tpf.output)
    elif tpf.mission == 'TESS':
        title = 'Pixel data (Camera {}.{})'.format(tpf.camera, tpf.ccd)
    else:
        title = "Pixel data"

    fig = figure(plot_width=plot_width,
                 plot_height=plot_height,
                 x_range=(tpf.column, tpf.column + tpf.shape[2]),
                 y_range=(tpf.row, tpf.row + tpf.shape[1]),
                 title=title,
                 tools='tap,box_select,wheel_zoom,reset',
                 toolbar_location="below",
                 border_fill_color="whitesmoke")

    fig.yaxis.axis_label = 'Pixel Row Number'
    fig.xaxis.axis_label = 'Pixel Column Number'

    vlo, lo, hi, vhi = np.nanpercentile(tpf.flux + pedestal,
                                        [0.2, 1, 95, 99.8])
    vstep = (np.log10(vhi) - np.log10(vlo)) / 300.0  # assumes counts >> 1.0!
    color_mapper = LogColorMapper(palette="Viridis256", low=lo, high=hi)

    fig.image([tpf.flux[fiducial_frame, :, :] + pedestal],
              x=tpf.column,
              y=tpf.row,
              dw=tpf.shape[2],
              dh=tpf.shape[1],
              dilate=True,
              color_mapper=color_mapper,
              name="tpfimg")

    # The colorbar will update with the screen stretch slider
    # The colorbar margin increases as the length of the tick labels grows.
    # This colorbar share of the plot window grows, shrinking plot area.
    # This effect is known, some workarounds might work to fix the plot area:
    # https://github.com/bokeh/bokeh/issues/5186
    color_bar = ColorBar(color_mapper=color_mapper,
                         ticker=LogTicker(desired_num_ticks=8),
                         label_standoff=-10,
                         border_line_color=None,
                         location=(0, 0),
                         background_fill_color='whitesmoke',
                         major_label_text_align='left',
                         major_label_text_baseline='middle',
                         title='e/s',
                         margin=0)
    fig.add_layout(color_bar, 'right')

    color_bar.formatter = PrintfTickFormatter(format="%14u")

    if tpf_source is not None:
        fig.rect('xx',
                 'yy',
                 1,
                 1,
                 source=tpf_source,
                 fill_color='gray',
                 fill_alpha=0.4,
                 line_color='white')

    # Configure the stretch slider and its callback function
    stretch_slider = RangeSlider(start=np.log10(vlo),
                                 end=np.log10(vhi),
                                 step=vstep,
                                 title='Screen Stretch (log)',
                                 value=(np.log10(lo), np.log10(hi)),
                                 orientation='horizontal',
                                 width=200,
                                 height=10,
                                 direction='ltr',
                                 show_value=True,
                                 sizing_mode='fixed',
                                 name='tpfstretch')

    def stretch_change_callback(attr, old, new):
        """TPF stretch slider callback."""
        fig.select('tpfimg')[0].glyph.color_mapper.high = 10**new[1]
        fig.select('tpfimg')[0].glyph.color_mapper.low = 10**new[0]

    stretch_slider.on_change('value', stretch_change_callback)

    return fig, stretch_slider
Ejemplo n.º 3
0
def density_handler(doc: Document) -> None:
    """
    Handler function for the density application.
    """

    task_id = doc.session_context.request.arguments.get('task_id')
    username = doc.session_context.request.arguments.get('username')
    user_dir = os.path.join(settings.USER_DATA, username)
    path_to_db = os.path.join(user_dir, task_id)

    try:
        conn = os.path.join(path_to_db, task_id + '.csv')
        df = pd.read_csv(conn)

        proteins = list(df.Protein.unique())
        lipids = list(df.Lipids.unique())
    except:
        proteins, lipids = [], []

        for o in os.listdir(path_to_db):
            key = o.split('/')[-1]
            if key.endswith('.npy'):
                if key.startswith('prot_'):
                    proteins.append('Protein(s)')
                else:
                    lipid = key.split('_')[0]
                    lipids.append(lipid)

    all_mpl_cmaps = [
        'viridis',
        'plasma',
        'inferno',
        'cividis',
        'Greys',
        'Purples',
        'Blues',
        'Greens',
        'Oranges',
        'Reds',
        'RdYlBu',
        'RdYlGn',
        'Spectral',
        'Spectral_r',
        'coolwarm',
        'coolwarm_r',
        'seismic',
        'YlOrBr',
        'YlOrRd',
        'OrRd',
        'PuRd',
        'RdPu',
        'BuPu',
        'GnBu',
        'PuBu',
        'YlGnBu',
        'PuBuGn',
        'BuGn',
        'YlGn',
        'PiYG',
        'PRGn',
        'BrBG',
        'PuOr',
        'RdGy',
        'RdBu',
    ]

    #TODO: globals declaration should not be necessary anymore.
    global prot_xyz
    prot_xyz = np.load(os.path.join(path_to_db, "prot_" + task_id + '.npy'))

    global l_xyz
    global x_min, x_max, y_min, y_max, z_min, z_max

    l_xyz = np.load(
        os.path.join(path_to_db, lipids[0] + "_" + task_id + '.npy'))

    x_min, x_max = l_xyz[:, 0].min(), l_xyz[:, 0].max()
    y_min, y_max = l_xyz[:, 1].min(), l_xyz[:, 1].max()
    z_min, z_max = l_xyz[:, 2].min(), l_xyz[:, 2].max()

    # widgets
    color_map = Select(title="Colormap",
                       value="viridis",
                       options=all_mpl_cmaps,
                       width=120)

    lipid = Select(title="Lipids", value=lipids[0], options=lipids, width=100)

    denstype = Select(title="Density Type",
                      value="All Proteins",
                      options=["All Proteins", "Average"],
                      width=120)

    number = Slider(title="Number of Bins",
                    value=380,
                    start=80,
                    end=500,
                    step=10,
                    width=200)

    protein = Select(title="Show Protein",
                     value="No",
                     options=["Yes", "No"],
                     width=90)

    gpcr = Select(title="Protein",
                  value=proteins[0],
                  options=proteins,
                  width=130)

    zrange = RangeSlider(start=z_min,
                         end=z_max,
                         value=(z_min, z_max),
                         step=0.2,
                         title="Z-Axis Range",
                         callback_policy='mouseup',
                         width=352)

    cbar_range = Slider(value=256,
                        start=0,
                        end=256,
                        step=1,
                        height=600,
                        orientation='vertical',
                        callback_policy='mouseup',
                        margin=(15, 0),
                        tooltips=False,
                        show_value=False)

    # colorschemes
    colormap = cm.get_cmap(color_map.value)
    bokehpalette = [
        mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N))
    ]

    def lipid_density(array, bins=160):
        """Given a 2D array, containing the x, y values of a lipid,
        return its histogram with edges."""
        x = array[:, 0]
        y = array[:, 1]

        lipid, e1, e2 = np.histogram2d(x, y, density=True, bins=bins)

        return lipid, e1, e2

    # Plot histogram image
    H, xe, ye = lipid_density(l_xyz, number.value)
    minx = np.abs(xe.min())
    miny = np.abs(ye.min())

    p1 = figure(plot_height=640, plot_width=640, tools='')
    image_source = ColumnDataSource(data=dict(image=[]))
    img = p1.image(image="image",
                   x=xe[0],
                   y=ye[0],
                   dw=xe[-1] + minx,
                   dh=ye[-1] + miny,
                   palette=bokehpalette,
                   source=image_source)

    circle_prot_source = ColumnDataSource(
        data=dict(x1=prot_xyz[:, 0], y1=prot_xyz[:, 1]))
    p1.circle(x="x1",
              y="y1",
              source=circle_prot_source,
              size=2,
              fill_alpha=0.2)

    cb_palette = LinearColorMapper(palette=bokehpalette,
                                   low=H.min(),
                                   high=H.max())
    color_bar = ColorBar(color_mapper=cb_palette,
                         width=8,
                         location=(0, 0),
                         label_standoff=10)
    color_bar.formatter = BasicTickFormatter(use_scientific=False)
    p1.add_layout(color_bar, 'right')

    # Make graph pretty
    p1.xgrid.grid_line_color = None
    p1.ygrid.grid_line_color = None
    p1.xaxis.major_tick_line_color = None
    p1.xaxis.minor_tick_line_color = None
    p1.yaxis.major_tick_line_color = None
    p1.yaxis.minor_tick_line_color = None
    p1.xaxis.major_label_text_font_size = '0pt'
    p1.yaxis.major_label_text_font_size = '0pt'
    p1.grid.visible = False
    p1.toolbar.logo = None
    p1.toolbar_location = None

    def update_all(cond=False, cmap=False):
        """
        Update the image showing all proteins.
        """
        if cond:
            # For efficiency execute only if GPCR structure changes
            global l_xyz
            global x_min, x_max, y_min, y_max, z_min, z_max

            l_xyz = np.load(
                os.path.join(path_to_db,
                             str(lipid.value) + "_" + task_id + '.npy'))
            x_min, x_max = l_xyz[:, 0].min(), l_xyz[:, 0].max()
            y_min, y_max = l_xyz[:, 1].min(), l_xyz[:, 1].max()
            z_min, z_max = l_xyz[:, 2].min(), l_xyz[:, 2].max()
            zrange.start = z_min
            zrange.end = z_max

            index = np.where((l_xyz[:, 2] > zrange.value[0])
                             & (l_xyz[:, 2] < zrange.value[1]))
            l_xyz_new = l_xyz[index]
        else:
            l_xyz_new = l_xyz

        if cmap:
            # For efficiency execute only if image colormap changes
            cb_cut_value = 256 - cbar_range.value

            cmap = color_map.value
            colormap = cm.get_cmap(cmap)
            bokehpalette = [
                mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N))
            ]
            bp_i = 0
            while bp_i < len(bokehpalette[:cb_cut_value]):
                bokehpalette[bp_i] = '#ffffff'
                bp_i += 1

            img.glyph.color_mapper.palette = bokehpalette
            color_bar.color_mapper.palette = bokehpalette

        # Update histogram image
        H, xe, ye = lipid_density(l_xyz_new, number.value)
        minx = np.abs(xe.min())
        miny = np.abs(ye.min())

        img.glyph.dw = xe[-1] + minx
        img.glyph.dh = ye[-1] + miny

        # update image source
        image_source.data = dict(image=[H])

    def update_protein(cond=False):
        """
        Update the protein representation.
        """
        if cond:
            # For efficiency execute only if GPCR structure changes
            global prot_xyz

        if protein.value == "Yes":
            circle_prot_source.data = dict(x1=prot_xyz[:, 0],
                                           y1=prot_xyz[:, 1])

        elif protein.value == "No":
            circle_prot_source.data = dict(x1=[], y1=[])

    def update_cbar():

        cb_cut_value = 256 - cbar_range.value

        cmap = color_map.value
        colormap = cm.get_cmap(cmap)
        bokehpalette = [
            mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N))
        ]

        bp_i = 0
        while bp_i < len(bokehpalette[:cb_cut_value]):
            bokehpalette[bp_i] = '#ffffff'
            bp_i += 1

        img.glyph.color_mapper.palette = bokehpalette
        color_bar.color_mapper.palette = bokehpalette

    # event listeners
    controls = [lipid, zrange, gpcr]
    for control in controls:
        control.on_change('value',
                          lambda attr, old, new: update_denstype(cond=True))

    number.on_change('value', lambda attr, old, new: update_denstype())
    color_map.on_change('value',
                        lambda attr, old, new: update_denstype(cmap=True))
    protein.on_change('value', lambda attr, old, new: update_protein())
    denstype.on_change('value', lambda attr, old, new: update_denstype())
    cbar_range.on_change('value', lambda attr, old, new: update_cbar())

    # deal with what gets updated and what not.
    def update_denstype(cond=False, cmap=False):
        update_all(cond, cmap)
        update_protein(cond)

    update_denstype()
    input1 = row([gpcr, lipid, color_map, protein])
    input2 = row([p1, cbar_range])
    input3 = row([number, zrange])
    input3 = column([input1, input2, input3])

    l = layout([input3])

    doc.add_root(l)
    doc.title = "Density App"
Ejemplo n.º 4
0
def make_map():
    #Create figure object.
    p = figure(title='Map of COVID-19 ' + plot_title[sel_var] + ' (' +
               txt_src + ')',
               plot_height=550,
               plot_width=950,
               x_range=(-180, 180),
               y_range=(-65, 90),
               toolbar_location='above',
               tools='pan, wheel_zoom, box_zoom, reset, tap',
               sizing_mode="scale_width")
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Choose linear or logarithmic color mapper
    if tog_lin.active:
        mapper = LinearColorMapper(palette=palette,
                                   low=0,
                                   high=plot_max[sel_var])
        ticker = BasicTicker()
    else:
        mapper = LogColorMapper(palette=palette,
                                low=plot_min[sel_var],
                                high=plot_max[sel_var])
        ticker = LogTicker()

    color_bar = ColorBar(color_mapper=mapper,
                         label_standoff=8,
                         height=20,
                         ticker=ticker,
                         border_line_color=None,
                         location=(0, 0),
                         orientation='horizontal')

    if not rb_abs_rel.active:
        color_bar.formatter = NumeralTickFormatter(format='0[.]0a')
    elif not tog_lin.active:
        color_bar.formatter = NumeralTickFormatter(format='0.[00000]')

    #Add patch renderer to figure.
    ren_map = p.patches('xs',
                        'ys',
                        source=source_map,
                        line_color='black',
                        line_width=0.25,
                        fill_color={
                            'field': 'Selected',
                            'transform': mapper
                        },
                        fill_alpha=1)

    #Specify figure layout.
    p.add_layout(color_bar, 'below')

    #Add hover tool
    p.add_tools(
        HoverTool(tooltips=[
            ('Country/region', '@Country'), ('Population', '@Population'),
            ('Tot Cases', '@Cases_Tot_Abs @Cases_Tot_Rel{custom}'),
            ('New Cases', '@Cases_New_Abs @Cases_New_Rel{custom}'),
            ('Avg Cases', '@Cases_Avg_Abs @Cases_Avg_Rel{custom}'),
            ('Tot Deaths', '@Deaths_Tot_Abs @Deaths_Tot_Rel{custom}'),
            ('New Deaths', '@Deaths_New_Abs @Deaths_New_Rel{custom}'),
            ('Avg Deaths', '@Deaths_Avg_Abs @Deaths_Avg_Rel{custom}')
        ],
                  formatters={
                      '@Cases_Tot_Rel': custom,
                      '@Cases_New_Rel': custom,
                      '@Cases_Avg_Rel': custom,
                      '@Deaths_Tot_Rel': custom,
                      '@Deaths_New_Rel': custom,
                      '@Deaths_Avg_Rel': custom
                  }))
    return p
Ejemplo n.º 5
0
    def densityApp(doc):
        """
        Handler function for the density application.
        """
        nonlocal t, lipids, resolution, prot_xyz, l_xyz

        all_mpl_cmaps = [
            'viridis',
            'plasma',
            'inferno',
            'cividis',
            'Greys',
            'Purples',
            'Blues',
            'Greens',
            'Oranges',
            'Reds',
            'RdYlBu',
            'RdYlGn',
            'Spectral',
            'Spectral_r',
            'coolwarm',
            'coolwarm_r',
            'seismic',
            'YlOrBr',
            'YlOrRd',
            'OrRd',
            'PuRd',
            'RdPu',
            'BuPu',
            'GnBu',
            'PuBu',
            'YlGnBu',
            'PuBuGn',
            'BuGn',
            'YlGn',
            'PiYG',
            'PRGn',
            'BrBG',
            'PuOr',
            'RdGy',
            'RdBu',
        ]
        lipids = [x for x in lipids if not x.startswith('prot')]

        x_min, x_max = l_xyz[:, 0].min(), l_xyz[:, 0].max()
        y_min, y_max = l_xyz[:, 1].min(), l_xyz[:, 1].max()
        z_min, z_max = l_xyz[:, 2].min(), l_xyz[:, 2].max()

        # widgets
        color_map = Select(title="Colormap",
                           value="viridis",
                           options=all_mpl_cmaps,
                           width=120)

        lipid = Select(title="Lipids",
                       value=lipids[0],
                       options=lipids,
                       width=100)

        number = Slider(title="Number of Bins",
                        value=150,
                        start=80,
                        end=500,
                        step=10,
                        width=200)

        protein = Select(title="Show Protein",
                         value="No",
                         options=["Yes", "No"],
                         width=90)

        zrange = RangeSlider(start=z_min,
                             end=z_max,
                             value=(z_min, z_max),
                             step=0.2,
                             title="Z-Axis Range",
                             callback_policy='mouseup',
                             width=352)

        cbar_range = Slider(value=256,
                            start=0,
                            end=256,
                            step=1,
                            height=600,
                            orientation='vertical',
                            callback_policy='mouseup',
                            margin=(15, 0),
                            tooltips=False,
                            show_value=False)

        # colorschemes
        colormap = cm.get_cmap(color_map.value)
        bokehpalette = [
            mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N))
        ]

        def lipid_density(array, bins=160):
            """Given a 2D array, containing the x, y values of a lipid,
            return its histogram with edges."""
            x = array[:, 0]
            y = array[:, 1]

            lipid, e1, e2 = np.histogram2d(x, y, density=True, bins=bins)

            return lipid, e1, e2

        # Plot histogram image
        H, xe, ye = lipid_density(l_xyz, number.value)
        minx = np.abs(xe.min())
        miny = np.abs(ye.min())

        p1 = figure(plot_height=640, plot_width=640, tools='')
        image_source = ColumnDataSource(data=dict(image=[]))
        img = p1.image(image="image",
                       x=xe[0],
                       y=ye[0],
                       dw=xe[-1] + minx,
                       dh=ye[-1] + miny,
                       palette=bokehpalette,
                       source=image_source)

        circle_prot_source = ColumnDataSource(
            data=dict(x1=prot_xyz[:, 0], y1=prot_xyz[:, 1]))
        p1.circle(x="x1",
                  y="y1",
                  source=circle_prot_source,
                  size=2,
                  fill_alpha=0.2)

        cb_palette = LinearColorMapper(palette=bokehpalette,
                                       low=H.min(),
                                       high=H.max())
        color_bar = ColorBar(color_mapper=cb_palette,
                             width=8,
                             location=(0, 0),
                             label_standoff=10)
        color_bar.formatter = BasicTickFormatter(use_scientific=False)
        p1.add_layout(color_bar, 'right')

        # Make graph pretty
        p1.xgrid.grid_line_color = None
        p1.ygrid.grid_line_color = None
        p1.xaxis.major_tick_line_color = None
        p1.xaxis.minor_tick_line_color = None
        p1.yaxis.major_tick_line_color = None
        p1.yaxis.minor_tick_line_color = None
        p1.xaxis.major_label_text_font_size = '0pt'
        p1.yaxis.major_label_text_font_size = '0pt'
        p1.grid.visible = False
        p1.toolbar.logo = None
        p1.toolbar_location = None

        def update_all(cond=False, cmap=False):
            """
            Update the image showing all proteins.
            """
            if cond:
                # For efficiency execute only if GPCR structure changes
                if filenames is not None:
                    update_l_xyz = np.load(lipid.value)
                else:
                    update_l_xyz = flat_density(t, [lipid.value], t.n_frames)

                x_min, x_max = update_l_xyz[:, 0].min(), update_l_xyz[:,
                                                                      0].max()
                y_min, y_max = update_l_xyz[:, 1].min(), update_l_xyz[:,
                                                                      1].max()
                z_min, z_max = update_l_xyz[:, 2].min(), update_l_xyz[:,
                                                                      2].max()
                zrange.start = z_min
                zrange.end = z_max

                index = np.where((update_l_xyz[:, 2] > zrange.value[0])
                                 & (update_l_xyz[:, 2] < zrange.value[1]))
                l_xyz_new = update_l_xyz[index]
            else:
                l_xyz_new = l_xyz

            if cmap:
                # For efficiency execute only if image colormap changes
                cb_cut_value = 256 - cbar_range.value

                cmap = color_map.value
                colormap = cm.get_cmap(cmap)
                bokehpalette = [
                    mpl.colors.rgb2hex(m)
                    for m in colormap(np.arange(colormap.N))
                ]
                bp_i = 0
                while bp_i < len(bokehpalette[:cb_cut_value]):
                    bokehpalette[bp_i] = '#ffffff'
                    bp_i += 1

                img.glyph.color_mapper.palette = bokehpalette
                color_bar.color_mapper.palette = bokehpalette

            # Update histogram image
            H, xe, ye = lipid_density(l_xyz_new, number.value)
            minx = np.abs(xe.min())
            miny = np.abs(ye.min())

            img.glyph.dw = xe[-1] + minx
            img.glyph.dh = ye[-1] + miny

            # update image source
            image_source.data = dict(image=[H])

        def update_protein():
            """
            Update the protein representation.
            """

            if protein.value == "Yes":
                circle_prot_source.data = dict(x1=prot_xyz[:, 0],
                                               y1=prot_xyz[:, 1])

            elif protein.value == "No":
                circle_prot_source.data = dict(x1=[], y1=[])

        def update_cbar():

            cb_cut_value = 256 - cbar_range.value

            cmap = color_map.value
            colormap = cm.get_cmap(cmap)
            bokehpalette = [
                mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N))
            ]

            bp_i = 0
            while bp_i < len(bokehpalette[:cb_cut_value]):
                bokehpalette[bp_i] = '#ffffff'
                bp_i += 1

            img.glyph.color_mapper.palette = bokehpalette
            color_bar.color_mapper.palette = bokehpalette

        # event listeners
        controls = [lipid, zrange]
        for control in controls:
            control.on_change(
                'value', lambda attr, old, new: update_denstype(cond=True))

        number.on_change('value', lambda attr, old, new: update_denstype())
        color_map.on_change('value',
                            lambda attr, old, new: update_denstype(cmap=True))
        protein.on_change('value', lambda attr, old, new: update_protein())
        cbar_range.on_change('value', lambda attr, old, new: update_cbar())

        # deal with what gets updated and what not.
        def update_denstype(cond=False, cmap=False):
            update_all(cond, cmap)
            update_protein()

        update_denstype()
        input1 = row([lipid, color_map, protein])
        input2 = row([p1, cbar_range])
        input3 = row([number, zrange])
        input3 = column([input1, input2, input3])

        l = layout([input3])

        doc.add_root(l)
        doc.title = "Density App"
Ejemplo n.º 6
0
# marking the Hover point
p2.circle('ra',
          'dec',
          source=source2,
          radius=0.0186,
          fill_color=None,
          line_color=None,
          hover_fill_color={
              'field': 'integ',
              'transform': mapper
          },
          line_width=3,
          hover_line_color='red')

color_bar.formatter = formatter
p2.add_layout(color_bar, 'left')

#infos
info, nlines = write_info('integ', tests['integ'])
txt = PreText(text=info, height=nlines * 20, width=p2.plot_width)
p2txt = column(widgetbox(txt), p2)

#layout = gridplot([[p2txt]], responsive=False)
info_col = Div(text=write_description('integ'), width=p2.plot_width)
layout = column(info_col, p2)

# End of Bokeh Block
curdoc().add_root(layout)
curdoc().title = "INTEG"
Ejemplo n.º 7
0
def lidar2js(path, ncfile, jsfile):
  fname_nc  = join(path,ncfile)
  if isfile(fname_nc):
    if Debug: 
      print "Found file: ", ncfile
    ds      = Dataset(fname_nc,'r',format="NETCDF3_CLASSIC") 
    t_raw   = ds.variables["time"]
    z       = ds.variables["alt1"][:]
    bsc532  = ds.variables["bsc532"][:]
    bsc1064 = ds.variables["bsc1064"][:]
    zb      = ds.variables["zb"][:]
    zpbl    = ds.variables["zpbl"][:]
    t       = num2date(t_raw[:], units = t_raw.units)
    tm      = t_raw[:]
    ds.close()
  else:
    if Debug: 
      print "Not found file: ", ncfile
    return "No Data"

  DX       = t[1]-t[0]
  Dx_sec   = DX.total_seconds()
  Nx       = len(t)
  Nx0      = int(max_days*86400.0/Dx_sec)
  if Nx0<Nx: Nx=Nx0
  tmin     = t[-Nx]
  tmax     = t[-1]+DX
  twidth   = 1000.0*(tmax-tmin).total_seconds()

  zmin = 0
  zmax = z[-1]

  my_cmap,my_norm,my_rgb = build_palette4(levs1,levs2,levs3,levs4)
  img532_raw             = my_norm(bsc532[-Nx:,:])
  img1064_raw            = my_norm(bsc1064[-Nx:,:])

  data1   = {'zbase':      zb[-Nx:], 
             'zpbl':       zpbl[-Nx:], 
             'tcenter':    t[-Nx:] + DX/2,
            }
  data2   = { 'image532':  [np.array(img532_raw.filled().T,  dtype=np.int8)], 
              'image1064': [np.array(img1064_raw.filled().T, dtype=np.int8)], 
            }
  data3   = { 'profile532': bsc532[-1,:],
              'range':      z
            }
  src     = ColumnDataSource(data=data1)
  src_img = ColumnDataSource(data=data2)
  src_z   = ColumnDataSource(data=data3)

  color_mapper = LinearColorMapper(palette=[rgb2hex(item) for item in my_rgb], 
                                   low=0, 
                                   high=my_cmap.N
                                   )

  plot = figure(x_range=(tmin,tmax), y_range=(zmin,zmax), 
              title="Attenuated Backscatter coefficient [/sr /km]",
              toolbar_location="above",
              tools = "pan,wheel_zoom,box_zoom,reset,save",
              active_scroll=None, 
              active_drag=None,
              active_inspect=None,
            #  toolbar_sticky=False,
              y_axis_label = 'Height [km]',
              plot_width=900, 
              plot_height=350, 
              )
  plot.toolbar.logo=None

  plot2 = figure(title="Last Profile at 532 nm - {}".format(t[-1]),
  	             tools = "pan,wheel_zoom,box_zoom,reset,save",
  	             y_axis_label = 'Height [km]',
  	             x_axis_label = 'Attenuated Backscatter coefficient [/sr /km]',
                 # y_axis_type="log",
                 active_inspect=None,
                 plot_width=900, 
                 plot_height=350
  	             )
  plot2.toolbar.logo=None
  
  plot2.line(x='profile532', y='range',
             source=src_z, 
             line_color="black", 
             )

  im = plot.image(image="image532", 
                  source=src_img,
                  color_mapper=color_mapper,
                  dh=zmax, dw=twidth, 
                  x=tmin, y=zmin
                  ) 

  #l1 = plot.line(   x='tcenter', y='zbase', source=source, line_width=2, alpha=0.8, color="black")
  #l2 = plot.line(   x='tcenter', y='zpbl' , source=source, line_width=2, alpha=0.8, color="red")

  r1 = plot.circle( x='tcenter', y='zbase', 
                    source=src, 
                    fill_color="black", 
                    line_color="black", 
                    fill_alpha=0.3,
                    size=4,
                    name="r1"
                    )
  r2 = plot.square( x='tcenter', y='zpbl', 
                    source=src, 
                    fill_color="red", 
                    line_color="red", 
                    fill_alpha=0.3,
                    size=4,
                    name="r2"
                    )
  for item in [r1,r2]: item.visible = False

  color_bar = ColorBar(color_mapper=color_mapper, 
                       ticker=FixedTicker(ticks=[0,5,20,25]),
                       label_standoff=12, 
                       border_line_color=None, 
                       location=(0,0)
                       )
  color_bar.bar_line_color = "black"
  color_bar.major_tick_line_color = "black"
  color_bar.formatter = FuncTickFormatter(code="return {}[tick].toExponential(2)".format(levs))

  legend = Legend(items=[("Cloud Base",[r1]), ("PBL Height",[r2])], 
                  location="top_left"
                  )
  legend.click_policy = "hide"
  legend.visible = False

  hover = HoverTool(names=["r1","r2"])
  hover.tooltips=[("Cloud base", "@zbase km"), 
                  ("PBL height", "@zpbl km"), 
                  ("Time", "@tcenter{%d-%b-%y %H:%M}")]
  hover.formatters = { "tcenter": "datetime"}

  hover2 = HoverTool(tooltips=[
                     ("Signal", "@profile532"), 
                     ("Range", "@range"), 
                     ])

  plot.add_layout(color_bar, 'right')
  plot.add_layout(legend)
  plot.add_tools(hover)

  plot2.add_tools(hover2)
  
  plot.xaxis.formatter = DatetimeTickFormatter(months = ['%Y-%b'],
                                               years  = ['%Y'],
                                               days   = ['%d-%b-%Y']
                                               )

  callback = CustomJS(args=dict(im=im), code="""
      var f = cb_obj.active
      if (f==0){
        im.glyph.image.field = "image532"
      } else {
        im.glyph.image.field = "image1064"
      }
      im.glyph.change.emit();
  """)
  radio_button_group = RadioButtonGroup(labels=["532 nm", "1064 nm"], active=0)
  radio_button_group.js_on_change('active',callback)

  callback2 = CustomJS(args=dict(leg=legend), code="""
    leg.visible = !leg.visible
    console.log("ol")
  """)
  toggle = Toggle(label="Legend", button_type="default")
  toggle.js_on_click(callback2)

  layout = column(
  				children=[ 
  					row(widgetbox(radio_button_group, width=200), widgetbox(toggle, width=80) ), 
  					plot,
  					Spacer(height=50),
  					# row(Spacer(width=50),plot2),
  					plot2, 
					], 
  				)

  			
  #show(plot)
  return create_js(layout,path,jsfile)
Ejemplo n.º 8
0
def make_plots_tab2(source_heat_map_temp, source_events_temp, source_boundaries, source_rolling_temp, source_data_aggregated_day_temp, dates_list, hour_list):

    colors_heat_map = ['#fff7fb', '#ece7f2', '#d0d1e6', '#a6bddb', '#74a9cf', '#3690c0', '#0570b0', '#045a8d', '#023858']
    mapper_heat_map = LogColorMapper(palette=colors_heat_map, low= 0, high=1000000)

    TOOLS_heat_map = "save,pan ,reset, xwheel_zoom"

    p_heat_map = figure(title="Water consumption in Log(Litres)",x_axis_type="datetime", x_range = dates_list, y_range = list(reversed(hour_list)),
                        tools=TOOLS_heat_map)

    heat_map = p_heat_map.rect(x="date", y="hour", width=1, height=1, source = source_heat_map_temp, fill_color={'field': 'rate', 'transform': mapper_heat_map}, line_color=None)
    p_events = p_heat_map.triangle(x = 'date', y = 'Hour', legend= "Events", source = source_events_temp, color = 'color', size= 12, line_color="black")

    #boundaries
    p_boundary_start = p_heat_map.line(x = 'start_date', y = 'hour', source =source_boundaries, line_dash = 'dashed', color = "firebrick", line_width = 4 )
    p_boundary_end = p_heat_map.line(x = 'end_date', y = 'hour', source =source_boundaries, line_dash = 'dashed', color = "firebrick", line_width = 4 )


    color_bar = ColorBar(color_mapper=mapper_heat_map, border_line_color=None,label_standoff=12, location=(0, 0))
    color_bar.formatter = NumeralTickFormatter(format='0.0')
    p_heat_map.add_layout(color_bar, 'right')

    heat_map_hover = HoverTool(renderers=[heat_map],
                        tooltips=OrderedDict([('Water Consumption (Litres)', '@rate'),
                                            ('date hour', '@date'),
                                             ('hour', '@hour'),
                                           ]))

    events_hover = HoverTool(renderers=[p_events],
            tooltips=OrderedDict([('Event description',
            '@{Hoofdtype Melding}'),
            ]))

    p_heat_map.grid.grid_line_color = None
    p_heat_map.axis.axis_line_color = None
    p_heat_map.axis.major_tick_line_color = None
    p_heat_map.xaxis.major_label_text_font_size = '0pt'  # turn off x-axis tick labels
    p_heat_map.yaxis.axis_label = 'Hour'
    p_heat_map.xaxis.axis_label = None
    p_heat_map.axis.major_label_standoff = 0

    p_heat_map.legend.location = "top_left"
    p_heat_map.legend.click_policy= "hide"
    p_heat_map.add_tools(heat_map_hover)
    p_heat_map.add_tools(events_hover)

    p_outliers = figure(title="Daily water consumptions in Litres", x_axis_type="datetime", tools=TOOLS_heat_map, x_range = dates_list)
    p_circle = p_outliers.circle(x = 'date', y = 'delta_total', size='s', color= 'c', alpha='a', legend= "Consumption in L",
                                 source = source_data_aggregated_day_temp)

    p_ub = p_outliers.line(x='date', y='ub', legend='upper_bound (2 sigma)', line_dash = 'dashed', line_width = 4, color = '#984ea3',
                           source = source_rolling_temp)
    p_mean = p_outliers.line(x='date', y='y_mean', source = source_rolling_temp, line_dash = 'dashed', line_width = 3,
                             legend='moving_average', color = '#4daf4a')

    #Dynamic boundaries
    p_boundary_start = p_outliers.line(x = 'start_date', y = 'y', source =source_boundaries, line_dash = 'dashed', color = "firebrick", line_width = 4 )
    p_boundary_end = p_outliers.line(x = 'end_date', y = 'y', source =source_boundaries, line_dash = 'dashed', color = "firebrick", line_width = 4 )


    p_outliers.legend.location = "top_left"
    p_outliers.legend.orientation = "horizontal"
    p_outliers.legend.click_policy= "hide"
    p_outliers.ygrid.band_fill_color = "olive"
    p_outliers.ygrid.band_fill_alpha = 0.1
    p_outliers.xaxis.axis_label = None
    p_outliers.yaxis.axis_label = 'Litres'
    p_outliers.xaxis.major_label_orientation = 3.1416 / 3
    p_outliers.x_range = p_heat_map.x_range# Same axes as the heatMap

    p_outliers.xaxis.formatter = FuncTickFormatter(code=""" var labels = %s; return labels[tick];""" % dates_list)


    circle_hover = HoverTool(renderers=[p_circle],
                        tooltips=OrderedDict([('date', '@date'),
                                              ('Water Consumption (L)', '@delta_total'),
                                             ]))

    p_ub_hover = HoverTool(renderers=[p_ub],
                        tooltips=OrderedDict([('date', '@date'),
                                              ('UpperBound water consumption (L)', '@ub'),
                                             ]))

    p_mean_hover = HoverTool(renderers=[p_mean],
                        tooltips=OrderedDict([('date', '@date'),
                                              ('Mean water consumption (L)', '@y_mean'),
                                             ]))

    p_outliers.add_tools(circle_hover)
    p_outliers.add_tools(p_ub_hover)
    p_outliers.add_tools(p_mean_hover)

    return p_heat_map, p_outliers