Ejemplo n.º 1
0
def test_binary_serialize_datetime():
    x = np.arange('2005-02-25', '2005-03', dtype='datetime64[D]')
    x_ms = np.array(
        [1109289600000, 1109376000000, 1109462400000, 1109548800000],
        dtype=np.int64)
    scatter = bqplot.Scatter(x=x)

    state = scatter.get_state()
    assert state['x']['dtype'] == 'float64'
    assert np.array(state['x']['value'], dtype=np.float64).astype(
        np.int64).tolist() == x_ms.tolist()

    x = np.array([
        pd.Timestamp('2005-02-25'),
        pd.Timestamp('2005-02-26'),
        pd.Timestamp('2005-02-27'),
        pd.Timestamp('2005-02-28')
    ])
    scatter = bqplot.Scatter(x=x)

    state = scatter.get_state()
    assert state['x']['dtype'] == 'float64'
    assert np.array(state['x']['value'], dtype=np.float64).astype(
        np.int64).tolist() == x_ms.tolist()

    # currently a roundtrip does not converse the datetime64 type
    scatter2 = bqplot.Scatter()
    scatter2.set_state(state)

    assert scatter2.x.dtype.kind == 'M'
    assert scatter2.x.astype(np.int64).tolist() == x_ms.tolist()
Ejemplo n.º 2
0
def test_binary_serialize_1d(figure):
    x = np.arange(10, dtype=np.float64)
    y = (x**2).astype(np.int32)
    scatter = bqplot.Scatter(x=x, y=y)

    state = scatter.get_state()
    assert state['x']['dtype'] == 'float64'
    assert state['y']['dtype'] == 'int32'
    
    assert state['x']['value'] == memoryview(x)
    assert state['y']['value'] == memoryview(y)

    assert state['x']['shape'] == (10,)
    assert state['y']['shape'] == (10,)

    scatter2 = bqplot.Scatter()
    scatter2.set_state(state)

    assert scatter.x.dtype == np.float64
    assert scatter.y.dtype == np.int32

    assert scatter.x.shape == (10,)
    assert scatter.y.shape == (10,)

    assert scatter2.x.tolist() == x.tolist()
    assert scatter2.y.tolist() == y.tolist()
Ejemplo n.º 3
0
    def __init__(self):
        '''Initialization of a Gomoku game with an empty board and a random starting party'''
        self.A = np.zeros(
            (15, 15),
            dtype=int)  # this holds the information of the current game status
        # 0 means empty place
        # 1 is red
        # 2 is blue

        # the visualization of the table is generated by bqplot
        sc_x = bq.LinearScale(max=15.5, min=-1.5)
        sc_y = bq.LinearScale(max=15.5, min=-1.5)
        scatt1 = bq.Scatter(x=[],
                            y=[],
                            scales={
                                'x': sc_x,
                                'y': sc_y
                            },
                            colors=['red'],
                            default_size=500)
        scatt2 = bq.Scatter(x=[],
                            y=[],
                            scales={
                                'x': sc_x,
                                'y': sc_y
                            },
                            colors=['blue'],
                            default_size=500)
        winline = bq.Lines(x=[],
                           y=[],
                           scales={
                               'x': sc_x,
                               'y': sc_y
                           },
                           colors=['lightgreen'],
                           stroke_width=5)
        props = dict(tick_values=np.arange(16) - 0.5,
                     grid_color='black',
                     tick_style={'font-size': 0})
        ax_x = bq.Axis(scale=sc_x, **props)
        ax_y = bq.Axis(scale=sc_y, orientation='vertical', **props)
        fig = bq.Figure(marks=[scatt1, scatt2, winline], axes=[ax_x, ax_y])
        fig.max_aspect_ratio = 1.0
        fig.min_aspect_ratio = 1.0
        fig.layout.height = '600px'
        self.fig = fig

        # the starting player is randomly selected
        self.who_is_next = np.random.randint(1, 3)
        self.fig.title = 'Next player is ' + ['red ', 'blue '
                                              ][self.who_is_next - 1]
        # initially noone is winning
        self.win_string = False
Ejemplo n.º 4
0
def plot_orbit(z0=0.5+0.5*1j, c=0+0*1j):
    sc_x = bqplot.LinearScale(min=-1.2, max=1.2)
    sc_y = bqplot.LinearScale(min=-1.2, max=1.2)

    c_point = bqplot.Scatter(x=[c.real], y=[c.imag], scales={'x': sc_x, 'y': sc_y}, colors=['red'],
                   enable_move=True, default_size=200)
    c_point.update_on_move = True

    z_point = bqplot.Scatter(x=[z0.real], y=[z0.imag], scales={'x': sc_x, 'y': sc_y}, colors=['green'],
                   enable_move=True, default_size=200)
    z_point.update_on_move = True

    c_label = bqplot.Label(x=[c.real+.05], y=[c.imag+.05], scales={'x': sc_x, 'y': sc_y}, colors=['red'],
                           text=['c'],
                           default_size=26, font_weight='bolder')

    z_label = bqplot.Label(x=[z0.real+.05], y=[z0.imag+.05], scales={'x': sc_x, 'y': sc_y}, colors=['green'],
                           text=['z0'],
                           default_size=26, font_weight='bolder')
    
    scatt = bqplot.Scatter(x=[], y=[], scales={'x': sc_x, 'y': sc_y}, colors=['black'], default_size=20)

    theta = np.linspace(0, 2.*np.pi, 1000)
    x = np.cos(theta)
    y = np.sin(theta)
    circle = bqplot.Lines(x=x, y=y, scales={'x': sc_x, 'y': sc_y}, colors=['black'])
    lin = bqplot.Lines(x=[], y=[], scales={'x': sc_x, 'y': sc_y}, colors=['black'], stroke_width=1)

    def update_line(change=None):
        out = orbit(z_point.x + 1j*z_point.y, c_point.x + 1j*c_point.y)
        c_label.x = c_point.x + 0.05
        c_label.y = c_point.y + 0.05
        z_label.x = z_point.x + 0.05
        z_label.y = z_point.y + 0.05
        lin.x = out.real
        lin.y = out.imag
        scatt.x = out.real.flatten()
        scatt.y = out.imag.flatten()

    update_line()
    # update line on change of x or y of scatter
    c_point.observe(update_line, names=['x'])
    c_point.observe(update_line, names=['y'])
    z_point.observe(update_line, names=['x'])
    z_point.observe(update_line, names=['y'])
    ax_x = bqplot.Axis(scale=sc_x, offset=dict(value=0.5), grid_lines='none')
    ax_y = bqplot.Axis(scale=sc_y, orientation='vertical', offset=dict(value=0.5), grid_lines='none')

    fig = bqplot.Figure(marks=[scatt, lin, circle, c_point, z_point, c_label, z_label], axes=[ax_x, ax_y],
                 min_aspect_ratio=1, max_aspect_ratio=1)
    fig.layout.height = '800px'
    return fig
Ejemplo n.º 5
0
def make_bq_plot(plot_type,
                 x,
                 y,
                 scales,
                 size,
                 interactions,
                 selected_style,
                 unselected_style,
                 display_legend=False,
                 labels=[''],
                 colors=['#43a2ca'],
                 stroke_width=3,
                 marker='circle'):

    if plot_type == 'scatter':
        chart = bqplot.Scatter(x=x,
                               y=y,
                               scales=scales,
                               size=size,
                               interactions=interactions,
                               selected_style=selected_style,
                               unselected_style=unselected_style,
                               display_legend=display_legend,
                               labels=labels,
                               marker=marker,
                               colors=colors)
    elif plot_type == 'lines':
        chart = bqplot.Lines(x=x,
                             y=y,
                             colors=colors,
                             stroke_width=stroke_width,
                             scales=scales,
                             size=size)

    return chart
Ejemplo n.º 6
0
def draw_graph(graph, pos=None):
    from numpy import array
    import networkx as nx
    import bqplot as bq

    if pos is None:
        pos = nx.spring_layout(graph)
    nodes = graph.nodes()
    x = [pos[n][0] for n in nodes]
    y = [pos[n][1] for n in nodes]
    lines_x = []
    lines_y = []
    for k, v in graph.edges():
        i1 = graph.nodes().index(k)
        i2 = graph.nodes().index(v)
        lines_x.append([x[i1], x[i2]])
        lines_y.append([y[i1], y[i2]])
    lines_x = array(lines_x)
    lines_y = array(lines_y)

    x_sc = bq.LinearScale()
    y_sc = bq.LinearScale()
    points = bq.Scatter(x=x, y=y, scales={'x': x_sc, 'y': y_sc})
    lines = bq.Lines(x=lines_x,
                     y=lines_y,
                     scales={
                         'x': x_sc,
                         'y': y_sc
                     },
                     colors=['red'])
    ax_x = bq.Axis(scale=x_sc)
    ax_y = bq.Axis(scale=y_sc, orientation='vertical')
    fig = bq.Figure(marks=[lines, points], axes=[ax_x, ax_y])
    return fig
Ejemplo n.º 7
0
    def __init__(self, model=None, *args, **kwargs):

        super(GeneratorCostView, self).__init__(*args, **kwargs)

        if model is not None:
            self.model = model
        else:
            self.model = Generator()

        self._scale_x = bq.LinearScale(min=self.model.minimum_real_power,
                                       max=self.model.maximum_real_power)

        self._scale_y = bq.LinearScale(
            min=0, max=(max(self.model.cost_curve_values) * 1.5 + 50))

        self._scales = {
            'x': self._scale_x,
            'y': self._scale_y,
        }

        self._scatter = bq.Scatter(x=self.model.cost_curve_points,
                                   y=self.model.cost_curve_values,
                                   scales=self._scales)

        self._lines = bq.Lines(x=self.model.cost_curve_points,
                               y=self.model.cost_curve_values,
                               scales=self._scales)

        self._axes_x = bq.Axis(scale=self._scale_x)
        self._axes_y = bq.Axis(scale=self._scale_y,
                               orientation='vertical',
                               padding_x=0.025)

        f = bq.Figure(marks=[
            self._lines,
            self._scatter,
        ],
                      axes=[
                          self._axes_x,
                          self._axes_y,
                      ])

        children = [f]

        self.children = children

        t.link((self.model, 'maximum_real_power'), (self._scale_x, 'max'))
        t.link((self.model, 'cost_curve_points'), (self._scatter, 'x'))
        t.link((self.model, 'cost_curve_values'), (self._scatter, 'y'))

        t.link((self._lines, 'x'), (self._scatter, 'x'))
        t.link((self._lines, 'y'), (self._scatter, 'y'))

        # self._scatter.observe(self._callback_ydata, names=['y'])

        with self._scatter.hold_sync():
            self._scatter.enable_move = True
            self._scatter.update_on_move = True
            self._scatter.interactions = {'click': None}
Ejemplo n.º 8
0
def representation_complexe():
    real = widgets.BoundedFloatText(value=1,
                                    min=-2.0,
                                    max=2.0,
                                    step=0.1,
                                    disabled=True)

    imag = widgets.BoundedFloatText(value=1,
                                    min=-2.0,
                                    max=2.0,
                                    step=0.1,
                                    disabled=True)

    sc_x = bqplot.LinearScale(min=-2, max=2)
    sc_y = bqplot.LinearScale(min=-2, max=2)
    ax_x = bqplot.Axis(scale=sc_x, offset=dict(value=0.5), grid_lines='none')
    ax_y = bqplot.Axis(scale=sc_y,
                       orientation='vertical',
                       offset=dict(value=0.5),
                       grid_lines='none')

    z_point = bqplot.Scatter(x=[real.value],
                             y=[imag.value],
                             scales={
                                 'x': sc_x,
                                 'y': sc_y
                             },
                             colors=['green'],
                             enable_move=True)
    z_point.update_on_move = True

    fig = bqplot.Figure(marks=[z_point],
                        axes=[ax_x, ax_y],
                        min_aspect_ratio=1,
                        max_aspect_ratio=1)

    complex_z = widgets.HBox([
        widgets.Label('$z = $'), real,
        widgets.Label('$ + $'), imag,
        widgets.Label('$i$')
    ])

    def update_z(change=None):
        real.value = z_point.x[0]
        imag.value = z_point.y[0]

    z_point.observe(update_z, names=['x', 'y'])

    #def update_point(change=None):
    #    z_point.x = [real.value]
    #    z_point.y = [imag.value]

    #real.observe(update_point, names='value')
    #imag.observe(update_point, names='value')

    return widgets.VBox([fig, complex_z],
                        layout=widgets.Layout(align_items="center"))
Ejemplo n.º 9
0
def test_scatter(figure):
    x = np.arange(10, dtype=np.float64)
    y = (x**2).astype(np.int32)
    scatter = bqplot.Scatter(x=x, y=y)
    assert scatter.x.dtype == np.float64
    assert scatter.y.dtype == np.int32

    assert scatter.x.shape == (10, )
    assert scatter.y.shape == (10, )
Ejemplo n.º 10
0
def add_del(scale, img):
    """Add function for ipywidget buttons to add and delete points"""

    scat = bq.Scatter(x=[],
                      y=[],
                      scales=scale,
                      colors=['orange'],
                      enable_move=True)

    image = bq.Image(x=np.array([scale['x'].min, scale['x'].max]),
                     y=np.array([scale['y'].min, scale['y'].max]),
                     image=img,
                     scales=scale,
                     enable_hover=False)

    interact_control = widgets.ToggleButtons(options=['Add', 'Delete'],
                                             style={'button_width': '130px'})

    def change_interact(shape):
        """Give a meaning to the buttons."""
        interact_params = {
            'Add': {
                'interactions': {
                    'click': 'add'
                },
                'enable_move': True
            },
            'Delete': {
                'interactions': {
                    'click': 'delete'
                },
                'enable_move': False
            }
        }

        for param, value in interact_params[interact_control.value].items():
            setattr(scat, param, value)

    interact_control.observe(change_interact)

    fig = bq.Figure(title='Cross-section',
                    marks=[image, scat],
                    padding_x=0,
                    padding_y=0)
    fig.axes = [
        bq.Axis(scale=scale['x']),
        bq.Axis(scale=scale['y'], orientation='vertical')
    ]

    return widgets.VBox([fig, interact_control])
Ejemplo n.º 11
0
    def create_fig(self):
        t1_values = self.get_values(self.t1)
        t2_values = self.get_values(self.t2)
        self.df = t1_values.merge(t2_values, how='inner', on='patient.id')

        sc_x = plt.LinearScale()
        sc_y = plt.LinearScale()

        self.mark = plt.Scatter(scales={'x': sc_x, 'y': sc_y}, default_size=16)

        ax_x = plt.Axis(scale=sc_x, label=self.t1.title)
        ax_y = plt.Axis(scale=sc_y,
                        label=self.t2.title,
                        orientation='vertical')
        self.fig = plt.Figure(marks=[self.mark], axes=[ax_x, ax_y])
Ejemplo n.º 12
0
    def create_line(self, y, display_legend=False):
        try:
            color = self.colors[self.num_lines % len(self.colors)]
            self.lines.append(
                bq.Lines(x=[],
                         y=[],
                         scales={
                             'x': self.xscale,
                             'y': self.yscale
                         },
                         interpolation='linear',
                         display_legend=display_legend,
                         colors=[color],
                         labels=[y],
                         enable_hover=True))
            self.scatters.append(
                bq.Scatter(x=[],
                           y=[],
                           scales={
                               'x': self.xscale,
                               'y': self.yscale
                           },
                           colors=[color],
                           enable_hover=True))
            self.labels.append(y)
            self.num_lines += 1

            self.lines[-1].tooltip = bq.Tooltip(fields=['name'],
                                                show_labels=True)
            self.lines[-1].interactions = {
                'hover': 'tooltip',
                'click': 'tooltip'
            }

            self.scatters[-1].tooltip = bq.Tooltip(fields=['y', 'x'],
                                                   labels=[y, self.xlabel],
                                                   formats=['.4f', ''],
                                                   show_labels=True)
            self.scatters[-1].interactions = {
                'hover': 'tooltip',
                'click': 'tooltip'
            }
        except Exception as e:
            self.debug.append_stdout(
                "Exception when adding a line and points to plot: {}".format(
                    e.args))
Ejemplo n.º 13
0
def make_pred_bqplot():
    x_sc = bq.LinearScale()
    y_sc = bq.LinearScale()

    ax_x = bq.Axis(label="Feature", scale=x_sc)  # , tick_format="0.0f"
    ax_y = bq.Axis(
        label="Target",
        scale=y_sc,
        orientation="vertical"  # , tick_format="0.0e"
    )

    line = bq.Lines(
        x=[0],
        y=[0],
        scales={
            "x": x_sc,
            "y": y_sc
        },
        colors=["darkblue"],
        opacities=[1],
    )

    scatter = bq.Scatter(
        x=[0],
        y=[0],
        scales={
            "x": x_sc,
            "y": y_sc
        },
        colors=["red"],
        opacities=[1],
    )
    out_plot = bq.Figure(
        axes=[ax_x, ax_y],
        marks=[line, scatter],
        #     interaction=interval_selector,
        # animation_duration=100,
    )

    out_plot.legend_style = {"stroke-width": 0}
    out_plot.layout.width = "flex"
    return {k: v for k, v in locals().items()}
Ejemplo n.º 14
0
 def gui_tips (self) :
     sc_r = bq.LinearScale(min=0, max=np.pi)
     sc_c = bq.ColorScale(colors=Palette.mkpal(["#000000", "#FFFFFF"]))
     tips = {}
     for shape in self._tips_shapes :
         for end in ("src", "dst") :
             edges = self.edges[self.edges["_shape_" + end] == shape]
             scatt = bq.Scatter(x=edges["_x_" + end],
                                y=edges["_y_" + end],
                                marker=shape,
                                rotation=edges["_angle_" + end],
                                color=edges["_color_" + end],
                                stroke="#000000",
                                scales={"x" : self._x_scale,
                                        "y" : self._y_scale,
                                        "color" : sc_c,
                                        "rotation" : sc_r,
                                })
             tips[end,shape] = scatt
     return tips
Ejemplo n.º 15
0
    def plot_scatter(self, x=[], y=[], color='red', filt=''):
        '''Create and return Scatter plot'''
        #TODO: tooltip format with all data
        tooltip = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '.2f'])
        scatt = bq.Scatter(default_size=3,
                           scales={
                               'x': self.sc_x,
                               'y': self.sc_y
                           },
                           tooltip=tooltip,
                           tooltip_style={'opacity': 0.5},
                           interactions={'hover': 'tooltip'},
                           unhovered_style={'opacity': 0.5},
                           display_legend=True)
        scatt.colors = [color]
        scatt.label = filt
        if ((y != [])):
            scatt.x = x
            scatt.y = y
        scatt.on_element_click(self.plot_images)

        return scatt
Ejemplo n.º 16
0
    def gui_marks (self) :
        sc_s = bq.LinearScale(min=5, max=10)
        sc_o = bq.LinearScale(min=0, max=1)
        sc_c = bq.ColorScale(colors=self.marks_palette)
        marks = {}
        for shape in self._marks_shapes :
            nodes = self.nodes[self.nodes["_marks_shape"] == shape]
            scatt = bq.Scatter(x=nodes["_marks_x"],
                               y=nodes["_marks_y"],
                               size=nodes["_marks_size"],
                               opacity=nodes["_marks_opacity"],
                               color=nodes["_marks_color"],
                               marker=shape,
                               stroke=self.opt.marks.stroke,
                               scales={"x" : self._x_scale,
                                       "y" : self._y_scale,
                                       "size" : sc_s,
                                       "opacity" : sc_o,
                                       "color" : sc_c})

            marks[shape] = scatt
        return marks
 def create_line(self, y, display_legend=False):
     color = self.colors[self.num_lines % len(self.colors)]
     self.lines.append(
         bq.Lines(x=[],
                  y=[],
                  scales={
                      'x': self.xscale,
                      'y': self.yscale
                  },
                  interpolation='linear',
                  display_legend=display_legend,
                  colors=[color],
                  labels=[y]))
     self.scatters.append(
         bq.Scatter(x=[],
                    y=[],
                    scales={
                        'x': self.xscale,
                        'y': self.yscale
                    },
                    colors=[color]))
     self.labels.append(y)
     self.num_lines += 1
Ejemplo n.º 18
0
def interactive_body(body,
                     angles,
                     bodies,
                     r_arm=True,
                     l_arm=True,
                     r_leg=True,
                     l_leg=True,
                     neck_p=True):
    """Plot an interactive body with which we can play. Only call this function on a complete body (for now)"""
    def refresh(_):
        i = 0
        to_update = []
        if l_arm:
            left_arm.x, left_arm.y = [[p[2][0], scat.x[i], scat.x[i + 1]],
                                      [p[2][1], scat.y[i], scat.y[i + 1]]]
            to_update.append(3)
            to_update.append(4)
            i += 2
        if r_arm:
            right_arm.x, right_arm.y = [[p[6][0], scat.x[i], scat.x[i + 1]],
                                        [p[6][1], scat.y[i], scat.y[i + 1]]]
            to_update.append(7)
            to_update.append(8)
            i += 2
        if l_leg:
            left_leg.x, left_leg.y = [[p[9][0], scat.x[i], scat.x[i + 1]],
                                      [p[9][1], scat.y[i], scat.y[i + 1]]]
            to_update.append(10)
            to_update.append(11)
            i += 2
        if r_leg:
            right_leg.x, right_leg.y = [[p[13][0], scat.x[i], scat.x[i + 1]],
                                        [p[13][1], scat.y[i], scat.y[i + 1]]]
            to_update.append(14)
            to_update.append(15)
            i += 2
        if neck_p:
            to_update.append(0)
            neck.x, neck.y = [[p[1][0], scat.x[i]], [p[1][1], scat.y[i]]]

        head.x = np.cos(np.linspace(0, 2 * np.pi, 100)) * 60 + neck.x[1]
        head.y = np.sin(np.linspace(0, 2 * np.pi, 100)) * 65 + neck.y[1]

        #update body
        for i in range(len(to_update)):
            body[0][to_update[i]] = [scat.x[i], scat.y[i]]

        body_angles = []
        b_angles = member_relative_angles(body)

        if l_arm:
            body_angles.append(b_angles[0])
            body_angles.append(b_angles[1])
        if r_arm:
            body_angles.append(b_angles[2])
            body_angles.append(b_angles[3])
        if l_leg:
            body_angles.append(b_angles[4])
            body_angles.append(b_angles[5])
        if r_leg:
            body_angles.append(b_angles[6])
            body_angles.append(b_angles[7])
        if neck_p:
            body_angles.append(b_angles[8])

        b = get_nearest_neighbor(np.transpose(all_angles),
                                 np.transpose(body_angles), bodies)[0]
        p2 = b[0]
        nchest.x, nchest.y = np.transpose(
            [p2[1], p2[2], p2[9], p2[13], p2[6], p2[1], p2[0]])

        nhead.x = np.cos(np.linspace(0, 2 * np.pi, 100)) * 60 + p2[0][0]
        nhead.y = np.sin(np.linspace(0, 2 * np.pi, 100)) * 65 + p2[0][1]

        nleft_arm.x, nleft_arm.y = [[p2[2][0], p2[3][0], p2[4][0]],
                                    [p2[2][1], p2[3][1], p2[4][1]]]
        nright_arm.x, nright_arm.y = [[p2[6][0], p2[7][0], p2[8][0]],
                                      [p2[6][1], p2[7][1], p2[8][1]]]
        nleft_leg.x, nleft_leg.y = [[p2[9][0], p2[10][0], p2[11][0]],
                                    [p2[9][1], p2[10][1], p2[11][1]]]
        nright_leg.x, nright_leg.y = [[p2[13][0], p2[14][0], p2[15][0]],
                                      [p2[13][1], p2[14][1], p2[15][1]]]

    scales = {
        'x': bqp.LinearScale(min=0, max=1000),
        'y': bqp.LinearScale(min=1000, max=0)
    }

    #initialization of the nearest neighbor of the interactive body.
    body_angles = []
    all_angles = []
    b_angles = member_relative_angles(body)
    a = np.transpose(angles)

    if l_arm:
        body_angles.append(b_angles[0])
        body_angles.append(b_angles[1])
        all_angles.append(a[0])
        all_angles.append(a[1])
    if r_arm:
        body_angles.append(b_angles[2])
        body_angles.append(b_angles[3])
        all_angles.append(a[2])
        all_angles.append(a[3])
    if l_leg:
        body_angles.append(b_angles[4])
        body_angles.append(b_angles[5])
        all_angles.append(a[4])
        all_angles.append(a[5])
    if r_leg:
        body_angles.append(b_angles[6])
        body_angles.append(b_angles[7])
        all_angles.append(a[6])
        all_angles.append(a[7])
    if neck_p:
        body_angles.append(b_angles[8])
        all_angles.append(a[8])

    nbody = get_nearest_neighbor(np.transpose(all_angles),
                                 np.transpose(body_angles), bodies)[0]

    #points of the interactive and neighbor bodies
    p = body[0]
    p2 = nbody[0]

    marks = []
    #Constructions of the two bodies: the interactive one and its nearest neighbor. body part beginnig with n... are part of the neighbor.
    #draw the chest
    chest = bqp.Lines(scales=scales)
    chest.x, chest.y = np.transpose([p[1], p[2], p[9], p[13], p[6], p[1]])
    marks.append(chest)

    nchest = bqp.Lines(scales=scales, colors=['red'])
    nchest.x, nchest.y = np.transpose(
        [p2[1], p2[2], p2[9], p2[13], p2[6], p2[1], p2[0]])
    marks.append(nchest)

    #draw the head
    head = bqp.Lines(scales=scales)
    head.x = np.cos(np.linspace(0, 2 * np.pi, 100)) * 60 + p[0][0]
    head.y = np.sin(np.linspace(0, 2 * np.pi, 100)) * 65 + p[0][1]
    marks.append(head)

    nhead_x = np.cos(np.linspace(0, 2 * np.pi, 100)) * 60 + p2[0][0]
    nhead_y = np.sin(np.linspace(0, 2 * np.pi, 100)) * 65 + p2[0][1]
    nhead = bqp.Lines(x=nhead_x, y=nhead_y, scales=scales, colors=['red'])
    marks.append(nhead)

    to_keep = list()
    if l_arm:
        to_keep.append(p[3])
        to_keep.append(p[4])
    if r_arm:
        to_keep.append(p[7])
        to_keep.append(p[8])
    if l_leg:
        to_keep.append(p[10])
        to_keep.append(p[11])
    if r_leg:
        to_keep.append(p[14])
        to_keep.append(p[15])
    if neck_p:
        to_keep.append(p[0])
    #movable points: arms first, left side first
    scat = bqp.Scatter(scales=scales,
                       enable_move=True,
                       update_on_move=True,
                       stroke_width=7)
    scat.x, scat.y = np.transpose(to_keep)
    marks.append(scat)

    i = 0
    left_arm = bqp.Lines(scales=scales)
    if l_arm:
        left_arm.x, left_arm.y = [[p[2][0], scat.x[i], scat.x[i + 1]],
                                  [p[2][1], scat.y[i], scat.y[i + 1]]]
        i += 2
    else:
        left_arm.x, left_arm.y = [[p[2][0], p[3][0], p[4][0]],
                                  [p[2][1], p[3][1], p[4][1]]]
    marks.append(left_arm)

    nleft_arm = bqp.Lines(scales=scales, colors=['red'])
    nleft_arm.x, nleft_arm.y = [[p2[2][0], p2[3][0], p2[4][0]],
                                [p2[2][1], p2[3][1], p2[4][1]]]
    marks.append(nleft_arm)

    right_arm = bqp.Lines(scales=scales)
    if r_arm:
        right_arm.x, right_arm.y = [[p[6][0], scat.x[i], scat.x[i + 1]],
                                    [p[6][1], scat.y[i], scat.y[i + 1]]]
        i += 2
    else:
        right_arm.x, right_arm.y = [[p[6][0], p[7][0], p[8][0]],
                                    [p[6][1], p[7][1], p[8][1]]]

    marks.append(right_arm)

    nright_arm = bqp.Lines(scales=scales, colors=['red'])
    nright_arm.x, nright_arm.y = [[p2[6][0], p2[7][0], p2[8][0]],
                                  [p2[6][1], p2[7][1], p2[8][1]]]
    marks.append(nright_arm)

    left_leg = bqp.Lines(scales=scales)
    if l_leg:
        left_leg.x, left_leg.y = [[p[9][0], scat.x[i], scat.x[i + 1]],
                                  [p[9][1], scat.y[i], scat.y[i + 1]]]
        i += 2
    else:
        left_leg.x, left_leg.y = [[p[9][0], p[10][0], p[11][0]],
                                  [p[9][1], p[10][1], p[11][1]]]
    marks.append(left_leg)

    nleft_leg = bqp.Lines(scales=scales, colors=['red'])
    nleft_leg.x, nleft_leg.y = [[p2[9][0], p2[10][0], p2[11][0]],
                                [p2[9][1], p2[10][1], p2[11][1]]]
    marks.append(nleft_leg)

    right_leg = bqp.Lines(scales=scales)
    if r_leg:
        right_leg.x, right_leg.y = [[p[13][0], scat.x[i], scat.x[i + 1]],
                                    [p[13][1], scat.y[i], scat.y[i + 1]]]
        i += 2
    else:
        right_leg.x, right_leg.y = [[p[13][0], p[14][0], p[15][0]],
                                    [p[13][1], p[14][1], p[15][1]]]
    marks.append(right_leg)

    nright_leg = bqp.Lines(scales=scales, colors=['red'])
    nright_leg.x, nright_leg.y = [[p2[13][0], p2[14][0], p2[15][0]],
                                  [p2[13][1], p2[14][1], p2[15][1]]]
    marks.append(nright_leg)

    neck = bqp.Lines(scales=scales)
    if neck_p:
        neck.x, neck.y = [[p[1][0], scat.x[i]], [p[1][1], scat.y[i]]]
        i += 1
    else:
        neck.x, neck.y = [[p[1][0], p[0][0]], [p[1][1], p[0][1]]]
    marks.append(neck)
    scat.observe(refresh, names=['x', 'y'])

    return bqp.Figure(marks=marks, padding_y=0., min_height=750, min_width=750)
Ejemplo n.º 19
0
def interactive_body(body,
                     l_arm=True,
                     r_arm=True,
                     l_leg=True,
                     r_leg=True,
                     neck_p=True,
                     general=True):
    """Plot an interactive body with which we can play."""

    middle = Limb(body.pts[9], body.pts[13]).middle()
    to_keep = list()
    to_keep2 = list()
    if l_arm:
        to_keep.append(body.pts[3].to_array())
        to_keep.append(body.pts[4].to_array())
    if r_arm:
        to_keep.append(body.pts[7].to_array())
        to_keep.append(body.pts[8].to_array())
    if l_leg:
        to_keep.append(body.pts[10].to_array())
        to_keep.append(body.pts[11].to_array())
    if r_leg:
        to_keep.append(body.pts[14].to_array())
        to_keep.append(body.pts[15].to_array())
    if neck_p:
        to_keep.append(body.pts[0].to_array())
    if general:
        to_keep2.append(middle.to_array())

    def refresh_rot(_):
        middle = Limb(body.pts[9], body.pts[13]).middle()
        if (not abs(scat2.x[0] - scat3.x[0]) < 15
            ) or not (abs(scat2.y[0] - scat3.y[0]) < 15):
            o = body.pts[1]
            a = Point(scat2.x[-1], scat2.y[-1]).angle(o) - middle.angle(o)
            body.rotate(a)

            middle = Limb(body.pts[9], body.pts[13]).middle()

            i = 0
            if l_arm:
                to_keep[i] = body.pts[3].to_array()
                to_keep[i + 1] = body.pts[4].to_array()
                i += 2
            if r_arm:
                to_keep[i] = body.pts[7].to_array()
                to_keep[i + 1] = body.pts[8].to_array()
                i += 2
            if l_leg:
                to_keep[i] = body.pts[10].to_array()
                to_keep[i + 1] = body.pts[11].to_array()
                i += 2
            if r_leg:
                to_keep[i] = body.pts[14].to_array()
                to_keep[i + 1] = body.pts[15].to_array()
                i += 2
            if neck_p:
                to_keep[i] = body.pts[0].to_array()
                i += 1
            if general:
                to_keep2[0] = [scat2.x[0], scat2.y[0]]

            scat.x, scat.y = np.transpose(to_keep)
            scat2.x, scat2.y = np.transpose(to_keep2)
            scat3.x, scat3.y = scat2.x, scat2.y

    def refresh(_):


        chest.x, chest.y = np.transpose([body.pts[1].to_array(), body.pts[2].to_array(), body.pts[9].to_array(), \
                                     body.pts[13].to_array(), body.pts[6].to_array(), body.pts[1].to_array()])

        i = 0
        to_update = []
        if l_arm:
            left_arm.x, left_arm.y = [[
                body.pts[2].x, scat.x[i], scat.x[i + 1]
            ], [body.pts[2].y, scat.y[i], scat.y[i + 1]]]
            to_update.append(3)
            to_update.append(4)
            i += 2
        if r_arm:
            right_arm.x, right_arm.y = [[
                body.pts[6].x, scat.x[i], scat.x[i + 1]
            ], [body.pts[6].y, scat.y[i], scat.y[i + 1]]]
            to_update.append(7)
            to_update.append(8)
            i += 2
        if l_leg:
            left_leg.x, left_leg.y = [[
                body.pts[9].x, scat.x[i], scat.x[i + 1]
            ], [body.pts[9].y, scat.y[i], scat.y[i + 1]]]
            to_update.append(10)
            to_update.append(11)
            i += 2
        if r_leg:
            right_leg.x, right_leg.y = [[
                body.pts[13].x, scat.x[i], scat.x[i + 1]
            ], [body.pts[13].y, scat.y[i], scat.y[i + 1]]]
            to_update.append(14)
            to_update.append(15)
            i += 2
        if neck_p:
            to_update.append(0)
            neck.x, neck.y = [[body.pts[1].x, scat.x[i]],
                              [body.pts[1].y, scat.y[i]]]

        head.x = np.cos(np.linspace(0, 2 * np.pi, 100)) * 60 + body.pts[0].x
        head.y = np.sin(np.linspace(0, 2 * np.pi, 100)) * 65 + body.pts[0].y

        #update body
        for i in range(len(to_update)):
            body.pts[to_update[i]].x = scat.x[i]
            body.pts[to_update[i]].y = scat.y[i]

        return

    scales = {
        'x': bqp.LinearScale(min=0, max=1000),
        'y': bqp.LinearScale(min=1000, max=0)
    }

    marks = []

    #movable points: arms first, left side first
    scat = bqp.Scatter(scales=scales,
                       enable_move=True,
                       update_on_move=True,
                       stroke_width=7)
    scat.x, scat.y = np.transpose(to_keep)
    if general:
        scat2 = bqp.Scatter(scales=scales,
                            enable_move=True,
                            update_on_move=True,
                            stroke_width=7)
        scat2.x, scat2.y = np.transpose(to_keep2)
        scat3 = bqp.Scatter(scales=scales,
                            enable_move=False,
                            update_on_move=False,
                            stroke_width=0)
        scat3.x, scat3.y = scat2.x, scat2.y

    marks.append(scat)
    if general:
        marks.append(scat2)

    #draw the chest
    chest = bqp.Lines(scales=scales)
    chest.x, chest.y = np.transpose([body.pts[1].to_array(), body.pts[2].to_array(), body.pts[9].to_array(), \
                                     body.pts[13].to_array(), body.pts[6].to_array(), body.pts[1].to_array()])
    marks.append(chest)

    #draw the head
    head = bqp.Lines(scales=scales)
    head.x = np.cos(np.linspace(0, 2 * np.pi, 100)) * 60 + body.pts[0].x
    head.y = np.sin(np.linspace(0, 2 * np.pi, 100)) * 65 + body.pts[0].y
    marks.append(head)

    i = 0
    #draw the left arm
    left_arm = bqp.Lines(scales=scales)
    if l_arm:
        left_arm.x, left_arm.y = [[body.pts[2].x, scat.x[i], scat.x[i + 1]],
                                  [body.pts[2].y, scat.y[i], scat.y[i + 1]]]
        i += 2
    else:
        left_arm.x, left_arm.y = [[
            body.pts[2].x, body.pts[3].x, body.pts[4].x
        ], [body.pts[2].y, body.pts[3].y, body.pts[4].y]]
    marks.append(left_arm)

    #draw the right arm
    right_arm = bqp.Lines(scales=scales)
    if r_arm:
        right_arm.x, right_arm.y = [[body.pts[6].x, scat.x[i], scat.x[i + 1]],
                                    [body.pts[6].y, scat.y[i], scat.y[i + 1]]]
        i += 2
    else:
        right_arm.x, right_arm.y = [[
            body.pts[6].x, body.pts[7].x, body.pts[8].x
        ], [body.pts[6].y, body.pts[7].y, body.pts[8].y]]

    marks.append(right_arm)

    #draw the left leg
    left_leg = bqp.Lines(scales=scales)
    if l_leg:
        left_leg.x, left_leg.y = [[body.pts[9].x, scat.x[i], scat.x[i + 1]],
                                  [body.pts[9].y, scat.y[i], scat.y[i + 1]]]
        i += 2
    else:
        left_leg.x, left_leg.y = [[
            body.pts[9].x, body.pts[10].x, body.pts[11].x
        ], [body.pts[9].y, body.pts[10].y, body.pts[11].y]]
    marks.append(left_leg)

    #draw the right leg
    right_leg = bqp.Lines(scales=scales)
    if r_leg:
        right_leg.x, right_leg.y = [[body.pts[13].x, scat.x[i], scat.x[i + 1]],
                                    [body.pts[13].y, scat.y[i], scat.y[i + 1]]]
        i += 2
    else:
        right_leg.x, right_leg.y = [[
            body.pts[13].x, body.pts[14].x, body.pts[15].x
        ], [body.pts[13].y, body.pts[14].y, body.pts[15].y]]
    marks.append(right_leg)

    #draw the neck
    neck = bqp.Lines(scales=scales)
    if neck_p:
        neck.x, neck.y = [[body.pts[1].x, scat.x[i]],
                          [body.pts[1].y, scat.y[i]]]
        i += 1
    else:
        neck.x, neck.y = [[body.pts[1].x, body.pts[0].x],
                          [body.pts[1].y, body.pts[0].y]]
    marks.append(neck)

    scat.observe(refresh, names=['x', 'y'])
    if general:
        scat2.observe(refresh_rot, names=['x', 'y'])

    return bqp.Figure(marks=marks, padding_y=0., min_height=750, min_width=750)
Ejemplo n.º 20
0
#def_tt_daughter = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '3.0f'], labels=['time', species['daughter_short'][init_species_ind]])
def_tt_parent = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '.3f'], labels=['time', 'amount of parent isotope'])
def_tt_daughter = bq.Tooltip(fields=['x', 'y'], formats=['.2f', '.3f'], labels=['time', 'amount of daughter isotope'])

# Define the Lines and Scatter plots
# NOTE: Scatter only necessary to allow tooltips to function.
init_x = decay_data['time']*species['half-lives'][init_species_ind]
if Plot_all_times:
    init_parent = decay_data['Parent']
    init_daughter = decay_data['Daughter']
else:
    init_parent = decay_data['Parent'][0:init_time_idx]
    init_daughter = decay_data['Daughter'][0:init_time_idx]
    
pts_parent = bq.Scatter(x=init_x, y=init_parent,
                      scales={'x': x_time, 'y': y_number}, marker='circle', default_size=2,
                      display_legend=False, colors=['red'], labels=[species['parent_short'][init_species_ind]], 
                      tooltip=def_tt_parent)
pts_daughter = bq.Scatter(x=init_x, y=init_daughter,
                        scales={'x': x_time, 'y': y_number}, marker='circle', default_size=2,
                        display_legend=False, colors=['blue'], labels=[species['daughter_short'][init_species_ind]],
                        tooltip=def_tt_daughter)
line_parent = bq.Lines(x=init_x, y=init_parent, 
                       scales={'x': x_time, 'y': y_number}, display_legend=True, colors=['red'], 
                       labels=[species['parent_short'][init_species_ind]], )
line_daughter = bq.Lines(x=init_x, y=init_daughter, 
                         scales={'x': x_time, 'y': y_number}, display_legend=True, colors=['blue'], 
                         labels=[species['daughter_short'][init_species_ind]] )

# Set up a vertical line on this plot to indicate the current time
times_x = [init_time, init_time]
times_y = [0, N_parent]
Ejemplo n.º 21
0
class Plot_interface(object):
    """Class to handle map and plot interaction"""

    # Declare class attributes
    pyccd_flag = False
    pyccd_flag2 = False
    current_band = ''
    band_index1 = 4
    band_index2 = 4
    click_col = ''
    point_color = ['#43a2ca']
    click_df = pd.DataFrame()
    sample_col = ''
    sample_df = pd.DataFrame()
    PyCCDdf = pd.DataFrame()
    table = pd.DataFrame()
    band_list = ['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2']
    year_range = [1986, 2018]
    doy_range = [1, 365]
    step = 1  #in years

    # Create widget controls
    next_pt = Button(value=False, description='Next point', disabled=False)
    previous_pt = Button(value=False,
                         description='Previous point',
                         disabled=False)
    pyccd_button = Button(value=False,
                          description='Run PyCCD 1',
                          disabled=False)
    pyccd_button2 = Button(value=False,
                           description='Run PyCCD 2',
                           disabled=False)
    band_selector1 = Dropdown(
        options=['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2'],
        description='Select band',
        value=None)
    band_selector2 = Dropdown(
        options=['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2'],
        description='Select band',
        value=None)
    image_band_1 = Dropdown(
        options=['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2'],
        description='Red:',
        value='SWIR1')
    image_band_2 = Dropdown(
        options=['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2'],
        description='Green:',
        value='NIR')
    image_band_3 = Dropdown(
        options=['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2'],
        description='Blue:',
        value='RED')
    stretch_min = FloatText(value=0, description='Min:', disabled=False)
    stretch_max = FloatText(value=6000, description='Min:', disabled=False)

    # Clear layers on map
    clear_layers = Button(value=False, description='Clear Map', disabled=False)

    # Color points by DOY
    color_check = widgets.Checkbox(value=False,
                                   description='Color DOY',
                                   disabled=False)

    idBox = widgets.Text(value='0', description='ID:', disabled=False)

    ylim = widgets.IntRangeSlider(value=[0, 4000],
                                  min=0,
                                  max=10000,
                                  step=500,
                                  description='YLim:',
                                  disabled=False,
                                  continuous_update=False,
                                  orientation='horizontal',
                                  readout=True,
                                  readout_format='d')

    xlim = widgets.IntRangeSlider(value=[2000, 2018],
                                  min=1986,
                                  max=2018,
                                  step=1,
                                  description='XLim:',
                                  disabled=False,
                                  continuous_update=False,
                                  orientation='horizontal',
                                  readout=True,
                                  readout_format='d')

    ylim2 = widgets.IntRangeSlider(value=[0, 4000],
                                   min=0,
                                   max=10000,
                                   step=500,
                                   description='YLim:',
                                   disabled=False,
                                   continuous_update=False,
                                   orientation='horizontal',
                                   readout=True,
                                   readout_format='d')

    xlim2 = widgets.IntRangeSlider(value=[2000, 2018],
                                   min=1986,
                                   max=2018,
                                   step=1,
                                   description='XLim:',
                                   disabled=False,
                                   continuous_update=False,
                                   orientation='horizontal',
                                   readout=True,
                                   readout_format='d')

    coords_label = Label()
    pt_message = HTML("Current ID: ")
    time_label = HTML(value='')
    selected_label = HTML("ID of selected point")
    hover_label = HTML("test value")
    text_brush = HTML(value='Selected year range:')
    kml_link = HTML(value='KML:')
    error_label = HTML(value='Load a point')

    # Create map including streets and satellite and controls
    m = ipyleaflet.Map(zoom=5,
                       layout={'height': '400px'},
                       center=(3.3890701010382958, -67.32297252983098),
                       dragging=True,
                       close_popup_on_click=False,
                       basemap=ipyleaflet.basemaps.Esri.WorldStreetMap)

    streets = ipyleaflet.basemap_to_tiles(
        ipyleaflet.basemaps.Esri.WorldImagery)
    m.add_layer(streets)

    dc = ipyleaflet.DrawControl(marker={'shapeOptions': {
        'color': '#ff0000'
    }},
                                polygon={},
                                circle={},
                                circlemarker={},
                                polyline={})

    # Table widget
    table_widget = qgrid.show_grid(table, show_toolbar=False)

    # Set plots
    # Plot scales. HERE
    lc1_x = bqplot.DateScale(min=datetime.date(xlim.value[0], 2, 1),
                             max=datetime.date(xlim.value[1], 1, 1))

    # DOY scale
    lc1_x3 = bqplot.LinearScale(min=0, max=365)

    lc2_y = bqplot.LinearScale(min=ylim.value[0], max=ylim.value[1])

    lc1_x2 = bqplot.DateScale(min=datetime.date(xlim.value[0], 2, 1),
                              max=datetime.date(xlim.value[1], 1, 1))
    lc2_y2 = bqplot.LinearScale(min=ylim.value[0], max=ylim.value[1])

    # Main scatter plot for samples
    lc2 = bqplot.Scatter(x=[],
                         y=[],
                         scales={
                             'x': lc1_x,
                             'y': lc2_y
                         },
                         size=[1, 1],
                         interactions={
                             'click': 'select',
                             'hover': 'tooltip'
                         },
                         selected_style={
                             'opacity': 1.0,
                             'fill': 'DarkOrange',
                             'stroke': 'Red'
                         },
                         unselected_style={'opacity': 0.5},
                         display_legend=True,
                         labels=['Sample point'])

    # Pyccd model fit
    lc4 = bqplot.Lines(
        x=[],
        y=[],
        colors=['black'],
        stroke_width=3,
        scales={
            'x': lc1_x,
            'y': lc2_y
        },
        size=[1, 1],
    )

    # Pyccd model break
    lc5 = bqplot.Scatter(x=[],
                         y=[],
                         marker='triangle-up',
                         colors=['red'],
                         scales={
                             'x': lc1_x,
                             'y': lc2_y
                         },
                         size=[1, 1],
                         display_legend=False,
                         labels=['Model Endpoint'])

    # Scatter plot for clicked points in map
    lc3 = bqplot.Scatter(x=[],
                         y=[],
                         scales={
                             'x': lc1_x2,
                             'y': lc2_y2
                         },
                         size=[1, 1],
                         colors=['gray'],
                         interactions={
                             'click': 'select',
                             'hover': 'tooltip'
                         },
                         selected_style={
                             'opacity': 1.0,
                             'fill': 'DarkOrange',
                             'stroke': 'Red'
                         },
                         unselected_style={'opacity': 0.5},
                         display_legend=True,
                         labels=['Clicked point'])

    # Pyccd model fit for clicked point
    lc6 = bqplot.Lines(
        x=[],
        y=[],
        colors=['black'],
        stroke_width=3,
        scales={
            'x': lc1_x2,
            'y': lc2_y2
        },
        size=[1, 1],
    )

    # Pyccd model break for clicked point
    lc7 = bqplot.Scatter(x=[],
                         y=[],
                         marker='triangle-up',
                         colors=['red'],
                         scales={
                             'x': lc1_x2,
                             'y': lc2_y2
                         },
                         size=[1, 1],
                         display_legend=False,
                         labels=['Model Endpoint'])

    # Scatter for sample DOY
    lc8 = bqplot.Scatter(x=[],
                         y=[],
                         scales={
                             'x': lc1_x3,
                             'y': lc2_y
                         },
                         size=[1, 1],
                         interactions={
                             'click': 'select',
                             'hover': 'tooltip'
                         },
                         selected_style={
                             'opacity': 1.0,
                             'fill': 'DarkOrange',
                             'stroke': 'Red'
                         },
                         unselected_style={'opacity': 0.5},
                         display_legend=True,
                         labels=['Sample point'])

    # Plot axes.
    x_ax1 = bqplot.Axis(label='Date',
                        scale=lc1_x,
                        num_ticks=6,
                        tick_format='%Y')
    x_ax2 = bqplot.Axis(label='Date',
                        scale=lc1_x2,
                        num_ticks=6,
                        tick_format='%Y')
    x_ax3 = bqplot.Axis(label='DOY', scale=lc1_x3, num_ticks=6)

    x_ay1 = bqplot.Axis(label='SWIR1', scale=lc2_y, orientation='vertical')
    x_ay2 = bqplot.Axis(label='SWIR1', scale=lc2_y2, orientation='vertical')

    # Create a figure for sample points.
    fig = bqplot.Figure(marks=[lc2, lc4, lc5],
                        axes=[x_ax1, x_ay1],
                        layout={
                            'height': '300px',
                            'width': '100%'
                        },
                        title="Sample TS")

    # Create a figure for clicked points.
    fig2 = bqplot.Figure(marks=[lc3, lc6, lc7],
                         axes=[x_ax2, x_ay2],
                         layout={
                             'height': '300px',
                             'width': '100%'
                         },
                         title="Clicked TS")

    # Create a figure for sample DOY.
    fig3 = bqplot.Figure(marks=[lc8],
                         axes=[x_ax3, x_ay1],
                         layout={
                             'height': '300px',
                             'width': '100%'
                         },
                         title="Clicked TS")

    def __init__(self, navigate):
        Plot_interface.navigate = navigate
        Plot_interface.band_index1 = 4
        Plot_interface.band_index2 = 4
        Plot_interface.pyccd_flag = False
        Plot_interface.pyccd_flag2 = False
        Plot_interface.table = None
        # Set up database
        conn = sqlite3.connect(Plot_interface.navigate.dbPath)
        Plot_interface.current_id = Plot_interface.navigate.current_id
        Plot_interface.c = conn.cursor()
        Plot_interface.minv = 0
        Plot_interface.maxv = 6000
        Plot_interface.b1 = 'SWIR1'
        Plot_interface.b2 = 'NIR'
        Plot_interface.b3 = 'RED'

    @classmethod
    def map_point(self):
        gjson = ipyleaflet.GeoJSON(
            data=Plot_interface.navigate.fc_df['geometry'][
                Plot_interface.current_id],
            name="Sample point")
        Plot_interface.m.center = gjson.data['coordinates'][::-1]
        Plot_interface.m.zoom = 12
        Plot_interface.m.add_layer(gjson)
        kmlstr = ee.FeatureCollection(
            ee.Geometry.Point(Plot_interface.navigate.fc_df['geometry'][
                Plot_interface.current_id]['coordinates'])).getDownloadURL(
                    "kml")
        Plot_interface.kml_link.value = "<a '_blank' rel='noopener noreferrer' href={}>KML Link</a>".format(
            kmlstr)

    @classmethod
    def get_ts(self):
        #try:
        Plot_interface.error_label.value = 'Loading'
        Plot_interface.current_band = Plot_interface.band_list[
            Plot_interface.band_index1]
        Plot_interface.sample_col = get_full_collection(
            Plot_interface.navigate.fc_df['geometry'][
                Plot_interface.current_id]['coordinates'],
            Plot_interface.year_range, Plot_interface.doy_range)
        Plot_interface.sample_df = get_df_full(
            Plot_interface.sample_col,
            Plot_interface.navigate.fc_df['geometry'][
                Plot_interface.current_id]['coordinates']).dropna()
        Plot_interface.error_label.value = 'Point loaded!'
        #except:
        #    Plot_interface.error_label.value = 'Point could not be loaded!'

    def clear_map(b):
        Plot_interface.m.clear_layers()
        Plot_interface.m.add_layer(Plot_interface.streets)
        Plot_interface.map_point()

    @classmethod
    def plot_ts(self):
        current_band = Plot_interface.band_list[Plot_interface.band_index1]
        Plot_interface.lc2.x = Plot_interface.sample_df['datetime']
        if Plot_interface.color_check.value == False:
            Plot_interface.lc2.colors = list(Plot_interface.point_color)
            Plot_interface.lc8.colors = list(Plot_interface.point_color)
        else:
            Plot_interface.lc2.colors = list(
                Plot_interface.sample_df['color'].values)
            Plot_interface.lc8.colors = list(
                Plot_interface.sample_df['color'].values)
        Plot_interface.lc2.y = Plot_interface.sample_df[current_band]
        Plot_interface.x_ay1.label = current_band
        Plot_interface.lc4.x = []
        Plot_interface.lc4.y = []
        Plot_interface.lc5.x = []
        Plot_interface.lc5.y = []

        Plot_interface.lc8.x = Plot_interface.sample_df['doy']
        Plot_interface.lc8.y = Plot_interface.sample_df[current_band]

        #if pyccd_flag:
        if Plot_interface.pyccd_flag:
            Plot_interface.run_pyccd(0)

    # Go back or forth between sample points
    def advance(b):
        # Plot point in map
        Plot_interface.lc4.x = []
        Plot_interface.lc4.y = []
        Plot_interface.lc5.x = []
        Plot_interface.lc5.y = []
        Plot_interface.lc5.display_legend = False
        Plot_interface.pyccd_flag = False
        Plot_interface.current_id += 1
        Plot_interface.pt_message.value = "Point ID: {}".format(
            Plot_interface.current_id)
        Plot_interface.map_point()
        Plot_interface.get_ts()
        Plot_interface.plot_ts()
        Plot_interface.change_table(0)
        Plot_interface.navigate.valid.value = False
        Plot_interface.navigate.description = 'Not Saved'

    def decrease(b):
        # Plot point in map
        Plot_interface.lc4.x = []
        Plot_interface.lc4.y = []
        Plot_interface.lc5.x = []
        Plot_interface.lc5.y = []
        Plot_interface.lc5.display_legend = False
        Plot_interface.pyccd_flag = False
        Plot_interface.current_id -= 1
        Plot_interface.pt_message.value = "Point ID: {}".format(
            Plot_interface.current_id)
        Plot_interface.map_point()
        Plot_interface.get_ts()
        Plot_interface.plot_ts()
        Plot_interface.change_table(0)
        Plot_interface.navigate.valid.value = False
        Plot_interface.navigate.description = 'Not Saved'

    def change_table(b):
        # Update the table based on current ID

        # Get header
        cursor = Plot_interface.c.execute('select * from measures')
        names = list(map(lambda x: x[0], cursor.description))
        previous_inputs = pd.DataFrame()
        for i, row in enumerate(
                Plot_interface.c.execute(
                    "SELECT * FROM measures WHERE id = '%s'" %
                    Plot_interface.current_id)):
            previous_inputs[i] = row
        previous_inputs = previous_inputs.T
        if previous_inputs.shape[0] > 0:
            previous_inputs.columns = names
        Plot_interface.table_widget.df = previous_inputs

    # Functions for changing image stretch
    def change_image_band1(change):
        new_band = change['new']
        Plot_interface.b1 = new_band

    def change_image_band2(change):
        new_band = change['new']
        Plot_interface.b2 = new_band

    def change_image_band3(change):
        new_band = change['new']
        Plot_interface.b3 = new_band

    # Band selection for sample point
    def on_band_selection1(change):
        new_band = change['new']
        #global band_index
        band_index = change['owner'].index
        Plot_interface.band_index1 = band_index
        Plot_interface.plot_ts()

    # Band selection for clicked point
    def on_band_selection2(change):
        new_band = change['new']
        band_index = change['owner'].index
        Plot_interface.band_index2 = band_index
        Plot_interface.lc3.x = Plot_interface.click_df['datetime']
        Plot_interface.lc3.y = Plot_interface.click_df[new_band]
        Plot_interface.x_ay2.label = new_band
        if Plot_interface.pyccd_flag2:
            Plot_interface.run_pyccd2(0)

    def change_yaxis(value):
        Plot_interface.lc2_y.min = Plot_interface.ylim.value[0]
        Plot_interface.lc2_y.max = Plot_interface.ylim.value[1]

    def change_xaxis(value):
        Plot_interface.lc1_x.min = datetime.date(Plot_interface.xlim.value[0],
                                                 2, 1)
        Plot_interface.lc1_x.max = datetime.date(Plot_interface.xlim.value[1],
                                                 2, 1)
        Plot_interface.year_range = [
            Plot_interface.xlim.value[0], Plot_interface.xlim.value[1]
        ]

    def change_yaxis2(value):
        Plot_interface.lc2_y2.min = Plot_interface.ylim2.value[0]
        Plot_interface.lc2_y2.max = Plot_interface.ylim2.value[1]

    def change_xaxis2(value):
        Plot_interface.lc1_x2.min = datetime.date(
            Plot_interface.xlim2.value[0], 2, 1)
        Plot_interface.lc1_x2.max = datetime.date(
            Plot_interface.xlim2.value[1], 2, 1)

    def hover_event(self, target):
        Plot_interface.hover_label.value = str(target['data']['x'])

    # Add layer from clicked point in sample TS figure
    def click_event(self, target):
        pt_index = target['data']['index']
        current_band = Plot_interface.band_list[Plot_interface.band_index1]
        image_id = Plot_interface.sample_df['id'].values[pt_index]
        selected_image = ee.Image(
            Plot_interface.sample_col.filterMetadata('system:index', 'equals',
                                                     image_id).first())
        tile_url = GetTileLayerUrl(
            selected_image.visualize(min=Plot_interface.stretch_min.value,
                                     max=Plot_interface.stretch_max.value,
                                     bands=[
                                         Plot_interface.b1, Plot_interface.b2,
                                         Plot_interface.b3
                                     ]))

        Plot_interface.m.add_layer(
            ipyleaflet.TileLayer(url=tile_url, name=image_id))

    # Add layer from clicked point in clicked TS figure
    def click_event2(self, target):
        pt_index = target['data']['index']
        current_band = Plot_interface.band_list[Plot_interface.band_index2]
        #Find clicked image. .values needed to access the nth element of that list instead of indexing by ID
        image_id = Plot_interface.click_df['id'].values[pt_index]
        selected_image = ee.Image(
            Plot_interface.click_col.filterMetadata('system:index', 'equals',
                                                    image_id).first())
        tile_url = GetTileLayerUrl(
            selected_image.visualize(min=Plot_interface.minv,
                                     max=Plot_interface.maxv,
                                     bands=[
                                         Plot_interface.b1, Plot_interface.b2,
                                         Plot_interface.b3
                                     ]))

        Plot_interface.m.add_layer(
            ipyleaflet.TileLayer(url=tile_url, name=image_id))

    # Plot TS from clicked point
    def handle_draw(self, action, geo_json):
        # Get the selected coordinates from the map's drawing control.
        current_band = Plot_interface.band_list[Plot_interface.band_index2]
        coords = geo_json['geometry']['coordinates']
        Plot_interface.click_col = get_full_collection(
            coords, Plot_interface.year_range, Plot_interface.doy_range)
        Plot_interface.click_df = get_df_full(Plot_interface.click_col,
                                              coords).dropna()
        Plot_interface.lc6.x = []
        Plot_interface.lc6.y = []
        Plot_interface.lc7.x = []
        Plot_interface.lc7.y = []
        Plot_interface.lc3.x = Plot_interface.click_df['datetime']
        Plot_interface.lc3.y = Plot_interface.click_df[current_band]

        if Plot_interface.color_check.value == False:
            Plot_interface.lc3.colors = list(Plot_interface.point_color)
        else:
            Plot_interface.lc3.colors = list(
                Plot_interface.click_df['color'].values)

    # Plotting pyccd
    def plot_pyccd(results, band, plotband, dates, yl, ylabel, ts_type):
        mask = np.array(results['processing_mask']).astype(np.bool_)
        predicted_values = []
        prediction_dates = []
        break_dates = []
        start_dates = []

        for num, result in enumerate(results['change_models']):
            days = np.arange(result['start_day'], result['end_day'] + 1)
            prediction_dates.append(days)
            break_dates.append(result['break_day'])
            start_dates.append(result['start_day'])
            intercept = result[list(result.keys())[6 + band]]['intercept']
            coef = result[list(result.keys())[6 + band]]['coefficients']

            predicted_values.append(
                intercept + coef[0] * days +
                coef[1] * np.cos(days * 1 * 2 * np.pi / 365.25) +
                coef[2] * np.sin(days * 1 * 2 * np.pi / 365.25) +
                coef[3] * np.cos(days * 2 * 2 * np.pi / 365.25) +
                coef[4] * np.sin(days * 2 * 2 * np.pi / 365.25) +
                coef[5] * np.cos(days * 3 * 2 * np.pi / 365.25) +
                coef[6] * np.sin(days * 3 * 2 * np.pi / 365.25))

        num_breaks = len(break_dates)

        break_y = [plotband[dates == i][0] for i in break_dates]

        #break_y = [0] * num_breaks
        break_dates_plot = [
            datetime.datetime.fromordinal(i).strftime('%Y-%m-%d %H:%M:%S.%f')
            for i in break_dates
        ]

        plot_dates = np.array(
            [datetime.datetime.fromordinal(i) for i in (dates)])

        # Predicted curves
        all_dates = []
        all_preds = []
        for _preddate, _predvalue in zip(prediction_dates, predicted_values):
            all_dates.append(_preddate)
            all_preds.append(_predvalue)

        all_preds = [item for sublist in all_preds for item in sublist]
        all_dates = [item for sublist in all_dates for item in sublist]

        date_ord = [
            datetime.datetime.fromordinal(i).strftime('%Y-%m-%d %H:%M:%S.%f')
            for i in all_dates
        ]
        _x = np.array(date_ord, dtype='datetime64')
        _y = all_preds

        if ts_type == 'sample_ts':
            Plot_interface.lc4.x = _x
            Plot_interface.lc4.y = _y
            Plot_interface.lc5.x = np.array(break_dates_plot,
                                            dtype='datetime64')
            Plot_interface.lc5.y = break_y
        elif ts_type == 'clicked_ts':
            Plot_interface.lc6.x = _x
            Plot_interface.lc6.y = _y
            Plot_interface.lc7.x = np.array(break_dates_plot,
                                            dtype='datetime64')
            Plot_interface.lc7.y = break_y

    # Go to a specific sample
    def go_to_sample(b):
        # Plot point in map
        Plot_interface.lc4.x = []
        Plot_interface.lc4.y = []
        Plot_interface.lc5.x = []
        Plot_interface.lc5.y = []
        Plot_interface.lc5.display_legend = False
        Plot_interface.pyccd_flag = False
        Plot_interface.current_id = int(b.value)
        Plot_interface.pt_message.value = "Point ID: {}".format(
            Plot_interface.current_id)
        Plot_interface.navigate.valid.value = False
        Plot_interface.navigate.description = 'Not Saved'
        Plot_interface.map_point()
        Plot_interface.get_ts()
        Plot_interface.plot_ts()

    # Run pyccd
    def run_pyccd(b):
        # Run pyCCD on current point
        Plot_interface.pyccd_flag = True
        Plot_interface.lc5.display_legend = True
        dfPyCCD = Plot_interface.sample_df

        dfPyCCD['pixel_qa'][dfPyCCD['pixel_qa'] > 4] = 0

        #TODO: Paramaterize everything
        params = {
            'QA_BITPACKED': False,
            'QA_FILL': 255,
            'QA_CLEAR': 0,
            'QA_WATER': 1,
            'QA_SHADOW': 2,
            'QA_SNOW': 3,
            'QA_CLOUD': 4
        }

        dates = np.array(dfPyCCD['ord_time'])
        blues = np.array(dfPyCCD['BLUE'])
        greens = np.array(dfPyCCD['GREEN'])
        reds = np.array(dfPyCCD['RED'])
        nirs = np.array(dfPyCCD['NIR'])
        swir1s = np.array(dfPyCCD['SWIR1'])
        swir2s = np.array(dfPyCCD['SWIR2'])
        thermals = np.array(dfPyCCD['THERMAL'])
        qas = np.array(dfPyCCD['pixel_qa'])
        results = ccd.detect(dates,
                             blues,
                             greens,
                             reds,
                             nirs,
                             swir1s,
                             swir2s,
                             thermals,
                             qas,
                             params=params)

        band_names = [
            'Blue SR', 'Green SR', 'Red SR', 'NIR SR', 'SWIR1 SR', 'SWIR2 SR',
            'THERMAL'
        ]
        plotlabel = band_names[Plot_interface.band_index1]

        plot_arrays = [blues, greens, reds, nirs, swir1s, swir2s]
        plotband = plot_arrays[Plot_interface.band_index1]
        Plot_interface.plot_pyccd(results, Plot_interface.band_index1,
                                  plotband, dates, (0, 4000), 'PyCCD Results',
                                  'sample_ts')

    def run_pyccd2(b):
        # Run pyCCD on current point
        Plot_interface.pyccd_flag2 = True

        # Display the legend
        Plot_interface.lc7.display_legend = True

        dfPyCCD = Plot_interface.click_df

        # First two lines no longer required bc we are removing NA's when we load the TS
        dfPyCCD['pixel_qa'][dfPyCCD['pixel_qa'] > 4] = 0

        #TODO: Paramaterize everything
        params = {
            'QA_BITPACKED': False,
            'QA_FILL': 255,
            'QA_CLEAR': 0,
            'QA_WATER': 1,
            'QA_SHADOW': 2,
            'QA_SNOW': 3,
            'QA_CLOUD': 4
        }

        dates = np.array(dfPyCCD['ord_time'])
        blues = np.array(dfPyCCD['BLUE'])
        greens = np.array(dfPyCCD['GREEN'])
        reds = np.array(dfPyCCD['RED'])
        nirs = np.array(dfPyCCD['NIR'])
        swir1s = np.array(dfPyCCD['SWIR1'])
        swir2s = np.array(dfPyCCD['SWIR2'])
        thermals = np.array(dfPyCCD['THERMAL'])
        qas = np.array(dfPyCCD['pixel_qa'])
        results = ccd.detect(dates,
                             blues,
                             greens,
                             reds,
                             nirs,
                             swir1s,
                             swir2s,
                             thermals,
                             qas,
                             params=params)

        band_names = [
            'Blue SR', 'Green SR', 'Red SR', 'NIR SR', 'SWIR1 SR', 'SWIR2 SR',
            'THERMAL'
        ]
        plotlabel = band_names[Plot_interface.band_index2]

        plot_arrays = [blues, greens, reds, nirs, swir1s, swir2s]
        plotband = plot_arrays[Plot_interface.band_index2]
        Plot_interface.plot_pyccd(results, Plot_interface.band_index2,
                                  plotband, dates, (0, 4000), 'PyCCD Results',
                                  'clicked_ts')

    ylim.observe(change_yaxis)
    xlim.observe(change_xaxis)
    ylim2.observe(change_yaxis2)
    xlim2.observe(change_xaxis2)
    next_pt.on_click(advance)
    previous_pt.on_click(decrease)
    pyccd_button.on_click(run_pyccd)
    pyccd_button2.on_click(run_pyccd2)
    clear_layers.on_click(clear_map)
    band_selector1.observe(on_band_selection1, names='value')
    band_selector2.observe(on_band_selection2, names='value')

    image_band_1.observe(change_image_band1, names='value')
    image_band_2.observe(change_image_band2, names='value')
    image_band_3.observe(change_image_band3, names='value')

    lc2.on_element_click(click_event)
    lc2.tooltip = hover_label
    lc2.on_hover(hover_event)

    lc3.on_element_click(click_event2)
    lc3.tooltip = hover_label
    lc3.on_hover(hover_event)

    idBox.on_submit(go_to_sample)

    dc.on_draw(handle_draw)
    m.add_control(dc)
    m.add_control(ipyleaflet.LayersControl())
Ejemplo n.º 22
0
def plot_signals_low_freq(data, v, w_j, n_days=60):
    signals_dict = signals_low_freq(data, w_j, n_days)
    signals_df = pd.DataFrame(signals_dict, index=["High Freq Signals"]).T

    pos_signals_date, neg_signals_date, exit_signals_date = entry_exit(
        signals_df)

    x_ord = bqplot.DateScale()
    y_sc = bqplot.LinearScale()

    line = bqplot.Lines(x=data.index,
                        y=data.values.squeeze(),
                        scales={
                            'x': x_ord,
                            'y': y_sc
                        },
                        stroke_width=2,
                        display_legend=False,
                        labels=['Underlying TS'])
    scatter1 = bqplot.Scatter(x=pd.DatetimeIndex(pos_signals_date),
                              y=data.loc[pos_signals_date].squeeze(),
                              colors=["green"],
                              scales={
                                  'x': x_ord,
                                  'y': y_sc
                              },
                              marker='triangle-up',
                              default_size=25)
    scatter2 = bqplot.Scatter(x=pd.DatetimeIndex(neg_signals_date),
                              y=data.loc[neg_signals_date].squeeze(),
                              colors=["red"],
                              scales={
                                  'x': x_ord,
                                  'y': y_sc
                              },
                              marker='triangle-down',
                              default_size=25)
    scatter3 = bqplot.Scatter(x=pd.DatetimeIndex(exit_signals_date),
                              y=data.loc[exit_signals_date].squeeze(),
                              colors=["white"],
                              scales={
                                  'x': x_ord,
                                  'y': y_sc
                              },
                              marker='square',
                              default_size=25)
    ax_x = bqplot.Axis(scale=x_ord)
    ax_y = bqplot.Axis(scale=y_sc,
                       orientation='vertical',
                       tick_format='0.2f',
                       grid_lines='solid')

    fig = bqplot.Figure(marks=[line, scatter1, scatter2, scatter3],
                        axes=[ax_x, ax_y])
    pz = bqplot.PanZoom(scales={'x': [x_ord], 'y': [y_sc]})
    pzx = bqplot.PanZoom(scales={'x': [x_ord]})
    pzy = bqplot.PanZoom(scales={
        'y': [y_sc],
    })

    #
    """zoom_interacts = ToggleButtons(
                                            options=OrderedDict([
                                                ('xy ', pz), 
                                                ('x ', pzx), 
                                                ('y ', pzy),   
                                                (' ', None)]),
                                                icons = ["arrows", "arrows-h", "arrows-v", "stop"],
                                                tooltips = ["zoom/pan in x & y", "zoom/pan in x only", "zoom/pan in y only", "cancel zoom/pan"]
                                            )
    zoom_interacts.style.button_width = '50px'

    ResetZoomButton = Button(
        description='',
        disabled=False,
        button_style='', # 'success', 'info', 'warning', 'danger' or ''
        tooltip='Reset zoom',
        icon='arrows-alt'
    )"""
    def resetZoom(new):
        # Reset the x and y axes on the figure
        fig.axes[0].scale.min = None
        fig.axes[1].scale.min = None
        fig.axes[0].scale.max = None
        fig.axes[1].scale.max = None

    ResetZoomButton.on_click(resetZoom)
    ResetZoomButton.layout.width = '95%'

    link((zoom_interacts, 'value'), (fig, 'interaction'))
    display(fig, zoom_interacts)
#x_lin.max = 0.2 # controls the length of the x-axis
#y_lin.max = 0.1 # controls the length of the y-axis

x_ax = bqp.Axis(label='risk', scale=x_lin, grid_lines='solid')
x_ay = bqp.Axis(label='return',
                scale=y_lin,
                orientation='vertical',
                grid_lines='solid')

def_tt = bqp.Tooltip(fields=['x', 'y'], formats=['.3f', '.3f'])

scatt = bqp.Scatter(x=[],
                    y=[],
                    scales={
                        'x': x_lin,
                        'y': y_lin
                    },
                    tooltip=def_tt,
                    display_legend=True,
                    labels=['Efficient Portfolio'],
                    colors=['#1B84ED'])
scatt_view = bqp.Scatter(x=[],
                         y=[],
                         scales={
                             'x': x_lin,
                             'y': y_lin
                         },
                         tooltip=def_tt,
                         display_legend=True,
                         labels=['Efficient Portfolio with Views Portfolio'],
                         colors=['#F39F41'])
Ejemplo n.º 24
0
k1 = r*np.sin(np.pi/180 * phi)
r2 = 10
d2 = -r2*np.cos(np.pi/180 * phi)
k2 = -r2*np.sin(np.pi/180 * phi)

# Axes for stars
# Sets axis scale for x and y to 
sc_x = bq.LinearScale(min=-10,max=10)
sc_y = bq.LinearScale(min=-10,max=10)

# Sets up the axes, grid-lines are set to black so that they blend in with the background.
x_ax = bq.Axis(scale=sc_x, grid_color='white', num_ticks=0)
y_ax = bq.Axis(scale=sc_y, orientation='vertical', grid_color='white', num_ticks=0)

# Create the stars and the figure to contain them
star1 = bq.Scatter(x=[d1], y=[k1], scales={'x': sc_x, 'y': sc_y}, colors=['blue'],default_size=500)
star2 = bq.Scatter(x=[d2], y=[k2], scales={'x': sc_x, 'y': sc_y}, colors=['red'])
# Gives reference to Earth
to_earth = bq.Lines(x = [[5,10],[10,9],[10,9]], y = [[6,6],[6,7],[6,5]], scales={'x': sc_x, 'y': sc_y}, colors=['yellow'])
earth_label = bq.Label(text=["To Earth"], x=[5], y=[4], colors=['yellow'], scales={'x': sc_x, 'y': sc_y})
fig_star = bq.Figure(title='Stellar System Top-Down View', marks=[star1,star2,to_earth,earth_label], axes=[x_ax, y_ax], 
                padding_y=0, animation=100, background_style={'fill' : 'black'},
               min_aspect_ratio=1, max_aspect_ratio=1)

fig_star.layout.height = fig.layout.width
fig_star.layout.width = fig.layout.width

## Update the widgets
dval1.observe(update, names=['value'])
gval1.observe(update, names=['value'])
bval1.observe(update, names=['value'])
Ejemplo n.º 25
0
a = a * 700

b = b * 30

x_sc = bqplot.LinearScale()
y_sc = bqplot.LinearScale()

ax_x = bqplot.Axis(scale=x_sc, label="X-value")
ax_y = bqplot.Axis(scale=y_sc, label="Y-value", orientation='vertical')

scatters1 = bqplot.Scatter(x=a[:, 0],
                           y=a[:, 1],
                           scales={
                               'x': x_sc,
                               'y': y_sc
                           },
                           default_size=5,
                           colors=["navy"],
                           sizes=[10])
scatters2 = bqplot.Scatter(x=b[:, 0],
                           y=b[:, 1],
                           scales={
                               'x': x_sc,
                               'y': y_sc
                           },
                           default_size=2,
                           colors=['orange'],
                           sizes=[5])

fig = bqplot.Figure(marks=[scatters1, scatters2], axes=[ax_x, ax_y])
Ejemplo n.º 26
0
class NetworkViewBase(ipyw.VBox):
    """An interactive, navigable display of the network.

    The NetworkViewBase class simply generates an interactive figure,
    without ipywidget buttons and dropdown menus. The NetworkModel extends
    this class, adding widget controls.

    Parameters
    ----------
    case : PSSTCase
        An instance of a PSST case.
    model : NetworkModel
        An instance of NetworkModel can be passed instead
        of a case. (Should not pass both.)

    Attributes
    ----------
    model : NetworkModel
        An instance of NetworkModel, containing state information for network.
    show_gen : Bool
        Display the points representing generators and connected lines.
    show_load : Bool
        Display the points representing loads and connected lines.
    show_bus_names : Bool
        Display names next to buses.
    show_gen_names : Bool
        Display names next to generators.
    show_load_names : Bool
        Display names next to loads.
    """

    model = t.Instance(NetworkModel)
    show_gen = t.Bool(default_value=True)
    show_load = t.Bool(default_value=True)

    show_background_lines = t.Bool(default_value=True)
    show_bus_names = t.Bool(default_value=True)
    show_gen_names = t.Bool(default_value=True)
    show_load_names = t.Bool(default_value=True)

    def __init__(self, case=None, model=None, *args, **kwargs):
        super(NetworkViewBase, self).__init__(*args, **kwargs)

        ##################
        # Load and Store Model
        ##################
        if model and case:
            warnings.warn(
                'You should pass a case OR a model, not both. The case argument you passed is being ignored.'
            )
        if not model:
            self.model = NetworkModel(case)
        else:
            self.model = model

        ##################
        # Scale Marks
        ##################
        self._scale_x = bq.LinearScale(min=self.model.x_min_view,
                                       max=self.model.x_max_view)
        self._scale_y = bq.LinearScale(min=self.model.y_min_view,
                                       max=self.model.y_max_view)
        self._scales = {
            'x': self._scale_x,
            'y': self._scale_y,
        }

        # Temp/experimental.
        self._my_scales = {
            'x': self._scale_x,
            'y': self._scale_y,
            'color': bq.ColorScale(colors=['Red', 'Green']),
        }

        ##################
        # Scatter Marks
        ##################
        # Tooltip
        scatter_tooltip = bq.Tooltip(fields=['name'])

        # Create Bus Scatter
        self._bus_scatter = bq.Scatter(
            x=self.model.bus_x_vals,
            y=self.model.bus_y_vals,
            scales=self._scales,
            names=self.model.bus_names,
            marker='rectangle',
            default_size=180,
            colors=[style.graph_main_1],
            default_opacities=[0.6],
            selected_style={
                'opacity': 0.8,
                'fill': style.graph_selected_1,
                'stroke': style.graph_accent_1
            },
            selected=self._get_indices_view_buses(),
            tooltip=scatter_tooltip,
        )
        # Create Gen Scatter
        self._gen_scatter = bq.Scatter(
            x=self.model.gen_x_vals,
            y=self.model.gen_y_vals,
            scales=self._scales,
            names=self.model.gen_names,
            marker='circle',
            default_size=150,
            colors=[style.graph_main_2],
            default_opacities=[0.6],
            selected_style={
                'opacity': 0.8,
                'fill': style.graph_selected_2,
                'stroke': style.graph_accent_2
            },
            tooltip=scatter_tooltip,
        )
        # Create Load Scatter
        self._load_scatter = bq.Scatter(
            x=self.model.load_x_vals,
            y=self.model.load_y_vals,
            scales=self._scales,
            names=self.model.load_names,
            marker='triangle-up',
            default_size=140,
            colors=[style.graph_main_3],
            default_opacities=[0.6],
            selected_style={
                'opacity': 0.8,
                'fill': style.graph_selected_3,
                'stroke': style.graph_accent_3
            },
            tooltip=scatter_tooltip,
        )

        ##################
        # Line Marks
        ##################

        # import numpy as np
        # self.vals = np.random.randint(0, 2, size=len(self.model.bus_x_edges))

        # Create Bus Lines
        self._bus_lines = bq.Lines(
            x=self.model.bus_x_edges,
            y=self.model.bus_y_edges,
            scales=self._scales,
            # colors=vals.
            colors=[style.graph_line_1],
            stroke_width=2,
            line_style='solid',
            opacities=[0.8],
        )
        # Create Gen Lines
        self._gen_lines = bq.Lines(
            x=self.model.gen_x_edges,
            y=self.model.gen_y_edges,
            scales=self._scales,
            # colors=['black'],
            colors=[style.graph_line_2],
            stroke_width=1.5,
            line_style='solid',
            opacities=[0.8])
        # Create Load Lines
        self._load_lines = bq.Lines(
            x=self.model.load_x_edges,
            y=self.model.load_y_edges,
            scales=self._scales,
            # colors=['black'],
            colors=[style.graph_line_3],
            stroke_width=1.5,
            line_style='solid',
            opacities=[0.8],
        )
        # All lines, in background
        self._background_lines = bq.Lines(
            x=self.model.x_edges,
            y=self.model.y_edges,
            scales=self._scales,
            colors=['gray'],
            stroke_width=1,
            line_style='dotted',
            opacities=[0.05],
            marker='circle',
            marker_size=30,
        )

        ##################
        # Bqplot Figure
        ##################
        self._all_marks = OrderedDict({
            'background_lines': self._background_lines,
            'bus_lines': self._bus_lines,
            'gen_lines': self._gen_lines,
            'load_lines': self._load_lines,
            'bus_scatter': self._bus_scatter,
            'gen_scatter': self._gen_scatter,
            'load_scatter': self._load_scatter,
        })

        fig_margin = {'top': 0, 'bottom': 0, 'left': 0, 'right': 0}
        self._figure = bq.Figure(
            marks=list(self._all_marks.values()),
            animation_duration=0,
            fig_margin=fig_margin,
        )

        # Set as children of VBox
        self.children = [self._figure]

        # Set defaults, triggering callback functions (setting proper children)
        self.show_background_lines = False
        self.show_gen_names = False
        self.show_load_names = False

        ##################
        # Link Traits
        ##################
        # Link Scales
        t.link((self.model, 'x_min_view'), (self._scale_x, 'min'))
        t.link((self.model, 'x_max_view'), (self._scale_x, 'max'))
        t.link((self.model, 'y_min_view'), (self._scale_y, 'min'))
        t.link((self.model, 'y_max_view'), (self._scale_y, 'max'))

        # Link Bus Scatter
        t.link((self.model, 'bus_x_vals'), (self._bus_scatter, 'x'))
        t.link((self.model, 'bus_y_vals'), (self._bus_scatter, 'y'))
        t.link((self.model, 'bus_names'), (self._bus_scatter, 'names'))

        # Link Gen Scatter
        t.link((self.model, 'gen_x_vals'), (self._gen_scatter, 'x'))
        t.link((self.model, 'gen_y_vals'), (self._gen_scatter, 'y'))
        t.link((self.model, 'gen_names'), (self._gen_scatter, 'names'))

        # Link Load Scatter
        t.link((self.model, 'load_x_vals'), (self._load_scatter, 'x'))
        t.link((self.model, 'load_y_vals'), (self._load_scatter, 'y'))
        t.link((self.model, 'load_names'), (self._load_scatter, 'names'))

        # Link Bus Lines
        t.link((self.model, 'bus_x_edges'), (self._bus_lines, 'x'))
        t.link((self.model, 'bus_y_edges'), (self._bus_lines, 'y'))

        # Link Gen Lines
        t.link((self.model, 'gen_x_edges'), (self._gen_lines, 'x'))
        t.link((self.model, 'gen_y_edges'), (self._gen_lines, 'y'))

        # Link Load Lines
        t.link((self.model, 'load_x_edges'), (self._load_lines, 'x'))
        t.link((self.model, 'load_y_edges'), (self._load_lines, 'y'))

        # Link names to show
        t.link((self, 'show_bus_names'), (self._bus_scatter, 'display_names'))
        t.link((self, 'show_gen_names'), (self._gen_scatter, 'display_names'))
        t.link((self, 'show_load_names'),
               (self._load_scatter, 'display_names'))

        # Set callbacks for clicking a bus
        # Click -> updates `model.view_buses` -> updates `bus_scatter.selected`
        self._bus_scatter.on_element_click(self._callback_bus_clicked)
        self.model.observe(self._callback_view_buses_change,
                           names='view_buses')

        # Callbacks for clicking a load/gen node (Simply flashes selected)
        self._gen_scatter.on_element_click(self._callback_nonebus_clicked)
        self._load_scatter.on_element_click(self._callback_nonebus_clicked)