Ejemplo n.º 1
0
def test_Span():
    line = Span()
    assert line.location is None
    assert line.location_units == 'data'
    assert line.dimension == 'width'
    assert line.x_range_name == 'default'
    assert line.y_range_name == 'default'
    assert line.level == 'annotation'
    assert line.render_mode == 'canvas'
    check_line_properties(line, "", 'black', 1.0)
    check_properties_existence(line, [
        "visible", "location", "location_units", "dimension", "x_range_name",
        "y_range_name", "level", "render_mode"
    ], LINE)
Ejemplo n.º 2
0
def test_Span():
    line = Span()
    assert line.plot is None
    assert line.location is None
    assert line.location_units == 'data'
    assert line.dimension == 'width'
    assert line.x_range_name == 'default'
    assert line.y_range_name == 'default'
    assert line.level == 'annotation'
    assert line.render_mode == 'canvas'
    yield check_line, line, "", 'black', 1.0
    yield (check_props, line, [
        "plot", "location", "location_units", "dimension", "x_range_name",
        "y_range_name", "level", "render_mode"
    ], LINE)
def grafica_distribucion_estandar(lista, file="index.html"):

    lista_ordenada = ordenamiento_insercion(lista)

    mu = media(lista_ordenada)
    sigma = desviacion_estandar(lista_ordenada)

    x, y = valores_x_y_distribucion_normal(lista_ordenada)

    output_file(file)

    f = figure()

    f.line(x, y)

    # Creating span annotation for mu
    span = Span(location=mu,
                dimension='height',
                line_color='blue',
                line_width=2)
    f.add_layout(span)

    # Creating a box annotations for sigmas
    sigma_1 = BoxAnnotation(left=mu - 1 * sigma,
                            right=mu + sigma,
                            line_width=1,
                            fill_color='grey',
                            fill_alpha=0.3)
    f.add_layout(sigma_1)

    sigma_2_left = BoxAnnotation(left=mu - 2 * sigma,
                                 right=mu - 1 * sigma,
                                 line_width=1,
                                 fill_color='grey',
                                 fill_alpha=0.2)
    f.add_layout(sigma_2_left)

    sigma_2_right = BoxAnnotation(left=mu + sigma,
                                  right=mu + 2 * sigma,
                                  line_width=1,
                                  fill_color='grey',
                                  fill_alpha=0.2)
    f.add_layout(sigma_2_right)

    show(f)
Ejemplo n.º 4
0
def add_equator_line(plot):
    plot.add_layout(
        Span(
            location=0,
            dimension="width",
            line_color=colors["equator"],
            line_dash="dashed",
            line_width=1,
        )
    )
    plot.add_layout(
        Label(
            text="Equator",
            x=-0.9 * constants.PLOTS_RANGE,
            y=0.03 * constants.PLOTS_RANGE,
            text_font_size="8pt",
            text_color=colors["equator"],
        )
    )
Ejemplo n.º 5
0
    def plot_changepoints(data, cp_list, colors=None):
        """
            This function plots vertical lines in correspondance with the changepoints location founded by models.
            The time series plot is given by the function plot_time_series(), previously implemented in the
            'plottingTools' class. The function returns a different plot for each model used.
        """
        results = {key: d[key] for d in cp_list for key in d}
        tab_list = []

        if not colors:
            colors = palettes.Set1[len(results.keys())]

        if isinstance(colors, str):
            colors = [colors] * len(results.keys())

        for key, color in zip(results.keys(), colors):
            f = figure(x_axis_type="datetime")
            f = time_series_plot.plot_time_series(data=data, fig=f, alpha=0.6)

            if type(results[key]) == int:
                results[key] = [results[key]]

            for value in results[key]:
                start_date = time.mktime(data.index[value].timetuple()) * 1000
                span_4 = Span(location=start_date,
                              dimension='height',
                              line_color=color,
                              line_dash='dashed',
                              line_width=1)
                f.add_layout(span_4)

            tab = Panel(child=f, title=key)
            tab_list.append(tab)

        tabs = Tabs(tabs=tab_list)
        show(tabs)
Ejemplo n.º 6
0
p = figure(plot_width=900,
           plot_height=600,
           title='各个商品打折套路解析',
           tools=[hover, 'box_select,reset,wheel_zoom,pan,crosshair'])

p.circle_x(x='pre',
           y='zkl',
           source=source3,
           size='size',
           fill_color='red',
           line_color='black',
           fill_alpha=0.6,
           line_dash=[8, 3])

x = Span(location=x_mean,
         dimension='height',
         line_color='green',
         line_alpha=0.7)
y = Span(location=y_mean,
         dimension='width',
         line_color='green',
         line_alpha=0.7)
p.add_layout(x)
p.add_layout(y)

bg1 = BoxAnnotation(bottom=y_mean,
                    right=x_mean,
                    fill_alpha=0.1,
                    fill_color='olive')
label1 = Label(x=0.1, y=0.8, text='少量少打折', text_font_size='10pt')
p.add_layout(bg1)
p.add_layout(label1)
Ejemplo n.º 7
0
    def __init__(self, m):
        if debug: print("Initializing new View object...")
        self.curdoc = curdoc  # reference to the current Bokeh document
        self.m = m
        self.firstrun = True

        self.subject_select = Select(title="Subjects:",
                                     value=sorted_xs[0],
                                     options=sorted_xs,
                                     width=200)
        self.model_select = Select(title="Model:",
                                   value=selected_model,
                                   options=stored_models,
                                   width=200)
        self.slice_slider_frontal = Slider(start=1,
                                           end=m.subj_bg.shape[2],
                                           value=50,
                                           step=1,
                                           title="Coronal slice",
                                           width=200)
        self.slice_slider_axial = Slider(start=1,
                                         end=m.subj_bg.shape[0],
                                         value=50,
                                         step=1,
                                         title="Axial slice",
                                         width=200)
        self.slice_slider_sagittal = Slider(start=1,
                                            end=m.subj_bg.shape[1],
                                            value=50,
                                            step=1,
                                            title="Sagittal slice",
                                            width=200)
        self.threshold_slider = Slider(start=0,
                                       end=1,
                                       value=0.4,
                                       step=0.05,
                                       title="Relevance threshold",
                                       width=200)
        self.clustersize_slider = Slider(start=0,
                                         end=250,
                                         value=50,
                                         step=10,
                                         title="Minimum cluster size",
                                         width=200)
        self.transparency_slider = Slider(start=0,
                                          end=1,
                                          value=0.3,
                                          step=0.05,
                                          title="Overlay transparency",
                                          width=200)

        # Initialize the figures:
        self.guide_frontal = figure(plot_width=208,
                                    plot_height=70,
                                    title='Relevance>threshold per slice:',
                                    toolbar_location=None,
                                    active_drag=None,
                                    active_inspect=None,
                                    active_scroll=None,
                                    active_tap=None)
        self.guide_frontal.title.text_font = 'arial'
        self.guide_frontal.title.text_font_style = 'normal'
        # guide_frontal.title.text_font_size = '10pt'
        self.guide_frontal.axis.visible = False
        self.guide_frontal.x_range.range_padding = 0
        self.guide_frontal.y_range.range_padding = 0

        self.guide_axial = figure(plot_width=208,
                                  plot_height=70,
                                  title='Relevance>threshold per slice:',
                                  toolbar_location=None,
                                  active_drag=None,
                                  active_inspect=None,
                                  active_scroll=None,
                                  active_tap=None)
        self.guide_axial.title.text_font = 'arial'
        self.guide_axial.title.text_font_style = 'normal'
        # guide_axial.title.text_font_size = '10pt'
        self.guide_axial.axis.visible = False
        self.guide_axial.x_range.range_padding = 0
        self.guide_axial.y_range.range_padding = 0

        self.guide_sagittal = figure(plot_width=208,
                                     plot_height=70,
                                     title='Relevance>threshold per slice:',
                                     toolbar_location=None,
                                     active_drag=None,
                                     active_inspect=None,
                                     active_scroll=None,
                                     active_tap=None)
        self.guide_sagittal.title.text_font = 'arial'
        self.guide_sagittal.title.text_font_style = 'normal'
        # guide_sagittal.title.text_font_size = '10pt'
        self.guide_sagittal.axis.visible = False
        self.guide_sagittal.x_range.range_padding = 0
        self.guide_sagittal.y_range.range_padding = 0

        self.clusthist = figure(plot_width=208,
                                plot_height=70,
                                title='Distribution of cluster sizes:',
                                toolbar_location=None,
                                active_drag=None,
                                active_inspect=None,
                                active_scroll=None,
                                active_tap=None)
        self.clusthist.title.text_font = 'arial'
        self.clusthist.title.text_font_style = 'normal'
        self.clusthist.axis.visible = False
        self.clusthist.x_range.range_padding = 0
        self.clusthist.y_range.range_padding = 0

        self.p_frontal = figure(
            plot_width=int(np.floor(m.subj_bg.shape[1] * scale_factor)),
            plot_height=int(np.floor(m.subj_bg.shape[0] * scale_factor)),
            title='',
            toolbar_location=None,
            active_drag=None,
            active_inspect=None,
            active_scroll=None,
            active_tap=None)
        self.p_frontal.axis.visible = False
        self.p_frontal.x_range.range_padding = 0
        self.p_frontal.y_range.range_padding = 0

        self.flip_frontal_view = Toggle(label='Flip L/R orientation',
                                        button_type='default',
                                        width=200,
                                        active=flip_left_right_in_frontal_plot)

        self.orientation_label_shown_left = Label(
            text='R' if flip_left_right_in_frontal_plot else 'L',
            render_mode='css',
            x=3,
            y=self.m.subj_bg.shape[0] - 13,
            text_align='left',
            text_color='white',
            text_font_size='20px',
            border_line_color='white',
            border_line_alpha=0,
            background_fill_color='black',
            background_fill_alpha=0,
            level='overlay',
            visible=True)
        self.orientation_label_shown_right = Label(
            text='L' if flip_left_right_in_frontal_plot else 'R',
            render_mode='css',
            x=self.m.subj_bg.shape[1] - 3,
            y=self.m.subj_bg.shape[0] - 13,
            text_align='right',
            text_color='white',
            text_font_size='20px',
            border_line_color='white',
            border_line_alpha=0,
            background_fill_color='black',
            background_fill_alpha=0,
            level='overlay',
            visible=True)

        self.p_frontal.add_layout(self.orientation_label_shown_left, 'center')
        self.p_frontal.add_layout(self.orientation_label_shown_right, 'center')

        # The vertical crosshair line on the frontal view that indicates the selected sagittal slice.
        self.frontal_crosshair_from_sagittal = Span(
            location=self.slice_slider_sagittal.value - 1,
            dimension='height',
            line_color='green',
            line_width=1,
            render_mode="css")

        # The horizontal crosshair line on the frontal view that indicates the selected axial slice.
        self.frontal_crosshair_from_axial = Span(
            location=self.slice_slider_axial.value - 1,
            dimension='width',
            line_color='green',
            line_width=1,
            render_mode="css")
        self.p_frontal.add_layout(self.frontal_crosshair_from_sagittal)
        self.p_frontal.add_layout(self.frontal_crosshair_from_axial)

        self.p_axial = figure(
            plot_width=int(np.floor(m.subj_bg.shape[1] * scale_factor)),
            plot_height=int(np.floor(m.subj_bg.shape[2] * scale_factor)),
            title='',
            toolbar_location=None,
            active_drag=None,
            active_inspect=None,
            active_scroll=None,
            active_tap=None)
        self.p_axial.axis.visible = False
        self.p_axial.x_range.range_padding = 0
        self.p_axial.y_range.range_padding = 0

        self.axial_crosshair_from_sagittal = Span(
            location=self.slice_slider_sagittal.value - 1,
            dimension='height',
            line_color='green',
            line_width=1,
            render_mode="css")
        self.axial_crosshair_from_frontal = Span(
            location=self.slice_slider_frontal.end -
            self.slice_slider_frontal.value + 1,
            dimension='width',
            line_color='green',
            line_width=1,
            render_mode="css")
        self.p_axial.add_layout(self.axial_crosshair_from_sagittal)
        self.p_axial.add_layout(self.axial_crosshair_from_frontal)

        self.p_sagittal = figure(
            plot_width=int(np.floor(m.subj_bg.shape[2] * scale_factor)),
            plot_height=int(np.floor(m.subj_bg.shape[0] * scale_factor)),
            title='',
            toolbar_location=None,
            active_drag=None,
            active_inspect=None,
            active_scroll=None,
            active_tap=None)
        self.p_sagittal.axis.visible = False
        self.p_sagittal.x_range.range_padding = 0
        self.p_sagittal.y_range.range_padding = 0

        self.sagittal_crosshair_from_frontal = Span(
            location=self.slice_slider_frontal.value - 1,
            dimension='height',
            line_color='green',
            line_width=1,
            render_mode="css")
        self.sagittal_crosshair_from_axial = Span(
            location=self.slice_slider_axial.end -
            self.slice_slider_axial.value - 1,
            dimension='width',
            line_color='green',
            line_width=1,
            render_mode="css")
        self.p_sagittal.add_layout(self.sagittal_crosshair_from_frontal)
        self.p_sagittal.add_layout(self.sagittal_crosshair_from_axial)

        self.loading_label = Label(text='Processing scan...',
                                   render_mode='css',
                                   x=self.m.subj_bg.shape[1] // 2,
                                   y=self.m.subj_bg.shape[2] // 2,
                                   text_align='center',
                                   text_color='white',
                                   text_font_size='25px',
                                   text_font_style='italic',
                                   border_line_color='white',
                                   border_line_alpha=1.0,
                                   background_fill_color='black',
                                   background_fill_alpha=0.5,
                                   level='overlay',
                                   visible=False)

        self.p_axial.add_layout(self.loading_label)

        self.render_backround()

        # create empty plot objects with empty ("fully transparent") ColumnDataSources):
        self.frontal_zeros = np.zeros_like(
            np.flipud(self.bg[:, :, self.slice_slider_frontal.value - 1]))
        self.axial_zeros = np.zeros_like(
            np.rot90(self.bg[self.m.subj_bg.shape[0] -
                             self.slice_slider_axial.value, :, :]))
        self.sagittal_zeros = np.zeros_like(
            np.flipud(
                self.
                bg[:, self.slice_slider_sagittal.end -
                   self.slice_slider_sagittal.value if self.flip_frontal_view.
                   active else self.slice_slider_sagittal.value - 1, :]))
        self.frontal_zeros[True] = 255  # value for a fully transparent pixel
        self.axial_zeros[True] = 255
        self.sagittal_zeros[True] = 255

        self.frontal_data = ColumnDataSource(data=dict(
            image=[self.frontal_zeros, self.frontal_zeros, self.frontal_zeros],
            x=[0, 0, 0],
            y=[0, 0, 0]))
        self.axial_data = ColumnDataSource(data=dict(
            image=[self.axial_zeros, self.axial_zeros, self.axial_zeros],
            x=[0, 0, 0],
            y=[0, 0, 0]))
        self.sagittal_data = ColumnDataSource(data=dict(image=[
            self.sagittal_zeros, self.sagittal_zeros, self.sagittal_zeros
        ],
                                                        x=[0, 0, 0],
                                                        y=[0, 0, 0]))

        self.p_frontal.image_rgba(image="image",
                                  x="x",
                                  y="y",
                                  dw=self.frontal_zeros.shape[1],
                                  dh=self.frontal_zeros.shape[0],
                                  source=self.frontal_data)
        self.p_axial.image_rgba(image="image",
                                x="x",
                                y="y",
                                dw=self.axial_zeros.shape[1],
                                dh=self.axial_zeros.shape[0],
                                source=self.axial_data)
        self.p_sagittal.image_rgba(image="image",
                                   x="x",
                                   y="y",
                                   dw=self.sagittal_zeros.shape[1],
                                   dh=self.sagittal_zeros.shape[0],
                                   source=self.sagittal_data)
        self.toggle_transparency = Toggle(label='Hide relevance overlay',
                                          button_type='default',
                                          width=200)
        self.toggle_regions = Toggle(label='Show outline of atlas region',
                                     button_type='default',
                                     width=200)

        self.region_ID = get_region_id(
            self.slice_slider_axial.value - 1, self.slice_slider_sagittal.end -
            self.slice_slider_sagittal.value if self.flip_frontal_view.active
            else self.slice_slider_sagittal.value - 1,
            self.slice_slider_frontal.value - 1)
        self.selected_region = get_region_name(
            self.slice_slider_axial.value - 1, self.slice_slider_sagittal.end -
            self.slice_slider_sagittal.value if self.flip_frontal_view.active
            else self.slice_slider_sagittal.value - 1,
            self.slice_slider_frontal.value - 1)
        self.region_div = Div(text="Region: " + self.selected_region,
                              sizing_mode="stretch_both",
                              css_classes=["region_divs"])

        self.cluster_size_div = Div(
            text="Cluster Size: " + "0", css_classes=[
                "cluster_divs"
            ])  # initialize with 0 because clust_labelimg does not exist yet
        self.cluster_mean_div = Div(text="Mean Intensity: " + "0",
                                    css_classes=["cluster_divs"])
        self.cluster_peak_div = Div(text="Peak Intensity: " + "0",
                                    css_classes=["cluster_divs"])

        # see InteractiveVis/static/ for default formatting/style definitions
        self.age_spinner = Spinner(
            title="Age:",
            placeholder="years",
            mode="int",
            low=55,
            high=99,
            width=int(np.floor(m.subj_bg.shape[1] * scale_factor) // 2 - 10),
            disabled=True)  #no subject selected at time of initialization
        self.sex_select = Select(
            title="Sex:",
            value="N/A",
            options=["male", "female", "N/A"],
            width=int(np.floor(m.subj_bg.shape[1] * scale_factor) // 2 - 10),
            disabled=True)
        self.tiv_spinner = Spinner(
            title="TIV:",
            placeholder="cm³",
            mode="float",
            low=1000,
            high=2100,
            width=int(np.floor(m.subj_bg.shape[1] * scale_factor) // 2 - 10),
            disabled=True)
        self.field_strength_select = Select(
            title="Field Strength [T]:",
            value="1.5",
            options=["1.5", "3.0"],
            width=int(np.floor(m.subj_bg.shape[1] * scale_factor) // 2 - 10),
            disabled=True)

        # Empty dummy figure to add ColorBar to, because annotations (like a ColorBar) must have a
        # parent figure in Bokeh:
        self.p_color_bar = figure(
            plot_width=100,
            plot_height=int(np.floor(m.subj_bg.shape[0] * scale_factor)),
            title='',
            toolbar_location=None,
            active_drag=None,
            active_inspect=None,
            active_scroll=None,
            active_tap=None,
            outline_line_alpha=0.0)
        self.p_color_bar.axis.visible = False
        self.p_color_bar.x_range.range_padding = 0
        self.p_color_bar.y_range.range_padding = 0

        self.color_mapper = LinearColorMapper(palette=color_palette,
                                              low=-1,
                                              high=1)
        self.color_bar = ColorBar(color_mapper=self.color_mapper,
                                  title="Relevance")
        self.p_color_bar.add_layout(self.color_bar)
        self.scan_upload = FileInput(accept='.nii.gz, .nii')
        self.residualize_button = Button(
            label="Start residualization and view scan", disabled=True)

        def dummy():
            pass

        self.residualize_button.on_click(
            dummy
        )  # TODO: remove this once on_click is working when setting callback only from the model class (bug in Bokeh 2.2.x ?)

        # Initialize column layout:
        self.layout = row(
            column(
                self.subject_select, self.model_select,
                Spacer(height=40, width=200, sizing_mode='scale_width'),
                self.threshold_slider, self.clusthist, self.clustersize_slider,
                self.transparency_slider, self.toggle_transparency,
                self.toggle_regions, self.region_div,
                column(self.cluster_size_div, self.cluster_mean_div,
                       self.cluster_peak_div)),
            column(
                row(self.age_spinner,
                    self.sex_select,
                    self.tiv_spinner,
                    self.field_strength_select,
                    self.scan_upload,
                    css_classes=["subject_divs"]),
                row(self.residualize_button),
                row(
                    column(self.p_frontal, self.slice_slider_frontal,
                           self.guide_frontal, self.flip_frontal_view),
                    column(self.p_axial, self.slice_slider_axial,
                           self.guide_axial),
                    column(self.p_sagittal, self.slice_slider_sagittal,
                           self.guide_sagittal), column(self.p_color_bar))))

        self.clust_hist_bins = list(range(
            0, 250 + 1,
            10))  # list from (0, 10, .., 250); range max is slider_max_size+1
Ejemplo n.º 8
0
p4.circle(x='pre',
          y='zkl',
          source=source4,
          size='size',
          fill_color='red',
          line_color='black',
          fill_alpha=0.6,
          line_dash='dotted')

p4.xgrid.grid_line_dash = [6, 4]
p4.ygrid.grid_line_dash = [6, 4]

# 绘制辅助线
x = Span(location=x_mean,
         dimension='height',
         line_color='red',
         line_alpha=0.8,
         line_width=3)
y = Span(location=y_mean,
         dimension='width',
         line_color='red',
         line_alpha=0.8,
         line_width=3)
p4.add_layout(x)
p4.add_layout(y)

#第一象限
bg1 = BoxAnnotation(bottom=y_mean,
                    left=x_mean,
                    fill_alpha=0.1,
                    fill_color='olive')
Ejemplo n.º 9
0
            plot_height=800,
            title="双11美妆产品品牌套路",
            tools=[hover, 'box_select,reset,wheel_zoom,pan,crosshair'])
p4.circle_x(x='off_all',
            y='zkl',
            size='size',
            source=source,
            color='red',
            alpha=0.7,
            line_color='black',
            line_dash=[8, 4],
            line_width=2)

x = Span(location=x_mean,
         dimension='height',
         line_color='green',
         line_alpha=0.7,
         line_width=1.5,
         line_dash=[6, 4])
y = Span(location=y_mean,
         dimension='width',
         line_color='green',
         line_alpha=0.7,
         line_width=1.5,
         line_dash=[6, 4])
p4.add_layout(x)
p4.add_layout(y)
# 绘制辅助线

bg1 = BoxAnnotation(bottom=y_mean,
                    right=x_mean,
                    fill_alpha=0.1,
f.xaxis.axis_label = "Atomic radius"
f.yaxis.axis_label = "Boiling point"

#Calculate the average boiling point for all three groups by dividing the sum by the number of values
gas_average_boil = sum(solid.data['boiling point']) / len(
    solid.data['boiling point'])
liquid_average_boil = sum(liquid.data['boiling point']) / len(
    liquid.data['boiling point'])
solid_average_boil = sum(solid.data['boiling point']) / len(
    solid.data['boiling point'])
solid_min_boil = min(solid.data['boiling point'])
solid_max_boil = max(solid.data['boiling point'])

#Create three spans
span_gas_average_boil = Span(location=gas_average_boil,
                             dimension='width',
                             line_color='green',
                             line_width=2)
span_liquid_average_boil = Span(location=liquid_average_boil,
                                dimension='width',
                                line_color='blue',
                                line_width=2)
span_solid_boil = Span(
    location=solid_average_boil,
    dimension='width',
    line_color='red',
    line_width=2
)  #Location for this span will be updated when the Select widget is changed by the user

#Add spans to the figure
f.add_layout(span_gas_average_boil)
f.add_layout(span_liquid_average_boil)
p.ygrid.grid_line_alpha = 0.8
p.ygrid.grid_line_dash = "dashed"
p.xgrid.grid_line_alpha = 0.8
p.xgrid.grid_line_dash = "dashed"

# 添加辅助线
from bokeh.models.annotations import Span
# 辅助线1: 平均折扣率
mean_discount = df["discount"].mean()
# 辅助线2:平均打折商品占比
mean_disper = df["dis_per"].mean()

# 横向的:平均折扣率
width = Span(
    location=mean_discount,  # 设置位置,对应坐标值
    dimension='width',  # 设置方向,width为横向,height为纵向  
    line_color='olive',
    line_width=3,  # 设置线颜色、线宽
    line_dash="dashed")
p.add_layout(width)

# 纵向的:平均打折占比
height = Span(
    location=mean_disper,  # 设置位置,对应坐标值
    dimension='height',  # 设置方向,width为横向,height为纵向  
    line_color='olive',
    line_width=3,  # 设置线颜色、线宽
    line_dash="dashed")
p.add_layout(height)

# 辅助矩形
from bokeh.models.annotations import BoxAnnotation
Ejemplo n.º 12
0
from bokeh.io import output_notebook
output_notebook() # 导入notebook绘图模块

''' 辅助标注 - 线 '''
from bokeh.models.annotations import Span # 导入Span模块画辅助线

# 创建数据并绘图
x = np.linspace(0, 20, 200)
y = np.sin(x) 
p = figure(y_range=(-2, 2))
p.line(x, y)

# 绘制辅助线1
upper = Span(location=1,           # 设置位置,对应坐标值
             dimension='width',    # 设置方向,width为横向,height为纵向  
             line_color='olive',   # 设置线颜色
             line_width=4          # 设置线宽
            )
p.add_layout(upper) # 在图中增加辅助线

# 绘制辅助线2
lower = Span(location=-1, dimension='width', line_color='firebrick', line_width=4)
p.add_layout(lower)

# 显示
show(p)


''' 辅助标注 - 矩形 '''
from bokeh.models.annotations import BoxAnnotation # 导入BoxAnnotation模块
Ejemplo n.º 13
0
    def exercise_8_creating_span_annotations_depicting_averages(self):
        # start Bokeh server by: bokeh serve server.py
        # Remove rows with NaN values and then map standard states to colors
        elements.dropna(
            inplace=True
        )  # if inplace is not set to True the changes are not written to the dataframe
        colormap = {'gas': 'yellow', 'liquid': 'orange', 'solid': 'red'}
        elements['color'] = [colormap[x] for x in elements['standard state']]
        elements[
            'van der Waals radius'] = elements['van der Waals radius'] / 10

        # Create three ColumnDataSources for elements of unique standard states
        gas = ColumnDataSource(elements[elements['standard state'] == 'gas'])
        liquid = ColumnDataSource(
            elements[elements['standard state'] == 'liquid'])
        solid = ColumnDataSource(
            elements[elements['standard state'] == 'solid'])

        # Create the figure object
        f = figure()

        # adding glyphs
        size_list = [i / 10 for i in gas.data["van der Waals radius"]]
        f.circle(x="atomic radius",
                 y="boiling point",
                 size="van der Waals radius",
                 fill_alpha=0.2,
                 color="color",
                 legend='Gas',
                 source=gas)

        f.circle(x="atomic radius",
                 y="boiling point",
                 size="van der Waals radius",
                 fill_alpha=0.2,
                 color="color",
                 legend='Liquid',
                 source=liquid)

        f.circle(x="atomic radius",
                 y="boiling point",
                 size="van der Waals radius",
                 fill_alpha=0.2,
                 color="color",
                 legend='Solid',
                 source=solid)

        # Add axis labels
        f.xaxis.axis_label = "Atomic radius"
        f.yaxis.axis_label = "Boiling point"

        # Calculate the average boiling point for all three groups by dividing the sum by the number of values
        gas_average_boil = sum(solid.data['boiling point']) / len(
            solid.data['boiling point'])
        liquid_average_boil = sum(liquid.data['boiling point']) / len(
            liquid.data['boiling point'])
        solid_average_boil = sum(solid.data['boiling point']) / len(
            solid.data['boiling point'])
        solid_min_boil = min(solid.data['boiling point'])
        solid_max_boil = max(solid.data['boiling point'])

        # Create three spans
        span_gas_average_boil = Span(location=gas_average_boil,
                                     dimension='width',
                                     line_color='yellow',
                                     line_width=2)
        span_liquid_average_boil = Span(location=liquid_average_boil,
                                        dimension='width',
                                        line_color='orange',
                                        line_width=2)
        span_solid_boil = Span(
            location=solid_average_boil,
            dimension='width',
            line_color='red',
            line_width=2
        )  # Location for this span will be updated when the Select widget is changed by the user

        # Add spans to the figure
        f.add_layout(span_gas_average_boil)
        f.add_layout(span_liquid_average_boil)
        f.add_layout(span_solid_boil)

        # Create a function that updates the location attribute value for span_solid_boil span
        # Also note that select.value returns values as strings so we need to convert the returned value to float
        def update_span(attr, old, new):
            span_solid_boil.location = float(select.value)

        # Select widgets expect a list of tuples of strings, so List[Tuple(String, String)], that's why you should convert average, max, and min to strings
        options = [(str(solid_average_boil), "Solid Average Boiling Point"),
                   (str(solid_min_boil), "Solid Minimum Boiling Point"),
                   (str(solid_max_boil), "Solid Maximum Boiling Point")]

        # Create the Select widget
        select = Select(title="Select span value", options=options)
        select.on_change("value", update_span)

        # Add Select widget to layout and then the layout to curdoc
        lay_out = layout([[select]])
        curdoc().add_root(f)
        curdoc().add_root(lay_out)
Ejemplo n.º 14
0
#Add axis labels
f.xaxis.axis_label = "Atomic radius"
f.yaxis.axis_label = "Boiling point"

#Calculate the average boiling point for all three groups by dividing the sum by the number of values
gas_average_boil = sum(gas.data['boiling point']) / len(
    gas.data['boiling point'])
liquid_average_boil = sum(liquid.data['boiling point']) / len(
    liquid.data['boiling point'])
solid_average_boil = sum(solid.data['boiling point']) / len(
    solid.data['boiling point'])

#Create three spans
span_gas_average_boil = Span(location=gas_average_boil,
                             dimension='width',
                             line_color='green',
                             line_width=2)
span_liquid_average_boil = Span(location=liquid_average_boil,
                                dimension='width',
                                line_color='blue',
                                line_width=2)
span_solid_average_boil = Span(location=solid_average_boil,
                               dimension='width',
                               line_color='red',
                               line_width=2)

#Add spans to the figure
f.add_layout(span_gas_average_boil)
f.add_layout(span_liquid_average_boil)
f.add_layout(span_solid_average_boil)
Ejemplo n.º 15
0
def make_graphs(data, countries, file_name):
    """
    # TODO write documentation
    :param data:
    :param countries:
    :param file_name:
    :return:
    """

    # BOKEH ----------------------------

    # output to static HTML file
    output_file(file_name)

    colours = Category10[max(len(countries), 3)]  # Category10 does not work with an input of <3
    if len(countries) > len(colours):
        raise ValueError(f"The maximum number of countries which can be plotted is {len(colours)}")

    # 1. Create the figures

    # Graph 1 - Active cases
    hover1 = HoverTool(tooltips=[('country', '$name'), ('date', '$x{%F}'), ('cases', '$y{0,0}k')],
                       formatters={'$x': 'datetime'})
    p1 = figure(width=1200, height=300, title="Active cases", tools=[hover1], x_axis_type="datetime",
                x_axis_label='date', y_axis_label="thousands of cases")
    p1.xaxis.formatter.months = '%b-%y'
    p1.y_range.start = 0

    # Graph 2 - Cases in previous week per 100k people
    hover2 = HoverTool(tooltips=[('country', '$name'), ('date', '$x{%F}'), ('cases', '$y{0,0}')],
                       formatters={'$x': 'datetime'})
    p2 = figure(width=600, height=300, title="Cases in previous week per 100k people", tools=[hover2],
                x_axis_type="datetime", x_axis_label='date', y_axis_label='cases')
    p2.xaxis.formatter.days = '%d-%b'
    p2.y_range.start = 0

    # Graph 3 - R-Number
    hover3 = HoverTool(tooltips=[('country', '$name'), ('date', '$x{%F}'), ('r-number', '$y')],
                       formatters={'$x': 'datetime'})
    p3 = figure(width=600, height=300, title="R-Number", tools=[hover3], x_axis_type="datetime", x_axis_label='date',
                y_axis_label='r-number')
    p3.xaxis.formatter.days = '%d-%b'

    # Graph 4 - Deaths in previous week per 100k people
    hover4 = HoverTool(tooltips=[('country', '$name'), ('date', '$x{%F}'), ('deaths', '$y{0.0}')],
                       formatters={'$x': 'datetime'})
    p4 = figure(width=600, height=300, title="Deaths in previous week per 100k people", tools=[hover4],
                x_axis_type="datetime", x_axis_label='date', y_axis_label='deaths')
    p4.xaxis.formatter.days = '%d-%b'
    p4.y_range.start = 0

    # Graph 5 - Total vaccinations per 100 people
    hover5 = HoverTool(tooltips=[('country', '$name'), ('date', '$x{%F}'), ('vaccinations', '$y{0,0}')],
                       formatters={'$x': 'datetime'})
    p5 = figure(width=600, height=300, title="Total vaccinations per 100 people", tools=[hover5],
                x_axis_type="datetime", x_axis_label='date', y_axis_label='vaccinations')
    p5.xaxis.formatter.days = '%d-%b'
    p5.y_range.start = 0

    # Create lists to contain country specific graphs for number of cases per day and number of deaths per day
    cases = []
    deaths = []

    # 2. Create glyphs

    for i, country in enumerate(countries):
        my_country = Country(data, country)

        # Plot graphs 1 - 4
        s1 = my_country.active_cases / 1000
        p1.line(s1.index, s1.values, name=country, legend_label=country, line_width=2, line_color=colours[i])

        s2 = my_country.cases_by_population[-60:]
        p2.line(s2.index, s2.values, name=country, legend_label=country, line_width=2, line_color=colours[i])
        
        s3 = my_country.r_number(4, 7)[-60:]
        p3.line(s3.index, s3.values, name=country, legend_label=country, line_width=2, line_color=colours[i])

        s4 = my_country.deaths_by_population[-60:]
        p4.line(s4.index, s4.values, name=country, legend_label=country, line_width=2, line_color=colours[i])

        # s5 = my_country.total_vaccinations_per_hundred()[-60:]
        s5 = my_country.vaccinations[-60:]
        p5.line(s5.index, s5.values, name=country, legend_label=country, line_width=2, line_color=colours[i])

        # Graph 6 - Cases
        p6 = figure(width=600, height=200, title=f'{country} - Cases per Day', x_axis_type="datetime",
                    x_axis_label='date', y_axis_label='cases')
        p6.vbar(my_country.date, top=my_country.cases, color=colours[i])
        p6.xaxis.formatter.months = '%b-%y'

        # Graph 7 - Deaths
        p7 = figure(width=600, height=200, title=f'{country} - Deaths per Day', x_axis_type="datetime",
                    x_axis_label='date', y_axis_label='deaths')
        p7.vbar(my_country.date, top=my_country.deaths, color=colours[i])
        p7.xaxis.formatter.months = '%b-%y'

        cases.append(p6)
        deaths.append(p7)

    for p in [p1, p2, p3, p4, p5]:
        p.legend.location = 'top_left'

    r_one = Span(location=1, dimension='width', line_color='maroon', line_width=2)
    p3.add_layout(r_one)

    # 3. Show the results
    show(layout([
        [p1],
        [p2, p3],
        [p4, p5],
        [cases, deaths]
    ]))
Ejemplo n.º 16
0
    def _plot_features_importance(feature_importances, plot_n, threshold, figsize):

        f1 = figure(tools="box_select, pan, reset, save")
        f1.plot_width = figsize[0]
        f1.plot_height = figsize[1]

        # Background settings
        f1.background_fill_color = '#859dcd'
        f1.background_fill_alpha = 0.05

        # Title settings
        f1.title.text = 'Feature Importances'
        f1.title.text_font = 'Helvetica'
        f1.title.text_font_size = '24px'
        f1.title.align = 'center'
        f1.title.text_font_style = "italic"

        # Axis settings
        f1.xaxis.axis_label = 'Normalized Importance'
        f1.yaxis.axis_label = 'First %d Features' % plot_n
        f1.ygrid.grid_line_color = None
        f1.yaxis.ticker = feature_importances.index[:plot_n].values
        f1.axis.axis_label_text_font_size = '18px'

        source = ColumnDataSource(data=feature_importances[:plot_n][::-1])
        source.add(feature_importances[:plot_n].index, 'index')
        source.add([0.001] * plot_n, 'x_label')

        labels = LabelSet(x='x_label', y='index', text='feature',
                          x_offset=0, y_offset=-8, text_font_size='14px', text_color='black',
                          level='glyph', source=source, render_mode='canvas')

        # Need to reverse the index to plot most important on top
        f1.hbar(right='normalized_importance', y='index', source=source,
                color='#3399c1', alpha=0.7, height=0.9)

        f1.add_layout(labels)

        hover = HoverTool(tooltips=[('Importance', '@importance{0.0000}')])
        f1.add_tools(hover)

        tab1 = Panel(child=f1, title='Features Importance')

        # Cumulative importance plot
        f2 = figure(tools="box_select, box_zoom, pan, reset, save")
        f2.plot_width = figsize[0]
        f2.plot_height = figsize[1]

        # Background settings
        f2.background_fill_color = '#859dcd'
        f2.background_fill_alpha = 0.05

        # Title settings
        f2.title.text = 'Cumulative Feature Importance'
        f2.title.text_font = 'Helvetica'
        f2.title.text_font_size = '24px'
        f2.title.align = 'center'
        f2.title.text_font_style = "italic"

        # Axis settings
        f2.xaxis.axis_label = 'Number of Features'
        f2.yaxis.axis_label = 'Cumulative Importance'
        f2.xgrid.grid_line_color = None
        f2.axis.axis_label_text_font_size = '18px'

        source = ColumnDataSource(data=feature_importances)
        source.add(list(range(1, len(feature_importances) + 1)), 'index')

        f2.line(x='index', y='cumulative_importance', source=source,
                color='#3399c1')

        if threshold:
            # Index of minimum number of features needed for cumulative importance threshold
            # np.where returns the index so need to add 1 to have correct number
            importance_index = np.min(np.where(feature_importances['cumulative_importance'] > threshold))
            span = Span(location=importance_index,
                        dimension='height', line_color='red',
                        line_dash='dashed', line_width=2)
            f2.add_layout(span)
            # threshold_source = ColumnDataSource(data={'importance_index': [importance_index + 1] * 2,
            #                                           'importance_value': [0, 1]})

            # f2.line(x='importance_index', y='importance_value', source=threshold_source,
            #         line_dash=[4, 2], line_color='red')

        hover = HoverTool(tooltips=[('Feature', '@feature'),
                                    ('Feature Importance', '@importance{0.0000}'),
                                    ('Cumulative Importance', '@cumulative_importance')],
                          mode='hline')
        f2.add_tools(hover)

        tab2 = Panel(child=f2, title='Cumulative Importance')
        tabs = Tabs(tabs=[tab1, tab2])

        show(tabs)

        print('%d features required for %0.2f of cumulative importance' % (importance_index + 1, threshold))
Ejemplo n.º 17
0
    def ex_7_create_label_annotations_for_span(self):
        # Remove rows with NaN values and then map standard states to colors
        elements.dropna(
            inplace=True
        )  # if inplace is not set to True the changes are not written to the dataframe
        colormap = {'gas': 'yellow', 'liquid': 'orange', 'solid': 'red'}
        elements['color'] = [colormap[x] for x in elements['standard state']]
        elements['size'] = elements['van der Waals radius'] / 10

        # Create three ColumnDataSources for elements of unique standard states
        gas = ColumnDataSource(elements[elements['standard state'] == 'gas'])
        liquid = ColumnDataSource(
            elements[elements['standard state'] == 'liquid'])
        solid = ColumnDataSource(
            elements[elements['standard state'] == 'solid'])

        # Define the output file path
        output_file("elements_annotations.html")

        # Create the figure object
        f = figure()

        # adding glyphs
        f.circle(x="atomic radius",
                 y="boiling point",
                 size='size',
                 fill_alpha=0.2,
                 color="color",
                 legend='Gas',
                 source=gas)
        f.circle(x="atomic radius",
                 y="boiling point",
                 size='size',
                 fill_alpha=0.2,
                 color="color",
                 legend='Liquid',
                 source=liquid)
        f.circle(x="atomic radius",
                 y="boiling point",
                 size='size',
                 fill_alpha=0.2,
                 color="color",
                 legend='Solid',
                 source=solid)

        # Add axis labels
        f.xaxis.axis_label = "Atomic radius"
        f.yaxis.axis_label = "Boiling point"

        # Calculate the average boiling point for all three groups by dividing the sum by the number of values
        gas_average_boil = sum(gas.data['boiling point']) / len(
            gas.data['boiling point'])
        liquid_average_boil = sum(liquid.data['boiling point']) / len(
            liquid.data['boiling point'])
        solid_average_boil = sum(solid.data['boiling point']) / len(
            solid.data['boiling point'])

        # Create three spans
        span_gas_average_boil = Span(location=gas_average_boil,
                                     dimension='width',
                                     line_color='yellow',
                                     line_width=2)
        span_liquid_average_boil = Span(location=liquid_average_boil,
                                        dimension='width',
                                        line_color='orange',
                                        line_width=2)
        span_solid_average_boil = Span(location=solid_average_boil,
                                       dimension='width',
                                       line_color='red',
                                       line_width=2)

        # Add spans to the figure
        f.add_layout(span_gas_average_boil)
        f.add_layout(span_liquid_average_boil)
        f.add_layout(span_solid_average_boil)

        # Add labels to spans
        label_span_gas_average_boil = Label(x=80,
                                            y=gas_average_boil,
                                            text="Gas average boiling point",
                                            render_mode="css",
                                            text_font_size="10px")
        label_span_liquid_average_boil = Label(
            x=80,
            y=liquid_average_boil,
            text="Liquid average boiling point",
            render_mode="css",
            text_font_size="10px")
        label_span_solid_average_boil = Label(
            x=80,
            y=solid_average_boil,
            text="Solid average boiling point",
            render_mode="css",
            text_font_size="10px")

        # Add labels to figure
        f.add_layout(label_span_gas_average_boil)
        f.add_layout(label_span_liquid_average_boil)
        f.add_layout(label_span_solid_average_boil)

        # Save and show the figure
        show(f)
Ejemplo n.º 18
0
def create_graph(results, config):
    # Bokeh描画用データ
    df = pd.DataFrame(results,
                      columns=[
                          'id', 'date', 'temperature', 'q1', 'q2', 'q3', 'q4',
                          'q5', 'q6', 'Y/N', 'exist'
                      ])
    source = ColumnDataSource(df)

    # 描画レイアウト
    p = figure(
        title=f"体温変化",
        plot_width=750,
        plot_height=400,
        x_axis_type="datetime",
        x_range=(df['date'][0], df['date'][df['date'].size - 1]),
        y_range=(35.0, 39.0),
        x_axis_label="日付",
        y_axis_label="体温",
        #https://docs.bokeh.org/en/latest/docs/user_guide/tools.html#configuring-plot-tools
        tools=
        "save, reset"  #xpan, xwheel_pan, xwheel_zoom : ypan, ywheel_pan, ywheel_zoom
    )

    # X軸の設定
    x_format = "%Y/%m/%d"
    formatter = DatetimeTickFormatter(seconds=[x_format],
                                      minutes=[x_format],
                                      hours=[x_format],
                                      days=[x_format],
                                      months=[x_format],
                                      years=[x_format])
    p.xaxis.formatter = formatter
    p.xaxis.major_label_orientation = pi / 4

    if config[0]:
        #基準体温
        nowspan = Span(location=config[1],
                       dimension="width",
                       line_color="#e49e61",
                       line_width=1)
        p.add_layout(nowspan)
        nowlabel = Label(x=p.x_range.start,
                         y=config[1],
                         text=f"基準体温",
                         text_color="#000000",
                         background_fill_color="#e49e61",
                         render_mode="css",
                         text_font_size="10px")
        p.add_layout(nowlabel)

    # メインチャート
    line = p.line('date', 'temperature', source=source, line_width=2)
    p.circle('date', 'temperature', source=source, line_width=5)

    # 吹き出し
    hover = HoverTool(tooltips=[("日付", "@date{" + x_format + "}"),
                                ("体温", "@temperature{00.0}")],
                      formatters={"@date": "datetime"},
                      mode="vline",
                      renderers=[line])
    #hover.renderers.append(line)
    p.add_tools(hover)

    # マウスの位置に縦棒を表示
    cross_hair = CrosshairTool(dimensions="height", line_alpha=0.2)
    p.add_tools(cross_hair)

    # FlaskでHTML上に表示するためにBokehのライブラリで生成されたJavaScriptとdiv要素を返す
    return components(p)
Ejemplo n.º 19
0
# Add axis labels
f.xaxis.axis_label = "Atomic Radius"
f.yaxis.axis_label = "Boiling Point"

# Define average boiling temperature for gas, liquid, and solid
gas_average = sum(gas.data['boiling point']) / len(gas.data['boiling point'])
liquid_average = sum(liquid.data['boiling point']) / len(
    liquid.data['boiling point'])
solid_average = sum(solid.data['boiling point']) / len(
    solid.data['boiling point'])
solid_min = min(solid.data['boiling point'])
solid_max = max(solid.data['boiling point'])

# Add boiling average as a span
gas_span = Span(location=gas_average,
                dimension='width',
                line_color='yellow',
                line_width=2)

liquid_span = Span(location=liquid_average,
                   dimension='width',
                   line_color='orange',
                   line_width=2)

solid_span = Span(location=solid_average,
                  dimension='width',
                  line_color='red',
                  line_width=2)

f.add_layout(gas_span)
f.add_layout(liquid_span)
f.add_layout(solid_span)
Ejemplo n.º 20
0
                      value=10,
                      step=1,
                      title="strike_price")
x = np.linspace(0, max_x, 500)
y = np.max([np.zeros(x.shape), x - strike_price.value],
           axis=0) - call_premium.value

source = ColumnDataSource(data=dict(x=x, y=y))
plot = figure(x_range=(0, max_x),
              y_range=(-30, max_x),
              plot_width=400,
              plot_height=400)

zero = Span(location=0,
            dimension='width',
            line_color='firebrick',
            line_dash='dashed',
            line_alpha=0.7,
            line_width=1)
plot.add_layout(zero)

plot.line('x',
          'y',
          source=source,
          line_width=3,
          line_alpha=0.6,
          color='cadetblue')

callback = CustomJS(args=dict(source=source,
                              call_premium=call_premium,
                              strike=strike_price),
                    code="""
Ejemplo n.º 21
0
# Add axis labels
f.xaxis.axis_label = "Atomic radius"
f.yaxis.axis_label = "Boiling point"

# Calculate the average boiling point for all three groups by dividing the sum by the number of values
gas_average_boil = sum(gas.data['boiling point']) / len(
    gas.data['boiling point'])
liquid_average_boil = sum(liquid.data['boiling point']) / len(
    liquid.data['boiling point'])
solid_average_boil = sum(solid.data['boiling point']) / len(
    solid.data['boiling point'])

# Create three spans
span_gas_average_boil = Span(location=gas_average_boil,
                             dimension='width',
                             line_color='yellow',
                             line_width=2)
span_liquid_average_boil = Span(location=liquid_average_boil,
                                dimension='width',
                                line_color='orange',
                                line_width=2)
span_solid_average_boil = Span(location=solid_average_boil,
                               dimension='width',
                               line_color='red',
                               line_width=2)

# Add spans to the figure
f.add_layout(span_gas_average_boil)
f.add_layout(span_liquid_average_boil)
f.add_layout(span_solid_average_boil)
Ejemplo n.º 22
0
def plot_instance(
    sols: pd.DataFrame,
    stats: pd.DataFrame,
    model: str,
    data: str = "",
    palette: Palette = Spectral5,
) -> Figure:
    """Plots objective data for an optimisation problem instance, and run time
       data for a satisfaction problem instance.

    Args:
        sols (pd.DataFrame): The solution data frame
        stats (pd.DataFrame): The statistics data frame
        model (str): The model file path or problem name of the instance
        data (str, optional): The data file path or name. Defaults to "".
        palette (Palette, optional): The colour palette to use. Defaults to Spectral5.

    Returns:
        Figure: The plotting figure
    """
    df_stats = stats[(stats.model.eq(model) | stats.problem.eq(model))
                     & stats.data_file.eq(data)]
    df_sols = sols[(sols.model.eq(model) | sols.problem.eq(model))
                   & sols.data_file.eq(data)]
    if df_stats.data_file.nunique() != 1:
        print(stats[stats.model.eq(model)])
        raise ValueError("Could not determine unique instance for plotting.")

    instance = "{} ({})".format(
        df_stats.problem.iloc[0],
        df_stats.model.iloc[0]
        if df_stats.data_file.iloc[0] == "" else df_stats.data_file.iloc[0],
    )

    if df_stats.method.eq("satisfy").any() or df_sols.empty:
        # Plot run time graph
        if df_stats.configuration.nunique() == 1:
            # Group by run only
            y = df_stats.run.unique()
            by = ["run"]
        elif df_stats.run.nunique() == 1:
            # Group by configuration only
            y = df_stats.configuration.unique()
            by = ["configuration"]
        else:
            # Group by both
            y = [(c, r) for c in df_stats.configuration.unique()
                 for r in df_stats.run.unique()]
            by = ["configuration", "run"]

        tooltips = [
            ("configuration", "@" + "_".join(by)),
            ("flatTime", "@flatTime"),
            ("solveTime", "@solveTime"),
            ("time", "@time"),
            ("status", "@status"),
        ]
        source = ColumnDataSource(df_stats.groupby(by=by).first())
        p = figure(
            y_range=FactorRange(*y),
            title="Run time for {}".format(instance),
            tooltips=tooltips,
        )
        p.hbar(
            y="_".join(by),
            left="flatTime",
            right="time",
            height=0.5,
            fill_color=factor_cmap(
                "_".join(by),
                palette=palette,
                factors=df_stats[by[-1]].unique(),
                start=len(by) - 1,
            ),
            line_color=None,
            source=source,
        )
        p.x_range.start = 0
        p.xaxis.axis_label = "Time (s)"
        p.yaxis.axis_label = "Configuration"
        return p
    else:
        # Plot objective graph
        source = ColumnDataSource(df_sols)
        tooltips = [
            ("configuration", "@configuration"),
            ("run", "@run"),
            ("time", "@time"),
            ("objective", "@objective"),
        ]

        p = figure(title="Objective value for {}".format(instance))
        colors = cycle(palette)
        for configuration in df_stats.configuration.unique():
            color = next(colors)
            dashes = cycle([[], [6], [2, 4], [2, 4, 6, 4], [6, 4, 2, 4]])
            for run, line_dash in zip(df_stats.run.unique(), dashes):
                view = CDSView(
                    source=source,
                    filters=[
                        GroupFilter(column_name="configuration",
                                    group=configuration),
                        GroupFilter(column_name="run", group=run),
                    ],
                )
                glyph = p.circle(
                    x="time",
                    y="objective",
                    color=color,
                    legend_label=", ".join([configuration, run]),
                    source=source,
                    view=view,
                )
                p.add_tools(HoverTool(renderers=[glyph], tooltips=tooltips))
                p.step(
                    x="time",
                    y="objective",
                    mode="after",
                    color=color,
                    line_dash=line_dash,
                    legend_label=", ".join([configuration, run]),
                    source=source,
                    view=view,
                )

                # Add markers for flatTime and time stats
                y_pos = df_sols.objective.median()
                if math.isnan(y_pos):
                    y_pos = 0
                stats = df_stats[df_stats.configuration.eq(configuration)
                                 & df_stats.run.eq(run)].iloc[0]
                start = Span(
                    location=stats.flatTime,
                    dimension="height",
                    line_alpha=0.5,
                    line_color=color,
                    line_dash=line_dash,
                )
                p.add_layout(start)
                end = Span(
                    location=stats.time,
                    dimension="height",
                    line_alpha=0.5,
                    line_color=color,
                    line_dash=line_dash,
                )
                p.add_layout(end)
                glyph = p.circle([stats.flatTime], [y_pos],
                                 fill_alpha=0,
                                 line_alpha=0)
                p.add_tools(
                    HoverTool(
                        renderers=[glyph],
                        tooltips=[
                            ("configuration", configuration),
                            ("run", run),
                            ("flatTime", str(stats.flatTime)),
                        ],
                        mode="vline",
                        point_policy="follow_mouse",
                    ))
                glyph = p.circle([stats.time], [y_pos],
                                 fill_alpha=0,
                                 line_alpha=0)
                end_tooltips = [
                    ("configuration", configuration),
                    ("run", run),
                    ("time", str(stats.time)),
                    ("status", str(stats.status)),
                ]
                if stats.status in ["SATISFIED", "OPTIMAL_SOLUTION"]:
                    end_tooltips.append(["objective", str(stats.objective)])
                p.add_tools(
                    HoverTool(
                        renderers=[glyph],
                        tooltips=end_tooltips,
                        mode="vline",
                        point_policy="follow_mouse",
                    ))
        p.x_range.start = 0
        p.x_range.end = df_stats.time.max()
        p.xaxis.axis_label = "Time (s)"
        p.yaxis.axis_label = "Objective"
        p.legend.click_policy = "hide"
        return p
def test_Span_accepts_datetime_location():
    obj = Span(location=datetime(2018, 8, 7, 0, 0))
    assert obj.location == 1533600000000.0
Ejemplo n.º 24
0
def _cycle_info_plot_bokeh(
    cell,
    cycle=None,
    step=None,
    title=None,
    points=False,
    x=None,
    y=None,
    info_level=0,
    h_cycle=None,
    h_step=None,
    show_it=False,
    label_cycles=True,
    label_steps=False,
    **kwargs,
):
    """Plot raw data with annotations.

    This function uses Bokeh for plotting and is intended for use in
    Jupyter Notebooks.
    """
    # TODO: check that correct new column-names are used
    # TODO: fix bokeh import
    from bokeh.io import output_notebook, show
    from bokeh.layouts import row, column
    from bokeh.models import ColumnDataSource, LabelSet
    from bokeh.models import HoverTool
    from bokeh.models.annotations import Span
    from bokeh.models.widgets import Slider, TextInput
    from bokeh.plotting import figure

    output_notebook(hide_banner=True)

    if points:
        if cycle is None or (len(cycle) > 1):
            print(
                "Plotting points only allowed when plotting one single cycle.")
            print("Turning points off.")
            points = False

    if h_cycle is None:
        h_cycle = "cycle_index"  # edit
    if h_step is None:
        h_step = "step_index"  # edit

    if x is None:
        x = "test_time"  # edit
    if y is None:
        y = "voltage"  # edit

    if isinstance(x, tuple):
        x, x_label = x
    else:
        x_label = x

    if isinstance(y, tuple):
        y, y_label = y
    else:
        y_label = y

    t_x = x  # used in generating title - replace with a selector
    t_y = y  # used in generating title - replace with a selector

    if title is None:
        title = f"{t_y} vs. {t_x}"

    cols = [x, y]
    cols.extend([h_cycle, h_step])

    df = cell.cell.raw.loc[:, cols]

    if cycle is not None:
        if not isinstance(cycle, (list, tuple)):
            cycle = [cycle]

        _df = df.loc[df[h_cycle].isin(cycle), :]
        if len(cycle) < 5:
            title += f" [c:{cycle}]"
        else:
            title += f" [c:{cycle[0]}..{cycle[-1]}]"
        if _df.empty:
            print(f"EMPTY (available cycles: {df[h_step].unique()})")
            return
        else:
            df = _df

    cycle = df[h_cycle].unique()

    if step is not None:
        if not isinstance(step, (list, tuple)):
            step = [step]

        _df = df.loc[df[h_step].isin(step), :]
        if len(step) < 5:
            title += f" (s:{step})"
        else:
            title += f" [s:{step[0]}..{step[-1]}]"
        if _df.empty:
            print(f"EMPTY (available steps: {df[h_step].unique()})")
            return
        else:
            df = _df

    x_min, x_max = df[x].min(), df[x].max()
    y_min, y_max = df[y].min(), df[y].max()

    if info_level > 0:
        table = cell.cell.steps
        df = _add_step_info_cols(df, table, cycle, step)

    source = ColumnDataSource(df)

    plot = figure(
        title=title,
        tools="pan,reset,save,wheel_zoom,box_zoom,undo,redo",
        x_range=[x_min, x_max],
        y_range=[y_min, y_max],
        **kwargs,
    )

    plot.line(x, y, source=source, line_width=3, line_alpha=0.6)

    # labelling cycles
    if label_cycles:
        cycle_line_positions = [
            df.loc[df[h_cycle] == c, x].min() for c in cycle
        ]
        cycle_line_positions.append(df.loc[df[h_cycle] == cycle[-1], x].max())
        for m in cycle_line_positions:
            _s = Span(
                location=m,
                dimension="height",
                line_color="red",
                line_width=3,
                line_alpha=0.5,
            )
            plot.add_layout(_s)

        s_y_pos = y_min + 0.9 * (y_max - y_min)
        s_x = []
        s_y = []
        s_l = []

        for s in cycle:
            s_x_min = df.loc[df[h_cycle] == s, x].min()
            s_x_max = df.loc[df[h_cycle] == s, x].max()
            s_x_pos = (s_x_min + s_x_max) / 2
            s_x.append(s_x_pos)
            s_y.append(s_y_pos)
            s_l.append(f"c{s}")

        c_labels = ColumnDataSource(data={x: s_x, y: s_y, "names": s_l})

        c_labels = LabelSet(
            x=x,
            y=y,
            text="names",
            level="glyph",
            source=c_labels,
            render_mode="canvas",
            text_color="red",
            text_alpha=0.7,
        )

        plot.add_layout(c_labels)

        # labelling steps
    if label_steps:
        for c in cycle:
            step = df.loc[df[h_cycle] == c, h_step].unique()
            step_line_positions = [
                df.loc[(df[h_step] == s) & (df[h_cycle] == c), x].min()
                for s in step[0:]
            ]
            for m in step_line_positions:
                _s = Span(
                    location=m,
                    dimension="height",
                    line_color="olive",
                    line_width=3,
                    line_alpha=0.1,
                )
                plot.add_layout(_s)

            # s_y_pos = y_min + 0.8 * (y_max - y_min)
            s_x = []
            s_y = []
            s_l = []

            for s in step:
                s_x_min = df.loc[(df[h_step] == s) & (df[h_cycle] == c),
                                 x].min()
                s_x_max = df.loc[(df[h_step] == s) & (df[h_cycle] == c),
                                 x].max()
                s_x_pos = s_x_min

                s_y_min = df.loc[(df[h_step] == s) & (df[h_cycle] == c),
                                 y].min()
                s_y_max = df.loc[(df[h_step] == s) & (df[h_cycle] == c),
                                 y].max()
                s_y_pos = (s_y_max + s_y_min) / 2

                s_x.append(s_x_pos)
                s_y.append(s_y_pos)
                s_l.append(f"s{s}")

            s_labels = ColumnDataSource(data={x: s_x, y: s_y, "names": s_l})

            s_labels = LabelSet(
                x=x,
                y=y,
                text="names",
                level="glyph",
                source=s_labels,
                render_mode="canvas",
                text_color="olive",
                text_alpha=0.3,
            )

            plot.add_layout(s_labels)

    hover = HoverTool()
    if info_level == 0:
        hover.tooltips = [
            (x, "$x{0.2f}"),
            (y, "$y"),
            ("cycle", f"@{h_cycle}"),
            ("step", f"@{h_step}"),
        ]
    elif info_level == 1:
        # insert C-rates etc here
        hover.tooltips = [
            (f"(x,y)", "($x{0.2f} $y"),
            ("cycle", f"@{h_cycle}"),
            ("step", f"@{h_step}"),
            ("step_type", "@type"),
            ("rate", "@rate_avr{0.2f}"),
        ]

    elif info_level == 2:
        hover.tooltips = [
            (x, "$x{0.2f}"),
            (y, "$y"),
            ("cycle", f"@{h_cycle}"),
            ("step", f"@{h_step}"),
            ("step_type", "@type"),
            ("rate (C)", "@rate_avr{0.2f}"),
            ("dv (%)", "@voltage_delta{0.2f}"),
            ("I-max (A)", "@current_max"),
            ("I-min (A)", "@current_min"),
            ("dCharge (%)", "@charge_delta{0.2f}"),
            ("dDischarge (%)", "@discharge_delta{0.2f}"),
        ]

    hover.mode = "vline"
    plot.add_tools(hover)

    plot.xaxis.axis_label = x_label
    plot.yaxis.axis_label = y_label

    if points:
        plot.scatter(x, y, source=source, alpha=0.3)

    if show_it:
        show(plot)

    return plot
Ejemplo n.º 25
0
x3, y3 = list(range(40, 50)), list(range(50, 60))

# create a new plot
f1 = figure(width=250, plot_height=250, title="Circles")
f1.circle(x1, y1, size=10, color="navy", alpha=0.5)

# create another one
f2 = figure(width=250, height=250, title="Triangles")
f2.triangle(x2, y2, size=10, color="firebrick", alpha=0.5)

# create and another
f3 = figure(width=250, height=250, title="Squares")
f3.square(x3, y3, size=10, color="olive", alpha=0.5)

#create a span annotation
span_4 = Span(location=4, dimension='height', line_color='green', line_width=2)
f1.add_layout(span_4)

#create a box annotation
box_2_6 = BoxAnnotation(left=2,
                        right=6,
                        fill_color="firebrick",
                        fill_alpha=0.3)
f1.add_layout(box_2_6)

# put all the plots in a grid layout
f = gridplot([[f1, f2], [None, f3]])

# show the results
show(f)
Ejemplo n.º 26
0
# 转债价格与股价
p1 = figure(title="转债价格-转股溢价率", tooltips=TOOLTIPS, **options)
p1.circle("bond_price",
          'to_stock_premium_rate',
          color={
              'field': 'credit',
              'transform': color_mapper
          },
          size=10,
          alpha=0.6,
          source=source)
p1.add_layout(color_bar, 'right')

# 添加参线:https://nbviewer.jupyter.org/github/gafeng/bokeh-notebooks/blob/master/tutorial/03%20-%20Adding%20Annotations.ipynb
upper = Span(location=100,
             dimension='height',
             line_color='green',
             line_width=1)
p1.add_layout(upper)

# 转债价格与转股价格
p2 = figure(title="转债价格-到期收益率",
            x_range=p1.x_range,
            tooltips=TOOLTIPS,
            **options)
p2.circle("bond_price",
          'income_before_taxes_rate',
          color={
              'field': 'credit',
              'transform': color_mapper
          },
          size=10,