Example #1
0
def render_ellipse(center_x, center_y, covariance_matrix, distance_square):
    """
    Renders a Bokeh Ellipse object given the ellipse center point, covariance, and distance square

    :param center_x: x-coordinate of ellipse center
    :param center_y: y-coordinate of ellipse center
    :param covariance_matrix: NumPy array containing the covariance matrix of the ellipse
    :param distance_square: value for distance square of ellipse
    :return: Bokeh Ellipse object
    """
    values, vectors = np.linalg.eigh(covariance_matrix)
    order = values.argsort()[::-1]
    values = values[order]
    vectors = vectors[:, order]

    angle_rads = np.arctan2(*vectors[:, 0][::-1])

    # Width and height are full width (the axes lengths are thus multiplied by 2.0 here)
    width, height = 2.0 * np.sqrt(values * distance_square)

    ellipse = Ellipse(x=center_x,
                      y=center_y,
                      width=width,
                      height=height,
                      angle=angle_rads,
                      line_width=line_width,
                      line_color=line_color,
                      fill_color=fill_color,
                      fill_alpha=fill_alpha)

    return ellipse
Example #2
0
    def plot_graph(self, title):
        if len(self.nrd_list) == 0:
            return None, None

        last = len(self.nrd_list) - 1
        self.graph.node_renderer.data_source.data = self.nrd_list[last]
        self.graph.edge_renderer.data_source.data = self.erd_list[last]

        TOOLTIPS = [
            ("index", "@index"),
            ("loc", "(@levels, @offsets)"),
            ("size", "@human_node_size"),
            ("nkvsets", "@node_len"),
            ("kblks", "@node_nkblks"),
            ("vblks", "@node_nvblks"),
        ]

        self.graph.node_renderer.glyph = Ellipse(height=self.el_size,
                                                 width=self.el_size,
                                                 fill_alpha=0.8,
                                                 fill_color="color")
        self.graph.edge_renderer.glyph = MultiLine(line_color="black",
                                                   line_alpha=0.8,
                                                   line_width=0.5)

        graph_layout = self.graph_layout_list[last]
        self.graph.layout_provider = StaticLayoutProvider(
            graph_layout=graph_layout)

        plot = figure(
            title=title,
            x_range=(-self.max_dim, self.max_dim),
            y_range=(-self.max_dim, self.max_dim),
            width=self.fig_width,
            height=self.fig_height,
            tools="wheel_zoom,box_zoom,pan,reset,undo",
            tooltips=TOOLTIPS,
            toolbar_location="right",
        )

        plot.ygrid.visible = False
        plot.renderers.append(self.graph)

        # Set up slider
        slider = None
        if len(self.nrd_list) > 1:
            slider = self.create_slider()

        return plot, slider
Example #3
0
def calculate_ellipse(center_x, center_y, covariance_matrix, distance_square):
    values, vectors = np.linalg.eigh(covariance_matrix)
    order = values.argsort()[::-1]
    values = values[order]
    vectors = vectors[:, order]

    angle_rads = np.arctan2(*vectors[:, 0][::-1])

    # Width and height are full width (the axes lengths are thus multiplied by 2.0 here)
    width, height = 2.0 * np.sqrt(values * distance_square)

    ellipse = Ellipse(x=center_x,
                      y=center_y,
                      width=width,
                      height=height,
                      angle=angle_rads,
                      line_width=line_width,
                      line_color=line_color,
                      fill_color=fill_color,
                      fill_alpha=fill_alpha)

    return ellipse
Example #4
0
    def add_ellipse(self,
                    centroid,
                    length,
                    width,
                    angle,
                    asymmetry=0.0,
                    **kwargs):
        """
        plot an ellipse on top of the camera

        Parameters
        ----------
        centroid: (float, float)
            position of centroid
        length: float
            major axis
        width: float
            minor axis
        angle: float
            rotation angle wrt x-axis about the centroid, anticlockwise, in radians
        asymmetry: float
            3rd-order moment for directionality if known
        kwargs:
            any MatPlotLib style arguments to pass to the Ellipse patch

        """
        ellipse = Ellipse(
            x=centroid[0],
            y=centroid[1],
            width=length,
            height=width,
            angle=angle,
            fill_color=None,
            **kwargs,
        )
        glyph = self.figure.add_glyph(ellipse)
        self._annotations.append(glyph)
        self.update()
        return ellipse
Example #5
0
def report_html_graph(logger, iteration=0):
    # type: (Logger, int) -> ()
    """
    reporting bokeh graph (html) to debug samples section
    :param logger: The task.logger to use for sending the plots
    :param iteration: The iteration number of the current reports
    """
    nodes = 8
    node_indices = list(range(nodes))
    plot = figure(
        title="Graph Layout Demonstration",
        x_range=(-1.1, 1.1),
        y_range=(-1.1, 1.1),
        tools="",
        toolbar_location=None,
    )
    graph = GraphRenderer()
    graph.node_renderer.data_source.add(node_indices, "index")
    graph.node_renderer.data_source.add(Spectral8, "color")
    graph.node_renderer.glyph = Ellipse(height=0.1,
                                        width=0.2,
                                        fill_color="color")
    graph.edge_renderer.data_source.data = dict(start=[0] * nodes,
                                                end=node_indices)
    # start of layout code
    circ = [i * 2 * math.pi / 8 for i in node_indices]
    x = [math.cos(i) for i in circ]
    y = [math.sin(i) for i in circ]
    graph_layout = dict(zip(node_indices, zip(x, y)))
    graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)
    plot.renderers.append(graph)
    output_file("graph.html")
    save(plot)
    logger.report_media("html",
                        "Graph_html",
                        iteration=iteration,
                        local_path="graph.html")
Example #6
0
from bokeh.plotting import figure

N = 8
node_indices = list(range(N))

plot = figure(title='Graph Layout Demonstration',
              x_range=(-1.1, 1.1),
              y_range=(-1.1, 1.1),
              tools='',
              toolbar_location=None)

graph = GraphRenderer()

graph.node_renderer.data_source.add(node_indices, 'index')
graph.node_renderer.data_source.add(Spectral8, 'color')
graph.node_renderer.glyph = Ellipse(height=0.1, width=0.2, fill_color='color')

graph.edge_renderer.data_source.data = dict(start=[0] * N, end=node_indices)

### start of layout code
circ = [i * 2 * math.pi / 8 for i in node_indices]
x = [math.cos(i) for i in circ]
y = [math.sin(i) for i in circ]

graph_layout = dict(zip(node_indices, zip(x, y)))
graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

plot.renderers.append(graph)

output_file('graph.html')
show(plot)
Example #7
0
    def __init__(self,
                 image_views,
                 sv_metadata,
                 sv_streamctrl,
                 positions=POSITIONS):
        """Initialize a resolution rings overlay.

        Args:
            image_views (ImageView): Associated streamvis image view instances.
            sv_metadata (MetadataHandler): A metadata handler to report metadata issues.
            sv_streamctrl (StreamControl): A StreamControl instance of an application.
            positions (list, optional): Scattering radii in Angstroms. Defaults to
                [1.4, 1.5, 1.6, 1.8, 2, 2.2, 2.6, 3, 5, 10].
        """
        self._sv_metadata = sv_metadata
        self._sv_streamctrl = sv_streamctrl
        self.positions = np.array(positions)

        # ---- add resolution tooltip to hover tool
        self._formatter_source = ColumnDataSource(data=dict(
            detector_distance=[np.nan],
            beam_energy=[np.nan],
            beam_center_x=[np.nan],
            beam_center_y=[np.nan],
        ))

        resolution_formatter = CustomJSHover(
            args=dict(params=self._formatter_source), code=js_resolution)

        hovertool_off = HoverTool(tooltips=[("intensity", "@image")],
                                  names=["image_glyph"])
        hovertool_on = HoverTool(
            tooltips=[("intensity", "@image"),
                      ("resolution", "@x{resolution} Å")],
            formatters={"@x": resolution_formatter},
            names=["image_glyph"],
        )

        # ---- resolution rings
        self._source = ColumnDataSource(
            dict(x=[], y=[], w=[], h=[], text_x=[], text_y=[], text=[]))
        ellipse_glyph = Ellipse(x="x",
                                y="y",
                                width="w",
                                height="h",
                                fill_alpha=0,
                                line_color="white")

        text_glyph = Text(
            x="text_x",
            y="text_y",
            text="text",
            text_align="center",
            text_baseline="middle",
            text_color="white",
        )

        cross_glyph = Cross(x="beam_center_x",
                            y="beam_center_y",
                            size=15,
                            line_color="red")

        for image_view in image_views:
            image_view.plot.add_glyph(self._source, ellipse_glyph)
            image_view.plot.add_glyph(self._source, text_glyph)
            image_view.plot.add_glyph(self._formatter_source, cross_glyph)

        # ---- toggle button
        def toggle_callback(state):
            hovertool = hovertool_on if state else hovertool_off
            for image_view in image_views:
                image_view.plot.tools[-1] = hovertool

        toggle = CheckboxGroup(labels=["Resolution Rings"], default_size=145)
        toggle.on_click(toggle_callback)
        self.toggle = toggle
Example #8
0
      line_width=3)),
 ("bezier",
  Bezier(x0="x",
         y0="y",
         x1="xp02",
         y1="y",
         cx0="xp01",
         cy0="yp01",
         cx1="xm01",
         cy1="ym01",
         line_color="#D95F02",
         line_width=2)),
 ("ellipse",
  Ellipse(x="x",
          y="y",
          width=screen(15),
          height=screen(25),
          angle=-0.7,
          fill_color="#1D91C0")),
 ("image_url",
  ImageURL(x="x",
           y="y",
           w=0.4,
           h=0.4,
           url=dict(value="https://static.bokeh.org/logos/logo.png"),
           anchor="center")),
 ("line", Line(x="x", y="y", line_color="#F46D43")),
 ("multi_line",
  MultiLine(xs="xs", ys="ys", line_color="#8073AC", line_width=2)),
 ("multi_polygons",
  MultiPolygons(xs="xsss",
                ys="ysss",
Example #9
0
source1 = ColumnDataSource({
    "x": [1, 2, 3, 4, 5],
    "y": [1, 2, 3, 4, 5],
    "who": ["a", "b", "c", "d", "e"]
})
source2 = ColumnDataSource({"x": x, "y": y})
source3 = ColumnDataSource({"x": x2, "y": z})
source4 = ColumnDataSource({"y": [2.5], "x": [0.5]})

plot = Plot(width=300, height=300)
plot.title = Title(text="Themed glyphs")

xaxis = LinearAxis(ticker=BasicTicker(), formatter=BasicTickFormatter())
yaxis = LinearAxis(ticker=BasicTicker(), formatter=BasicTickFormatter())
plot.add_layout(xaxis, "below")
plot.add_layout(yaxis, "left")

plot.add_glyph(source1, Scatter(x="x", y="y", marker="diamond", size=20))
plot.add_glyph(source1, Text(x=dodge("x", -0.2), y=dodge("y", 0.1),
                             text="who"))
plot.add_glyph(source2, Line(x="x", y="y"))
plot.add_glyph(source3, Ellipse(x="x",
                                y="y",
                                width=0.2,
                                height=0.3,
                                angle=-0.7))
plot.add_glyph(source4, glyph=HBar(y="y", right="x", height=1.5))

output_file("theme_glyphs.html", title="themed_glyphs.py example")
show(plot)
children_visual = []
for child in deformable_object.children:
    if not child.ellipse:
        source = child.data_source
        visual = Patch(x='x',
                       y='y',
                       line_color=c_black,
                       line_width=0,
                       fill_color=None,
                       fill_alpha=0.5)
    else:
        source = child.data_source
        visual = Ellipse(x='x',
                         y='y',
                         width='w',
                         height='h',
                         line_color=c_black,
                         line_width=0,
                         fill_color=None,
                         fill_alpha=0.5)
    figure.add_glyph(source, visual)
    children_visual.append(visual)

# plot force symbols
for force_symbol in deformable_object.force_symbols:
    # sigma
    source = force_symbol.data_source['sigma']
    visual = Patch(x='x',
                   y='y',
                   line_color=c_black,
                   line_width=1,
                   fill_color=c_orange,
Example #11
0
x = np.linspace(-2, 2, N)
y = x**2
w = x / 15.0 + 0.3
h = y / 20.0 + 0.3

source = ColumnDataSource(dict(x=x, y=y, w=w, h=h))

plot = Plot(title=None,
            width=300,
            height=300,
            min_border=0,
            toolbar_location=None)

glyph = Ellipse(x="x",
                y="y",
                width="w",
                height="h",
                angle=-0.7,
                fill_color="#cab2d6")
plot.add_glyph(source, glyph)

xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')

yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

curdoc().add_root(plot)
Example #12
0
# debug_pallet.append('#ff0000')
# debug_pallet.append('#0000ff')

# TODO: make rectangle, rect?
plot = figure(title='Graph Layout Demonstration',
              x_range=(0, WIDTH),
              y_range=(0, HEIGHT),
              tools='',
              toolbar_location=None)

graph = GraphRenderer()

graph.node_renderer.data_source.add(node_indices, 'index')
graph.node_renderer.data_source.add(color_list, 'color')
graph.node_renderer.glyph = Ellipse(height=CIRCLE_SIZE,
                                    width=CIRCLE_SIZE,
                                    fill_color='color')

start_indices = []
end_indices = []

for start_index, vertex in enumerate(graph_data.vertexes):
    for e in vertex.edges:
        start_indices.append(start_index)
        end_indices.append(graph_data.vertexes.index(e.destination))

graph.edge_renderer.data_source.data = dict(start=start_indices,
                                            end=end_indices)

# TODO: test with this code
# graph.edge_renderer.data_source.data = dict(