Пример #1
0
def _create_plot_component(obj):
    # Spectrogram plot

    obj.data = fr.getDataSets(".chi")
    frequencies = obj.data[0][0]
    index = ArrayDataSource(data=frequencies)

    values = [obj.data[i][1] for i in xrange(len(obj.data))]
    print len(obj.data[1][1])
    print len(obj.data)
    p = WaterfallRenderer(
        index=index,
        values=values,
        index_mapper=LinearMapper(range=DataRange1D(low=0, high=SPECTROGRAM_LENGTH)),
        value_mapper=LinearMapper(range=DataRange1D(low=0, high=SPECTROGRAM_LENGTH)),
        x2_mapper=LinearMapper(low_pos=0, high_pos=100, range=DataRange1D(low=10.0, high=101.0)),
        y2_mapper=LinearMapper(low_pos=0, high_pos=100, range=DataRange1D(low=0, high=600000)),
    )
    spectrogram_plot = p
    obj.spectrogram_plot = p
    dummy = Plot()
    dummy.padding = 50
    dummy.index_axis.mapper.range = p.index_mapper.range
    dummy.index_axis.title = "Frequency (hz)"
    dummy.add(p)

    c2 = VPlotContainer()
    c2.add(dummy)

    return c2
Пример #2
0
 def _plot_default(self):
     plot_data = ArrayPlotData(index=self.sigma, value=self.mu)
     self.plot_data = plot_data
     plot = Plot(data=plot_data)
     line = create_line_plot([self.sigma, self.mu],
                             add_grid=True,
                             value_bounds=(min(self.mean), max(self.mean)),
                             add_axis=True,
                             index_sort='ascending',
                             orientation='h')
     scatter = create_scatter_plot(
         [np.sqrt(np.diag(self.covar)),
          np.squeeze(self.mean)],
         index_bounds=(line.index_range.low, line.index_range.high),
         value_bounds=(line.value_range.low, line.value_range.high),
         marker='circle',
         color='blue')
     plot.add(line)
     left, bottom = line.underlays[-2:]
     left.title = 'Return'
     bottom.title = 'Risk'
     plot.add(scatter)
     cursor = CursorTool(line, drag_button='left', color='blue')
     self.cursor = cursor
     #cursor.current_position = self.sigma[0], self.mu[0]
     line.overlays.append(cursor)
     line.tools.append(PanTool(line, drag_button='right'))
     #line.overlays.append(ZoomTool(line))
     return plot
Пример #3
0
    def _signals_plot_default(self):
        print('_signals_plot_default')
        """Create the Plot instance."""

        plot = Plot()

        plot.add(self.signals_renderer)

        x_axis = PlotAxis(component=plot,
                          mapper=self.signals_renderer.index_mapper,
                          orientation='bottom')
        # y_axis = PlotAxis(component=plot,
        #                     mapper=self.signals_renderer.value_mapper,
        #                     orientation='left')
        plot.overlays.extend([x_axis])

        plot.origin_axis_visible = False
        plot.padding_top = 0
        plot.padding_left = 0
        plot.padding_right = 0
        plot.padding_bottom = 50
        plot.border_visible = False
        plot.bgcolor = "white"
        plot.use_downsampling = True
        return plot
Пример #4
0
class MyPlot(HasTraits):
    """ Displays a plot with a few buttons to control which overlay
        to display
    """
    plot = Instance(Plot)

    traits_view = View(Item('plot', editor=ComponentEditor(), show_label=False),
                        resizable=True)

    def __init__(self, x_index, y_index, data, **kw):
        super(MyPlot, self).__init__(**kw)

        # Create the data source for the MultiLinePlot.
        ds = MultiArrayDataSource(data=data)

        xs = ArrayDataSource(x_index, sort_order='ascending')
        xrange = DataRange1D()
        xrange.add(xs)

        ys = ArrayDataSource(y_index, sort_order='ascending')
        yrange = DataRange1D()
        yrange.add(ys)

        mlp = MultiLinePlot(
                        index = xs,
                        yindex = ys,
                        index_mapper = LinearMapper(range=xrange),
                        value_mapper = LinearMapper(range=yrange),
                        value=ds,
                        global_max = np.nanmax(data),
                        global_min = np.nanmin(data),
                        **kw)

        self.plot = Plot()
        self.plot.add(mlp)
Пример #5
0
class MyPlot(HasTraits):
    """ Displays a plot with a few buttons to control which overlay
        to display
    """
    plot = Instance(Plot)

    traits_view = View(Item('plot', editor=ComponentEditor(),
                            show_label=False),
                       resizable=True)

    def __init__(self, x_index, y_index, data, **kw):
        super(MyPlot, self).__init__(**kw)

        # Create the data source for the MultiLinePlot.
        ds = MultiArrayDataSource(data=data)

        xs = ArrayDataSource(x_index, sort_order='ascending')
        xrange = DataRange1D()
        xrange.add(xs)

        ys = ArrayDataSource(y_index, sort_order='ascending')
        yrange = DataRange1D()
        yrange.add(ys)

        mlp = MultiLinePlot(index=xs,
                            yindex=ys,
                            index_mapper=LinearMapper(range=xrange),
                            value_mapper=LinearMapper(range=yrange),
                            value=ds,
                            global_max=np.nanmax(data),
                            global_min=np.nanmin(data),
                            **kw)

        self.plot = Plot()
        self.plot.add(mlp)
def _create_plot_component():

    # Create some data
    numpts = 1000
    x = numpy.arange(0, numpts)
    y = numpy.random.random(numpts)
    marker_size = numpy.random.normal(4.0, 4.0, numpts)
    color = numpy.random.random(numpts)

    # Create a plot data object and give it this data
    pd = ArrayPlotData()
    pd.set_data("index", x)
    pd.set_data("value", y)

    # Because this is a non-standard renderer, we can't call plot.plot, which
    # sets up the array data sources, mappers and default index/value ranges.
    # So, its gotta be done manually for now.

    index_ds = ArrayDataSource(x)
    value_ds = ArrayDataSource(y)
    color_ds = ArrayDataSource(color)

    # Create the plot
    plot = Plot(pd)
    plot.index_range.add(index_ds)
    plot.value_range.add(value_ds)

    # Create the index and value mappers using the plot data ranges
    imapper = LinearMapper(range=plot.index_range)
    vmapper = LinearMapper(range=plot.value_range)

    # Create the scatter renderer
    scatter = ColormappedScatterPlot(
        index=index_ds,
        value=value_ds,
        color_data=color_ds,
        color_mapper=jet(range=DataRange1D(
            low=0.0, high=1.0)),
        fill_alpha=0.4,
        index_mapper=imapper,
        value_mapper=vmapper,
        marker='circle',
        marker_size=marker_size)

    # Append the renderer to the list of the plot's plots
    plot.add(scatter)
    plot.plots['var_size_scatter'] = [scatter]

    # Tweak some of the plot properties
    plot.title = "Variable Size and Color Scatter Plot"
    plot.line_width = 0.5
    plot.padding = 50

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot, constrain_key="shift"))
    zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
    plot.overlays.append(zoom)

    return plot
Пример #7
0
def _create_plot_component(obj):
    # Setup the spectrum plot
    frequencies = linspace(0.0, float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2)
    obj.spectrum_data = ArrayPlotData(frequency=frequencies)
    empty_amplitude = zeros(NUM_SAMPLES/2)
    obj.spectrum_data.set_data('amplitude', empty_amplitude)

    obj.spectrum_plot = Plot(obj.spectrum_data)
    spec_renderer = obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum",
                           color="red")[0]
    obj.spectrum_plot.padding = 50
    obj.spectrum_plot.title = "Spectrum"
    spec_range = list(obj.spectrum_plot.plots.values())[0][0].value_mapper.range
    spec_range.low = 0.0
    spec_range.high = 5.0
    obj.spectrum_plot.index_axis.title = 'Frequency (hz)'
    obj.spectrum_plot.value_axis.title = 'Amplitude'

    # Time Series plot
    times = linspace(0.0, float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES)
    obj.time_data = ArrayPlotData(time=times)
    empty_amplitude = zeros(NUM_SAMPLES)
    obj.time_data.set_data('amplitude', empty_amplitude)

    obj.time_plot = Plot(obj.time_data)
    obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue")
    obj.time_plot.padding = 50
    obj.time_plot.title = "Time"
    obj.time_plot.index_axis.title = 'Time (seconds)'
    obj.time_plot.value_axis.title = 'Amplitude'
    time_range = list(obj.time_plot.plots.values())[0][0].value_mapper.range
    time_range.low = -0.2
    time_range.high = 0.2

    # Spectrogram plot
    values = [zeros(NUM_SAMPLES/2) for i in range(SPECTROGRAM_LENGTH)]
    p = WaterfallRenderer(index = spec_renderer.index, values = values,
            index_mapper = LinearMapper(range = obj.spectrum_plot.index_mapper.range),
            value_mapper = LinearMapper(range = DataRange1D(low=0, high=SPECTROGRAM_LENGTH)),
            y2_mapper = LinearMapper(low_pos=0, high_pos=8,
                            range=DataRange1D(low=0, high=15)),
            )
    spectrogram_plot = p
    obj.spectrogram_plot = p
    dummy = Plot()
    dummy.padding = 50
    dummy.index_axis.mapper.range = p.index_mapper.range
    dummy.index_axis.title = "Frequency (hz)"
    dummy.add(p)

    container = HPlotContainer()
    container.add(obj.spectrum_plot)
    container.add(obj.time_plot)

    c2 = VPlotContainer()
    c2.add(dummy)
    c2.add(container)

    return c2
Пример #8
0
def _create_plot_component():

    # Create some data
    numpts = 1000
    x = numpy.arange(0, numpts)
    y = numpy.random.random(numpts)
    marker_size = numpy.random.normal(4.0, 4.0, numpts)
    color = numpy.random.random(numpts)

    # Create a plot data object and give it this data
    pd = ArrayPlotData()
    pd.set_data("index", x)
    pd.set_data("value", y)

    # Because this is a non-standard renderer, we can't call plot.plot, which
    # sets up the array data sources, mappers and default index/value ranges.
    # So, its gotta be done manually for now.

    index_ds = ArrayDataSource(x)
    value_ds = ArrayDataSource(y)
    color_ds = ArrayDataSource(color)

    # Create the plot
    plot = Plot(pd)
    plot.index_range.add(index_ds)
    plot.value_range.add(value_ds)

    # Create the index and value mappers using the plot data ranges
    imapper = LinearMapper(range=plot.index_range)
    vmapper = LinearMapper(range=plot.value_range)

    # Create the scatter renderer
    scatter = ColormappedScatterPlot(
                    index=index_ds,
                    value=value_ds,
                    color_data=color_ds,
                    color_mapper=jet(range=DataRange1D(low=0.0, high=1.0)),
                    fill_alpha=0.4,
                    index_mapper = imapper,
                    value_mapper = vmapper,
                    marker='circle',
                    marker_size=marker_size)

    # Append the renderer to the list of the plot's plots
    plot.add(scatter)
    plot.plots['var_size_scatter'] = [scatter]

    # Tweak some of the plot properties
    plot.title = "Variable Size and Color Scatter Plot"
    plot.line_width = 0.5
    plot.padding = 50

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot, constrain_key="shift"))
    zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
    plot.overlays.append(zoom)

    return plot
Пример #9
0
 def _pulse_plot_default(self):
     plot = Plot(self.pulse_plot_data, padding=8, padding_left=64, padding_bottom=36)
     plot.plot(('x', 'y'), style='line', color='blue', name='data')
     edge_marker = LinePlot(index=ArrayDataSource(np.array((0, 0))),
                            value=ArrayDataSource(np.array((0, 1e9))),
                            color='red',
                            index_mapper=LinearMapper(range=plot.index_range),
                            value_mapper=LinearMapper(range=plot.value_range),
                            name='marker')
     plot.add(edge_marker)
     plot.index_axis.title = 'time [ns]'
     plot.value_axis.title = 'intensity'
     return plot
Пример #10
0
    def _plot_default(self):
        """Create the Plot instance."""

        plot = Plot(title="MultiLinePlot Demo")
        plot.add(self.multi_line_plot_renderer)

        x_axis = PlotAxis(component=plot,
                          mapper=self.multi_line_plot_renderer.index_mapper,
                          orientation='bottom',
                          title='t (seconds)')
        y_axis = PlotAxis(component=plot,
                          mapper=self.multi_line_plot_renderer.value_mapper,
                          orientation='left',
                          title='channel')
        plot.overlays.extend([x_axis, y_axis])
        return plot
Пример #11
0
    def _plot_default(self):
        """Create the Plot instance."""

        plot = Plot(title="MultiLinePlot Demo")
        plot.add(self.multi_line_plot_renderer)

        x_axis = PlotAxis(component=plot,
                            mapper=self.multi_line_plot_renderer.index_mapper,
                            orientation='bottom',
                            title='t (seconds)')
        y_axis = PlotAxis(component=plot,
                            mapper=self.multi_line_plot_renderer.value_mapper,
                            orientation='left',
                            title='channel')
        plot.overlays.extend([x_axis, y_axis])
        return plot
Пример #12
0
    def _plots_default(self):
        plotdata = self.get_data_sets()
        plots = Plot(plotdata)
        plotsDict = {}

        # plot background sonar image and impound lines
        xbounds = self.model.survey_rng_m
        ybounds = self.model.depth_m
        plots.img_plot("sonarimg", colormap=jet,
                        xbounds=xbounds, ybounds=ybounds)
        ip = plots.plot(('impound1_X','impound1_Y'), type='line', marker='square')
        plotsDict['Impoundment line'] = ip
        plots.x_axis.title = 'Distance along survey line (m)'
        plots.y_axis.title = 'Depth (m)'

        # add core samples as scatter with separate y-axis
        corex = plotdata.get_data('coreX')
        corey = plotdata.get_data('coreY')
        scatter = create_scatter_plot((corex,corey), marker='diamond',
                                       color='red' )
        scatter.index_range = plots.index_range
        axis = PlotAxis(scatter, orientation='right')
        axis.title = 'Core sample dist from survey line (m)'
        scatter.underlays.append(axis)
        plots.add(scatter)

        # create vertical line for indicating selected core sample position
        vals1 = [0 for x in corey]
        vline = create_line_plot((corey,vals1), color='blue', orientation='v')
        vline.value_range = scatter.index_range
        plots.add(vline)

        # Add Legend
        legend = Legend(component=plots, padding=10, align="ur")
        legend.tools.append(LegendTool(legend, drag_button="left"))
        legend.plots = plotsDict
        plots.overlays.append(legend)

        # Add tools
        scatter.tools.append(PickTool(scatter))
        plots.tools.append(TraceTool(plots))
        plots.tools.append(PanTool(plots))
        plots.tools.append(ZoomTool(plots))

        return plots
def _create_plot_component():

    # Create some x-y data series to plot
    x = linspace(-2.0, 10.0, 100)
    pd = ArrayPlotData(index=x)
    for i in range(5):
        pd.set_data("y" + str(i), jn(i, x))

    # Create some line plots of some of the data
    plot1 = Plot(pd)
    plot1.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red")

    # Tweak some of the plot properties
    plot1.title = "My First Line Plot"
    plot1.padding = 50
    plot1.padding_top = 75
    plot1.legend.visible = True

    x = linspace(-5, 15.0, 100)
    y = jn(5, x)
    foreign_plot = create_line_plot((x, y),
                                    color=tuple(COLOR_PALETTE[0]),
                                    width=2.0)
    left, bottom = add_default_axes(foreign_plot)
    left.orientation = "right"
    bottom.orientation = "top"
    plot1.add(foreign_plot)

    # Attach some tools to the plot
    broadcaster = BroadcasterTool()
    broadcaster.tools.append(PanTool(plot1))
    broadcaster.tools.append(PanTool(foreign_plot))

    for c in (plot1, foreign_plot):
        zoom = ZoomTool(component=c, tool_mode="box", always_on=False)
        broadcaster.tools.append(zoom)

    plot1.tools.append(broadcaster)

    return plot1
Пример #14
0
def _create_plot_component():

    # Create some x-y data series to plot
    x = linspace(-2.0, 10.0, 100)
    pd = ArrayPlotData(index = x)
    for i in range(5):
        pd.set_data("y" + str(i), jn(i,x))

    # Create some line plots of some of the data
    plot1 = Plot(pd)
    plot1.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red")

    # Tweak some of the plot properties
    plot1.title = "My First Line Plot"
    plot1.padding = 50
    plot1.padding_top = 75
    plot1.legend.visible = True

    x = linspace(-5, 15.0, 100)
    y = jn(5, x)
    foreign_plot = create_line_plot((x,y), color=tuple(COLOR_PALETTE[0]), width=2.0)
    left, bottom = add_default_axes(foreign_plot)
    left.orientation = "right"
    bottom.orientation = "top"
    plot1.add(foreign_plot)

    # Attach some tools to the plot
    broadcaster = BroadcasterTool()
    broadcaster.tools.append(PanTool(plot1))
    broadcaster.tools.append(PanTool(foreign_plot))

    for c in (plot1, foreign_plot):
        zoom = ZoomTool(component=c, tool_mode="box", always_on=False)
        broadcaster.tools.append(zoom)

    plot1.tools.append(broadcaster)

    return plot1
class PoincarePlotFastMovieMakerWorker(object):
    """
    special fast movie generation class which uses chaco library
    """
    def __init__(self, pp_specs_manager):
        self.manager = pp_specs_manager
        self.pp_specs = self.manager.getMiniPoincarePlotSpecs()
        if len(self.pp_specs) == 0:
            return
        self.gc = None
        self.p0 = self.pp_specs[0]

        #set up specific values for fonts sizes based on products of a movie
        #height and arbitrary constants to give looking good picture
        if self.manager.movie_axis_font == None:
            self.axis_font = 'modern ' + str(nvl_and_positive(
                self.manager.movie_axis_font_size, self.manager.movie_height / 38))
        else:
            self.axis_font = self.manager.movie_axis_font

        if self.manager.movie_title_font == None:
            self.title_font = 'modern ' + str(nvl_and_positive(
                self.manager.movie_title_font_size, self.manager.movie_height / 30))
        else:
            self.title_font = self.manager.movie_title_font

        self.time_label_font = 'modern ' + str(nvl_and_positive(
            self.manager.movie_time_label_font_size, self.manager.movie_height / 35))

        self.tick_font = nvl(self.manager.movie_tick_font, None)
        self.frame_pad = nvl_and_positive(self.manager.movie_frame_pad, 50)

    def initiate(self):
        if len(self.pp_specs) == 0:
            return False

        # only positive values are accepted
        x = self.p0.x_data[pl.where(self.p0.x_data > 0)]
        y = self.p0.y_data[pl.where(self.p0.y_data > 0)]

        x_min = pl.amin(x)
        x_max = pl.amax(x)
        y_min = pl.amin(y)
        y_max = pl.amax(y)
        value_min = x_min if x_min < y_min else y_min
        self.value_max = x_max if x_max > y_max else y_max

        self.pd = ArrayPlotData()
        self.pd.set_data("index", x)
        self.pd.set_data("value", y)

        index_ds = ArrayDataSource(x)
        value_ds = ArrayDataSource(y)

        # Create the plot
        self._plot = Plot(self.pd)

        axis_defaults = {
                         #'axis_line_weight': 2,
                         #'tick_weight': 2,
                         #'tick_label_color': 'green',
                         'title_font': self.axis_font,
                         }
        if self.tick_font:
            axis_defaults['tick_label_font'] = self.tick_font

        #a very important and weird trick; used to remove default ticks labels
        self._plot.x_axis = None
        self._plot.y_axis = None
        #end trick

        #add new x label and x's ticks labels
        x_axis = PlotAxis(orientation='bottom',
                  title=nvl(self.manager.x_label, 'RR(n) [ms]'),
                  mapper=self._plot.x_mapper,
                  **axis_defaults)
        self._plot.overlays.append(x_axis)

        #add new y label and y's ticks labels
        y_axis = PlotAxis(orientation='left',
                   title=nvl(self.manager.y_label, 'RR(n+1) [ms]'),
                   mapper=self._plot.y_mapper,
                   **axis_defaults)
        self._plot.overlays.append(y_axis)

        self._plot.index_range.add(index_ds)
        self._plot.value_range.add(value_ds)

        self._plot.index_mapper.stretch_data = False
        self._plot.value_mapper.stretch_data = False
        self._plot.value_range.set_bounds(value_min, self.value_max)
        self._plot.index_range.set_bounds(value_min, self.value_max)

        # Create the index and value mappers using the plot data ranges
        imapper = LinearMapper(range=self._plot.index_range)
        vmapper = LinearMapper(range=self._plot.value_range)

        color = "white"

        self.scatter = __PoincarePlotScatterPlot__(
                        self.p0,
                        self.manager,
                        index=index_ds,
                        value=value_ds,
                        #color_data=color_ds,
                        #color_mapper=color_mapper,
                        #fill_alpha=0.4,
                        color=color,
                        index_mapper=imapper,
                        value_mapper=vmapper,
                        marker='circle',
                        marker_size=self.manager.active_point_size,
                        line_width=0
                        #outline_color='white'
                        )
        self._plot.add(self.scatter)

        #self._plot.plots['var_size_scatter'] = [self.scatter]

        # Tweak some of the plot properties
        _title = nvl(self.manager.movie_title, "Poincare plot")
        if len(_title) > 0:
            self._plot.title = _title
            self._plot.title_font = self.title_font

        self._plot.line_width = 0.5
        self._plot.padding = self.frame_pad

        self._plot.do_layout(force=True)
        self._plot.outer_bounds = [self.manager.movie_width,
                                   self.manager.movie_height]

        self.gc = PlotGraphicsContext(self._plot.outer_bounds,
                                      dpi=self.manager.movie_dpi)
        self.gc.render_component(self._plot)
        self.gc.set_line_width(0)

        self.gc.save(self._get_filename(self.p0))

        self.x_mean_old = None
        self.y_mean_old = None
        self._time_label_font = None

        return True

    def plot(self, idx):
        if len(self.pp_specs) == 0:
            return
        p = self.pp_specs[idx]
        p_old = None if idx == 0 else self.pp_specs[idx - 1]

        if idx > 0:

            self.gc.set_line_width(0)

            if not p_old == None and not p_old.mean_plus == None:
                r_points = pl.array([[p_old.mean_plus, p_old.mean_minus]])
                r_points = self.scatter.map_screen(r_points)
                self.gc.set_fill_color((1.0, 1.0, 1.0, 1.0))
                self.gc.draw_marker_at_points(r_points,
                                    self.manager.centroid_point_size, CIRCLE)

            __update_graphics_context__(self.gc, self.scatter, p, self.manager)

            r_points = pl.array([[p.mean_plus, p.mean_minus]])
            r_points = self.scatter.map_screen(r_points)
            self.gc.set_fill_color(self.manager.centroid_color_as_tuple)
            self.gc.draw_marker_at_points(r_points,
                                    self.manager.centroid_point_size, CIRCLE)
            #self.gc.save_state()

        self._draw_time_text(self.gc, p)
        self.gc.save_state()

        if self.manager.movie_frame_step > 0 and idx > 0:
            # only frames module movie_frame_step are generated
            if not self.manager.movie_frame_step % idx == 0:
                return

        if self.manager.movie_identity_line:
            __draw_identity_line__(self.gc, self.value_max, self.scatter)

        self.gc.save(self._get_filename(p))

    def _draw_time_text(self, gc, pp_spec):
        if self.manager.movie_create_time_label == False:
            return
        if pp_spec.level == 0:
            (H, M, S) = get_time_label_parts_for_miliseconds(0,
                                hour_label=self.manager.movie_hour_label,
                                minute_label=self.manager.movie_minute_label,
                                second_label=self.manager.movie_second_label)
        else:
            (H, M, S) = get_time_label_parts_for_miliseconds(
                                pp_spec.cum_inactive,
                                hour_label=self.manager.movie_hour_label,
                                minute_label=self.manager.movie_minute_label,
                                second_label=self.manager.movie_second_label)

        if not self._time_label_font:
            self._time_label_font = str_to_font(None, None, self.time_label_font)

        gc.set_font(self._time_label_font)

        shift = 10
        if self.manager.movie_time_label_in_line == True:
            if self.manager.movie_time_label_prefix:
                time_line = '%s %s %s %s' % (self.manager.movie_time_label_prefix, H, M, S)
            else:
                time_line = '%s %s %s' % (H, M, S)
            _, _, tw, th = gc.get_text_extent(time_line)
            x = self._plot.outer_bounds[0] / 2 - tw / 2 - self._plot.padding_left
            y = self._plot.outer_bounds[1] - self._plot.padding_top - th
            gc.set_fill_color((1.0, 1.0, 1.0, 1.0))
            gc.rect(x, y, tw, th + shift)
            gc.draw_path()
            gc.set_fill_color((0.0, 0.0, 0.0, 1.0))
            gc.show_text_at_point(time_line, x, y)
        else:
            for idx, time_e in enumerate([H, M, S]):
                _, _, tw, th = gc.get_text_extent(time_e)
                x = self._plot.outer_bounds[0] - tw - self._plot.padding_right
                y = self._plot.outer_bounds[1] / 2 - idx * (th + shift)
                gc.set_fill_color((1.0, 1.0, 1.0, 1.0))
                #gc.rect(x, y, tw + shift, th)
                gc.rect(x, y, tw, th + shift)
                gc.draw_path()
                gc.set_fill_color((0.0, 0.0, 0.0, 1.0))
                gc.show_text_at_point(time_e, x, y)

        return

    def _get_filename(self, pp_spec):
        if self.manager.movie_frame_filename_with_time:
            (H, M, S) = get_time_for_miliseconds(0 if pp_spec.level == 0
                                                 else pp_spec.cum_inactive)
            if pp_spec.frame_file.endswith(PNG_EXTENSION):
                filename = pp_spec.frame_file.rsplit(PNG_EXTENSION)[0]
                return '%s_%02d_%02d_%02d%s' % (filename, H, M, S, PNG_EXTENSION)
        return pp_spec.frame_file
Пример #16
0
class PlotWindow(HasTraits):
    _plot_data = Instance(ArrayPlotData)
    _plot = Instance(Plot)
    _click_tool = Instance(ClickerTool)
    _img_plot = Instance(ImagePlot)
    _right_click_avail = 0
    name = Str
    view = View(Item(name='_plot', editor=ComponentEditor(),
                     show_label=False), )

    def __init__(self):
        super(HasTraits, self).__init__()
        # -------------- Initialization of plot system ----------------
        padd = 25
        self._plot_data = ArrayPlotData()
        self._x = []
        self._y = []
        self.man_ori = [1, 2, 3, 4]
        self._plot = Plot(self._plot_data, default_origin="top left")
        self._plot.padding_left = padd
        self._plot.padding_right = padd
        self._plot.padding_top = padd
        self._plot.padding_bottom = padd
        self._quiverplots = []

        # -------------------------------------------------------------

    def left_clicked_event(self):
        print("left clicked")
        if len(self._x) < 4:
            self._x.append(self._click_tool.x)
            self._y.append(self._click_tool.y)
        print(self._x, self._y)

        self.drawcross("coord_x", "coord_y", self._x, self._y, "red", 5)
        self._plot.overlays = []
        self.plot_num_overlay(self._x, self._y, self.man_ori)

    def right_clicked_event(self):
        print("right clicked")
        if len(self._x) > 0:
            self._x.pop()
            self._y.pop()
            print(self._x, self._y)

            self.drawcross("coord_x", "coord_y", self._x, self._y, "red", 5)
            self._plot.overlays = []
            self.plot_num_overlay(self._x, self._y, self.man_ori)
        else:
            if (self._right_click_avail):
                print("deleting point")
                self.py_rclick_delete(self._click_tool.x, self._click_tool.y,
                                      self.cameraN)
                x = []
                y = []
                self.py_get_pix_N(x, y, self.cameraN)
                self.drawcross("x", "y", x[0], y[0], "blue", 4)

    def attach_tools(self):
        self._click_tool = ClickerTool(self._img_plot)
        self._click_tool.on_trait_change(self.left_clicked_event,
                                         'left_changed')
        self._click_tool.on_trait_change(self.right_clicked_event,
                                         'right_changed')
        self._img_plot.tools.append(self._click_tool)
        self._zoom_tool = SimpleZoom(component=self._plot,
                                     tool_mode="box",
                                     always_on=False)
        self._zoom_tool.max_zoom_out_factor = 1.0
        self._img_plot.tools.append(self._zoom_tool)
        if self._plot.index_mapper is not None:
            self._plot.index_mapper.on_trait_change(self.handle_mapper,
                                                    'updated',
                                                    remove=False)
        if self._plot.value_mapper is not None:
            self._plot.value_mapper.on_trait_change(self.handle_mapper,
                                                    'updated',
                                                    remove=False)

    def drawcross(self, str_x, str_y, x, y, color1, mrk_size):
        """
        Draws crosses on images
        """
        self._plot_data.set_data(str_x, x)
        self._plot_data.set_data(str_y, y)
        self._plot.plot((str_x, str_y),
                        type="scatter",
                        color=color1,
                        marker="plus",
                        marker_size=mrk_size)
        self._plot.request_redraw()

    def drawline(self, str_x, str_y, x1, y1, x2, y2, color1):
        self._plot_data.set_data(str_x, [x1, x2])
        self._plot_data.set_data(str_y, [y1, y2])
        self._plot.plot((str_x, str_y), type="line", color=color1)
        self._plot.request_redraw()

    def drawquiver(self, x1c, y1c, x2c, y2c, color, linewidth=1.0, scale=1.0):
        """ drawquiver draws multiple lines at once on the screen x1,y1->x2,y2 in the current camera window
        parameters:
            x1c - array of x1 coordinates
            y1c - array of y1 coordinates
            x2c - array of x2 coordinates
            y2c - array of y2 coordinates
            color - color of the line
            linewidth - linewidth of the line
        example usage:
            drawquiver ([100,200],[100,100],[400,400],[300,200],'red',linewidth=2.0)
            draws 2 red lines with thickness = 2 :  100,100->400,300 and 200,100->400,200

        """
        x1, y1, x2, y2 = self.remove_short_lines(x1c,
                                                 y1c,
                                                 x2c,
                                                 y2c,
                                                 min_length=0)
        if len(x1) > 0:
            xs = ArrayDataSource(x1)
            ys = ArrayDataSource(y1)

            quiverplot = QuiverPlot(
                index=xs,
                value=ys,
                index_mapper=LinearMapper(range=self._plot.index_mapper.range),
                value_mapper=LinearMapper(range=self._plot.value_mapper.range),
                origin=self._plot.origin,
                arrow_size=0,
                line_color=color,
                line_width=linewidth,
                ep_index=np.array(x2) * scale,
                ep_value=np.array(y2) * scale)
            self._plot.add(quiverplot)
            # we need this to track how many quiverplots are in the current
            # plot
            self._quiverplots.append(quiverplot)
            # import pdb; pdb.set_trace()

    def remove_short_lines(self, x1, y1, x2, y2, min_length=2):
        """ removes short lines from the array of lines
        parameters:
            x1,y1,x2,y2 - start and end coordinates of the lines
        returns:
            x1f,y1f,x2f,y2f - start and end coordinates of the lines, with short lines removed
        example usage:
            x1,y1,x2,y2=remove_short_lines([100,200,300],[100,200,300],[100,200,300],[102,210,320])
            3 input lines, 1 short line will be removed (100,100->100,102)
            returned coordinates:
            x1=[200,300]; y1=[200,300]; x2=[200,300]; y2=[210,320]
        """
        # dx, dy = 2, 2  # minimum allowable dx,dy
        x1f, y1f, x2f, y2f = [], [], [], []
        for i in range(len(x1)):
            if abs(x1[i] - x2[i]) > min_length or abs(y1[i] -
                                                      y2[i]) > min_length:
                x1f.append(x1[i])
                y1f.append(y1[i])
                x2f.append(x2[i])
                y2f.append(y2[i])
        return x1f, y1f, x2f, y2f

    def handle_mapper(self):
        for i in range(0, len(self._plot.overlays)):
            if hasattr(self._plot.overlays[i], 'real_position'):
                coord_x1, coord_y1 = self._plot.map_screen(
                    [self._plot.overlays[i].real_position])[0]
                self._plot.overlays[i].alternate_position = (coord_x1,
                                                             coord_y1)

    def plot_num_overlay(self, x, y, txt):
        for i in range(0, len(x)):
            coord_x, coord_y = self._plot.map_screen([(x[i], y[i])])[0]
            ovlay = TextBoxOverlay(component=self._plot,
                                   text=str(txt[i]),
                                   alternate_position=(coord_x, coord_y),
                                   real_position=(x[i], y[i]),
                                   text_color="white",
                                   border_color="red")
            self._plot.overlays.append(ovlay)

    def update_image(self, image, is_float):
        if is_float:
            self._plot_data.set_data('imagedata', image.astype(np.float))
        else:
            self._plot_data.set_data('imagedata', image.astype(np.byte))

        self._plot.request_redraw()
Пример #17
0
def clone_plot(clonetool, drop_position):
    # A little sketchy...
    canvas = clonetool.component.container.component.component

    # Create a new Plot object
    oldplot = clonetool.component
    newplot = Plot(oldplot.data)
    basic_traits = [
        "orientation", "default_origin", "bgcolor", "border_color",
        "border_width", "border_visible", "draw_layer", "unified_draw",
        "fit_components", "fill_padding", "visible", "aspect_ratio", "title"
    ]

    for attr in basic_traits:
        setattr(newplot, attr, getattr(oldplot, attr))

    # copy the ranges
    dst = newplot.range2d
    src = oldplot.range2d
    #for attr in ('_low_setting', '_low_value', '_high_setting', '_high_value'):
    #    setattr(dst, attr, getattr(src, attr))
    dst._xrange.sources = copy(src._xrange.sources)
    dst._yrange.sources = copy(src._yrange.sources)

    newplot.padding = oldplot.padding
    newplot.bounds = oldplot.bounds[:]
    newplot.resizable = ""
    newplot.position = drop_position

    newplot.datasources = copy(oldplot.datasources)

    for name, renderers in list(oldplot.plots.items()):
        newrenderers = []
        for renderer in renderers:
            new_r = clone_renderer(renderer)
            new_r.index_mapper = LinearMapper(range=newplot.index_range)
            new_r.value_mapper = LinearMapper(range=newplot.value_range)
            new_r._layout_needed = True
            new_r.invalidate_draw()
            new_r.resizable = "hv"
            newrenderers.append(new_r)
        newplot.plots[name] = newrenderers
    #newplot.plots = copy(oldplot.plots)

    for name, renderers in list(newplot.plots.items()):
        newplot.add(*renderers)

    newplot.index_axis.title = oldplot.index_axis.title
    newplot.index_axis.unified_draw = True
    newplot.value_axis.title = oldplot.value_axis.title
    newplot.value_axis.unified_draw = True

    # Add new tools to the new plot
    newplot.tools.append(
        AxisTool(component=newplot, range_controller=canvas.range_controller))

    # Add tools to the new plot
    pan_traits = [
        "drag_button", "constrain", "constrain_key", "constrain_direction",
        "speed"
    ]
    zoom_traits = [
        "tool_mode", "always_on", "axis", "enable_wheel", "drag_button",
        "wheel_zoom_step", "enter_zoom_key", "exit_zoom_key", "pointer",
        "color", "alpha", "border_color", "border_size", "disable_on_complete",
        "minimum_screen_delta", "max_zoom_in_factor", "max_zoom_out_factor"
    ]
    move_traits = [
        "drag_button", "end_drag_on_leave", "cancel_keys", "capture_mouse",
        "modifier_key"
    ]

    if not MULTITOUCH:
        for tool in oldplot.tools:
            if isinstance(tool, PanTool):
                newtool = tool.clone_traits(pan_traits)
                newtool.component = newplot
                break
        else:
            newtool = PanTool(newplot)
        # Reconfigure the pan tool to always use the left mouse, because we will
        # put plot move on the right mouse button
        newtool.drag_button = "left"
        newplot.tools.append(newtool)

        for tool in oldplot.tools:
            if isinstance(tool, MoveTool):
                newtool = tool.clone_traits(move_traits)
                newtool.component = newplot
                break
        else:
            newtool = MoveTool(newplot, drag_button="right")
        newplot.tools.append(newtool)

        for tool in oldplot.tools:
            if isinstance(tool, ZoomTool):
                newtool = tool.clone_traits(zoom_traits)
                newtool.component = newplot
                break
        else:
            newtool = ZoomTool(newplot)
        newplot.tools.append(newtool)

    else:
        pz = MPPanZoom(newplot)
        #pz.pan.constrain = True
        #pz.pan.constrain_direction = "x"
        #pz.zoom.mode = "range"
        #pz.zoom.axis = "index"
        newplot.tools.append(MPPanZoom(newplot))
        #newplot.tools.append(MTMoveTool(

    newplot._layout_needed = True

    clonetool.dest.add(newplot)
    newplot.invalidate_draw()
    newplot.request_redraw()
    canvas.request_redraw()
    return
Пример #18
0
    def create_hplot(self, key=None, mini=False):
        if mini:
            hpc = HPlotContainer(bgcolor='darkgrey',
                                 height=MINI_HEIGHT,
                                 resizable='h',
                                 padding=0)
        else:
            hpc = HPlotContainer(bgcolor='lightgrey',
                                 padding=HPLOT_PADDING,
                                 resizable='hv')

        # make slice plot for showing intesity profile of main plot
        #************************************************************
        slice_plot = Plot(self.data,
                          width=SLICE_PLOT_WIDTH,
                          orientation="v",
                          resizable="v",
                          padding=MAIN_PADDING,
                          padding_left=MAIN_PADDING_LEFT,
                          bgcolor='beige',
                          origin='top left')

        slice_plot.x_axis.visible = False
        slice_key = key + '_slice'
        ydata_key = key + '_y'
        slice_plot.plot((ydata_key, slice_key), name=slice_key)

        # make main plot for editing depth lines
        #************************************************************
        main = Plot(
            self.data,
            border_visible=True,
            bgcolor='beige',
            origin='top left',
            padding=MAIN_PADDING,
            padding_left=MAIN_PADDING_LEFT,
        )
        if mini:
            main.padding = MINI_PADDING

        # add intensity img to plot and get reference for line inspector
        #************************************************************
        img_plot = main.img_plot(key,
                                 name=key,
                                 xbounds=self.model.xbounds[key],
                                 ybounds=self.model.ybounds[key],
                                 colormap=self._cmap)[0]

        # add line plots: use method since these may change
        #************************************************************
        self.update_line_plots(key, main, update=True)

        # set slice plot index range to follow main plot value range
        #************************************************************
        slice_plot.index_range = main.value_range

        # add vertical core lines to main plots and slices
        #************************************************************
        # save pos and distance in session dict for view info and control
        for core in self.model.core_samples:
            loc_index, loc, dist = self.model.core_info_dict[core.core_id]
            # add boundarys to slice plot
            ref_line = self.model.final_lake_depth
            self.plot_core_depths(slice_plot, core, ref_line, loc_index)
            # add positions to main plots
            self.plot_core(main, core, ref_line, loc_index, loc)

        # now add tools depending if it is a mini plot or not
        #************************************************************
        if mini:
            # add range selection tool only
            # first add a reference line to attach it to
            reference = self.make_reference_plot()
            main.add(reference)
            # attache range selector to this plot
            range_tool = RangeSelection(reference)
            reference.tools.append(range_tool)
            range_overlay = RangeSelectionOverlay(reference,
                                                  metadata_name="selections")
            reference.overlays.append(range_overlay)
            range_tool.on_trait_change(self._range_selection_handler,
                                       "selection")
            # add zoombox to mini plot
            main.plot(('zoombox_x', 'zoombox_y'),
                      type='polygon',
                      face_color=ZOOMBOX_COLOR,
                      alpha=ZOOMBOX_ALPHA)
            # add to hplot and dict
            hpc.add(main)
            self.hplot_dict['mini'] = hpc

        else:
            # add zoom tools
            main.tools.append(PanTool(main))
            zoom = ZoomTool(main, tool_mode='box', axis='both', alpha=0.5)
            main.tools.append(zoom)
            main.overlays.append(zoom)
            main.value_mapper.on_trait_change(self.zoom_all_value, 'updated')
            main.index_mapper.on_trait_change(self.zoom_all_index, 'updated')
            # add line inspector and attach to freeze tool
            #*********************************************
            line_inspector = LineInspector(component=img_plot,
                                           axis='index_x',
                                           inspect_mode="indexed",
                                           is_interactive=True,
                                           write_metadata=True,
                                           metadata_name='x_slice',
                                           is_listener=True,
                                           color="white")
            img_plot.overlays.append(line_inspector)
            self.inspector_freeze_tool.tool_set.add(line_inspector)

            # add listener for changes to metadata made by line inspector
            #************************************************************
            img_plot.on_trait_change(self.metadata_changed, 'index.metadata')

            # set slice plot index range to follow main plot value range
            #************************************************************
            slice_plot.index_range = main.value_range

            # add clickable legend ; must update legend when depth_dict updated
            #******************************************************************
            legend = Legend(component=main,
                            padding=0,
                            align="ur",
                            font='modern 8')
            legend_highlighter = LegendHighlighter(legend, drag_button="right")
            legend.tools.append(legend_highlighter)
            self.update_legend_plots(legend, main)
            legend.visible = False
            self.legend_dict[key] = [legend, legend_highlighter]
            main.overlays.append(legend)

            # add main and slice plot to hplot container and dict
            #****************************************************
            main.title = 'frequency = {} kHz'.format(key)
            main.title_font = TITLE_FONT
            hpc.add(main, slice_plot)
            self.hplot_dict[key] = hpc

        return hpc
Пример #19
0
class CameraWindow(HasTraits):
    """ CameraWindow class contains the relevant information and functions for a single camera window: image, zoom, pan
	important members:
		_plot_data  - contains image data to display (used by update_image)
		_plot - instance of Plot class to use with _plot_data
		_click_tool - instance of Clicker tool for the single camera window, to handle mouse processing
	"""
    _plot_data = Instance(ArrayPlotData)
    _plot = Instance(Plot)
    _click_tool = Instance(Clicker)
    rclicked = Int(0)

    cam_color = ''

    name = Str
    view = View(Item(name='_plot', editor=ComponentEditor(), show_label=False))

    # view = View( Item(name='_plot',show_label=False) )

    def __init__(self, color):
        """ Initialization of plot system 
		"""
        padd = 25
        self._plot_data = ArrayPlotData()
        self._plot = Plot(self._plot_data, default_origin="top left")
        self._plot.padding_left = padd
        self._plot.padding_right = padd
        self._plot.padding_top = padd
        self._plot.padding_bottom = padd
        self.right_p_x0,self.right_p_y0,self.right_p_x1,self.right_p_y1,self._quiverplots=[],[],[],[],[]
        self.cam_color = color

    def attach_tools(self):
        """ attach_tools(self) contains the relevant tools: clicker, pan, zoom
		"""
        self._click_tool = Clicker(self._img_plot)
        self._click_tool.on_trait_change(
            self.left_clicked_event,
            'left_changed')  #set processing events for Clicker
        self._click_tool.on_trait_change(self.right_clicked_event,
                                         'right_changed')
        self._img_plot.tools.append(self._click_tool)
        pan = PanTool(self._plot, drag_button='middle')
        zoom_tool = ZoomTool(self._plot, tool_mode="box", always_on=False)
        #		zoom_tool = BetterZoom(component=self._plot, tool_mode="box", always_on=False)
        zoom_tool.max_zoom_out_factor = 1.0  # Disable "bird view" zoom out
        self._img_plot.overlays.append(zoom_tool)
        self._img_plot.tools.append(pan)

    def left_clicked_event(
        self
    ):  #TODO: why do we need the clicker_tool if we can handle mouse clicks here?
        """ left_clicked_event - processes left click mouse avents and displays coordinate and grey value information
		on the screen
		"""
        print "x = %d, y= %d, grey= %d " % (self._click_tool.x,
                                            self._click_tool.y,
                                            self._click_tool.data_value)
        #need to priny gray value

    def right_clicked_event(self):
        self.rclicked = 1  #flag that is tracked by main_gui, for right_click_process function of main_gui
        #self._click_tool.y,self.name])
        #self.drawcross("coord_x","coord_y",self._click_tool.x,self._click_tool.y,"red",5)
        #print ("right clicked, "+self.name)
        #need to print cross and manage other camera's crosses

    def update_image(self, image, is_float):
        """ update_image - displays/updates image in the curren camera window
		parameters:
			image - image data
			is_float - if true, displays an image as float array,
			else displays as byte array (B&W or gray)
		example usage:
			update_image(image,is_float=False)
		"""
        if is_float:
            self._plot_data.set_data('imagedata', image.astype(np.float))
        else:
            self._plot_data.set_data('imagedata', image.astype(np.byte))

        if not hasattr(
                self,
                '_img_plot'):  #make a new plot if there is nothing to update
            self._img_plot = Instance(ImagePlot)
            self._img_plot = self._plot.img_plot('imagedata', colormap=gray)[0]
            self.attach_tools()

        # self._plot.request_redraw()

    def drawcross(self, str_x, str_y, x, y, color1, mrk_size, marker1="plus"):
        """ drawcross draws crosses at a given location (x,y) using color and marker in the current camera window
		parameters:
			str_x - label for x coordinates
			str_y - label for y coordinates
			x - array of x coordinates
			y - array of y coordinates
			mrk_size - marker size
			makrer1 - type of marker, e.g "plus","circle"
		example usage:
			drawcross("coord_x","coord_y",[100,200,300],[100,200,300],2)
			draws plus markers of size 2 at points (100,100),(200,200),(200,300)
		"""
        self._plot_data.set_data(str_x, x)
        self._plot_data.set_data(str_y, y)
        self._plot.plot((str_x, str_y),
                        type="scatter",
                        color=color1,
                        marker=marker1,
                        marker_size=mrk_size)
        #self._plot.request_redraw()

    def drawquiver(self, x1c, y1c, x2c, y2c, color, linewidth=1.0):
        """ drawquiver draws multiple lines at once on the screen x1,y1->x2,y2 in the current camera window
		parameters:
			x1c - array of x1 coordinates
			y1c - array of y1 coordinates
			x2c - array of x2 coordinates
			y2c - array of y2 coordinates
			color - color of the line
			linewidth - linewidth of the line
		example usage:
			drawquiver ([100,200],[100,100],[400,400],[300,200],'red',linewidth=2.0)
			draws 2 red lines with thickness = 2 :  100,100->400,300 and 200,100->400,200
					
		"""
        x1, y1, x2, y2 = self.remove_short_lines(x1c, y1c, x2c, y2c)
        if len(x1) > 0:
            xs = ArrayDataSource(x1)
            ys = ArrayDataSource(y1)

            quiverplot=QuiverPlot(index=xs,value=ys,\
                   index_mapper=LinearMapper(range=self._plot.index_mapper.range),\
                   value_mapper=LinearMapper(range=self._plot.value_mapper.range),\
                   origin = self._plot.origin,arrow_size=0,\
                   line_color=color,line_width=linewidth,ep_index=np.array(x2),ep_value=np.array(y2)
                   )
            self._plot.add(quiverplot)
            self._quiverplots.append(
                quiverplot
            )  #we need this to track how many quiverplots are in the current plot
            # import pdb; pdb.set_trace()

    def remove_short_lines(self, x1, y1, x2, y2):
        """ removes short lines from the array of lines 
		parameters:
			x1,y1,x2,y2 - start and end coordinates of the lines
		returns:
			x1f,y1f,x2f,y2f - start and end coordinates of the lines, with short lines removed
		example usage:
			x1,y1,x2,y2=remove_short_lines([100,200,300],[100,200,300],[100,200,300],[102,210,320])
			3 input lines, 1 short line will be removed (100,100->100,102)
			returned coordinates:
			x1=[200,300]; y1=[200,300]; x2=[200,300]; y2=[210,320]
		"""
        dx, dy = 2, 2  #minimum allowable dx,dy
        x1f, y1f, x2f, y2f = [], [], [], []
        for i in range(len(x1)):
            if abs(x1[i] - x2[i]) > dx or abs(y1[i] - y2[i]) > dy:
                x1f.append(x1[i])
                y1f.append(y1[i])
                x2f.append(x2[i])
                y2f.append(y2[i])
        return x1f, y1f, x2f, y2f

    def drawline(self, str_x, str_y, x1, y1, x2, y2, color1):
        """ drawline draws 1 line on the screen by using lineplot x1,y1->x2,y2
		parameters:
			str_x - label of x coordinate
			str_y - label of y coordinate
			x1,y1,x2,y2 - start and end coordinates of the line
			color1 - color of the line
		example usage:
			drawline("x_coord","y_coord",100,100,200,200,red)
			draws a red line 100,100->200,200
		"""
        self._plot_data.set_data(str_x, [x1, x2])
        self._plot_data.set_data(str_y, [y1, y2])
        self._plot.plot((str_x, str_y), type="line", color=color1)
Пример #20
0
    def _get_plot_multiline(self):

        if self.data is None or len(self.data.shape) == 1:
            return

        numpoints = self.data.shape[1]

        if self.scale_type == 'Time':
            index_x = self._create_dates(numpoints, start=self.first_day)
        else:
            index_x = np.arange(numpoints)

        index_y = np.linspace(1, self.data.shape[0], self.data.shape[0])

        xs = ArrayDataSource(index_x)
        xrange = DataRange1D()
        xrange.add(xs)

        ys = ArrayDataSource(index_y)
        yrange = DataRange1D()
        yrange.add(ys)

        # The data source for the MultiLinePlot.
        ds = MultiArrayDataSource(data=self.data)

        corr_plot = \
            MultiLinePlot(
                index=xs,
                yindex=ys,
                index_mapper=LinearMapper(range=xrange),
                value_mapper=LinearMapper(range=yrange),
                value=ds,
                global_max=self.data.max(),
                global_min=self.data.min())

        corr_plot.value_mapper.range.low = 0
        corr_plot.value_mapper.range.high = self.data.shape[0] + 1

        self.multi_line_plot_renderer = corr_plot

        plot = Plot(title=self.p_title)

        if self.scale_type == 'Time':
            # Just the last axis shows tick_labels
            bottom_axis = PlotAxis(component=plot,
                                   orientation="bottom",
                                   title=self.x_lbl,
                                   tick_generator=ScalesTickGenerator(
                                       scale=CalendarScaleSystem()))
        else:
            bottom_axis = PlotAxis(orientation='bottom',
                                   title=self.x_lbl,
                                   title_font="modern 12",
                                   tick_visible=True,
                                   small_axis_style=True,
                                   axis_line_visible=False,
                                   component=plot)

        if self.y_lbl_type == 'Custom' and \
            len(self.y_labels) == self.data.shape[0]:
            # a new value in the list defaults to None so raise an error before
            # the operator ends inputing it.

            left_axis = LabelAxis(component=plot,
                                  orientation='left',
                                  title=self.x_lbl,
                                  mapper=corr_plot.value_mapper,
                                  tick_interval=1.0,
                                  labels=self.y_labels,
                                  positions=index_y)
        else:
            left_axis = PlotAxis(
                component=plot,
                orientation='left',
                title=self.y_lbl,
                title_font="modern 12",
                #title_spacing=0,
                tick_label_font="modern 8",
                tick_visible=True,
                small_axis_style=True,
                axis_line_visible=False,
                ensure_labels_bounded=True,
                #tick_label_color="transparent",
                mapper=corr_plot.value_mapper)

        plot.overlays.extend([bottom_axis, left_axis])

        plot.add(corr_plot)

        plot.padding_bottom = 50

        return plot
Пример #21
0
def clone_plot(clonetool, drop_position):
    # A little sketchy...
    canvas = clonetool.component.container.component.component

    # Create a new Plot object
    oldplot = clonetool.component
    newplot = Plot(oldplot.data)
    basic_traits = ["orientation", "default_origin", "bgcolor", "border_color",
                    "border_width", "border_visible", "draw_layer", "unified_draw",
                    "fit_components", "fill_padding", "visible", "aspect_ratio",
                    "title"]

    for attr in basic_traits:
        setattr(newplot, attr, getattr(oldplot, attr))

    # copy the ranges
    dst = newplot.range2d
    src = oldplot.range2d
    #for attr in ('_low_setting', '_low_value', '_high_setting', '_high_value'):
    #    setattr(dst, attr, getattr(src, attr))
    dst._xrange.sources = copy(src._xrange.sources)
    dst._yrange.sources = copy(src._yrange.sources)

    newplot.padding = oldplot.padding
    newplot.bounds = oldplot.bounds[:]
    newplot.resizable = ""
    newplot.position = drop_position

    newplot.datasources = copy(oldplot.datasources)

    for name, renderers in oldplot.plots.items():
        newrenderers = []
        for renderer in renderers:
            new_r = clone_renderer(renderer)
            new_r.index_mapper = LinearMapper(range=newplot.index_range)
            new_r.value_mapper = LinearMapper(range=newplot.value_range)
            new_r._layout_needed = True
            new_r.invalidate_draw()
            new_r.resizable = "hv"
            newrenderers.append(new_r)
        newplot.plots[name] = newrenderers
    #newplot.plots = copy(oldplot.plots)

    for name, renderers in newplot.plots.items():
        newplot.add(*renderers)

    newplot.index_axis.title = oldplot.index_axis.title
    newplot.index_axis.unified_draw = True
    newplot.value_axis.title = oldplot.value_axis.title
    newplot.value_axis.unified_draw = True

    # Add new tools to the new plot
    newplot.tools.append(AxisTool(component=newplot,
        range_controller=canvas.range_controller))

    # Add tools to the new plot
    pan_traits = ["drag_button", "constrain", "constrain_key", "constrain_direction",
                  "speed"]
    zoom_traits = ["tool_mode", "always_on", "axis", "enable_wheel", "drag_button",
                   "wheel_zoom_step", "enter_zoom_key", "exit_zoom_key", "pointer",
                   "color", "alpha", "border_color", "border_size", "disable_on_complete",
                   "minimum_screen_delta", "max_zoom_in_factor", "max_zoom_out_factor"]
    move_traits = ["drag_button", "end_drag_on_leave", "cancel_keys", "capture_mouse",
                   "modifier_key"]

    if not MULTITOUCH:
        for tool in oldplot.tools:
            if isinstance(tool, PanTool):
                newtool = tool.clone_traits(pan_traits)
                newtool.component = newplot
                break
        else:
            newtool = PanTool(newplot)
        # Reconfigure the pan tool to always use the left mouse, because we will
        # put plot move on the right mouse button
        newtool.drag_button = "left"
        newplot.tools.append(newtool)

        for tool in oldplot.tools:
            if isinstance(tool, MoveTool):
                newtool = tool.clone_traits(move_traits)
                newtool.component = newplot
                break
        else:
            newtool = MoveTool(newplot, drag_button="right")
        newplot.tools.append(newtool)

        for tool in oldplot.tools:
            if isinstance(tool, ZoomTool):
                newtool = tool.clone_traits(zoom_traits)
                newtool.component = newplot
                break
        else:
            newtool = ZoomTool(newplot)
        newplot.tools.append(newtool)

    else:
        pz = MPPanZoom(newplot)
        #pz.pan.constrain = True
        #pz.pan.constrain_direction = "x"
        #pz.zoom.mode = "range"
        #pz.zoom.axis = "index"
        newplot.tools.append(MPPanZoom(newplot))
        #newplot.tools.append(MTMoveTool(

    newplot._layout_needed = True

    clonetool.dest.add(newplot)
    newplot.invalidate_draw()
    newplot.request_redraw()
    canvas.request_redraw()
    return
Пример #22
0
def _create_plot_component(obj):
    # Setup the spectrum plot

    frequencies = linspace(0.0, 16, num=16)  ##
    obj.spectrum_data = ArrayPlotData(frequency=frequencies)
    empty_amplitude = zeros(16)  ##
    obj.spectrum_data.set_data('amplitude', empty_amplitude)
    background = array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) * 20
    obj.spectrum_data.set_data('background', background)

    obj.spectrum_plot = Plot(obj.spectrum_data)

    obj.spectrum_plot.plot(("frequency", "background"), value_scale="linear",\
    type='bar', bar_width=0.8, color='auto')
    obj.spectrum_plot.plot(("frequency", "amplitude"), value_scale="linear",\
    name="Spectrum", type='bar', bar_width=0.8, color='auto')#[0]
    obj.spectrum_plot.padding = 50
    obj.spectrum_plot.title = "Spectrum"
    spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range
    spec_range.low = 0.0
    spec_range.high = 75.0
    obj.spectrum_plot.index_axis.title = 'Frequency (hz)'
    obj.spectrum_plot.value_axis.title = 'Amplitude'

    # Word Plots
    # Setup the unseen spectrum plot
    dum_frequencies = linspace(0.0,
                               float(SAMPLING_RATE) / 4,
                               num=NUM_SAMPLES / 4)
    obj.dum_spectrum_data = ArrayPlotData(frequency=dum_frequencies)
    dum_empty_amplitude = zeros(NUM_SAMPLES / 4)
    obj.dum_spectrum_data.set_data('amplitude', dum_empty_amplitude)

    obj.dum_spectrum_plot = Plot(obj.dum_spectrum_data)
    spec_renderer = obj.dum_spectrum_plot.plot(("frequency", "amplitude"),
                                               name="Spectrum",
                                               color="red")[0]

    values = [zeros(NUM_SAMPLES / 4) for i in xrange(SPECTROGRAM_LENGTH)]

    p = WaterfallRenderer(index = spec_renderer.index, values = values,
            index_mapper = LinearMapper(range = obj.dum_spectrum_plot.\
            index_mapper.range),
            value_mapper = LinearMapper(range = DataRange1D(low=0,\
            high=SPECTROGRAM_LENGTH)),
            y2_mapper = LinearMapper(low_pos=0, high_pos=8,
                            range=DataRange1D(low=0, high=15)),
            )
    spectrogram_plot = p
    obj.spectrogram_plot = p
    dummy = Plot()
    dummy.title = "Current Spectral Envelope"
    dummy.padding = 50
    dummy.index_axis.mapper.range = p.index_mapper.range
    dummy.index_axis.title = "Frequency (hz)"
    dummy.add(p)

    values2 = [zeros(NUM_SAMPLES / 4) for i in xrange(SPECTROGRAM_LENGTH)]
    p2 = WaterfallRenderer(index = spec_renderer.index, values = values2,
            index_mapper = LinearMapper(range = obj.dum_spectrum_plot.\
            index_mapper.range),
            value_mapper = LinearMapper(range = DataRange1D(low=0,\
            high=SPECTROGRAM_LENGTH)),
            y2_mapper = LinearMapper(low_pos=0, high_pos=8,
                            range=DataRange1D(low=0, high=15)),
            )
    spectrogram_plot2 = p2
    obj.spectrogram_plot2 = p2
    dummy2 = Plot()
    dummy2.title = "Target Spectral Envelope"
    dummy2.padding = 50
    dummy2.index_axis.mapper.range = p.index_mapper.range
    dummy2.index_axis.title = "Frequency (hz)"
    dummy2.add(p2)

    container = HPlotContainer()
    container.add(dummy)
    container.add(dummy2)

    c2 = VPlotContainer()
    c2.add(container)
    c2.add(obj.spectrum_plot)

    return c2
Пример #23
0
def _create_plot_component(obj):
    # Setup the spectrum plot
    frequencies = linspace(0.0, float(SAMPLING_RATE) / 2, num=NUM_SAMPLES / 2)
    obj.spectrum_data = ArrayPlotData(frequency=frequencies)
    empty_amplitude = zeros(NUM_SAMPLES / 2)
    obj.spectrum_data.set_data('amplitude', empty_amplitude)

    obj.spectrum_plot = Plot(obj.spectrum_data)
    spec_renderer = obj.spectrum_plot.plot(("frequency", "amplitude"),
                                           name="Spectrum",
                                           color="red")[0]
    obj.spectrum_plot.padding = 50
    obj.spectrum_plot.title = "Spectrum"
    spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range
    spec_range.low = 0.0
    spec_range.high = 5.0
    obj.spectrum_plot.index_axis.title = 'Frequency (hz)'
    obj.spectrum_plot.value_axis.title = 'Amplitude'

    # Time Series plot
    times = linspace(0.0, float(NUM_SAMPLES) / SAMPLING_RATE, num=NUM_SAMPLES)
    obj.time_data = ArrayPlotData(time=times)
    empty_amplitude = zeros(NUM_SAMPLES)
    obj.time_data.set_data('amplitude', empty_amplitude)

    obj.time_plot = Plot(obj.time_data)
    obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue")
    obj.time_plot.padding = 50
    obj.time_plot.title = "Time"
    obj.time_plot.index_axis.title = 'Time (seconds)'
    obj.time_plot.value_axis.title = 'Amplitude'
    time_range = obj.time_plot.plots.values()[0][0].value_mapper.range
    time_range.low = -0.2
    time_range.high = 0.2

    # Spectrogram plot
    values = [zeros(NUM_SAMPLES / 2) for i in xrange(SPECTROGRAM_LENGTH)]
    p = WaterfallRenderer(
        index=spec_renderer.index,
        values=values,
        index_mapper=LinearMapper(range=obj.spectrum_plot.index_mapper.range),
        value_mapper=LinearMapper(
            range=DataRange1D(low=0, high=SPECTROGRAM_LENGTH)),
        y2_mapper=LinearMapper(low_pos=0,
                               high_pos=8,
                               range=DataRange1D(low=0, high=15)),
    )
    spectrogram_plot = p
    obj.spectrogram_plot = p
    dummy = Plot()
    dummy.padding = 50
    dummy.index_axis.mapper.range = p.index_mapper.range
    dummy.index_axis.title = "Frequency (hz)"
    dummy.add(p)

    container = HPlotContainer()
    container.add(obj.spectrum_plot)
    container.add(obj.time_plot)

    c2 = VPlotContainer()
    c2.add(dummy)
    c2.add(container)

    return c2
Пример #24
0
class plot_window (HasTraits):
    _plot_data = Instance(ArrayPlotData)
    _plot = Instance(Plot)
    _click_tool = Instance(clicker_tool)
    _img_plot = Instance(ImagePlot)
    _right_click_avail = 0
    name = Str
    view = View(
        Item(name='_plot', editor=ComponentEditor(), show_label=False),

    )

    def __init__(self):
        # -------------- Initialization of plot system ----------------
        padd = 25
        self._plot_data = ArrayPlotData()
        self._x = []
        self._y = []
        self.man_ori = [1, 2, 3, 4]
        self._plot = Plot(self._plot_data, default_origin="top left")
        self._plot.padding_left = padd
        self._plot.padding_right = padd
        self._plot.padding_top = padd
        self._plot.padding_bottom = padd
        self._quiverplots = []

        # -------------------------------------------------------------
    def left_clicked_event(self):
        print ("left clicked")
        if len(self._x) < 4:
            self._x.append(self._click_tool.x)
            self._y.append(self._click_tool.y)
        print self._x
        print self._y
        self.drawcross("coord_x", "coord_y", self._x, self._y, "red", 5)
        self._plot.overlays = []
        self.plot_num_overlay(self._x, self._y, self.man_ori)

    def right_clicked_event(self):
        print ("right clicked")
        if len(self._x) > 0:
            self._x.pop()
            self._y.pop()
            print self._x
            print self._y
            self.drawcross("coord_x", "coord_y", self._x, self._y, "red", 5)
            self._plot.overlays = []
            self.plot_num_overlay(self._x, self._y, self.man_ori)
        else:
            if (self._right_click_avail):
                print "deleting point"
                self.py_rclick_delete(self._click_tool.x,
                                      self._click_tool.y, self.cameraN)
                x = []
                y = []
                self.py_get_pix_N(x, y, self.cameraN)
                self.drawcross("x", "y", x[0], y[0], "blue", 4)

    def attach_tools(self):
        self._click_tool = clicker_tool(self._img_plot)
        self._click_tool.on_trait_change(
            self.left_clicked_event, 'left_changed')
        self._click_tool.on_trait_change(
            self.right_clicked_event, 'right_changed')
        self._img_plot.tools.append(self._click_tool)
        self._zoom_tool = SimpleZoom(
            component=self._plot, tool_mode="box", always_on=False)
        self._zoom_tool.max_zoom_out_factor = 1.0
        self._img_plot.tools.append(self._zoom_tool)
        if self._plot.index_mapper is not None:
            self._plot.index_mapper.on_trait_change(
                self.handle_mapper, 'updated', remove=False)
        if self._plot.value_mapper is not None:
            self._plot.value_mapper.on_trait_change(
                self.handle_mapper, 'updated', remove=False)

    def drawcross(self, str_x, str_y, x, y, color1, mrk_size):
        self._plot_data.set_data(str_x, x)
        self._plot_data.set_data(str_y, y)
        self._plot.plot((str_x, str_y), type="scatter",
                        color=color1, marker="plus", marker_size=mrk_size)
        self._plot.request_redraw()

    def drawline(self, str_x, str_y, x1, y1, x2, y2, color1):
        self._plot_data.set_data(str_x, [x1, x2])
        self._plot_data.set_data(str_y, [y1, y2])
        self._plot.plot((str_x, str_y), type="line", color=color1)
        self._plot.request_redraw()

    def drawquiver(self, x1c, y1c, x2c, y2c, color, linewidth=1.0):
        """ drawquiver draws multiple lines at once on the screen x1,y1->x2,y2 in the current camera window
        parameters:
            x1c - array of x1 coordinates
            y1c - array of y1 coordinates
            x2c - array of x2 coordinates
            y2c - array of y2 coordinates
            color - color of the line
            linewidth - linewidth of the line
        example usage:
            drawquiver ([100,200],[100,100],[400,400],[300,200],'red',linewidth=2.0)
            draws 2 red lines with thickness = 2 :  100,100->400,300 and 200,100->400,200

        """
        x1, y1, x2, y2 = self.remove_short_lines(x1c, y1c, x2c, y2c)
        if len(x1) > 0:
            xs = ArrayDataSource(x1)
            ys = ArrayDataSource(y1)

            quiverplot = QuiverPlot(index=xs, value=ys,
                                    index_mapper=LinearMapper(
                                        range=self._plot.index_mapper.range),
                                    value_mapper=LinearMapper(
                                        range=self._plot.value_mapper.range),
                                    origin=self._plot.origin, arrow_size=0,
                                    line_color=color, line_width=linewidth, ep_index=np.array(x2), ep_value=np.array(y2)
                                    )
            self._plot.add(quiverplot)
            # we need this to track how many quiverplots are in the current
            # plot
            self._quiverplots.append(quiverplot)
            # import pdb; pdb.set_trace()

    def remove_short_lines(self, x1, y1, x2, y2):
        """ removes short lines from the array of lines
        parameters:
            x1,y1,x2,y2 - start and end coordinates of the lines
        returns:
            x1f,y1f,x2f,y2f - start and end coordinates of the lines, with short lines removed
        example usage:
            x1,y1,x2,y2=remove_short_lines([100,200,300],[100,200,300],[100,200,300],[102,210,320])
            3 input lines, 1 short line will be removed (100,100->100,102)
            returned coordinates:
            x1=[200,300]; y1=[200,300]; x2=[200,300]; y2=[210,320]
        """
        dx, dy = 2, 2  # minimum allowable dx,dy
        x1f, y1f, x2f, y2f = [], [], [], []
        for i in range(len(x1)):
            if abs(x1[i] - x2[i]) > dx or abs(y1[i] - y2[i]) > dy:
                x1f.append(x1[i])
                y1f.append(y1[i])
                x2f.append(x2[i])
                y2f.append(y2[i])
        return x1f, y1f, x2f, y2f

    def handle_mapper(self):
        for i in range(0, len(self._plot.overlays)):
            if hasattr(self._plot.overlays[i], 'real_position'):
                coord_x1, coord_y1 = self._plot.map_screen(
                    [self._plot.overlays[i].real_position])[0]
                self._plot.overlays[i].alternate_position = (
                    coord_x1, coord_y1)

    def plot_num_overlay(self, x, y, txt):
        for i in range(0, len(x)):
            coord_x, coord_y = self._plot.map_screen([(x[i], y[i])])[0]
            ovlay = TextBoxOverlay(component=self._plot,
                                   text=str(txt[i]), alternate_position=(coord_x, coord_y),
                                   real_position=(x[i], y[i]),
                                   text_color="white",
                                   border_color="red"
                                   )
            self._plot.overlays.append(ovlay)

    def update_image(self, image, is_float):
        if is_float:
            self._plot_data.set_data('imagedata', image.astype(np.float))
        else:
            self._plot_data.set_data('imagedata', image.astype(np.byte))
        self._plot.request_redraw()
Пример #25
0
    def create_hplot(self, key=None, mini=False):
        if mini:
            hpc = HPlotContainer(bgcolor='darkgrey',
                                 height=MINI_HEIGHT,
                                 resizable='h',
                                 padding=HPLOT_PADDING
                                 )
        else:
            hpc = HPlotContainer(bgcolor='lightgrey',
                                 padding=HPLOT_PADDING,
                                 resizable='hv'
                                 )

        # make slice plot for showing intesity profile of main plot
        #************************************************************
        slice_plot = Plot(self.data,
                          width=SLICE_PLOT_WIDTH,
                          orientation="v",
                          resizable="v",
                          padding=MAIN_PADDING,
                          padding_left=MAIN_PADDING_LEFT,
                          padding_bottom=MAIN_PADDING_BOTTOM,
                          bgcolor='beige',
                          origin='top left'
                          )
        mini_slice = Plot(self.data,
                          width=SLICE_PLOT_WIDTH,
                          orientation="v",
                          resizable="v",
                          padding=MAIN_PADDING,
                          padding_left=MAIN_PADDING_LEFT,
                          padding_bottom=MAIN_PADDING_BOTTOM,
                          bgcolor='beige',
                          origin='top left'
                          )
        slice_plot.x_axis.visible = True
        slice_key = key + '_slice'
        ydata_key = key + '_y'
        slice_plot.plot((ydata_key, slice_key), name=slice_key)

        # make plot to show line at depth of cursor.  y values constant
        slice_depth_key = key + '_depth'
        slice_plot.plot(('slice_depth_depth', 'slice_depth_y'),
                        name=slice_depth_key, color='red')
        self.update_slice_depth_line_plot(slice_plot, depth=0)

        # make main plot for editing depth lines
        #************************************************************
        main = Plot(self.data,
                    border_visible=True,
                    bgcolor='beige',
                    origin='top left',
                    padding=MAIN_PADDING,
                    padding_left=MAIN_PADDING_LEFT,
                    padding_bottom=MAIN_PADDING_BOTTOM
                    )
        if mini:
            #main.padding = MINI_PADDING
            main.padding_bottom = MINI_PADDING_BOTTOM

        # add intensity img to plot and get reference for line inspector
        #************************************************************
        img_plot = main.img_plot(key, name=key,
                                 xbounds=self.model.xbounds[key],
                                 ybounds=self.model.ybounds[key],
                                 colormap=self._cmap
                                 )[0]

        # add line plots: use method since these may change
        #************************************************************
        self.update_line_plots(key, main, update=True)
        self.plot_mask_array(key, main)

        # set slice plot index range to follow main plot value range
        #************************************************************
        slice_plot.index_range = main.value_range

        # add vertical core lines to main plots and slices
        #************************************************************
        # save pos and distance in session dict for view info and control
        for core in self.model.core_samples:
            # add boundarys to slice plot
            self.plot_core_depths(slice_plot, core, ref_depth_line=None)
            # add positions to main plots
            self.plot_core(main, core, ref_depth_line=None)

        # now add tools depending if it is a mini plot or not
        #************************************************************
        if mini:
            # add range selection tool only
            # first add a reference line to attach it to
            reference = self.make_reference_plot()
            main.add(reference)
            main.plots['reference'] = [reference]
            # attache range selector to this plot
            range_tool = RangeSelection(reference)
            reference.tools.append(range_tool)
            range_overlay = RangeSelectionOverlay(reference,
                                                  metadata_name="selections")
            reference.overlays.append(range_overlay)
            range_tool.on_trait_change(self._range_selection_handler,
                                       "selection")
            # add zoombox to mini plot
            main.plot(('zoombox_x', 'zoombox_y'), type='polygon',
                      face_color=ZOOMBOX_COLOR, alpha=ZOOMBOX_ALPHA)
            # add to hplot and dict
            hpc.add(main, mini_slice)
            self.hplot_dict['mini'] = hpc

        else:
            # add zoom tools
            zoom = ZoomTool(main, tool_mode='box', axis='both', alpha=0.5,
                            drag_button="left")
            main.tools.append(zoom)
            main.overlays.append(zoom)
            self.zoom_tools[key] = zoom
            main.value_mapper.on_trait_change(self.zoom_all_value, 'updated')
            main.index_mapper.on_trait_change(self.zoom_all_index, 'updated')

            # add line inspector and attach to freeze tool
            #*********************************************
            line_inspector = LineInspector(component=img_plot,
                                           axis='index_x',
                                           inspect_mode="indexed",
                                           is_interactive=True,
                                           write_metadata=True,
                                           metadata_name='x_slice',
                                           is_listener=True,
                                           color="white")

            img_plot.overlays.append(line_inspector)
            self.inspector_freeze_tool.tool_set.add(line_inspector)

            # add listener for changes to metadata made by line inspector
            #************************************************************
            img_plot.on_trait_change(self.metadata_changed, 'index.metadata')

            # set slice plot index range to follow main plot value range
            #************************************************************
            slice_plot.index_range = main.value_range

            # add clickable legend ; must update legend when depth_dict updated
            #******************************************************************
            legend = Legend(component=main, padding=0,
                            align="ur", font='modern 8')
            legend_highlighter = LegendHighlighter(legend,
                                                   drag_button="right")
            legend.tools.append(legend_highlighter)
            self.legend_dict[key] = [legend, legend_highlighter]
            self.update_legend_plots(legend, main)
            legend.visible = False
            main.overlays.append(legend)
            legend_highlighter.on_trait_change(self.legend_moved, '_drag_state')

            # add pan tool
            pan_tool = PanTool(main, drag_button="right")
            main.tools.append(pan_tool)
            self.pan_tool_dict[key] = pan_tool

            # add main and slice plot to hplot container and dict
            #****************************************************
            main.title = 'frequency = {} kHz'.format(key)
            main.title_font = TITLE_FONT
            hpc.add(main, slice_plot)
            self.hplot_dict[key] = hpc

        return hpc
Пример #26
0
    def _get_plot_multiline(self):

        if self.data is None or len(self.data.shape) == 1:
            return

        numpoints = self.data.shape[1]

        if self.scale_type == 'Time':
            index_x = self._create_dates(numpoints, start=self.first_day)
        else:
            index_x = np.arange(numpoints)

        index_y = np.linspace(1, self.data.shape[0], self.data.shape[0])

        xs = ArrayDataSource(index_x)
        xrange = DataRange1D()
        xrange.add(xs)

        ys = ArrayDataSource(index_y)
        yrange = DataRange1D()
        yrange.add(ys)

        # The data source for the MultiLinePlot.
        ds = MultiArrayDataSource(data=self.data)

        corr_plot = \
            MultiLinePlot(
                index=xs,
                yindex=ys,
                index_mapper=LinearMapper(range=xrange),
                value_mapper=LinearMapper(range=yrange),
                value=ds,
                global_max=self.data.max(),
                global_min=self.data.min())

        corr_plot.value_mapper.range.low = 0
        corr_plot.value_mapper.range.high = self.data.shape[0] + 1

        self.multi_line_plot_renderer = corr_plot

        plot = Plot(title=self.p_title)

        if self.scale_type == 'Time':
            # Just the last axis shows tick_labels
            bottom_axis = PlotAxis(component=plot, orientation="bottom", title=self.x_lbl,
                                   tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
        else:
            bottom_axis = PlotAxis(orientation='bottom',
                                   title=self.x_lbl,
                                   title_font="modern 12",
                                   tick_visible=True,
                                   small_axis_style=True,
                                   axis_line_visible=False,
                                   component=plot)

        if self.y_lbl_type == 'Custom' and \
            len(self.y_labels) == self.data.shape[0]:
            # a new value in the list defaults to None so raise an error before
            # the operator ends inputing it. 

            left_axis = LabelAxis(component=plot,
                                  orientation='left',
                                  title=self.x_lbl,
                                  mapper=corr_plot.value_mapper,
                                  tick_interval=1.0,
                                  labels=self.y_labels,
                                  positions=index_y)
        else:
            left_axis = PlotAxis(component=plot,
                                 orientation='left',
                                 title=self.y_lbl,
                                 title_font="modern 12",
                                 #title_spacing=0,
                                 tick_label_font="modern 8",
                                 tick_visible=True,
                                 small_axis_style=True,
                                 axis_line_visible=False,
                                 ensure_labels_bounded=True,
                                 #tick_label_color="transparent",
                                 mapper=corr_plot.value_mapper)


        plot.overlays.extend([bottom_axis, left_axis])

        plot.add(corr_plot)

        plot.padding_bottom = 50

        return plot
Пример #27
0
class CameraWindow (HasTraits):
	""" CameraWindow class contains the relevant information and functions for a single camera window: image, zoom, pan
	important members:
		_plot_data  - contains image data to display (used by update_image)
		_plot - instance of Plot class to use with _plot_data
		_click_tool - instance of Clicker tool for the single camera window, to handle mouse processing
	"""
	_plot_data=Instance(ArrayPlotData)
	_plot=Instance(Plot)
	_click_tool=Instance(Clicker)
	rclicked=Int(0)
	
	cam_color = ''

	name=Str
	view = View( Item(name='_plot',editor=ComponentEditor(), show_label=False) )
	# view = View( Item(name='_plot',show_label=False) )
   
	def __init__(self, color):
		""" Initialization of plot system 
		"""
		padd=25
		self._plot_data=ArrayPlotData()
		self._plot=Plot(self._plot_data, default_origin="top left")
		self._plot.padding_left=padd
		self._plot.padding_right=padd
		self._plot.padding_top=padd
		self._plot.padding_bottom=padd
		self.right_p_x0,self.right_p_y0,self.right_p_x1,self.right_p_y1,self._quiverplots=[],[],[],[],[]
		self.cam_color = color

	def attach_tools(self):
		""" attach_tools(self) contains the relevant tools: clicker, pan, zoom
		"""
		self._click_tool=Clicker(self._img_plot)
		self._click_tool.on_trait_change(self.left_clicked_event, 'left_changed') #set processing events for Clicker
		self._click_tool.on_trait_change(self.right_clicked_event, 'right_changed')
		self._img_plot.tools.append(self._click_tool)
		pan = PanTool(self._plot, drag_button = 'middle')
		zoom_tool= ZoomTool(self._plot, tool_mode="box", always_on=False)
#		zoom_tool = BetterZoom(component=self._plot, tool_mode="box", always_on=False)
		zoom_tool.max_zoom_out_factor=1.0 # Disable "bird view" zoom out
		self._img_plot.overlays.append(zoom_tool)
		self._img_plot.tools.append(pan)

		
	def left_clicked_event(self): #TODO: why do we need the clicker_tool if we can handle mouse clicks here?
		""" left_clicked_event - processes left click mouse avents and displays coordinate and grey value information
		on the screen
		"""
		print "x = %d, y= %d, grey= %d " % (self._click_tool.x,self._click_tool.y,self._click_tool.data_value)
		#need to priny gray value

	def right_clicked_event(self):
		self.rclicked=1 #flag that is tracked by main_gui, for right_click_process function of main_gui
		#self._click_tool.y,self.name])
		#self.drawcross("coord_x","coord_y",self._click_tool.x,self._click_tool.y,"red",5)
		#print ("right clicked, "+self.name)
		#need to print cross and manage other camera's crosses


	def update_image(self,image,is_float):
		""" update_image - displays/updates image in the curren camera window
		parameters:
			image - image data
			is_float - if true, displays an image as float array,
			else displays as byte array (B&W or gray)
		example usage:
			update_image(image,is_float=False)
		"""
		if is_float:
			self._plot_data.set_data('imagedata',image.astype(np.float))
		else:
			self._plot_data.set_data('imagedata',image.astype(np.byte))
	   
		if not hasattr(self,'_img_plot'): #make a new plot if there is nothing to update
			self._img_plot=Instance(ImagePlot)
			self._img_plot=self._plot.img_plot('imagedata',colormap=gray)[0]
			self.attach_tools()
			
			
		   # self._plot.request_redraw()

	def drawcross(self, str_x,str_y,x,y,color1,mrk_size,marker1="plus"):
		""" drawcross draws crosses at a given location (x,y) using color and marker in the current camera window
		parameters:
			str_x - label for x coordinates
			str_y - label for y coordinates
			x - array of x coordinates
			y - array of y coordinates
			mrk_size - marker size
			makrer1 - type of marker, e.g "plus","circle"
		example usage:
			drawcross("coord_x","coord_y",[100,200,300],[100,200,300],2)
			draws plus markers of size 2 at points (100,100),(200,200),(200,300)
		"""
		self._plot_data.set_data(str_x,x)
		self._plot_data.set_data(str_y,y)
		self._plot.plot((str_x,str_y),type="scatter",color=color1,marker=marker1,marker_size=mrk_size)
		#self._plot.request_redraw()

	def drawquiver(self,x1c,y1c,x2c,y2c,color,linewidth=1.0):
		""" drawquiver draws multiple lines at once on the screen x1,y1->x2,y2 in the current camera window
		parameters:
			x1c - array of x1 coordinates
			y1c - array of y1 coordinates
			x2c - array of x2 coordinates
			y2c - array of y2 coordinates
			color - color of the line
			linewidth - linewidth of the line
		example usage:
			drawquiver ([100,200],[100,100],[400,400],[300,200],'red',linewidth=2.0)
			draws 2 red lines with thickness = 2 :  100,100->400,300 and 200,100->400,200
					
		"""
		x1,y1,x2,y2=self.remove_short_lines(x1c,y1c,x2c,y2c)
		if len(x1)>0:
			xs=ArrayDataSource(x1)
			ys=ArrayDataSource(y1)

			quiverplot=QuiverPlot(index=xs,value=ys,\
								  index_mapper=LinearMapper(range=self._plot.index_mapper.range),\
								  value_mapper=LinearMapper(range=self._plot.value_mapper.range),\
								  origin = self._plot.origin,arrow_size=0,\
								  line_color=color,line_width=linewidth,ep_index=np.array(x2),ep_value=np.array(y2)
								  )
			self._plot.add(quiverplot)
			self._quiverplots.append(quiverplot) #we need this to track how many quiverplots are in the current plot
			# import pdb; pdb.set_trace()
			
	def remove_short_lines(self,x1,y1,x2,y2):
		""" removes short lines from the array of lines 
		parameters:
			x1,y1,x2,y2 - start and end coordinates of the lines
		returns:
			x1f,y1f,x2f,y2f - start and end coordinates of the lines, with short lines removed
		example usage:
			x1,y1,x2,y2=remove_short_lines([100,200,300],[100,200,300],[100,200,300],[102,210,320])
			3 input lines, 1 short line will be removed (100,100->100,102)
			returned coordinates:
			x1=[200,300]; y1=[200,300]; x2=[200,300]; y2=[210,320]
		"""
		dx,dy=2,2 #minimum allowable dx,dy
		x1f,y1f,x2f,y2f=[],[],[],[]
		for i in range(len(x1)):
			if abs(x1[i]-x2[i])>dx or abs(y1[i]-y2[i])>dy:
				x1f.append(x1[i])
				y1f.append(y1[i])
				x2f.append(x2[i])
				y2f.append(y2[i])
		return x1f,y1f,x2f,y2f
				
	def drawline(self,str_x,str_y,x1,y1,x2,y2,color1):
		""" drawline draws 1 line on the screen by using lineplot x1,y1->x2,y2
		parameters:
			str_x - label of x coordinate
			str_y - label of y coordinate
			x1,y1,x2,y2 - start and end coordinates of the line
			color1 - color of the line
		example usage:
			drawline("x_coord","y_coord",100,100,200,200,red)
			draws a red line 100,100->200,200
		"""
		self._plot_data.set_data(str_x,[x1,x2])
		self._plot_data.set_data(str_y,[y1,y2])
		self._plot.plot((str_x,str_y),type="line",color=color1)
Пример #28
0
def _create_plot_component(obj):
    # Setup the spectrum plot

    frequencies = linspace(0.0, 16, num=16)  ##
    obj.spectrum_data = ArrayPlotData(frequency=frequencies)
    empty_amplitude = zeros(16)  ##
    obj.spectrum_data.set_data("amplitude", empty_amplitude)
    background = array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) * 20
    obj.spectrum_data.set_data("background", background)

    obj.spectrum_plot = Plot(obj.spectrum_data)

    obj.spectrum_plot.plot(("frequency", "background"), value_scale="linear", type="bar", bar_width=0.8, color="auto")
    obj.spectrum_plot.plot(
        ("frequency", "amplitude"), value_scale="linear", name="Spectrum", type="bar", bar_width=0.8, color="auto"
    )  # [0]
    obj.spectrum_plot.padding = 50
    obj.spectrum_plot.title = "Spectrum"
    spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range
    spec_range.low = 0.0
    spec_range.high = 75.0
    obj.spectrum_plot.index_axis.title = "Frequency (hz)"
    obj.spectrum_plot.value_axis.title = "Amplitude"

    # Word Plots
    # Setup the unseen spectrum plot
    dum_frequencies = linspace(0.0, float(SAMPLING_RATE) / 4, num=NUM_SAMPLES / 4)
    obj.dum_spectrum_data = ArrayPlotData(frequency=dum_frequencies)
    dum_empty_amplitude = zeros(NUM_SAMPLES / 4)
    obj.dum_spectrum_data.set_data("amplitude", dum_empty_amplitude)

    obj.dum_spectrum_plot = Plot(obj.dum_spectrum_data)
    spec_renderer = obj.dum_spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red")[0]

    values = [zeros(NUM_SAMPLES / 4) for i in xrange(SPECTROGRAM_LENGTH)]

    p = WaterfallRenderer(
        index=spec_renderer.index,
        values=values,
        index_mapper=LinearMapper(range=obj.dum_spectrum_plot.index_mapper.range),
        value_mapper=LinearMapper(range=DataRange1D(low=0, high=SPECTROGRAM_LENGTH)),
        y2_mapper=LinearMapper(low_pos=0, high_pos=8, range=DataRange1D(low=0, high=15)),
    )
    spectrogram_plot = p
    obj.spectrogram_plot = p
    dummy = Plot()
    dummy.title = "Current Spectral Envelope"
    dummy.padding = 50
    dummy.index_axis.mapper.range = p.index_mapper.range
    dummy.index_axis.title = "Frequency (hz)"
    dummy.add(p)

    values2 = [zeros(NUM_SAMPLES / 4) for i in xrange(SPECTROGRAM_LENGTH)]
    p2 = WaterfallRenderer(
        index=spec_renderer.index,
        values=values2,
        index_mapper=LinearMapper(range=obj.dum_spectrum_plot.index_mapper.range),
        value_mapper=LinearMapper(range=DataRange1D(low=0, high=SPECTROGRAM_LENGTH)),
        y2_mapper=LinearMapper(low_pos=0, high_pos=8, range=DataRange1D(low=0, high=15)),
    )
    spectrogram_plot2 = p2
    obj.spectrogram_plot2 = p2
    dummy2 = Plot()
    dummy2.title = "Target Spectral Envelope"
    dummy2.padding = 50
    dummy2.index_axis.mapper.range = p.index_mapper.range
    dummy2.index_axis.title = "Frequency (hz)"
    dummy2.add(p2)

    container = HPlotContainer()
    container.add(dummy)
    container.add(dummy2)

    c2 = VPlotContainer()
    c2.add(container)
    c2.add(obj.spectrum_plot)

    return c2