Exemplo n.º 1
1
def show(sample_size):
    global session
    global scatter_plot
    global source
    global pie_chart_source
    global line_chart_source
    global slider
    DB.__init__(sample_size)
    min_time = DB.min_time()
    max_time = DB.max_time()
    print min_time
    print min_time
    xs, ys, color, time = DB.get_current()
    xs = [xs[i] for i,v in enumerate(time) if time[i] == min_time]
    ys = [ys[i] for i,v in enumerate(time) if time[i] == min_time]
    color = [color[i] for i,v in enumerate(time) if time[i] == min_time]

    time_dict = Counter(time)
    pie_chart_source = ColumnDataSource(data=ChartMath.compute_color_distribution('x', 'y', 'color', color))
    line_chart_source = ColumnDataSource(data=dict(x=[key for key in time_dict], y=[time_dict[key] for key in time_dict]))
    source = ColumnDataSource(data=dict(x=xs, y=ys, color=color))

    scatter_plot = Figure(plot_height=800,
                          plot_width=1200,
                          title="Plot of Voters",
                          tools="pan, reset, resize, save, wheel_zoom",
                          )

    scatter_plot.circle('x', 'y', color='color', source=source, line_width=0, line_alpha=0.001, fill_alpha=0.5, size=15)
    scatter_plot.patches('x', 'y', source=state_source, fill_alpha=0.1, line_width=3, line_alpha=1)

    scatter_plot.x_range.on_change('end', update_coordinates)
    line_chart = Figure(title="Distribution over Time", plot_width=350, plot_height=350)
    line_chart.line(x='x', y='y', source=line_chart_source)
    pie_chart_plot = Figure(plot_height=350,
                            plot_width=350,
                            title="Voter Distribution",
                            x_range=(-1, 1),
                            y_range=(-1, 1))
    pie_chart_plot.wedge(x=0, y=0, source=pie_chart_source, radius=1, start_angle="x", end_angle="y", color="color")
    slider = Slider(start=min_time, end=max_time, value=min_time, step=1, title="Time")

    slider.on_change('value', update_coordinates)
    h = hplot(scatter_plot, vplot(pie_chart_plot, line_chart))
    vplot(slider, h, width=1600, height=1800)
    session = push_session(curdoc())
    session.show()
    #script = autoload_server(scatter_plot, session_id=session.id)
    session.loop_until_closed()
Exemplo n.º 2
0
    def __plot_control_chart(self, index):
        plot_args = self.__conf.plot_args[index]
        annotations = self.__conf.annotations[index]
        if not annotations:
            annotations = PlotAnnotationContainer()
        plot = Figure(plot_height=500, plot_width=600,
                      x_range=FactorRange(factors=self.__factors,
                                          name='x_factors'))
        plot.toolbar.logo = None
        plot.title.text = 'Control chart'
        hover_tool = self.__create_tooltips()
        plot.add_tools(hover_tool)
        plot.xaxis.major_label_orientation = pi / 4
        plot.xaxis.major_label_standoff = 10
        if not self.__values['_calc_value'].empty:
            if 'color' not in plot_args:
                plot_args['color'] = 'navy'
            if 'alpha' not in plot_args:
                plot_args['alpha'] = 0.5
            self.__values['s_fac'] = self.__factors
            col_ds = ColumnDataSource(self.__values, name='control_data')
            col_ds.js_on_change('data', CustomJS(code="refresh_maps();"))
            plot.circle('s_fac', '_calc_value', source=col_ds, name='circle',
                        **plot_args)
            plot.line('s_fac', '_calc_value', source=col_ds, name='line',
                      **plot_args)
        min_anno, max_anno = annotations.calc_min_max_annotation(
            self.__values['_calc_value'])
        annotations.plot(plot, self.__values['_calc_value'])

        anno_range = max_anno - min_anno
        if anno_range and not isnan(anno_range):
            plot.y_range.start = min_anno - anno_range
            plot.y_range.end = max_anno + anno_range
        return plot
Exemplo n.º 3
0
    def plot_light_curve_source(figure: Figure,
                                data_source: ColumnDataSource,
                                time_column_name: str = 'Time (BTJD)',
                                flux_column_name: str = 'Relative flux',
                                color_value_column_name: str = 'Time (BTJD)'):
        """
        Plots the light curve data source on the passed figure.

        :param figure: The figure to plot to.
        :param data_source: The data source containing the light curve data.
        :param time_column_name: The name of the time column whose values will be used on the x axis.
        :param flux_column_name: The name of the flux column whose values will be used on the y axis.
        :param color_value_column_name: The name of the column whose values will be used to determine data point color.
        """
        mapper = LinearColorMapper(
            palette='Plasma256',
            low=np.min(data_source.data[color_value_column_name]),
            high=np.max(data_source.data[color_value_column_name]))
        colors = {'field': color_value_column_name, 'transform': mapper}
        figure.circle(time_column_name,
                      flux_column_name,
                      source=data_source,
                      fill_color=colors,
                      fill_alpha=0.1,
                      line_color=colors,
                      line_alpha=0.4)
Exemplo n.º 4
0
def qqnorm_viz(
    actual_qs: np.ndarray,
    theory_qs: np.ndarray,
    col: str,
    plot_width: int,
    plot_height: int,
) -> Panel:
    """
    Render a qq plot
    """
    tooltips = [("x", "@x"), ("y", "@y")]
    fig = Figure(
        plot_width=plot_width,
        plot_height=plot_height,
        title=f"{col}",
        tools="hover",
        toolbar_location=None,
        tooltips=tooltips,
    )
    fig.circle(
        x=theory_qs,
        y=actual_qs,
        size=3,
        color=PALETTE[0],
    )
    all_values = np.concatenate((theory_qs, actual_qs))
    fig.line(
        x=[np.min(all_values), np.max(all_values)],
        y=[np.min(all_values), np.max(all_values)],
        color="red",
    )
    tweak_figure(fig, "qq")
    fig.xaxis.axis_label = "Normal Quantiles"
    fig.yaxis.axis_label = f"Quantiles of {col}"
    return Panel(child=fig, title="QQ normal plot")
Exemplo n.º 5
0
    def construct_figure(self, x, y, metric):
        # workaround to format date in the hover tool at the moment bokeh
        source = ColumnDataSource(data=dict(x=x, y=y, time=[e.strftime('%d %b %Y') for e in x]))

        hover = HoverTool(
            tooltips=[
                ("Date", "@time"),
                ("Return", "@y{0.0%}"),
            ]
        )

        # create a new plot with a a datetime axis type
        p2 = Figure(x_axis_type="datetime", title=metric,toolbar_location="above",
                    tools=[hover, 'box_zoom, box_select, crosshair,resize, reset, save,  wheel_zoom'])

        # add renderers
        p2.circle(x, y, size=8, color='black', alpha=0.2, legend=metric, source=source)
        p2.line(x, y, color='navy', legend=metric, source=source)

        # NEW: customize by setting attributes
        # p2.title = metric
        p2.legend.location = "top_left"
        p2.grid.grid_line_alpha = 0
        p2.xaxis.axis_label = 'Date'
        p2.yaxis.axis_label = metric
        p2.ygrid.band_fill_color = "olive"
        p2.ygrid.band_fill_alpha = 0.1
        p2.xaxis.formatter = DatetimeTickFormatter(formats={'days': ['%d %b'], 'months': ['%b %Y']})
        p2.yaxis.formatter = NumeralTickFormatter(format="0.0%")
        # format="0.0%"

        return p2
Exemplo n.º 6
0
def plot1():
    # copy/pasted from Bokeh Getting Started Guide - used as an example
    grouped = autompg.groupby("yr")
    mpg = grouped.mpg
    avg, std = mpg.mean(), mpg.std()
    years = list(grouped.groups)
    american = autompg[autompg["origin"] == 1]
    japanese = autompg[autompg["origin"] == 3]

    p = Figure(title="MPG by Year (Japan and US)")

    p.vbar(x=years,
           bottom=avg - std,
           top=avg + std,
           width=0.8,
           fill_alpha=0.2,
           line_color=None,
           legend="MPG 1 stddev")

    p.circle(x=japanese["yr"],
             y=japanese["mpg"],
             size=10,
             alpha=0.5,
             color="red",
             legend="Japanese")

    p.triangle(x=american["yr"],
               y=american["mpg"],
               size=10,
               alpha=0.3,
               color="blue",
               legend="American")

    p.legend.location = "top_left"
    return json.dumps(json_item(p, "myplot"))
Exemplo n.º 7
0
def create_figure():
    xs, ys, colors, sizes = model.get_axes_values()
    fig_args = dict(tools='pan', plot_height=600, plot_width=800)

    if model.x_field in model.discrete_column_names and model.y_field in model.discrete_column_names:
        figure = Figure(x_range=xs, y_range=ys, **fig_args)
        figure.axis.major_label_orientation = math.pi / 4
    elif model.x_field in model.discrete_column_names:
        figure = Figure(x_range=xs, **fig_args)
        figure.xaxis.major_label_orientation = math.pi / 4
    elif model.y_field in model.discrete_column_names:
        figure = Figure(y_range=ys, **fig_args)
        figure.yaxis.major_label_orientation = math.pi / 4
    else:
        figure = Figure(**fig_args)

    figure.circle(x=xs, y=ys, color=colors, size=sizes, line_color="white", alpha=0.8)
    figure.toolbar_location = None
    figure.xaxis.axis_label = model.x_field
    figure.yaxis.axis_label = model.y_field
    figure.background_fill_color = model.background_fill
    figure.border_fill_color = model.background_fill
    figure.axis.axis_line_color = "white"
    figure.axis.axis_label_text_color = "white"
    figure.axis.major_label_text_color = "white"
    figure.axis.major_tick_line_color = "white"
    figure.axis.minor_tick_line_color = "white"
    figure.axis.minor_tick_line_color = "white"
    figure.grid.grid_line_dash = [6, 4]
    figure.grid.grid_line_alpha = .3
    return figure
Exemplo n.º 8
0
def plotnorm(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None,
             tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400):
    """ Make a light-weight norm figure """

    fields = ['zs', 'sizes', 'colors', 'abssnr', 'key', 'snrs']

    if not circleinds: circleinds = range(len(data['snrs']))

    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems() if key in fields}))
    norm = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='SNR observed',
                  y_axis_label='SNR expected', tools=tools, webgl=True)
    norm.circle('abssnr', 'zs', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source)

    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems() if key in fields}))
        norm.cross('abssnr', 'zs', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems() if key in fields}))
        norm.circle('abssnr', 'zs', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2)

    hover = norm.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = norm.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return norm
Exemplo n.º 9
0
def line_plot(ticker, alias, x_range=None):
    p = Figure(
        title=alias, x_range=x_range, x_axis_type='datetime',
        plot_width=1000, plot_height=200, title_text_font_size="10pt",
        tools="pan,wheel_zoom,box_select,reset"
    )
    p.circle('date', ticker, size=2, source=source, nonselection_alpha=0.02)
    return p
Exemplo n.º 10
0
 def plot_lang(self, fig: Figure, lang: str, source: ColumnDataSource):
     col = next(COLORS)
     common_kw = {
         "line_color": col,
         "source": source,
         "legend_label": f"{lang} Code Count",
     }
     fig.circle("x", "y", fill_color="white", size=8, **common_kw)
     fig.line("x", "y", line_width=2, **common_kw)
Exemplo n.º 11
0
 def create_2d_plot(self) -> Figure:
     fig = Figure(width=300, height=300, x_range=(-2, 2), y_range=(-2, 2))
     fig.circle(x='x', y='y', color='color', source=self.data_source)
     fig.segment(x0='x',
                 y0='y',
                 x1='xn',
                 y1='yn',
                 color='color',
                 line_dash='dotted',
                 source=self.data_source)
     return fig
Exemplo n.º 12
0
def Main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-st", dest="stationId", nargs='*')
    parser.add_argument("-ct", dest="cityName", nargs='*')
    parser.add_argument("-pr", dest="percentage", nargs='*')
    parser.add_argument("-tc1", dest="taskColor1", nargs='*')
    args = parser.parse_args()
    for i in range(len(args.stationId)):
        Data, Date, Max, Min = prepareCSVData(args.cityName[i])
        plotDate = Data['right']
        source = ColumnDataSource(data=Data)
        AverageTemp = []
        for index in range(len(Min)):
            Average = (Min[index] + Max[index]) / 2
            AverageTemp.append(Average)
        plot_graph = Figure(x_axis_type="datetime",
                            plot_width=1000,
                            title="2016 Daily Growing Degree Days- " +
                            args.cityName[i],
                            toolbar_location=None)
        color = "#ADD8E6"
        for j in range(len(args.percentage)):
            minPer, MaxPer = getComputePercentage(Min, Max, args.percentage[j])
            plot_graph.quad(top=MaxPer,
                            bottom=minPer,
                            left='left',
                            right='right',
                            source=source,
                            color=color,
                            legend="percentile " + str(args.percentage[j]) +
                            "-" + str(100 - int(args.percentage[j])))
            color = "#D2B48C"
        plot_graph.circle(Max,
                          Min,
                          alpha=0.9,
                          color="#0000FF",
                          fill_alpha=0.2,
                          size=10,
                          source=source,
                          legend='2016')
        plot_graph.line(plotDate,
                        AverageTemp,
                        source=source,
                        line_color='Red',
                        line_width=0.5,
                        legend='Average')
        plot_graph.xaxis.axis_label = "MONTHS"
        plot_graph.yaxis.axis_label = "Daily Accumulation Celcius"
        plot_graph.grid[0].ticker.desired_num_ticks = 12

        output_file("./plots/secTask-1" + args.cityName[i] + ".html",
                    title="2016 Daily Growing Degree Days-(" +
                    args.cityName[i] + ")")
        save(plot_graph)
def plot1():
    # copy/pasted from Bokeh Getting Started Guide
    x = linspace(-6, 6, 100)
    y = cos(x)
    p = Figure(width=500, height=500, toolbar_location="below",
               title="Plot 1")
    p.circle(x, y, size=7, color="firebrick", alpha=0.5)

    # following above points:
    #  + pass plot object 'p' into json_item
    #  + wrap the result in json.dumps and return to frontend
    return bokeh.embed.json_item(p, "myplot")
Exemplo n.º 14
0
    def create_fig(self, sources):
        """
        Implementation of :meth:`LivePlot.create_fig` to set up the bokeh figure
        """

        fig = Figure(background_fill_color= None,
                     toolbar_location = None,
                     x_range=[-100, 100], y_range=[-100, 100], tools="", **self._fig_args)



        # Remove existing axes and grid
        fig.xgrid.grid_line_color = None
        fig.ygrid.grid_line_color = None
        fig.axis.visible = False


        # Draw circular grid
        th = np.linspace(0, 360, 100)

        # Draw visibility field
        self.vis_horizon = 10
        #fig.patch(*pol2rect([90 - self.vis_horizon]*len(th), th), color='lightgray')
        fig.patch(*azel2rect(th, [self.vis_horizon]*len(th)), color='lightgray')


        for r in [0, 20, 40, 60, 80]:
            fig.line(*azel2rect(th, [r]*len(th)), line_dash='dashed')

        for th in np.arange(0,360,45):
            fig.line(*azel2rect([th,th], [0,90]), line_dash='dashed')

        # Add grid labels
        lx,ly = azel2rect([0, 90, 180, 270], [0]*4)
        lx[1] -= 30
        lx[2] -= 20
        ly[0] -= 10
        lx[0] -= 10
        src_labels = ColumnDataSource(dict(
            labels= ['N (0)', 'E (90)', 'S (180)', 'W (270)'],
            label_x= lx,
            label_y =ly))

        fig.add_layout(LabelSet(x='label_x', y='label_y', text='labels', source=src_labels))



        fig.line(source=sources['dpass'], x='x', y = 'y', line_width=2)
        fig.circle(source=sources['ant_cmd'], x='x', y='y', size=20, fill_color=None)
        fig.circle(source=sources['ant_cur'], x='x', y='y', size=10, color='green')
        fig.circle(source=sources['sat'], x= 'x', y ='y', size=10, color= 'yellow')

        return fig
Exemplo n.º 15
0
class ScatterDiagram(Component):
    def __init__(self, environment: Environment):
        super().__init__()
        self.environment = environment

        self.data_source = ColumnDataSource(
            data=dict(x_axis=[], y_axis=[], color=[]))
        self.diagram = Figure(plot_width=400, plot_height=400)

        self.x_axis_menu = Select(title="x axis",
                                  value="radius",
                                  options=list(BlobStatistics))
        self.y_axis_menu = Select(title="y axis",
                                  value="speed",
                                  options=list(BlobStatistics))
        self.color_menu = Select(title="colours",
                                 value="time of birth",
                                 options=list(BlobStatistics))

        self.color_mapper = LinearColorMapper(palette='Cividis11')
        self.color_bar = ColorBar(color_mapper=self.color_mapper,
                                  location=(0, 0))
        self.diagram.circle('x_axis',
                            'y_axis',
                            color={
                                'field': 'color',
                                'transform': self.color_mapper
                            },
                            source=self.data_source)
        self.diagram.add_layout(self.color_bar, 'right')

        self.component = column(
            self.diagram,
            row(self.x_axis_menu, self.y_axis_menu, self.color_menu))

    def refresh(self):
        self.data_source.data = {
            'x_axis': [
                BlobStatistics[self.x_axis_menu.value](organism,
                                                       self.environment)
                for organism in self.environment.organisms.organism_list
            ],
            'y_axis': [
                BlobStatistics[self.y_axis_menu.value](organism,
                                                       self.environment)
                for organism in self.environment.organisms.organism_list
            ],
            'color': [
                BlobStatistics[self.color_menu.value](organism,
                                                      self.environment)
                for organism in self.environment.organisms.organism_list
            ]
        }
Exemplo n.º 16
0
def make_plot(source, AverageTemp, Parcentile_5_Min, Parcentile_5_Max,
              Parcentile_25_Min, Parcentile_25_Max, MinTemp, MaxTemp, plotDate,
              cityName):
    plot = Figure(title='Optional Task # 1 : Growing Degree-day for ' +
                  cityName,
                  x_axis_type="datetime",
                  plot_width=1000,
                  title_text_font_size='12pt',
                  tools="",
                  toolbar_location=None)
    colors = Blues4[0:3]

    plot.circle(MaxTemp,
                MinTemp,
                alpha=0.9,
                color="#66ff33",
                fill_alpha=0.2,
                size=10,
                source=source,
                legend='2015')
    plot.quad(top=Parcentile_5_Max,
              bottom=Parcentile_5_Min,
              left='left',
              right='right',
              source=source,
              color="#e67300",
              legend="Percentile 5-95")
    plot.quad(top=Parcentile_25_Max,
              bottom=Parcentile_25_Min,
              left='left',
              right='right',
              source=source,
              color="#66ccff",
              legend="percentile 25-75")
    plot.line(plotDate,
              AverageTemp,
              source=source,
              line_color='Red',
              line_width=0.75,
              legend='AverageTemp')

    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = "Months"
    plot.yaxis.axis_label = "Temperature (C)"
    plot.axis.major_label_text_font_size = "10pt"
    plot.axis.axis_label_text_font_size = "12pt"
    plot.axis.axis_label_text_font_style = "bold"
    plot.x_range = DataRange1d(range_padding=0.0, bounds=None)
    plot.grid.grid_line_alpha = 0.3
    plot.grid[0].ticker.desired_num_ticks = 12
    return plot
Exemplo n.º 17
0
 def make_line(self):
     '''
     makes a bokeh line chart with markers
     '''
     p = Figure(x_axis_label=self.xlabel,
                y_axis_label=self.ylabel,
                title=self.title)
     p.line(y='y', x='x', source=self.source_visible)
     p.circle(y='y',
              x='x',
              source=self.source_visible,
              size=4,
              hover_fill_color='firebrick',
              hover_line_color='white')
     return p
Exemplo n.º 18
0
def _add_nodes(G: nx.Graph,
               plot: Figure) -> Union[ColumnDataSource, GlyphRenderer]:
    """Add nodes from G to the plot.

    Args:
        G (nx.Graph): Networkx graph.
        plot (figure): Plot to add the nodes to.

    Returns:
        Union[ColumnDataSource, GlyphRenderer]: node source and glyphs.
    """
    nodes_df = pd.DataFrame([G.nodes[u] for u in sorted(G.nodes())])
    nodes_src = ColumnDataSource(data=nodes_df.to_dict(orient='list'))

    nodes_glyph = plot.circle(x='x',
                              y='y',
                              size=NODE_SIZE,
                              level=NODE_LEVEL,
                              line_color='line_color',
                              fill_color='fill_color',
                              line_width='line_width',
                              nonselection_fill_alpha=1,
                              nonselection_line_alpha=1,
                              source=nodes_src)

    return nodes_src, nodes_glyph
Exemplo n.º 19
0
    def init_plot(self):
        x = fft.rfftfreq(self.CHUNK_SIZE) * self.SAMPLE_RATE
        x_max = x[-1]
        self.init_y = linspace(0, x_max, len(x))
        y = self.init_y
        source = ColumnDataSource(data=dict(x=x, y=y))

        # TODO: range and size (toolbar), maybe could be user settings
        plot = Figure(plot_height=400,
                      plot_width=800,
                      title="freq anal",
                      tools="crosshair,pan,reset,resize,save,wheel_zoom",
                      x_range=[0, x_max],
                      y_range=[0, 15])

        rad = x_max / float(len(x))
        data = plot.circle('x',
                           'y',
                           source=source,
                           line_color=None,
                           radius=rad)
        self.data_source = data.data_source

        # TODO: maybe not the best place
        curdoc().add_root(plot)
Exemplo n.º 20
0
def jwst_noise(result_dict, plot=True, output_file='noise.html'):
    """Plot background

    Parameters
    ----------
    result_dict : dict
        Dictionary from pandexo output. If parameter space was run in run_pandexo
        make sure to restructure the input as a list of dictionaries without they key words
        that run_pandexo assigns.
    plot : bool
        (Optional) True renders plot, Flase does not. Default=True
    output_file : str
        (Optional) Default = 'noise.html'
    Return
    ------
    x : numpy array
        micron
    y : numpy array
        1D noise (ppm)

    See Also
    --------
    jwst_1d_spec, jwst_1d_bkg, jwst_1d_flux, jwst_1d_snr, jwst_2d_det, jwst_2d_sat
    """
    TOOLS = "pan,wheel_zoom,box_zoom,reset,save"  #saturation

    x = result_dict['FinalSpectrum']['wave']
    y = result_dict['FinalSpectrum']['error_w_floor'] * 1e6
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]
    ymed = np.median(y)

    plot_noise_1d1 = Figure(
        tools=TOOLS,  #responsive=True,
        x_axis_label='Wavelength (micron)',
        y_axis_label='Error on Spectrum (PPM)',
        title="Error Curve",
        plot_width=800,
        plot_height=300,
        y_range=[0, 2.0 * ymed])
    ymed = np.median(y)
    plot_noise_1d1.circle(x, y, line_width=4, alpha=.7)
    if plot:
        outputfile(output_file)
        show(plot_noise_1d1)
    return x, y
Exemplo n.º 21
0
def gen_fig(shape, source, tool=''):
	'''function to generate either a circle or line graph'''
	p = Figure(plot_width=500, plot_height=500,\
		title='Selected - Sample by Wave', tools = [tool])
	p.title_text_color = "CadetBlue"
	p.title_text_font = "helvetica"
	p.xaxis.axis_label = "Wave"
	p.xaxis.axis_label_text_font_size = '9pt'
	p.yaxis.axis_label = "Sample Size"
	p.yaxis.axis_label_text_font_size = '9pt'
	if shape == 'circle':
		p.circle('Years', 'SampleSize', source=source,\
			size=10, color="CadetBlue", alpha=0.5)
	elif shape == 'line':
		p.line('Years', 'SampleSize', source=source,\
			line_width=3, color='CadetBlue',line_alpha=0.7)
	return p
Exemplo n.º 22
0
def plotstat(data, circleinds=None, crossinds=None, edgeinds=None, url_path=None, fileroot=None, 
             tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400):
    """ Make a light-weight stat figure """

    fields = ['imkur', 'specstd', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    specstd = [data['specstd'][i] for i in inds]
    specstd_min = min(specstd)
    specstd_max = max(specstd)
    imkur = [data['imkur'][i] for i in inds]
    imkur_min = min(imkur)
    imkur_max = max(imkur)

    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems() if key in fields}))
    stat = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='Spectral std',
                  y_axis_label='Image kurtosis', x_range=(specstd_min, specstd_max), 
                  y_range=(imkur_min, imkur_max), tools=tools, webgl=True)
    stat.circle('specstd', 'imkur', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source)

    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems() if key in fields}))
        stat.cross('specstd', 'imkur', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems() if key in fields}))
        stat.circle('specstd', 'imkur', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2)

    hover = stat.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = stat.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return stat
Exemplo n.º 23
0
def plotdmt(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None,
            tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=950, plot_height=500):
    """ Make a light-weight dm-time figure """

    fields = ['dm', 'time', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    dm = [data['dm'][i] for i in inds]
    dm_min = min(min(dm), max(dm)/1.2)
    dm_max = max(max(dm), min(dm)*1.2)
    time = [data['time'][i] for i in inds]
    time_min = min(time)
    time_max = max(time)

    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems() if key in fields}))
    dmt = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='Time (s; relative)',
                 y_axis_label='DM (pc/cm3)', x_range=(time_min, time_max), y_range=(dm_min, dm_max), 
                 webgl=True, tools=tools)
    dmt.circle('time', 'dm', size='sizes', fill_color='colors', line_color=None, fill_alpha=0.2, source=source)

    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems() if key in fields}))
        dmt.cross('time', 'dm', size='sizes', fill_color='colors', line_alpha=0.3, source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems() if key in fields}))
        dmt.circle('time', 'dm', size='sizes', line_color='colors', fill_color='colors', line_alpha=0.5, fill_alpha=0.2, source=sourceedge)
    hover = dmt.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
#        url = '{}/cands_{}_sc@scan-seg@seg-i@candint-dm@[email protected]'.format(url_path, fileroot)
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = dmt.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return dmt
Exemplo n.º 24
0
def plotloc(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None,
            tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400):
    """ Make a light-weight loc figure """

    fields = ['l1', 'm1', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    l1 = [data['l1'][i] for i in inds]
    l1_min = min(l1)
    l1_max = max(l1)
    m1 = [data['m1'][i] for i in inds]
    m1_min = min(m1)
    m1_max = max(m1)

    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems() if key in fields}))
    loc = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='l1 (rad)', y_axis_label='m1 (rad)',
                 x_range=(l1_min, l1_max), y_range=(m1_min,m1_max), tools=tools, webgl=True)
    loc.circle('l1', 'm1', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source)

    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems() if key in fields}))
        loc.cross('l1', 'm1', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems() if key in fields}))
        loc.circle('l1', 'm1', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2)

    hover = loc.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = loc.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return loc
Exemplo n.º 25
0
def jwst_noise(result_dict, plot=True, output_file= 'noise.html'): 
    """Plot background
    
    Parameters
    ----------
    result_dict : dict
        Dictionary from pandexo output. If parameter space was run in run_pandexo 
        make sure to restructure the input as a list of dictionaries without they key words 
        that run_pandexo assigns. 
    plot : bool 
        (Optional) True renders plot, Flase does not. Default=True
    output_file : str
        (Optional) Default = 'noise.html'
    Return
    ------
    x : numpy array
        micron
    y : numpy array
        1D noise (ppm)

    See Also
    --------
    jwst_1d_spec, jwst_1d_bkg, jwst_1d_flux, jwst_1d_snr, jwst_2d_det, jwst_2d_sat
    """  
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"    #saturation

    x = result_dict['FinalSpectrum']['wave']
    y = result_dict['FinalSpectrum']['error_w_floor']*1e6
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]    
    ymed = np.median(y)


    plot_noise_1d1 = Figure(tools=TOOLS,#responsive=True,
                         x_axis_label='Wavelength (micron)',
                         y_axis_label='Error on Spectrum (PPM)', title="Error Curve",
                         plot_width=800, plot_height=300, y_range = [0,2.0*ymed])
    ymed = np.median(y)
    plot_noise_1d1.circle(x, y, line_width = 4, alpha = .7)
    if plot: 
        outputfile(output_file)
        show(plot_noise_1d1)
    return x,y
    def _replacement_plot(self, source):
        start = self.now - datetime.timedelta(days=self.RECOATING_PERIOD)
        start_timestamp = datetime.datetime(start.year, start.month, start.day, 0, 0, 0, 0).timestamp()
        end_timestamp = datetime.datetime(self.now.year, self.now.month, self.now.day, 0, 0, 0, 0).timestamp()
        x_range = DataRange1d(start=1000 * start_timestamp, end=1000 * end_timestamp)
        y_range = DataRange1d(start=0, end=120)
        plot = Figure(x_axis_type='datetime',
                      x_range=x_range,
                      y_range=y_range,
                      tools=['tap'],
                      toolbar_location=None)

        # required recoated segments
        plot.line(x=[start, self.now],
                  y=[0, 91],
                  legend='required recoated segments',
                  line_width=2,
                  line_color='blue')

        # recoated segments
        plot.line(x='ReplacementDate',
                  y='RecoatingsSinceYearStart',
                  source=source,
                  legend='recoated segments',
                  line_width=2,
                  color='orange')
        plot.circle(x='ReplacementDate',
                    y='RecoatingsSinceYearStart',
                    source=source,
                    legend='recoated segments',
                    size=6,
                    color='orange')

        date_format = '%d %b %Y'
        formats = dict(hours=[date_format], days=[date_format], months=[date_format], years=[date_format])
        plot.xaxis[0].formatter = DatetimeTickFormatter(formats=formats)

        plot.legend.location = 'top_left'

        plot.min_border_top = 20
        plot.min_border_bottom = 30

        return plot
def add_geom(fig: Figure, geom: BaseGeometry, **kwargs):
    """Add Shapely geom into Bokeh plot.

    Args:
        fig (Figure):
        geom (BaseGeometry):
    """
    if isinstance(geom, Point):
        fig.circle(*geom.xy, **kwargs)
    elif isinstance(geom, LineString):
        fig.line(*geom.xy, **kwargs)
    elif isinstance(geom, Polygon):
        fig.patch(*geom.exterior.xy, **kwargs)
    elif isinstance(geom, BaseMultipartGeometry):
        for item in geom:
            add_geom(fig, item, **kwargs)
    else:
        raise TypeError('Object geom {geom} no instance of {types}.'.format(
            geom=geom, types=BaseGeometry))
Exemplo n.º 28
0
    def construct_best_odds_figure(self, x, y, z, t, trade_id, sticker):
        # workaround to format date in the hover tool at the moment bokeh does not supported in the tool tips
        source_back_odds = ColumnDataSource(data=dict(x=x, y=y, time=[e.strftime('%d-%m-%Y %H:%M:%S') for e in x]))

        hover = HoverTool(
            tooltips=[
                ("index", "$index"),
                ("x", "@time"),
                ("y", "@y"),
            ],
            active=False
        )

        # create a new plot with a a datetime axis type
        p2 = Figure(plot_width=1000, plot_height=600, title=sticker, toolbar_location="above", x_axis_type="datetime",
                    tools=[hover, 'box_zoom, box_select, crosshair, resize, reset, save,  wheel_zoom'])
        orders = self.map_trade_id_to_orders[trade_id, sticker]
        for order in orders:
            a = [order.placed_dt]
            b = [order.price]
            source_placed = ColumnDataSource(data=dict(a=a, b=b, time=[a[0].strftime('%d-%m-%Y %H:%M:%S')]))
            p2.square(a, b, legend="placed", fill_color="red", line_color="red", size=8, source=source_placed)

        p2.circle(x, y, size=8, color='navy', alpha=0.2, legend="best back odds", source=source_back_odds)
        p2.line(x, y, color='navy', legend="best back odds", source=source_back_odds)

        # lay odds
        source_lay_odds = ColumnDataSource(data=dict(z=z, t=t, time=[e.strftime('%d-%m-%Y %H:%M:%S') for e in z]))
        p2.triangle(z, t, size=8, color='green', alpha=0.2, legend="best lay odds", source=source_lay_odds)
        p2.line(z, t, color='green', legend="best lay odds", source=source_lay_odds)

        # NEW: customize by setting attributes
        # p2.title = sticker
        p2.legend.location = "top_left"
        p2.grid.grid_line_alpha = 0
        p2.xaxis.axis_label = 'Date'
        p2.yaxis.axis_label = "Best odds"
        p2.ygrid.band_fill_color = "olive"
        p2.ygrid.band_fill_alpha = 0.1

        return p2
Exemplo n.º 29
0
def make_plot(source,AverageTemp,Parcentile_5_Min,Parcentile_5_Max,Parcentile_25_Min,Parcentile_25_Max,MinTemp,MaxTemp,plotDate,cityName):
    plot = Figure(title='Optional Task # 1 : Growing Degree-day for '+cityName, x_axis_type="datetime", plot_width=1000, title_text_font_size='12pt', tools="", toolbar_location=None)
    colors = Blues4[0:3]
    
    plot.circle(MaxTemp,MinTemp, alpha=0.9, color="#66ff33", fill_alpha=0.2, size=10,source=source,legend ='2015')
    plot.quad(top=Parcentile_5_Max, bottom=Parcentile_5_Min, left='left',right='right',
              source=source,color="#e67300", legend="Percentile 5-95")
    plot.quad(top=Parcentile_25_Max, bottom=Parcentile_25_Min,left='left',right='right',
              source=source,color="#66ccff",legend="percentile 25-75")
    plot.line(plotDate,AverageTemp,source=source,line_color='Red', line_width=0.75, legend='AverageTemp')

    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = "Months"
    plot.yaxis.axis_label = "Temperature (C)"
    plot.axis.major_label_text_font_size = "10pt"
    plot.axis.axis_label_text_font_size = "12pt"
    plot.axis.axis_label_text_font_style = "bold"
    plot.x_range = DataRange1d(range_padding=0.0, bounds=None)
    plot.grid.grid_line_alpha = 0.3
    plot.grid[0].ticker.desired_num_ticks = 12
    return plot
Exemplo n.º 30
0
    def show_light_curve(self, light_curve_path: Path):
        """
        Shows a figure of the light curve at the passed path.

        :param light_curve_path: The path of the light curve.
        """
        fluxes, times = self.load_fluxes_and_times_from_fits_file(
            light_curve_path)
        figure = Figure(title=str(light_curve_path),
                        x_axis_label='Flux',
                        y_axis_label='Time',
                        active_drag='box_zoom')
        color = 'mediumblue'
        figure.line(times, fluxes, line_color=color, line_alpha=0.1)
        figure.circle(times,
                      fluxes,
                      line_color=color,
                      line_alpha=0.4,
                      fill_color=color,
                      fill_alpha=0.1)
        figure.sizing_mode = 'stretch_width'
        show(figure)
Exemplo n.º 31
0
def make_plots(linesources, pointsources):
    plots = []
    i=0
    for linesource, pointsource in zip(linesources, pointsources):
        fig = Figure(title=None, toolbar_location=None, tools=[],
                   x_axis_type="datetime",
                   width=300, height=70)

        fig.xaxis.visible = False
        if i in [0, 9] :
            fig.xaxis.visible = True
            fig.height = 90
        fig.yaxis.visible = False
        fig.xgrid.visible = True
        fig.ygrid.visible = False
        fig.min_border_left = 10
        fig.min_border_right = 10
        fig.min_border_top = 5
        fig.min_border_bottom = 5
        if not i in [0, 9]:
            fig.xaxis.major_label_text_font_size = "0pt"
        #fig.yaxis.major_label_text_font_size = "0pt"
        fig.xaxis.major_tick_line_color = None
        fig.yaxis.major_tick_line_color = None
        fig.xaxis.minor_tick_line_color = None
        fig.yaxis.minor_tick_line_color = None
        fig.background_fill_color = "whitesmoke"

        fig.line(x='date', y="y", source=linesource)
        fig.circle(x='date', y='y', size=5, source=pointsource)
        fig.text(x='date', y='y', text='text', x_offset=5, y_offset=10, text_font_size='7pt', source=pointsource)

        fig.title.align = 'left'
        fig.title.text_font_style = 'normal'

        plots.append(fig)
        i+=1
    return plots
Exemplo n.º 32
0
    def handle_submit(self):
        filename_sentence_pairs = utils.get_sentences(self.text_input.value)
        sentences = [pair[1] for pair in filename_sentence_pairs]
        encodings = utils.get_encodings(sentences)
        embedding = self.projector.fit_transform(encodings)

        tooltip_sentences = []
        for sentence in sentences:
            index = sentence.lower().index(self.text_input.value)
            subsentence = sentence[max(index-settings.TEXT_TOOLTIP_WINDOW_SIZE, 0):\
                                   min(settings.TEXT_TOOLTIP_WINDOW_SIZE+index, len(sentence))]
            if len(subsentence) < len(sentence):
                subsentence = '...' + subsentence + '...'
            tooltip_sentences.append(subsentence)

        filename_to_color = dict()
        for filename, _ in filename_sentence_pairs:
            if filename not in filename_to_color:
                filename_to_color[filename] = self.COLORS[len(
                    filename_to_color)]
        color = [
            filename_to_color[filename]
            for filename, _ in filename_sentence_pairs
        ]

        source = ColumnDataSource(data=dict(x=embedding[:, 0],
                                            y=embedding[:, 1],
                                            text=tooltip_sentences,
                                            fill_color=color))

        figure = Figure(tooltips=[('text', '@text')])
        figure.circle('x',
                      'y',
                      fill_color='fill_color',
                      radius=0.05,
                      line_color=None,
                      source=source)
        self.layout.children[-1] = column(figure, sizing_mode='stretch_both')
Exemplo n.º 33
0
def plotCorrelation(res):
    from bokeh.models import HoverTool,ColumnDataSource
    from bokeh.plotting import Figure
    width=600
    height=600
    plot = Figure(title='',title_text_font_size="11pt",
            plot_width=width, plot_height=height,
           x_axis_label='method1',y_axis_label='method2',
           tools="pan, wheel_zoom, resize, hover, reset, save",
           background_fill="#FAFAFA")

    x=res['perc_x']
    y=res['perc_y']
    source = ColumnDataSource(data=dict(x=x,y=y, protein=res.locus_tag))
    plot.circle(x,y, color='blue', line_color='gray',fill_alpha=0.5, size=10, source=source)
    hover = plot.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([
        ("binders1", "@x"),
        ("binders2", "@y"),
        ("protein", "@protein"),
    ])
    js,html = embedPlot(plot)
    return html
Exemplo n.º 34
0
Arquivo: main.py Projeto: zlxs23/bokeh
def create_figure():
    xs, ys, colors, sizes = model.get_axes_values()
    fig_args = dict(tools='pan', plot_height=600, plot_width=800)

    if model.x_field in model.discrete_column_names and model.y_field in model.discrete_column_names:
        figure = Figure(x_range=xs, y_range=ys, **fig_args)
        figure.axis.major_label_orientation = math.pi / 4
    elif model.x_field in model.discrete_column_names:
        figure = Figure(x_range=xs, **fig_args)
        figure.xaxis.major_label_orientation = math.pi / 4
    elif model.y_field in model.discrete_column_names:
        figure = Figure(y_range=ys, **fig_args)
        figure.yaxis.major_label_orientation = math.pi / 4
    else:
        figure = Figure(**fig_args)

    figure.circle(x=xs,
                  y=ys,
                  color=colors,
                  size=sizes,
                  line_color="white",
                  alpha=0.8)
    figure.toolbar_location = None
    figure.xaxis.axis_label = model.x_field
    figure.yaxis.axis_label = model.y_field
    figure.background_fill_color = model.background_fill
    figure.border_fill_color = model.background_fill
    figure.axis.axis_line_color = "white"
    figure.axis.axis_label_text_color = "white"
    figure.axis.major_label_text_color = "white"
    figure.axis.major_tick_line_color = "white"
    figure.axis.minor_tick_line_color = "white"
    figure.axis.minor_tick_line_color = "white"
    figure.grid.grid_line_dash = [6, 4]
    figure.grid.grid_line_alpha = .3
    return figure
Exemplo n.º 35
0
def map():
    x_range = (-10000000, -11000000)
    y_range = (3500000, 5200000)

    plot = Figure(
        tools=TOOLS, title="Power Plant Locations", plot_width=1000, plot_height=500, x_range=x_range, y_range=y_range
    )
    plot.add_tile(STAMEN_TONER)
    plot.axis.visible = False
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = None
    m1 = plot.circle(x="lat", y="lon", source=source_map_bwr, size="size", fill_alpha=0, line_width=2, color="red")
    m2 = plot.square(x="lat", y="lon", source=source_map_pwr, size="size", fill_alpha=0, line_width=2, color="red")
    plot.select(dict(type=HoverTool)).tooltips = [("Plant Name", "@name"), ("Reactor and Containment", "@type")]

    return plot
Exemplo n.º 36
0
	def init_plot(self):
		x = fft.rfftfreq(self.CHUNK_SIZE)*self.SAMPLE_RATE
		x_max = x[-1]
		self.init_y = linspace(0, x_max, len(x))
		y = self.init_y
		source = ColumnDataSource(data=dict(x=x, y=y))
		
		# TODO: range and size (toolbar), maybe could be user settings
		plot = Figure(plot_height=400, plot_width=800, title="freq anal",
					  tools="crosshair,pan,reset,resize,save,wheel_zoom",
					  x_range=[0, x_max], y_range=[0, 15])
					  
		rad = x_max/float(len(x))
		data = plot.circle('x', 'y', source=source, line_color=None, radius=rad)
		self.data_source = data.data_source
		
		# TODO: maybe not the best place
		curdoc().add_root(plot)
Exemplo n.º 37
0
# Create Column Data Source that will be used by the plot
source = ColumnDataSource(
    data=dict(x=[], y=[], color=[], title=[], year=[], revenue=[]))

hover = HoverTool(tooltips=[("Title", "@title"), ("Year",
                                                  "@year"), ("$", "@revenue")])

p = Figure(plot_height=600,
           plot_width=800,
           title="",
           toolbar_location=None,
           tools=[hover])
p.circle(x="x",
         y="y",
         source=source,
         size=7,
         color="color",
         line_color=None,
         fill_alpha="alpha")


def select_movies():
    genre_val = genre.value
    director_val = director.value.strip()
    cast_val = cast.value.strip()
    selected = movies[(movies.Reviews >= reviews.value)
                      & (movies.BoxOffice >= (boxoffice.value * 1e6)) &
                      (movies.Year >= min_year.value) &
                      (movies.Year <= max_year.value) &
                      (movies.Oscars >= oscars.value)]
    if (genre_val != "All"):
Exemplo n.º 38
0
import pandas as pd

from bokeh.plotting import Figure, show, output_file, ColumnDataSource
from bokeh.models import HoverTool

df = pd.read_csv('mean_success_housing.csv')
df['success_metric'] = df['_c0']
print df.head()


source1 = ColumnDataSource(data=df)
hover1 = HoverTool(tooltips=[("zipcode","@zipcode"),
                             ("success_metric","@success_metric")])

p = Figure(title='Mean Success by zip vs Housing Costs',
           x_axis_label='$/sq. ft.',
           y_axis_label='success_metric',
           tools=['crosshair,resize,reset,save', hover1])

p.circle('2016_02', 'success_metric', color='red',alpha=0.4, source=source1)

output_file("mean_success_housing.html", title="Success vs Housing cost")
show(p)
Exemplo n.º 39
0
def plot():

    # FIGURES AND X-AXIS
    fig1 = Figure(title = 'Dive Profile',  plot_width = WIDTH, plot_height = HEIGHT, tools = TOOLS)
    fig2 = Figure(title = 'Dive Controls', plot_width = WIDTH, plot_height = HEIGHT, tools = TOOLS, x_range=fig1.x_range)
    fig3 = Figure(title = 'Attitude',      plot_width = WIDTH, plot_height = HEIGHT, tools = TOOLS, x_range=fig1.x_range)
    figs = gridplot([[fig1],[fig2],[fig3]])

    # Formatting x-axis
    timeticks = DatetimeTickFormatter(formats=dict(seconds =["%b%d %H:%M:%S"],
                                                   minutes =["%b%d %H:%M"],
                                                   hourmin =["%b%d %H:%M"],
                                                   hours =["%b%d %H:%M"],
                                                   days  =["%b%d %H:%M"],
                                                   months=["%b%d %H:%M"],
                                                   years =["%b%d %H:%M %Y"]))
    fig1.xaxis.formatter = timeticks
    fig2.xaxis.formatter = timeticks
    fig3.xaxis.formatter = timeticks

    # removing gridlines
    fig1.xgrid.grid_line_color = None
    fig1.ygrid.grid_line_color = None
    fig2.xgrid.grid_line_color = None
    fig2.ygrid.grid_line_color = None
    fig3.xgrid.grid_line_color = None
    fig3.ygrid.grid_line_color = None

    # INPUT WIDGETS
    collection_list = CONN[DB].collection_names(include_system_collections=False)
    gliders = sorted([platformID for platformID in collection_list if len(platformID)>2])
    gliders = Select(title = 'PlatformID', value = gliders[0], options = gliders)
    prev_glider = Button(label = '<')
    next_glider = Button(label = '>')
    glider_controlbox = HBox(children = [gliders, prev_glider, next_glider], height=80)

    chunkations = Select(title = 'Chunkation', value = 'segment', options = ['segment', '24hr', '30days', '-ALL-'])
    chunk_indicator = TextInput(title = 'index', value = '0')
    prev_chunk = Button(label = '<')
    next_chunk = Button(label = '>')
    chunk_ID   = PreText(height=80)
    chunk_controlbox = HBox(chunkations,
                            HBox(chunk_indicator, width=25),
                            prev_chunk, next_chunk,
                            chunk_ID,
                            height = 80)

    control_box = HBox(glider_controlbox,
                        chunk_controlbox)

    # DATA VARS
    deadby_date = ''
    depth    = ColumnDataSource(dict(x=[],y=[]))
    vert_vel = ColumnDataSource(dict(x=[],y=[]))

    mbpump   = ColumnDataSource(dict(x=[],y=[]))
    battpos  = ColumnDataSource(dict(x=[],y=[]))
    pitch    = ColumnDataSource(dict(x=[],y=[]))

    mfin      = ColumnDataSource(dict(x=[],y=[]))
    cfin      = ColumnDataSource(dict(x=[],y=[]))
    mroll     = ColumnDataSource(dict(x=[],y=[]))
    mheading = ColumnDataSource(dict(x=[],y=[]))
    cheading = ColumnDataSource(dict(x=[],y=[]))

    # AXIS setup
    colors = COLORS[:]

    fig1.y_range.flipped = True
    fig1.yaxis.axis_label = 'm_depth (m)'
    fig1.extra_y_ranges = {'vert_vel': Range1d(start=-50, end=50),
                           'dummy':    Range1d(start=0, end=100)}
    fig1.add_layout(place = 'right',
                    obj = LinearAxis(y_range_name = 'vert_vel',
                                     axis_label   = 'vertical velocity (cm/s)'))
    fig1.add_layout(place = 'left',
                    obj = LinearAxis(y_range_name = 'dummy',
                                     axis_label   = ' '))
    fig1.yaxis[1].visible = False
    fig1.yaxis[1].axis_line_alpha = 0
    fig1.yaxis[1].major_label_text_alpha = 0
    fig1.yaxis[1].major_tick_line_alpha = 0
    fig1.yaxis[1].minor_tick_line_alpha = 0


    fig2.yaxis.axis_label = 'pitch (deg)'
    fig2.y_range.start, fig2.y_range.end = -40,40
    fig2.extra_y_ranges = {'battpos': Range1d(start=-1, end = 1),
                           'bpump':   Range1d(start=-275, end=275)}
    fig2.add_layout(place = 'right',
                    obj = LinearAxis(y_range_name = 'battpos',
                                     axis_label = 'battpos (in)'))
    fig2.add_layout(place = 'left',
                    obj = LinearAxis(y_range_name = 'bpump',
                                     axis_label   = 'bpump (cc)'))
    fig2.yaxis[1].visible = False # necessary for spacing. later gets set to true


    fig3.yaxis.axis_label = 'fin/roll (deg)'
    fig3.y_range.start, fig3.y_range.end = -30, 30
    fig3.extra_y_ranges = {'heading': Range1d(start=0, end=360), #TODO dynamic avg centering
                           'dummy':   Range1d(start=0, end=100)}
    fig3.add_layout(place = 'right',
                    obj = LinearAxis(y_range_name = 'heading',
                                     axis_label   = 'headings (deg)'))
    fig3.add_layout(place = 'left',
                    obj = LinearAxis(y_range_name = 'dummy',
                                     axis_label   = ' '))
    fig3.yaxis[1].visible = False
    fig3.yaxis[1].axis_line_alpha = 0
    fig3.yaxis[1].major_label_text_alpha = 0
    fig3.yaxis[1].major_tick_line_alpha = 0
    fig3.yaxis[1].minor_tick_line_alpha = 0

    # PLOT OBJECTS
    fig1.line(  'x', 'y', source = depth,    legend = 'm_depth',     color = 'red')
    fig1.circle('x', 'y', source = depth,    legend = 'm_depth',     color = 'red')
    fig1.line(  'x', 'y', source = vert_vel, legend = 'vert_vel',    color = 'green',     y_range_name = 'vert_vel')
    fig1.circle('x', 'y', source = vert_vel, legend = 'vert_vel',    color = 'green',     y_range_name = 'vert_vel')
    fig1.renderers.append(Span(location = 0, dimension = 'width',    y_range_name = 'vert_vel',
                               line_color= 'green', line_dash='dashed', line_width=1))

    fig2.line(  'x', 'y', source = pitch,   legend = "m_pitch",    color = 'indigo')
    fig2.circle('x', 'y', source = pitch,   legend = "m_pitch",    color = 'indigo')
    fig2.line(  'x', 'y', source = battpos, legend = 'm_battpos',  color = 'magenta',   y_range_name = 'battpos')
    fig2.circle('x', 'y', source = battpos, legend = 'm_battpos',  color = 'magenta',   y_range_name = 'battpos')
    fig2.line(  'x', 'y', source = mbpump,  legend = "m_'bpump'",  color = 'blue',      y_range_name = 'bpump')
    fig2.circle('x', 'y', source = mbpump,  legend = "m_'bpump'",  color = 'blue',      y_range_name = 'bpump')
    fig2.renderers.append(Span(location = 0, dimension = 'width',
                               line_color= 'black', line_dash='dashed', line_width=1))
    fig3.line(  'x', 'y', source = mfin,       legend = 'm_fin',     color = 'cyan')
    fig3.circle('x', 'y', source = mfin,       legend = 'm_fin',     color = 'cyan')
    fig3.line(  'x', 'y', source = cfin,       legend = 'c_fin',     color = 'orange')
    fig3.circle('x', 'y', source = cfin,       legend = 'c_fin',     color = 'orange')
    fig3.line(  'x', 'y', source = mroll,      legend = 'm_roll',    color = 'magenta')
    fig3.circle('x', 'y', source = mroll,      legend = 'm_roll',    color = 'magenta')
    fig3.line(  'x', 'y', source = mheading,   legend = 'm_heading', color = 'blue',    y_range_name = 'heading')
    fig3.circle('x', 'y', source = mheading,   legend = 'm_heading', color = 'blue',    y_range_name = 'heading')
    fig3.line(  'x', 'y', source = cheading,   legend = 'c_heading', color = 'indigo',  y_range_name = 'heading')
    fig3.circle('x', 'y', source = cheading,   legend = 'c_heading', color = 'indigo',  y_range_name = 'heading')
    fig3.renderers.append(Span(location = 0, dimension = 'width',    y_range_name = 'default',
                               line_color= 'black', line_dash='dashed', line_width=1))

    # CALLBACK FUNCS
    def update_data(attrib,old,new):
        g = gliders.value
        chnk = chunkations.value
        chindex = abs(int(chunk_indicator.value))

        depth.data    = dict(x=[],y=[])
        vert_vel.data = dict(x=[],y=[])
        mbpump.data   = dict(x=[],y=[])
        battpos.data  = dict(x=[],y=[])
        pitch.data    = dict(x=[],y=[])

        mfin.data     = dict(x=[],y=[])
        cfin.data     = dict(x=[],y=[])
        mroll.data    = dict(x=[],y=[])
        mheading.data = dict(x=[],y=[])
        cheading.data = dict(x=[],y=[])


        depth.data,startend   = load_sensor(g, 'm_depth', chnk, chindex)

        if chnk == 'segment':
            xbd = startend[2]
            chunk_ID.text = '{} {} \n{} ({}) \nSTART: {} \nEND:   {}'.format(g, xbd['mission'],
                                                                             xbd['onboard_filename'], xbd['the8x3_filename'],
                                                                             e2ts(xbd['start']), e2ts(xbd['end']))
            if len(set(depth.data['x']))<=1 and attrib == 'chunk':
                if old > new:
                    next_chunk.clicks += 1
                else:
                    prev_chunk.clicks += 1
                return
            elif len(set(depth.data['x']))<=1 and chunk_indicator.value == 0:
                chunk_indicator.value = 1

        elif chnk in ['24hr', '30days']:
            chunk_ID.text = '{} \nSTART: {} \nEND:   {}'.format(g, e2ts(startend[0]), e2ts(startend[1]))
        elif chnk == '-ALL-':
            chunk_ID.text = '{} \nSTART: {} \nEND:   {}'.format(g,e2ts(depth.data['x'][0] /1000),
                                                                  e2ts(depth.data['x'][-1]/1000))


        vert_vel.data  = calc_vert_vel(depth.data)

        mbpump.data,_     = load_sensor(g, 'm_de_oil_vol', chnk, chindex)
        if len(mbpump.data['x']) > 1:
            #for yax in fig2.select('mbpump'):
            #    yax.legend = 'm_de_oil_vol'
            pass
        else:
            mbpump.data,_     = load_sensor(g, 'm_ballast_pumped', chnk, chindex)
            #for yax in fig2.select('mbpump'):
            #    yax.legend = 'm_ballast_pumped'
        battpos.data,_ = load_sensor(g, 'm_battpos',    chnk, chindex)
        pitch.data,_   = load_sensor(g, 'm_pitch',      chnk, chindex)
        pitch.data['y'] = [math.degrees(y) for y in pitch.data['y']]

        mfin.data,_     = load_sensor(g, 'm_fin',     chnk, chindex)
        cfin.data,_     = load_sensor(g, 'c_fin',     chnk, chindex)
        mroll.data,_    = load_sensor(g, 'm_roll',    chnk, chindex)
        mheading.data,_ = load_sensor(g, 'm_heading', chnk, chindex)
        cheading.data,_ = load_sensor(g, 'c_heading', chnk, chindex)
        mfin.data['y']     = [math.degrees(y) for y in mfin.data['y']]
        cfin.data['y']     = [math.degrees(y) for y in cfin.data['y']]
        mheading.data['y'] = [math.degrees(y) for y in mheading.data['y']]
        cheading.data['y'] = [math.degrees(y) for y in cheading.data['y']]
        mroll.data['y']    = [math.degrees(y) for y in mroll.data['y']]

        fig1.yaxis[1].visible = True
        fig2.yaxis[1].visible = True
        fig3.yaxis[1].visible = True


    #GLIDER SELECTS
    def glider_buttons(increment):
        ops = gliders.options
        new_index = ops.index(gliders.value) + increment
        if new_index >= len(ops):
            new_index = 0
        elif new_index < 0:
            new_index = len(ops)-1
        gliders.value = ops[new_index]
        chunkation_update(None, None, None) #reset chunk indicator and clicks
    def next_glider_func():
        glider_buttons(1)
    def prev_glider_func():
        glider_buttons(-1)
    def update_glider(attrib,old,new):
        chunk_indicator.value = '0'
        #update_data(None,None,None)


    gliders.on_change('value', update_glider)
    next_glider.on_click(next_glider_func)
    prev_glider.on_click(prev_glider_func)


        #CHUNK SELECTS
    def chunkation_update(attrib,old,new):
        chunk_indicator.value = '0'
        prev_chunk.clicks = 0
        next_chunk.clicks = 0
        update_data(None,None,None)
        if new == '-ALL-':
            chunk_indicator.value = '-'

    def chunk_func():
        chunkdiff = prev_chunk.clicks - next_chunk.clicks
        if chunkdiff < 0:
            prev_chunk.clicks = 0
            next_chunk.clicks = 0
            chunkdiff = 0
        print (chunkdiff)
        chunk_indicator.value = str(chunkdiff)

    def chunk_indicator_update(attrib,old,new):
        try:
            if abs(int(old)-int(new))>1: #manual update, triggers new non-manual indicator update, ie else clause below
                prev_chunk.clicks = int(new)
                next_chunk.clicks = 0
            else:
                update_data('chunk',int(old),int(new))
            print("UPDATE", old, new)
        except Exception as e:
            print(type(e),e, old, new)

    chunkations.on_change('value', chunkation_update)
    chunk_indicator.on_change('value', chunk_indicator_update)
    next_chunk.on_click(chunk_func)
    prev_chunk.on_click(chunk_func)

    update_data(None,None,None)

    return vplot(control_box, figs)
Exemplo n.º 40
0
                            start=0.00, end=0.40, step=0.01)

x_axis = Select(title="X Axis", options=sorted(axis_map.keys()), value='Annual Income')
y_axis = Select(title='Y Axis', options=sorted(axis_map.keys()), value='Expected ROI')


# Create Column Data Source that will be used by the plot
source = ColumnDataSource(data=dict(x=[], y=[], color=[], title=[], year=[], revenue=[]))

hover = HoverTool(tooltips=[('Interest Rate', '@interest_rate%'),
                            ('Payments / Income', '@payments_to_income%'),
                            ('FICO', '@fico')
                            ])

p = Figure(plot_height=600, plot_width=800, title='', toolbar_location=None, tools=[hover])
p.circle(x='x', y='y', source=source, size=7, color='blue', line_color=None, alpha=0.8)

# Remove scientific notation
yaxis = p.select(dict(type=Axis, layout='left'))[0]
yaxis.formatter.use_scientific = False

p.xaxis[0].formatter = yaxis.formatter


def select_notes():
    """
    Filters the dataframe into notes that satisfy all constraints in web app
    """
    selected = df[
        (df.annual_inc >= min_income.value * 1000) &
        (df.default_prob <= max_default.value) &
Exemplo n.º 41
0
def correlation():
    "the scatter plot"

    args = flask.request.args

    xattr = args.get("x", "atomic_number")
    yattr = args.get("y", "covalent_radius_pyykko")
    categ = args.get("categ", "name_series")

    data = get_data()
    properties = get_property_names(data)
    categories = get_category_names()

    fig = Figure(title="{} vs {}".format(properties[xattr], properties[yattr]),
                 plot_width=PLOT_WIDTH,
                 plot_height=PLOT_HEIGHT,
                 tools="box_zoom,pan,resize,save,reset",
                 toolbar_location="above",
                 toolbar_sticky=False,
                 )

    fig.xaxis.axis_label = properties[xattr]
    fig.yaxis.axis_label = properties[yattr]

    ccm = get_color_mapper(categ, data)

    if categ == "None":
        legend = None
        color_dict = "#1F77B4"
    else:
        legend = categ
        color_dict = {"field": categ, "transform": ccm}

    fig.circle(x=xattr, y=yattr, fill_alpha=0.7, size=10,
               source=ColumnDataSource(data=data),
               fill_color=color_dict,
               line_color=color_dict,
               legend=legend)

    if categ != "None":
        fig.legend.location = (0, 0)
        fig.legend.plot = None
        fig.add_layout(fig.legend[0], "right")

    hover = HoverTool(tooltips=HOVER_TOOLTIPS)

    fig.add_tools(hover)

    script, div = components(fig)

    js_resources = INLINE.render_js()
    css_resources = INLINE.render_css()

    html = render_template(
        "correlations.html",
        plot_script=script,
        plot_div=div,
        properties=properties,
        categories=categories,
        xselected=xattr,
        yselected=yattr,
        catselected=categ,
        js_resources=js_resources,
        css_resources=css_resources,
    )

    return encode_utf8(html)
Exemplo n.º 42
0
from bokeh.io import curdoc
from bokeh.layouts import column, row
from bokeh.plotting import ColumnDataSource, Figure
from bokeh.models.widgets import Select, TextInput


def get_data(N):
    return dict(x=random(size=N), y=random(size=N), r=random(size=N) * 0.03)


source = ColumnDataSource(data=get_data(200))


p = Figure(tools="", toolbar_location=None)
r = p.circle(x='x', y='y', radius='r', source=source,
             color="navy", alpha=0.6, line_color="white")


COLORS = ["black", "firebrick", "navy", "olive", "goldenrod"]
select = Select(title="Color", value="navy", options=COLORS)
input  = TextInput(title="Number of points", value="200")


def update_color(attrname, old, new):
    r.glyph.fill_color = select.value
select.on_change('value', update_color)

def update_points(attrname, old, new):
    N = int(input.value)
    source.data = get_data(N)
input.on_change('value', update_points)
Exemplo n.º 43
0
dataset_type = Select(title = "Dataset", value='movielens_1m', options = ['All', 'All MovieLens', 'movielens_1m', 'Last_FM', 'git'])

checkbox_button_group = CheckboxGroup(labels=labels, active = [0,1,2])
checkbox_button_group_content = CheckboxGroup(labels=c_labels, active = [0])


hover = HoverTool(tooltips=[
    ("Dataset","@dataset"),
    ("User Vector","@user_vector"),
    ("Content Vector", "@content_vector"),
    ("Algorithm", "@alg_type"),
    ("Num_preds", "@num_run")
])

p = Figure(plot_height=600, plot_width=800, title="", toolbar_location=None, tools=[hover])
p.circle(x="x", y="y", source=source, size=7, color="color", line_color=None)

def select_run():
    num_preds_val = num_preds.value
    alg_type_val = alg_type.value
    dataset_val = dataset_type.value
    selected = hermes_data
#     selected = movies[
#         (movies.Reviews >= reviews.value) &
#         (movies.BoxOffice >= (boxoffice.value * 1e6)) &
#         (movies.Year >= min_year.value) &
#         (movies.Year <= max_year.value) &
#         (movies.Oscars >= oscars.value)
#     ]

    if num_preds_val != 'All':
Exemplo n.º 44
0
def create_component_jwst(result_dict):
    """Generate front end plots JWST
    
    Function that is responsible for generating the front-end interactive plots for JWST.

    Parameters 
    ----------
    result_dict : dict 
        the dictionary returned from a PandExo run
    
    Returns
    -------
    tuple 
        A tuple containing `(script, div)`, where the `script` is the
        front-end javascript required, and `div` is a dictionary of plot
        objects.
    """  
    noccultations = result_dict['timing']['Number of Transits']
    
    # select the tools we want
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"

    #Define units for x and y axis
    punit = result_dict['input']['Primary/Secondary']
    p=1.0
    if punit == 'fp/f*': p = -1.0
    else: punit = '('+punit+')^2'
    
    if result_dict['input']['Calculation Type'] =='phase_spec':
        x_axis_label='Time (secs)'
        frac = 1.0
    else:
        x_axis_label='Wavelength [microns]'
        frac = result_dict['timing']['Num Integrations Out of Transit']/result_dict['timing']['Num Integrations In Transit']

    electrons_out = result_dict['RawData']['electrons_out']
    electrons_in = result_dict['RawData']['electrons_in']
    
    var_in = result_dict['RawData']['var_in']
    var_out = result_dict['RawData']['var_out']
    
    
    x = result_dict['FinalSpectrum']['wave']
    y = result_dict['FinalSpectrum']['spectrum_w_rand']
    err = result_dict['FinalSpectrum']['error_w_floor']

    y_err = []
    x_err = []
    for px, py, yerr in zip(x, y, err):
        np.array(x_err.append((px, px)))
        np.array(y_err.append((py - yerr, py + yerr)))

    source = ColumnDataSource(data=dict(x=x, y=y, y_err=y_err, x_err=x_err, err=err, 
                                electrons_out=electrons_out, electrons_in=electrons_in, var_in=var_in, var_out=var_out, 
                                p=var_in*0+p,nocc=var_in*0+noccultations, frac = var_in*0+frac))
    original = ColumnDataSource(data=dict(x=x, y=y, y_err=y_err, x_err=x_err, err=err, electrons_out=electrons_out, electrons_in=electrons_in, var_in=var_in, var_out=var_out))

    ylims = [min(result_dict['OriginalInput']['model_spec'])- 0.1*min(result_dict['OriginalInput']['model_spec']),
                 0.1*max(result_dict['OriginalInput']['model_spec'])+max(result_dict['OriginalInput']['model_spec'])]
    xlims = [min(result_dict['FinalSpectrum']['wave']), max(result_dict['FinalSpectrum']['wave'])]

    plot_spectrum = Figure(plot_width=800, plot_height=300, x_range=xlims,
                               y_range=ylims, tools=TOOLS,#responsive=True,
                                 x_axis_label=x_axis_label,
                                 y_axis_label=punit, 
                               title="Original Model with Observation")
    
    plot_spectrum.line(result_dict['OriginalInput']['model_wave'],result_dict['OriginalInput']['model_spec'], color= "black", alpha = 0.5, line_width = 4)
        
    plot_spectrum.circle('x', 'y', source=source, line_width=3, line_alpha=0.6)
    plot_spectrum.multi_line('x_err', 'y_err', source=source)

    callback = CustomJS(args=dict(source=source, original=original), code="""
            // Grab some references to the data
            var sdata = source.get('data');
            var odata = original.get('data');

            // Create copies of the original data, store them as the source data
            sdata['x'] = odata['x'].slice(0);
            sdata['y'] = odata['y'].slice(0);

            sdata['y_err'] = odata['y_err'].slice(0);
            sdata['x_err'] = odata['x_err'].slice(0);
            sdata['err'] = odata['err'].slice(0);

            sdata['electrons_out'] = odata['electrons_out'].slice(0);
            sdata['electrons_in'] = odata['electrons_in'].slice(0);
            sdata['var_in'] = odata['var_in'].slice(0);
            sdata['var_out'] = odata['var_out'].slice(0);

            // Create some variables referencing the source data
            var x = sdata['x'];
            var y = sdata['y'];
            var y_err = sdata['y_err'];
            var x_err = sdata['x_err'];
            var err = sdata['err'];
            var p = sdata['p'];
            var frac = sdata['frac'];
            var og_ntran = sdata['nocc'];

            var electrons_out = sdata['electrons_out'];
            var electrons_in = sdata['electrons_in'];
            var var_in = sdata['var_in'];
            var var_out = sdata['var_out'];

            var f = wbin.get('value');
            var ntran = ntran.get('value');

            var wlength = Math.pow(10.0,f);

            var ind = [];
            ind.push(0);
            var start = 0;


            for (i = 0; i < x.length-1; i++) {
                if (x[i+1] - x[start] >= wlength) {
                    ind.push(i+1);
                    start = i;
                }
            }

            if (ind[ind.length-1] != x.length) {
                ind.push(x.length);
            }

            var xout = [];


            var foutout = [];
            var finout = [];
            var varinout = [];
            var varoutout = [];

            var xslice = []; 

            var foutslice = [];
            var finslice = [];
            var varoutslice = [];
            var varinslice = [];

            function add(a, b) {
                return a+b;
            }

            for (i = 0; i < ind.length-1; i++) {
                xslice = x.slice(ind[i],ind[i+1]);

                foutslice = electrons_out.slice(ind[i],ind[i+1]);
                finslice = electrons_in.slice(ind[i],ind[i+1]);
                
                varinslice = var_in.slice(ind[i],ind[i+1]);
                varoutslice = var_out.slice(ind[i],ind[i+1]);

                xout.push(xslice.reduce(add, 0)/xslice.length);
                foutout.push(foutslice.reduce(add, 0));
                finout.push(finslice.reduce(add, 0));
                
                varinout.push(varinslice.reduce(add, 0));
                varoutout.push(varoutslice.reduce(add, 0));

                xslice = [];
                foutslice = [];
                finslice = [];
                varinslice = [];
                varoutslice = [];
            }
            
            var new_err = 1.0;
            var rand = 1.0;

            for (i = 0; i < x.length; i++) {
                new_err = Math.pow((frac[i]/foutout[i]),2)*varinout[i] + Math.pow((finout[i]*frac[i]/Math.pow(foutout[i],2)),2)*varoutout[i];
                new_err = Math.sqrt(new_err)*Math.sqrt(og_ntran[i]/ntran);
                rand = new_err*(Math.random()-Math.random());
                y[i] = p[i]*((1.0 - frac[i]*finout[i]/foutout[i]) + rand); 
                x[i] = xout[i];
                x_err[i][0] = xout[i];
                x_err[i][1] = xout[i];
                y_err[i][0] = y[i] + new_err;
                y_err[i][1] = y[i] - new_err;            
            }

            source.trigger('change');
        """)

    #var_tot = (frac/electrons_out)**2.0 * var_in + (electrons_in*frac/electrons_out**2.0)**2.0 * var_out

    sliderWbin =  Slider(title="binning", value=np.log10(x[1]-x[0]), start=np.log10(x[1]-x[0]), end=np.log10(max(x)/2.0), step= .05, callback=callback)
    callback.args["wbin"] = sliderWbin
    sliderTrans =  Slider(title="Num Trans", value=noccultations, start=1, end=50, step= 1, callback=callback)
    callback.args["ntran"] = sliderTrans
    layout = column(row(sliderWbin,sliderTrans), plot_spectrum)


    #out of transit 2d output 
    out = result_dict['PandeiaOutTrans']
    
    # Flux 1d
    x, y = out['1d']['extracted_flux']
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]

    plot_flux_1d1 = Figure(tools=TOOLS,
                         x_axis_label='Wavelength [microns]',
                         y_axis_label='Flux (e/s)', title="Out of Transit Flux Rate",
                         plot_width=800, plot_height=300)
    plot_flux_1d1.line(x, y, line_width = 4, alpha = .7)
    tab1 = Panel(child=plot_flux_1d1, title="Total Flux")

    # BG 1d
    x, y = out['1d']['extracted_bg_only']
    y = y[~np.isnan(y)]
    x = x[~np.isnan(y)]
    plot_bg_1d1 = Figure(tools=TOOLS,
                         x_axis_label='Wavelength [microns]',
                         y_axis_label='Flux (e/s)', title="Background",
                         plot_width=800, plot_height=300)
    plot_bg_1d1.line(x, y, line_width = 4, alpha = .7)
    tab2 = Panel(child=plot_bg_1d1, title="Background Flux")

    # SNR 1d accounting for number of occultations
    x= out['1d']['sn'][0]
    y = out['1d']['sn'][1]
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]
    y = y*np.sqrt(noccultations)
    plot_snr_1d1 = Figure(tools=TOOLS,
                         x_axis_label=x_axis_label,
                         y_axis_label='SNR', title="Pandeia SNR",
                         plot_width=800, plot_height=300)
    plot_snr_1d1.line(x, y, line_width = 4, alpha = .7)
    tab3 = Panel(child=plot_snr_1d1, title="SNR")


    # Error bars (ppm) 

    x = result_dict['FinalSpectrum']['wave']
    y = result_dict['FinalSpectrum']['error_w_floor']*1e6
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]    
    ymed = np.median(y)


    plot_noise_1d1 = Figure(tools=TOOLS,#responsive=True,
                         x_axis_label=x_axis_label,
                         y_axis_label='Error on Spectrum (PPM)', title="Error Curve",
                         plot_width=800, plot_height=300, y_range = [0,2.0*ymed])
    ymed = np.median(y)
    plot_noise_1d1.circle(x, y, line_width = 4, alpha = .7)
    tab4 = Panel(child=plot_noise_1d1, title="Error")

    #Not happy? Need help picking a different mode? 
    plot_spectrum2 = Figure(plot_width=800, plot_height=300, x_range=xlims,y_range=ylims, tools=TOOLS,
                             x_axis_label=x_axis_label,
                             y_axis_label=punit, title="Original Model",y_axis_type="log")

    plot_spectrum2.line(result_dict['OriginalInput']['model_wave'],result_dict['OriginalInput']['model_spec'],
                        line_width = 4,alpha = .7)
    tab5 = Panel(child=plot_spectrum2, title="Original Model")


    #create set of five tabs 
    tabs1d = Tabs(tabs=[ tab1, tab2,tab3, tab4, tab5])



    # Detector 2d
    data = out['2d']['detector']

    
    xr, yr = data.shape
    
    plot_detector_2d = Figure(tools="pan,wheel_zoom,box_zoom,resize,reset,hover,save",
                         x_range=[0, yr], y_range=[0, xr],
                         x_axis_label='Pixel', y_axis_label='Spatial',
                         title="2D Detector Image",
                        plot_width=800, plot_height=300)
    
    plot_detector_2d.image(image=[data], x=[0], y=[0], dh=[xr], dw=[yr],
                      palette="Spectral11")


    #2d tabs 

    #2d snr 
    data = out['2d']['snr']
    data[np.isinf(data)] = 0.0
    xr, yr = data.shape
    plot_snr_2d = Figure(tools=TOOLS,
                         x_range=[0, yr], y_range=[0, xr],
                         x_axis_label='Pixel', y_axis_label='Spatial',
                         title="Signal-to-Noise Ratio",
                        plot_width=800, plot_height=300)
    
    plot_snr_2d.image(image=[data], x=[0], y=[0], dh=[xr], dw=[yr],
                      palette="Spectral11")
    
    tab1b = Panel(child=plot_snr_2d, title="SNR")

    #saturation
    
    data = out['2d']['saturation']
    xr, yr = data.shape
    plot_sat_2d = Figure(tools=TOOLS,
                         x_range=[0, yr], y_range=[0, xr],
                         x_axis_label='Pixel', y_axis_label='Spatial',
                         title="Saturation",
                        plot_width=800, plot_height=300)
    
    plot_sat_2d.image(image=[data], x=[0], y=[0], dh=[xr], dw=[yr],
                      palette="Spectral11")
    
    tab2b = Panel(child=plot_sat_2d, title="Saturation")

    tabs2d = Tabs(tabs=[ tab1b, tab2b])
    
 
    result_comp = components({'plot_spectrum':layout, 
                              'tabs1d': tabs1d, 'det_2d': plot_detector_2d,
                              'tabs2d': tabs2d})

    return result_comp
Exemplo n.º 45
0
        indye = set(indb).intersection(
            indt).intersection(set(indyey).union(indyex))

        noerrorlegend = bandname if len(indne) == 0 else ''

        source = ColumnDataSource(
            data=dict(
                x=[phototime[i] for i in indne],
                y=[photoAB[i] for i in indne],
                err=[photoABerrs[i] for i in indne],
                desc=[photoband[i] for i in indne],
                instr=[photoinstru[i] for i in indne],
                src=[photoevent[i] for i in indne]
            )
        )
        p1.circle('x', 'y', source=source, color=bandcolorf(band),
                  legend='', size=2, line_alpha=0.75, fill_alpha=0.75)

        source = ColumnDataSource(
            data=dict(
                x=[phototime[i] for i in indye],
                y=[photoAB[i] for i in indye],
                err=[photoABerrs[i] for i in indye],
                desc=[photoband[i] for i in indye],
                instr=[photoinstru[i] for i in indye],
                src=[photoevent[i] for i in indye]
            )
        )
        p1.circle('x', 'y', source=source, color=bandcolorf(band),
                  legend=bandname, size=2, line_alpha=0.75, fill_alpha=0.75)

    p1.legend.label_text_font_size = '8pt'
Exemplo n.º 46
0
### Step 3: Build the charts

# Build state bar chart
state_bar_chart = Bar(build_state_data(), label="state",
                      values='complaint_count', toolbar_location=None,
                      title="Complaints by State", width=1300, height=200,
                      ylabel="", xlabel="", color="#2cb34a")

# Build zip code scatter plot
zip_data = build_zip_data()
zip_source.data = dict(x = zip_data["median_income"],
                       y = zip_data["complaint_count"])
zip_scatter_plot = Figure(plot_height=500, plot_width=1000,
                          title="Complaints by Median Income",
                          title_text_font_size='14pt', x_range=Range1d(0,100000))
zip_scatter_plot.circle(x="x", y="y", source=zip_source, size=4,
                        color="#addc91", line_color=None, fill_alpha="0.95")
zip_xaxis = zip_scatter_plot.select(dict(type=Axis, layout="below"))[0]
zip_xaxis.formatter.use_scientific = False

# Build the data table
columns = [
    TableColumn(field="labels", title="Label"),
    TableColumn(field="data", title="Data")
]

data_table = DataTable(source=table_source, columns=columns,
                       height=150, width=250)
table_source.data = build_data_table()

### Step 4: Construct the document
Exemplo n.º 47
0
from bokeh.plotting import Figure, output_file, show, ColumnDataSource
from bokeh.models import HBox
from bokeh.models.widgets import Slider, Select
# from bokeh.sampledata.autompg import autompg as am

cir_x=[10]
cir_y=[10]
cir_size=[10]

cir_source = ColumnDataSource(data=dict(
                                        x1=cir_x,
                                        y1=cir_y,
                                        sz=cir_size))

p1 = Figure(plot_width=300, plot_height=300)
p1.circle('x1', 'y1', size='sz', color='red', source=cir_source)

my_slider = Slider(start=0, end=100, step=1, value=50, title="Circle Radius")

def update_size(attrname, old, new):
    new_sz = [my_slider.value]
    cir_source.data = dict(x1=cir_x, y1=cir_y, sz=new_sz)

for w in [my_slider]:
    w.on_change('value', update_size)

hlayout = HBox(my_slider, p1)

output_file('circle1.html')
curdoc().add_root(hlayout)
#show(hlayout)
Exemplo n.º 48
0
                                        y=[evhys[i] for i in ind],
                                        ra=[evras[i] for i in ind],
                                        dec=[evdecs[i] for i in ind],
                                        event=[evnames[i] for i in ind],
                                        claimedtype=[evtypes[i] for i in ind]))
    if ct == 'Unknown':
        tcolor = 'black'
        falpha = 0.0
    else:
        tcolor = colors[ci]
        falpha = 1.0
    glyphs.append(
        p1.circle('x',
                  'y',
                  source=source,
                  color=tcolor,
                  fill_alpha=falpha,
                  legend=ct,
                  size=glsize))

hover = HoverTool(tooltips=tt, renderers=glyphs)
p1.add_tools(hover)

p1.legend.location = "bottom_center"
p1.legend.orientation = "horizontal"
p1.legend.label_text_font_size = '7pt'
p1.legend.label_width = 20
p1.legend.label_height = 8
p1.legend.glyph_height = 8
p1.legend.spacing = 0
Exemplo n.º 49
0
# set up initial data
n_samples = 1500
n_clusters = 2
algorithm = 'MiniBatchKMeans'
dataset = 'Noisy Circles'

X, y = get_dataset(dataset, n_samples)
X, y_pred = clustering(X, algorithm, n_clusters)
spectral = np.hstack([Spectral6] * 20)
colors = [spectral[i] for i in y]

# set up plot (styling in theme.yaml)
plot = Figure(toolbar_location=None, title=algorithm)
source = ColumnDataSource(data=dict(x=X[:, 0], y=X[:, 1], colors=colors))
plot.circle('x', 'y', fill_color='colors', line_color=None, source=source)

# set up widgets
clustering_algorithms= [
    'MiniBatchKMeans',
    'AffinityPropagation',
    'MeanShift',
    'SpectralClustering',
    'Ward',
    'AgglomerativeClustering',
    'DBSCAN',
    'Birch'
]

datasets_names = [
    'Noisy Circles',
Exemplo n.º 50
0
def update_explorer():
    games = pd.read_csv('static/games_full.csv')

    games["color"] = "blue"
    games.fillna(0, inplace=True)

    axis_map = {
        "Year Published": "yearpublished",
        "Average Rating": "bayes_avg_rating",
        "Boardgamegeek Rank": "rank",
        "Min Players": "minplayers",
        "Max Players": "maxplayers",
        "Min Playtime": "minplaytime",
        "Max Playtime": "maxplaytime",
        "Min Age": "minage"
    }
    ordered_keys = [
        "Year Published",
        "Average boardgamegeek Rating",
        "Rank",
        "Min Players",
        "Max Players",
        "Min Playtime",
        "Max Playtime",
        "Min Age"
    ]

    # Create Column Data Source that will be used by the plot
    source = ColumnDataSource(data=dict(x=[], y=[], color=[], name=[], year=[], thumbnail=[]))

    hover = HoverTool(
        tooltips="""
            <section style="width:350px; float:left; padding:10px;">
                    <img src="@img" height="42" alt="@name" width="42" style="float: left; margin: 0px 15px 15px 0px;" border="2"></img>
                    <span style="font-size: 17px; font-weight: bold;">@name (@year)</span>
            </section>
            """)

    x_axis = Select(title="X Axis", options=ordered_keys, value="Year Published")
    y_axis = Select(title="Y Axis", options=ordered_keys, value="Average boardgamegeek Rating")

    filter = {}
    filter['minplayers'] = request.args.get('minplayers', type=int)
    filter['maxplayers'] = request.args.get('maxplayers', type=int)
    filter['minplaytime'] = request.args.get('minplaytime', type=int)
    filter['maxplaytime'] = request.args.get('maxplaytime', type=int)
    filter['minyear'] = request.args.get("minyear", type=int)
    filter['maxyear'] = request.args.get("maxyear", type=int)
    filter['minage'] = request.args.get("minage", type=int)
    filter['rank'] = request.args.get("rank", type=int)
    x_axis = request.args.get("xaxis")
    y_axis = request.args.get("yaxis")

    p = Figure(plot_height=600, plot_width=750, title="", toolbar_location=None, tools=[hover])
    p.circle(x="x", y="y", source=source, size=7, color="color", line_color=None, fill_alpha=0.25)

    def select_games():
        selected = games[
                        (games["maxplayers"] <= filter['maxplayers']) &
                        (games["minplayers"] >= filter['minplayers']) &
                        (games["maxplaytime"] <= filter['maxplaytime']) &
                        (games["minplaytime"] >= filter['minplaytime']) &
                        (games["yearpublished"] >= filter['minyear']) &
                        (games["yearpublished"] <= filter['maxyear']) &
                        (games["minage"] >= filter['minage']) &
                        (games["rank"] <= filter['rank'])
                        ]
        return selected

    def update(attrname, old, new):
        df = select_games()

        x_name = axis_map[x_axis]
        y_name = axis_map[y_axis]

        p.xaxis.axis_label = x_axis
        p.yaxis.axis_label = y_axis
        p.title = "%d games selected" % len(df)
        source.data = dict(
            x=df[x_name],
            y=df[y_name],
            color=df["color"],
            name=df["name"],
            year=df["yearpublished"],
            img=df['thumbnail'].apply(lambda s: 'http:'+str(s))
        )

    update(None, None, None)  # initial view

    script, div = components(p)
    return jsonify(plot=render_template('explore_plot.html',script=script, div=div), flag = 0)
plot_field = Figure(plot_height=400,
                    plot_width=400,
                    tools=toolset,
                    title="Vector valued function",
                    x_range=[curveintegral_settings.x_min, curveintegral_settings.x_max],
                    y_range=[curveintegral_settings.y_min, curveintegral_settings.y_max]
                    )

# remove grid from plot
plot_field.grid[0].grid_line_alpha = 0.0
plot_field.grid[1].grid_line_alpha = 0.0

# Plot the direction field
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_segments)
plot_field.patches('xs', 'ys', source=source_patches)
plot_field.circle('x', 'y', source=source_basept, color='blue', size=1.5)
# Plot curve
plot_field.line('x', 'y', source=source_curve, color='black', legend='curve')
# Plot parameter point
plot_field.scatter('x', 'y', source=source_param, color='black', legend='c(t)')
# Plot corresponding tangent vector
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_param, color='black')
plot_field.patches('xs', 'ys', source=source_param, color='black')

# Generate a figure container for the integral value
plot_integral = Figure(title_text_font_size="12pt",
                       plot_height=200,
                       plot_width=400,
                       title="Integral along curve",
                       x_range=[curveintegral_settings.parameter_min, curveintegral_settings.parameter_max],
                       y_range=[-10,10]
Exemplo n.º 52
0
Arquivo: main.py Projeto: 0-T-0/bokeh
director = TextInput(title="Director name contains")
cast = TextInput(title="Cast names contains")
x_axis = Select(title="X Axis", options=sorted(axis_map.keys()), value="Tomato Meter")
y_axis = Select(title="Y Axis", options=sorted(axis_map.keys()), value="Number of Reviews")

# Create Column Data Source that will be used by the plot
source = ColumnDataSource(data=dict(x=[], y=[], color=[], title=[], year=[], revenue=[]))

hover = HoverTool(tooltips=[
    ("Title","@title"),
    ("Year", "@year"),
    ("$", "@revenue")
])

p = Figure(plot_height=600, plot_width=800, title="", toolbar_location=None, tools=[hover])
p.circle(x="x", y="y", source=source, size=7, color="color", line_color=None, fill_alpha="alpha")

def select_movies():
    genre_val = genre.value
    director_val = director.value.strip()
    cast_val = cast.value.strip()
    selected = movies[
        (movies.Reviews >= reviews.value) &
        (movies.BoxOffice >= (boxoffice.value * 1e6)) &
        (movies.Year >= min_year.value) &
        (movies.Year <= max_year.value) &
        (movies.Oscars >= oscars.value)
    ]
    if (genre_val != "All"):
        selected = selected[selected.Genre.str.contains(genre_val)==True]
    if (director_val != ""):
Exemplo n.º 53
0
def create_component_hst(result_dict):
    """Generate front end plots HST
    
    Function that is responsible for generating the front-end spectra plots for HST.
    
    Parameters
    ----------
    result_dict : dict 
        The dictionary returned from a PandExo (HST) run

    Returns
    -------
    tuple
        A tuple containing `(script, div)`, where the `script` is the
        front-end javascript required, and `div` is a dictionary of plot
        objects.
    """                                   
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"

    #plot planet spectrum
    mwave = result_dict['planet_spec']['model_wave']
    mspec = result_dict['planet_spec']['model_spec']
    
    binwave = result_dict['planet_spec']['binwave']
    binspec = result_dict['planet_spec']['binspec']
    
    error = result_dict['planet_spec']['error']
    error = np.zeros(len(binspec))+ error
    xlims = [result_dict['planet_spec']['wmin'], result_dict['planet_spec']['wmax']]
    ylims = [np.min(binspec)-2.0*error[0], np.max(binspec)+2.0*error[0]]
    
    eventType = result_dict['calc_start_window']['eventType'] 

    if eventType=='tranist':
        y_axis = '(Rp/R*)^2'
    elif eventType =='eclipse':
        y_axis='Fp/F*'

    plot_spectrum = Figure(plot_width=800, plot_height=300, x_range=xlims,
                               y_range=ylims, tools=TOOLS,#responsive=True,
                                 x_axis_label='Wavelength [microns]',
                                 y_axis_label=y_axis, 
                               title="Original Model with Observation")
    
    y_err = []
    x_err = []
    for px, py, yerr in zip(binwave, binspec, error):
        np.array(x_err.append((px, px)))
        np.array(y_err.append((py - yerr, py + yerr)))

    plot_spectrum.line(mwave,mspec, color= "black", alpha = 0.5, line_width = 4)
    plot_spectrum.circle(binwave,binspec, line_width=3, line_alpha=0.6)
    plot_spectrum.multi_line(x_err, y_err)
    
    
    #earliest and latest start times 
    obsphase1 = result_dict['calc_start_window']['obsphase1']
    obstr1 = result_dict['calc_start_window']['obstr1']
    rms = result_dict['calc_start_window']['light_curve_rms']
    obsphase2 = result_dict['calc_start_window']['obsphase2']
    obstr2 = result_dict['calc_start_window']['obstr2']
    phase1 = result_dict['calc_start_window']['phase1']    
    phase2 = result_dict['calc_start_window']['phase2']
    trmodel1 = result_dict['calc_start_window']['trmodel1']
    trmodel2 = result_dict['calc_start_window']['trmodel2']    
    
    if isinstance(rms, float):
        rms = np.zeros(len(obsphase1))+rms
    y_err1 = []
    x_err1 = []
    for px, py, yerr in zip(obsphase1, obstr1, rms):
        np.array(x_err1.append((px, px)))
        np.array(y_err1.append((py - yerr, py + yerr)))

    y_err2 = []
    x_err2 = []
    for px, py, yerr in zip(obsphase2, obstr2, rms):
        np.array(x_err2.append((px, px)))
        np.array(y_err2.append((py - yerr, py + yerr)))

    early = Figure(plot_width=400, plot_height=300,
                               tools=TOOLS,#responsive=True,
                                 x_axis_label='Orbital Phase',
                                 y_axis_label='Flux', 
                               title="Earliest Start Time")
    
    early.line(phase1, trmodel1, color='black',alpha=0.5, line_width = 4)
    early.circle(obsphase1, obstr1, line_width=3, line_alpha=0.6)
    early.multi_line(x_err1, y_err1)
     
    late = Figure(plot_width=400, plot_height=300, 
                                tools=TOOLS,#responsive=True,
                                 x_axis_label='Orbital Phase',
                                 y_axis_label='Flux', 
                               title="Latest Start Time")
    late.line(phase2, trmodel2, color='black',alpha=0.5, line_width = 3)
    late.circle(obsphase2, obstr2, line_width=3, line_alpha=0.6)
    late.multi_line(x_err2, y_err2)
        
    start_time = row(early, late)
    
    result_comp = components({'plot_spectrum':plot_spectrum, 
                              'start_time':start_time})

    return result_comp
Exemplo n.º 54
0
class DynamicPlotHandler(Handler):
    def __init__(self, network):
        self._network = weakref.ref(network)
        self.sources = {}
        self._last_time_list = None
        self._update_complete = False
        self._recurring_update = RecurringTask(self.plan_update_data, delay=5)
        self._pcb = None  # Periodic callback
        self._ntcb = None  # Next Tick callback
        super().__init__()

    @property
    def network(self):
        return self._network()

    def organize_data(self):

        self._log.debug("Organize Data")

        self.s = {}
        for point in self.network.trends:
            self.s[point.history.name] = (point.history, point.history.units)
        self.lst_of_trends = [his[0] for name, his in self.s.items()]

    def build_data_sources(self):
        sources = {}
        self.organize_data()
        for each in self.lst_of_trends:
            df = pd.DataFrame(each)
            df = df.reset_index()
            df["name"] = each.name
            df["units"] = str(each.units)
            df["time_s"] = df["index"].apply(str)
            df.states = each.states
            try:
                df = (
                    df.fillna(method="ffill")
                    .fillna(method="bfill")
                    .replace(["inactive", "active"], [0, 1])
                )
            except TypeError:
                df = df.fillna(method="ffill").fillna(method="bfill")

            sources[each.name] = ColumnDataSource(
                data=dict(
                    x=df["index"],
                    y=df[each.name],
                    time=df["time_s"],
                    name=df["name"],
                    units=df["units"],
                )
            )
        return sources

    def build_plot(self):
        self._log.debug("Build Plot")

        self.stop_update_data()
        self.sources = self.build_data_sources()

        TOOLS = "pan,box_zoom,wheel_zoom,save,reset"
        self.p = Figure(
            x_axis_type="datetime",
            x_axis_label="Time",
            y_axis_label="Numeric Value",
            title="BAC0 Trends",
            tools=TOOLS,
            plot_width=800,
            plot_height=600,
            toolbar_location="above",
        )

        self.p.background_fill_color = "#f4f3ef"
        self.p.border_fill_color = "#f4f3ef"
        self.p.extra_y_ranges = {
            "bool": Range1d(start=0, end=1.1),
            "enum": Range1d(start=0, end=10),
        }
        self.p.add_layout(LinearAxis(y_range_name="bool", axis_label="Binary"), "left")
        self.p.add_layout(
            LinearAxis(y_range_name="enum", axis_label="Enumerated"), "right"
        )

        hover = HoverTool(
            tooltips=[
                ("name", "@name"),
                ("value", "@y"),
                ("units", "@units"),
                ("time", "@time"),
            ]
        )
        self.p.add_tools(hover)

        self.legends_list = []

        length = len(self.s.keys())
        if length <= 10:
            if length < 3:
                length = 3
            color_mapper = dict(zip(self.s.keys(), d3["Category10"][length]))
        else:
            # This would be a very loaded trend...
            color_mapper = dict(zip(self.s.keys(), Spectral6[:length]))

        for each in self.lst_of_trends:
            if each.states == "binary":
                self.p.circle(
                    "x",
                    "y",
                    source=self.sources[each.name],
                    name=each.name,
                    color=color_mapper[each.name],
                    legend=("{} | {} (OFF-ON)".format(each.name, each.description)),
                    y_range_name="bool",
                    size=10,
                )
                # self.legends_list.append(
                #    (("{} | {} (OFF-ON)".format(each.name, each.description)), [c])
                # )
            elif each.states == "multistates":
                self.p.diamond(
                    "x",
                    "y",
                    source=self.sources[each.name],
                    name=each.name,
                    color=color_mapper[each.name],
                    legend=(
                        "{} | {} ({})".format(each.name, each.description, each.units)
                    ),
                    y_range_name="enum",
                    size=20,
                )
            else:
                self.p.line(
                    "x",
                    "y",
                    source=self.sources[each.name],
                    name=each.name,
                    color=color_mapper[each.name],
                    legend=(
                        "{} | {} ({})".format(each.name, each.description, each.units)
                    ),
                    line_width=2,
                )

            self.p.legend.location = "top_left"
            # legend = Legend(items=self.legends_list, location=(0, -60))
            self.p.legend.click_policy = "hide"
            # self.p.add_layout(legend, "right")
            self.plots = [self.p]

    def update_data(self):
        self._log.debug("Update Data")
        doc = curdoc()
        # self.organize_data()
        if self._last_time_list:
            if self._last_time_list != self.s.keys():
                self._list_have_changed = True
                self.stop_update_data()
                # doc.add_next_tick_callback(self.modify_document)
                self.modify_document(doc)
            else:
                self._list_have_changed = False

        l = []
        for each in self.p.renderers:
            l.append(each.name)

            # for each in self.lst_of_trends:
            #    df = pd.DataFrame(each)
            #    df = df.reset_index()
            #    df['name'] = each.name
            #    df['units'] = str(each.units)
            #    df['time_s'] = df['index'].apply(str)

            #    try:
            #        df = df.fillna(method='ffill').fillna(
            #            method='bfill').replace(['inactive', 'active'], [0, 1])
            #    except TypeError:
            #        df = df.fillna(method='ffill').fillna(method='bfill')

            index = l.index(each.name)
        #    renderer = self.p.renderers[index]
        #    new_data = {}
        #    new_data['name'] = df['name']
        #    new_data['x'] = df['index']
        #    new_data['y'] = df[each.name]
        #    if each.states == 'binary':
        #        new_data['units'] = [each.units[int(x)] for x in df[each.name]]
        #    elif each.states == 'multistates':
        #        new_data['units'] = [
        #            each.units[int(math.fabs(x-1))] for x in df[each.name]]
        #    else:
        #        new_data['units'] = df['units']
        #    new_data['time'] = df['time_s']
        #    renderer.data_source.data = new_data
        try:
            new_data = self.build_data_sources()
            for each in self.lst_of_trends:
                self.sources[each.name].data = new_data[each.name].data

        except KeyError:
            self._log.warning(
                "Problem updating {} on chart, will try again next time.".format(
                    each.name
                )
            )

        else:
            self._last_time_list = self.s.keys()
            # self.start_update_data()
            self._update_complete = True

    def modify_document(self, doc):
        doc.clear()
        self.build_plot()
        layout = gridplot(self.plots, ncols=2)

        doc.add_root(layout)
        self._pcb = doc.add_periodic_callback(self.update_data, 10000)
        return doc

    def plan_update_data(self):
        doc = curdoc()
        if self._update_complete == True:
            self._update_complete = False
            self._ntcb = doc.add_next_tick_callback(self.update_data)

    def stop_update_data(self):
        doc = curdoc()
        try:
            doc.remove_periodic_callback(self._pcb)
        except:
            pass
        if self._recurring_update.is_running:
            self._recurring_update.stop()
            while self._recurring_update.is_running:
                pass
        try:
            doc.remove_next_tick_callback(self._ntcb)
        except (ValueError, RuntimeError):
            pass  # Already gone

    def start_update_data(self):
        if not self._recurring_update.is_running:
            try:
                self._recurring_update.start()
                while not self._recurring_update.is_running:
                    pass
            except RuntimeError:
                pass
Exemplo n.º 55
0
def create_component_jwst(result_dict):
    """Generate front end plots JWST
    
    Function that is responsible for generating the front-end interactive plots for JWST.

    Parameters 
    ----------
    result_dict : dict 
        the dictionary returned from a PandExo run
    
    Returns
    -------
    tuple 
        A tuple containing `(script, div)`, where the `script` is the
        front-end javascript required, and `div` is a dictionary of plot
        objects.
    """  
    timing = result_dict['timing']
    noccultations = result_dict['timing']['Number of Transits']
    out = result_dict['PandeiaOutTrans']
    
    # select the tools we want
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"

    #Define units for x and y axis
    punit = result_dict['input']['Primary/Secondary']
    p=1.0
    if punit == 'fp/f*': p = -1.0
    else: punit = punit
    
    if result_dict['input']['Calculation Type'] =='phase_spec':
        x_axis_label='Time (secs)'
        frac = 1.0
    else:
        x_axis_label='Wavelength [microns]'
        frac = result_dict['timing']['Num Integrations Out of Transit']/result_dict['timing']['Num Integrations In Transit']

    electrons_out = result_dict['RawData']['electrons_out']
    electrons_in = result_dict['RawData']['electrons_in']
    
    var_in = result_dict['RawData']['var_in']
    var_out = result_dict['RawData']['var_out']
    
    
    x = result_dict['FinalSpectrum']['wave']
    y = result_dict['FinalSpectrum']['spectrum_w_rand']
    err = result_dict['FinalSpectrum']['error_w_floor']

    y_err = []
    x_err = []
    for px, py, yerr in zip(x, y, err):
        np.array(x_err.append((px, px)))
        np.array(y_err.append((py - yerr, py + yerr)))

    source = ColumnDataSource(data=dict(x=x, y=y, y_err=y_err, x_err=x_err, err=err, 
                                electrons_out=electrons_out, electrons_in=electrons_in, var_in=var_in, var_out=var_out, 
                                p=var_in*0+p,nocc=var_in*0+noccultations, frac = var_in*0+frac))
    original = ColumnDataSource(data=dict(x=x, y=y, y_err=y_err, x_err=x_err, err=err, electrons_out=electrons_out, electrons_in=electrons_in, var_in=var_in, var_out=var_out))

    ylims = [min(result_dict['OriginalInput']['model_spec'])- 0.1*min(result_dict['OriginalInput']['model_spec']),
                 0.1*max(result_dict['OriginalInput']['model_spec'])+max(result_dict['OriginalInput']['model_spec'])]
    xlims = [min(result_dict['FinalSpectrum']['wave']), max(result_dict['FinalSpectrum']['wave'])]

    plot_spectrum = Figure(plot_width=800, plot_height=300, x_range=xlims,
                               y_range=ylims, tools=TOOLS,#responsive=True,
                                 x_axis_label=x_axis_label,
                                 y_axis_label=punit, 
                               title="Original Model with Observation")
    
    plot_spectrum.line(result_dict['OriginalInput']['model_wave'],result_dict['OriginalInput']['model_spec'], color= "black", alpha = 0.5, line_width = 4)
        
    plot_spectrum.circle('x', 'y', source=source, line_width=3, line_alpha=0.6)
    plot_spectrum.multi_line('x_err', 'y_err', source=source)

    callback = CustomJS(args=dict(source=source, original=original), code="""
            // Grab some references to the data
            var sdata = source.get('data');
            var odata = original.get('data');

            // Create copies of the original data, store them as the source data
            sdata['x'] = odata['x'].slice(0);
            sdata['y'] = odata['y'].slice(0);

            sdata['y_err'] = odata['y_err'].slice(0);
            sdata['x_err'] = odata['x_err'].slice(0);
            sdata['err'] = odata['err'].slice(0);

            sdata['electrons_out'] = odata['electrons_out'].slice(0);
            sdata['electrons_in'] = odata['electrons_in'].slice(0);
            sdata['var_in'] = odata['var_in'].slice(0);
            sdata['var_out'] = odata['var_out'].slice(0);

            // Create some variables referencing the source data
            var x = sdata['x'];
            var y = sdata['y'];
            var y_err = sdata['y_err'];
            var x_err = sdata['x_err'];
            var err = sdata['err'];
            var p = sdata['p'];
            var frac = sdata['frac'];
            var og_ntran = sdata['nocc'];

            var electrons_out = sdata['electrons_out'];
            var electrons_in = sdata['electrons_in'];
            var var_in = sdata['var_in'];
            var var_out = sdata['var_out'];

            var f = wbin.get('value');
            var ntran = ntran.get('value');

            var wlength = Math.pow(10.0,f);

            var ind = [];
            ind.push(0);
            var start = 0;


            for (i = 0; i < x.length-1; i++) {
                if (x[i+1] - x[start] >= wlength) {
                    ind.push(i+1);
                    start = i;
                }
            }

            if (ind[ind.length-1] != x.length) {
                ind.push(x.length);
            }

            var xout = [];


            var foutout = [];
            var finout = [];
            var varinout = [];
            var varoutout = [];

            var xslice = []; 

            var foutslice = [];
            var finslice = [];
            var varoutslice = [];
            var varinslice = [];

            function add(a, b) {
                return a+b;
            }

            for (i = 0; i < ind.length-1; i++) {
                xslice = x.slice(ind[i],ind[i+1]);

                foutslice = electrons_out.slice(ind[i],ind[i+1]);
                finslice = electrons_in.slice(ind[i],ind[i+1]);
                
                varinslice = var_in.slice(ind[i],ind[i+1]);
                varoutslice = var_out.slice(ind[i],ind[i+1]);

                xout.push(xslice.reduce(add, 0)/xslice.length);
                foutout.push(foutslice.reduce(add, 0));
                finout.push(finslice.reduce(add, 0));
                
                varinout.push(varinslice.reduce(add, 0));
                varoutout.push(varoutslice.reduce(add, 0));

                xslice = [];
                foutslice = [];
                finslice = [];
                varinslice = [];
                varoutslice = [];
            }
            
            var new_err = 1.0;
            var rand = 1.0;

            for (i = 0; i < x.length; i++) {
                new_err = Math.pow((frac[i]/foutout[i]),2)*varinout[i] + Math.pow((finout[i]*frac[i]/Math.pow(foutout[i],2)),2)*varoutout[i];
                new_err = Math.sqrt(new_err)*Math.sqrt(og_ntran[i]/ntran);
                rand = new_err*(Math.random()-Math.random());
                y[i] = p[i]*((1.0 - frac[i]*finout[i]/foutout[i]) + rand); 
                x[i] = xout[i];
                x_err[i][0] = xout[i];
                x_err[i][1] = xout[i];
                y_err[i][0] = y[i] + new_err;
                y_err[i][1] = y[i] - new_err;            
            }

            source.trigger('change');
        """)

    #var_tot = (frac/electrons_out)**2.0 * var_in + (electrons_in*frac/electrons_out**2.0)**2.0 * var_out

    sliderWbin =  Slider(title="binning", value=np.log10(x[1]-x[0]), start=np.log10(x[1]-x[0]), end=np.log10(max(x)/2.0), step= .05, callback=callback)
    callback.args["wbin"] = sliderWbin
    sliderTrans =  Slider(title="Num Trans", value=noccultations, start=1, end=50, step= 1, callback=callback)
    callback.args["ntran"] = sliderTrans
    layout = column(row(sliderWbin,sliderTrans), plot_spectrum)


    #out of transit 2d output 
    raw = result_dict['RawData']
    
    # Flux 1d
    x, y = raw['wave'], raw['e_rate_out']*result_dict['timing']['Seconds per Frame']*(timing["APT: Num Groups per Integration"]-1)
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]

    plot_flux_1d1 = Figure(tools=TOOLS,
                         x_axis_label='Wavelength [microns]',
                         y_axis_label='e-/integration', title="Flux Per Integration",
                         plot_width=800, plot_height=300)
    plot_flux_1d1.line(x, y, line_width = 4, alpha = .7)
    tab1 = Panel(child=plot_flux_1d1, title="Flux per Int")

    # BG 1d
    #x, y = out['1d']['extracted_bg_only']
    #y = y[~np.isnan(y)]
    #x = x[~np.isnan(y)]
    #plot_bg_1d1 = Figure(tools=TOOLS,
    #                     x_axis_label='Wavelength [microns]',
    #                     y_axis_label='Flux (e/s)', title="Background",
    #                     plot_width=800, plot_height=300)
    #plot_bg_1d1.line(x, y, line_width = 4, alpha = .7)
    #tab2 = Panel(child=plot_bg_1d1, title="Background Flux")

    # SNR 
    y = np.sqrt(y) #this is computing the SNR (sqrt of photons in a single integration)


    plot_snr_1d1 = Figure(tools=TOOLS,
                         x_axis_label=x_axis_label,
                         y_axis_label='sqrt(e-)/integration', title="SNR per integration",
                         plot_width=800, plot_height=300)
    plot_snr_1d1.line(x, y, line_width = 4, alpha = .7)
    tab3 = Panel(child=plot_snr_1d1, title="SNR per Int")


    # Error bars (ppm) 
    x = result_dict['FinalSpectrum']['wave']
    y = result_dict['FinalSpectrum']['error_w_floor']*1e6
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]    
    ymed = np.median(y)


    plot_noise_1d1 = Figure(tools=TOOLS,#responsive=True,
                         x_axis_label=x_axis_label,
                         y_axis_label='Spectral Precision (ppm)', title="Spectral Precision",
                         plot_width=800, plot_height=300, y_range = [0,2.0*ymed])
    ymed = np.median(y)
    plot_noise_1d1.circle(x, y, line_width = 4, alpha = .7)
    tab4 = Panel(child=plot_noise_1d1, title="Precision")

    #Not happy? Need help picking a different mode? 
    plot_spectrum2 = Figure(plot_width=800, plot_height=300, x_range=xlims,y_range=ylims, tools=TOOLS,
                             x_axis_label=x_axis_label,
                             y_axis_label=punit, title="Original Model",y_axis_type="log")

    plot_spectrum2.line(result_dict['OriginalInput']['model_wave'],result_dict['OriginalInput']['model_spec'],
                        line_width = 4,alpha = .7)
    tab5 = Panel(child=plot_spectrum2, title="Original Model")


    #create set of five tabs 
    tabs1d = Tabs(tabs=[ tab1,tab3, tab4, tab5])



    # Detector 2d
    data = out['2d']['detector']

    
    xr, yr = data.shape
    
    plot_detector_2d = Figure(tools="pan,wheel_zoom,box_zoom,resize,reset,hover,save",
                         x_range=[0, yr], y_range=[0, xr],
                         x_axis_label='Pixel', y_axis_label='Spatial',
                         title="2D Detector Image",
                        plot_width=800, plot_height=300)
    
    plot_detector_2d.image(image=[data], x=[0], y=[0], dh=[xr], dw=[yr],
                      palette="Spectral11")


    #2d tabs 

    #2d snr 
    data = out['2d']['snr']
    data[np.isinf(data)] = 0.0
    xr, yr = data.shape
    plot_snr_2d = Figure(tools=TOOLS,
                         x_range=[0, yr], y_range=[0, xr],
                         x_axis_label='Pixel', y_axis_label='Spatial',
                         title="Signal-to-Noise Ratio",
                        plot_width=800, plot_height=300)
    
    plot_snr_2d.image(image=[data], x=[0], y=[0], dh=[xr], dw=[yr],
                      palette="Spectral11")
    
    tab1b = Panel(child=plot_snr_2d, title="SNR")

    #saturation
    
    data = out['2d']['saturation']
    xr, yr = data.shape
    plot_sat_2d = Figure(tools=TOOLS,
                         x_range=[0, yr], y_range=[0, xr],
                         x_axis_label='Pixel', y_axis_label='Spatial',
                         title="Saturation",
                        plot_width=800, plot_height=300)
    
    plot_sat_2d.image(image=[data], x=[0], y=[0], dh=[xr], dw=[yr],
                      palette="Spectral11")
    
    tab2b = Panel(child=plot_sat_2d, title="Saturation")

    tabs2d = Tabs(tabs=[ tab1b, tab2b])
    
 
    result_comp = components({'plot_spectrum':layout, 
                              'tabs1d': tabs1d, 'det_2d': plot_detector_2d,
                              'tabs2d': tabs2d})

    return result_comp
Exemplo n.º 56
0
            indne = set(indb).intersection(indt).intersection(indne)
            indye = set(indb).intersection(indt).intersection(indye)

            noerrorlegend = bandname if len(indne) == 0 else ''

            source = ColumnDataSource(
                data = dict(
                    x = [phototime[i] for i in indne],
                    y = [photoAB[i] for i in indne],
                    err = [photoerrs[i] for i in indne],
                    desc = [photoband[i] for i in indne],
                    instr = [photoinstru[i] for i in indne],
                    src = [photosource[i] for i in indne]
                )
            )
            p1.circle('x', 'y', source = source, color=bandcolorf(band), fill_color="white", legend=noerrorlegend, size=4)

            source = ColumnDataSource(
                data = dict(
                    x = [phototime[i] for i in indye],
                    y = [photoAB[i] for i in indye],
                    err = [photoerrs[i] for i in indye],
                    desc = [photoband[i] for i in indye],
                    instr = [photoinstru[i] for i in indye],
                    src = [photosource[i] for i in indye]
                )
            )
            p1.multi_line([err_xs[x] for x in indye], [err_ys[x] for x in indye], color=bandcolorf(band))
            p1.circle('x', 'y', source = source, color=bandcolorf(band), legend=bandname, size=4)

            upplimlegend = bandname if len(indye) == 0 and len(indne) == 0 else ''
Exemplo n.º 57
0
class DynamicPlotHandler(Handler):
    def __init__(self, network):
        self._network = weakref.ref(network)
        self.sources = {}
        self._last_time_list = None
        self._update_complete = False
        self._recurring_update = RecurringTask(self.plan_update_data, delay=5)
        self._pcb = None  # Periodic callback
        self._ntcb = None  # Next Tick callback
        super().__init__()

    @property
    def network(self):
        return self._network()

    def organize_data(self):

        self._log.debug("Organize Data")

        self.s = {}
        for point in self.network.trends:
            self.s[point.history.name] = (point.history, point.history.units)
        self.lst_of_trends = [his[0] for name, his in self.s.items()]

    def build_data_sources(self):
        sources = {}
        self.organize_data()
        for each in self.lst_of_trends:
            df = pd.DataFrame(each)
            df = df.reset_index()
            df["name"] = each.name
            df["units"] = str(each.units)
            df["time_s"] = df["index"].apply(str)
            df.states = each.states
            try:
                df = (
                    df.fillna(method="ffill")
                    .fillna(method="bfill")
                    .replace(["inactive", "active"], [0, 1])
                )
            except TypeError:
                df = df.fillna(method="ffill").fillna(method="bfill")

            sources[each.name] = ColumnDataSource(
                data=dict(
                    x=df["index"],
                    y=df[each.name],
                    time=df["time_s"],
                    name=df["name"],
                    units=df["units"],
                )
            )
        return sources

    def build_plot(self):
        self._log.debug("Build Plot")

        self.stop_update_data()
        self.sources = self.build_data_sources()

        TOOLS = "pan,box_zoom,wheel_zoom,save,reset"
        self.p = Figure(
            x_axis_type="datetime",
            x_axis_label="Time",
            y_axis_label="Numeric Value",
            title="BAC0 Trends",
            tools=TOOLS,
            plot_width=800,
            plot_height=600,
            toolbar_location="above",
        )

        self.p.background_fill_color = "#f4f3ef"
        self.p.border_fill_color = "#f4f3ef"
        self.p.extra_y_ranges = {
            "bool": Range1d(start=0, end=1.1),
            "enum": Range1d(start=0, end=10),
        }
        self.p.add_layout(LinearAxis(y_range_name="bool", axis_label="Binary"), "left")
        self.p.add_layout(
            LinearAxis(y_range_name="enum", axis_label="Enumerated"), "right"
        )

        hover = HoverTool(
            tooltips=[
                ("name", "@name"),
                ("value", "@y"),
                ("units", "@units"),
                ("time", "@time"),
            ]
        )
        self.p.add_tools(hover)

        length = len(self.s.keys())
        if length <= 10:
            if length < 3:
                length = 3
            color_mapper = dict(zip(self.s.keys(), d3["Category10"][length]))
        else:
            # This would be a very loaded trend...
            color_mapper = dict(zip(self.s.keys(), Spectral6[:length]))

        for each in self.lst_of_trends:
            if each.states == "binary":
                self.p.circle(
                    "x",
                    "y",
                    source=self.sources[each.name],
                    name=each.name,
                    color=color_mapper[each.name],
                    legend=("%s | %s (OFF-ON)" % (each.name, each.description)),
                    y_range_name="bool",
                    size=10,
                )
            elif each.states == "multistates":
                self.p.diamond(
                    "x",
                    "y",
                    source=self.sources[each.name],
                    name=each.name,
                    color=color_mapper[each.name],
                    legend=("%s | %s (%s)" % (each.name, each.description, each.units)),
                    y_range_name="enum",
                    size=20,
                )
            else:
                self.p.line(
                    "x",
                    "y",
                    source=self.sources[each.name],
                    name=each.name,
                    color=color_mapper[each.name],
                    legend=("%s | %s (%s)" % (each.name, each.description, each.units)),
                    line_width=2,
                )

            self.p.legend.location = "bottom_right"
            self.p.legend.click_policy = "hide"

            self.plots = [self.p]

    def update_data(self):
        self._log.debug("Update Data")
        doc = curdoc()
        # self.organize_data()
        if self._last_time_list:
            if self._last_time_list != self.s.keys():
                self._list_have_changed = True
                self.stop_update_data()
                # doc.add_next_tick_callback(self.modify_document)
                self.modify_document(doc)
            else:
                self._list_have_changed = False

        l = []
        for each in self.p.renderers:
            l.append(each.name)

            # for each in self.lst_of_trends:
            #    df = pd.DataFrame(each)
            #    df = df.reset_index()
            #    df['name'] = each.name
            #    df['units'] = str(each.units)
            #    df['time_s'] = df['index'].apply(str)

            #    try:
            #        df = df.fillna(method='ffill').fillna(
            #            method='bfill').replace(['inactive', 'active'], [0, 1])
            #    except TypeError:
            #        df = df.fillna(method='ffill').fillna(method='bfill')

            index = l.index(each.name)
        #    renderer = self.p.renderers[index]
        #    new_data = {}
        #    new_data['name'] = df['name']
        #    new_data['x'] = df['index']
        #    new_data['y'] = df[each.name]
        #    if each.states == 'binary':
        #        new_data['units'] = [each.units[int(x)] for x in df[each.name]]
        #    elif each.states == 'multistates':
        #        new_data['units'] = [
        #            each.units[int(math.fabs(x-1))] for x in df[each.name]]
        #    else:
        #        new_data['units'] = df['units']
        #    new_data['time'] = df['time_s']
        #    renderer.data_source.data = new_data
        try:
            new_data = self.build_data_sources()
            for each in self.lst_of_trends:
                self.sources[each.name].data = new_data[each.name].data

        except KeyError:
            self._log.warning(
                "Problem updating {} on chart, will try again next time.".format(
                    each.name
                )
            )

        else:
            self._last_time_list = self.s.keys()
            # self.start_update_data()
            self._update_complete = True

    def modify_document(self, doc):
        curdoc().clear()
        # doc = curdoc()
        try:
            curdoc().remove_periodic_callback(self._pcb)
        except:
            pass
        doc.clear()
        self.build_plot()
        layout = gridplot(self.plots, ncols=2)

        doc.add_root(layout)
        self._pcb = doc.add_periodic_callback(self.update_data, 10000)
        return doc

    def plan_update_data(self):
        doc = curdoc()
        if self._update_complete == True:
            self._update_complete = False
            self._ntcb = doc.add_next_tick_callback(self.update_data)

    def stop_update_data(self):
        doc = curdoc()
        if self._recurring_update.is_running:
            self._recurring_update.stop()
            while self._recurring_update.is_running:
                pass
            try:
                doc.remove_next_tick_callback(self._ntcb)
            except (ValueError, RuntimeError):
                pass  # Already gone

    def start_update_data(self):
        if not self._recurring_update.is_running:
            try:
                self._recurring_update.start()
                while not self._recurring_update.is_running:
                    pass
            except RuntimeError:
                pass
Exemplo n.º 58
0
def create_component_hst(result_dict):
    """Generate front end plots HST
    
    Function that is responsible for generating the front-end spectra plots for HST.
    
    Parameters
    ----------
    result_dict : dict 
        The dictionary returned from a PandExo (HST) run

    Returns
    -------
    tuple
        A tuple containing `(script, div)`, where the `script` is the
        front-end javascript required, and `div` is a dictionary of plot
        objects.
    """                                   
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"

    #plot planet spectrum
    mwave = result_dict['planet_spec']['model_wave']
    mspec = result_dict['planet_spec']['model_spec']
    
    binwave = result_dict['planet_spec']['binwave']
    binspec = result_dict['planet_spec']['binspec']
    
    error = result_dict['planet_spec']['error']
    error = np.zeros(len(binspec))+ error
    xlims = [result_dict['planet_spec']['wmin'], result_dict['planet_spec']['wmax']]
    ylims = [np.min(binspec)-2.0*error[0], np.max(binspec)+2.0*error[0]]
    
    plot_spectrum = Figure(plot_width=800, plot_height=300, x_range=xlims,
                               y_range=ylims, tools=TOOLS,#responsive=True,
                                 x_axis_label='Wavelength [microns]',
                                 y_axis_label='(Rp/R*)^2', 
                               title="Original Model with Observation")
    
    y_err = []
    x_err = []
    for px, py, yerr in zip(binwave, binspec, error):
        np.array(x_err.append((px, px)))
        np.array(y_err.append((py - yerr, py + yerr)))

    plot_spectrum.line(mwave,mspec, color= "black", alpha = 0.5, line_width = 4)
    plot_spectrum.circle(binwave,binspec, line_width=3, line_alpha=0.6)
    plot_spectrum.multi_line(x_err, y_err)
    
    
    #earliest and latest start times 
    obsphase1 = result_dict['calc_start_window']['obsphase1']
    obstr1 = result_dict['calc_start_window']['obstr1']
    rms = result_dict['calc_start_window']['light_curve_rms']
    obsphase2 = result_dict['calc_start_window']['obsphase2']
    obstr2 = result_dict['calc_start_window']['obstr2']
    phase1 = result_dict['calc_start_window']['phase1']    
    phase2 = result_dict['calc_start_window']['phase2']
    trmodel1 = result_dict['calc_start_window']['trmodel1']
    trmodel2 = result_dict['calc_start_window']['trmodel2']    
    
    if isinstance(rms, float):
        rms = np.zeros(len(obsphase1))+rms
    y_err1 = []
    x_err1 = []
    for px, py, yerr in zip(obsphase1, obstr1, rms):
        np.array(x_err1.append((px, px)))
        np.array(y_err1.append((py - yerr, py + yerr)))

    y_err2 = []
    x_err2 = []
    for px, py, yerr in zip(obsphase2, obstr2, rms):
        np.array(x_err2.append((px, px)))
        np.array(y_err2.append((py - yerr, py + yerr)))

    early = Figure(plot_width=400, plot_height=300,
                               tools=TOOLS,#responsive=True,
                                 x_axis_label='Orbital Phase',
                                 y_axis_label='Flux', 
                               title="Earliest Start Time")
    
    early.line(phase1, trmodel1, color='black',alpha=0.5, line_width = 4)
    early.circle(obsphase1, obstr1, line_width=3, line_alpha=0.6)
    early.multi_line(x_err1, y_err1)
     
    late = Figure(plot_width=400, plot_height=300, 
                                tools=TOOLS,#responsive=True,
                                 x_axis_label='Orbital Phase',
                                 y_axis_label='Flux', 
                               title="Latest Start Time")
    late.line(phase2, trmodel2, color='black',alpha=0.5, line_width = 3)
    late.circle(obsphase2, obstr2, line_width=3, line_alpha=0.6)
    late.multi_line(x_err2, y_err2)
        
    start_time = row(early, late)
    
    result_comp = components({'plot_spectrum':plot_spectrum, 
                              'start_time':start_time})

    return result_comp
Exemplo n.º 59
0
              plot_width=400,
              tools=toolset,
              title="Time dependent PDEs",
              x_range=[pde_settings.x_min, pde_settings.x_max],
              y_range=[-1, 1]
              )

# Plot the numerical solution at time=t by the x,u values in the source property
plot.line('x', 'u', source=plot_data_num,
          line_width=.5,
          line_alpha=.6,
          line_dash=[4, 4],
          color='red')
plot.line('x', 'u', source=plot_data_ana,
          line_width=.5,
          line_alpha=.6,
          color='blue',
          legend='analytical solution')
plot.circle('x', 'u', source=plot_data_num,
            color='red',
            legend='numerical solution')

# calculate data
init_pde()

# lists all the controls in our app
controls = widgetbox(initial_condition,time_slider,h_slider,k_slider,pde_type, solver_type,width=400)

# make layout
curdoc().add_root(row(plot,controls,width=800))