Пример #1
0
    def init(self, parent):
        factory = self.factory
        container = OverlayPlotContainer(bgcolor='transparent',
                                         padding=0, spacing=0)

        window = Window(parent, component=container)

        interval = self.high - self.low
        data = ([self.low, self.high], [0.5]*2)
        plot = create_line_plot(data, color='black', bgcolor="sys_window")
        plot.x_mapper.range.low = self.low - interval*0.1
        plot.x_mapper.range.high = self.high + interval*0.1
        plot.y_mapper.range.high = 1.0
        plot.y_mapper.range.low = 0.0

        range_selection = RangeSelection(plot, left_button_selects=True)
        # Do not allow the user to reset the range
        range_selection.event_state = "selected"
        range_selection.deselect = lambda x: None
        range_selection.on_trait_change(self.update_interval, 'selection')

        plot.tools.append(range_selection)
        plot.overlays.append(RangeKnobsOverlay(plot))
        self.plot = plot
        container.add(self.plot)

        # To set the low and high, we're actually going to set the
        # 'selection' metadata on the line plot to the tuple (low,high).
        plot.index.metadata["selections"] = (0, 1.0)

        # Tell the editor what to display
        self.control = window.control
        self.control.SetSize((factory.width, factory.height))
Пример #2
0
    def __init__(self, **traits):
        super(HistDemo, self).__init__(**traits)
        img = cv.imread("lena.jpg")
        gray_img = cv.Mat()
        cv.cvtColor(img, gray_img, cv.CV_BGR2GRAY)
        self.img = gray_img
        self.img2 = self.img.clone()
        result = cv.MatND()

        r = cv.vector_float32([0, 256])
        ranges = cv.vector_vector_float32([r, r])

        cv.calcHist(cv.vector_Mat([self.img]),
                    channels=cv.vector_int([0, 1]),
                    mask=cv.Mat(),
                    hist=result,
                    histSize=cv.vector_int([256]),
                    ranges=ranges)

        data = ArrayPlotData(x=np.arange(0, len(result[:])), y=result[:])
        self.plot = Plot(data, padding=10)
        line = self.plot.plot(("x", "y"))[0]
        self.select_tool = RangeSelection(line, left_button_selects=True)
        line.tools.append(self.select_tool)
        self.select_tool.on_trait_change(self._selection_changed, "selection")
        line.overlays.append(RangeSelectionOverlay(component=line))

        cv.imshow("Hist Demo", self.img)

        self.timer = Timer(50, self.on_timer)
class HistDemo(HasTraits):
    plot = Instance(Plot)
    timer = Instance(Timer)
    need_update = Bool(False)
    view = View(
        Item("plot", editor=ComponentEditor(), show_label=False),
        resizable=True,
        width=500,
        height=250,
        title="Hist Demo",
    )

    def __init__(self, **traits):
        super(HistDemo, self).__init__(**traits)
        img = cv.imread("lena.jpg")
        gray_img = cv.Mat()
        cv.cvtColor(img, gray_img, cv.CV_BGR2GRAY)
        self.img = gray_img
        self.img2 = self.img.clone()
        result = cv.MatND()

        r = cv.vector_float32([0, 256])
        ranges = cv.vector_vector_float32([r, r])

        cv.calcHist(
            cv.vector_Mat([self.img]),
            channels=cv.vector_int([0, 1]),
            mask=cv.Mat(),
            hist=result,
            histSize=cv.vector_int([256]),
            ranges=ranges,
        )

        data = ArrayPlotData(x=np.arange(0, len(result[:])), y=result[:])
        self.plot = Plot(data, padding=10)
        line = self.plot.plot(("x", "y"))[0]
        self.select_tool = RangeSelection(line, left_button_selects=True)
        line.tools.append(self.select_tool)
        self.select_tool.on_trait_change(self._selection_changed, "selection")
        line.overlays.append(RangeSelectionOverlay(component=line))

        cv.imshow("Hist Demo", self.img)

        self.timer = Timer(50, self.on_timer)

    def _selection_changed(self):
        if self.select_tool.selection != None:
            self.need_update = True

    def on_timer(self):
        if self.need_update:
            x0, x1 = self.select_tool.selection
            self.img2[:] = self.img[:]
            np.clip(self.img2[:], x0, x1, out=self.img2[:])
            self.img2[:] -= x0
            self.img2[:] *= 256.0 / (x1 - x0)
            cv.imshow("Hist Demo", self.img2)
            self.need_update = False
Пример #4
0
class HistDemo(HasTraits):
    plot = Instance(Plot)
    timer = Instance(Timer)
    need_update = Bool(False)
    view = View(Item("plot", editor=ComponentEditor(), show_label=False),
                resizable=True,
                width=500,
                height=250,
                title="Hist Demo")

    def __init__(self, **traits):
        super(HistDemo, self).__init__(**traits)
        img = cv.imread("lena.jpg")
        gray_img = cv.Mat()
        cv.cvtColor(img, gray_img, cv.CV_BGR2GRAY)
        self.img = gray_img
        self.img2 = self.img.clone()
        result = cv.MatND()

        r = cv.vector_float32([0, 256])
        ranges = cv.vector_vector_float32([r, r])

        cv.calcHist(cv.vector_Mat([self.img]),
                    channels=cv.vector_int([0, 1]),
                    mask=cv.Mat(),
                    hist=result,
                    histSize=cv.vector_int([256]),
                    ranges=ranges)

        data = ArrayPlotData(x=np.arange(0, len(result[:])), y=result[:])
        self.plot = Plot(data, padding=10)
        line = self.plot.plot(("x", "y"))[0]
        self.select_tool = RangeSelection(line, left_button_selects=True)
        line.tools.append(self.select_tool)
        self.select_tool.on_trait_change(self._selection_changed, "selection")
        line.overlays.append(RangeSelectionOverlay(component=line))

        cv.imshow("Hist Demo", self.img)

        self.timer = Timer(50, self.on_timer)

    def _selection_changed(self):
        if self.select_tool.selection != None:
            self.need_update = True

    def on_timer(self):
        if self.need_update:
            x0, x1 = self.select_tool.selection
            self.img2[:] = self.img[:]
            np.clip(self.img2[:], x0, x1, out=self.img2[:])
            self.img2[:] -= x0
            self.img2[:] *= 256.0 / (x1 - x0)
            cv.imshow("Hist Demo", self.img2)
            self.need_update = False
Пример #5
0
    def setup_plots(self):
        '''
        
        Args: 
        Returns:
        Raises:
        '''  
        ext = self.extension
        
        if ext == "S2":
            color = "green"
        else:
            color = "blue"

        self.create_plot("AAE " + ext, ylabel="[ ]", color=color)
        self.create_plot("ARE " + ext, ylabel="[ ]", color=color)
        self.create_plot("Jerk " + ext, ylabel="[m/s2/s]", color=color)
        self.create_plot("SI " + ext, ylabel="[ ]", color=color)
        self.create_plot("VI " + ext, ylabel="[ ]", color=color)
        
        p = self.plots["VI " + ext]
        
        null_ds = ArrayDataSource([])
        self.time_plot = LinePlot(index = self.time_src, value = null_ds,
                        index_mapper = LinearMapper(range=DataRange1D(self.time_src)),
                        value_mapper = LinearMapper(range=DataRange1D(null_ds)),  
                        color = "black",
                        border_visible = True,
                        bgcolor = "white",
                        height = 10,
                        resizable = "h",
                        padding_top=50,
                        padding_bottom=40,
                        padding_left=50,
                        padding_right=20)
        self.ticker = ScalesTickGenerator()  
        self.x_axis = LabelAxis(self.time_plot, orientation="bottom", title="Time [sec]", label_rotation=0)
        #self.x_axis = PlotAxis(self.time_plot, orientation="bottom", tick_generator = self.ticker, title="Time [sec]")
        self.time_plot.underlays.append(self.x_axis)
        self.container.add(self.time_plot)
        
        # Add a range overlay to the miniplot that is hooked up to the range
        # of the main price_plot
        range_tool = RangeSelection(self.time_plot)
        self.time_plot.tools.append(range_tool)
        range_overlay = RangeSelectionOverlay(self.time_plot, metadata_name="selections")
        self.time_plot.overlays.append(range_overlay)
        range_tool.on_trait_change(self._range_selection_handler, "selection")
        self.range_tool = range_tool

        p.plot_conactory.index_range.on_trait_change(self._plot_range_handler, "updated")
        self.zoom_overlay = ZoomOverlay(source=self.time_plot, destination=p.plot_conactory)
        self.container.overlays.append(self.zoom_overlay)
Пример #6
0
    def _create_price_plots(self, times, prices, mini_height=75):
        """ Creates the two plots of prices and returns them.  One of the
        plots can be zoomed and panned, and the other plot (smaller) always
        shows the full data.

        *dates* and *prices* are two data sources.
        """

        # Create the price plot
        price_plot = FilledLinePlot(index = times, value = prices,
                        index_mapper = LinearMapper(range=DataRange1D(times)),
                        value_mapper = LinearMapper(range=DataRange1D(prices)),
                        edge_color = "blue",
                        face_color = "paleturquoise",
                        bgcolor = "white",
                        border_visible = True)

        # Add pan and zoom
        price_plot.tools.append(PanTool(price_plot, constrain=True,
                                        constrain_direction="x"))
        price_plot.overlays.append(ZoomTool(price_plot, drag_button="right",
                                              always_on=True,
                                              tool_mode="range",
                                              axis="index",
                                              max_zoom_out_factor=1.0,
                                             ))

        # Create the miniplot
        miniplot = LinePlot(index = times, value = prices,
                        index_mapper = LinearMapper(range=DataRange1D(times)),
                        value_mapper = LinearMapper(range=DataRange1D(prices)),
                        color = "black",
                        border_visible = True,
                        bgcolor = "white",
                        height = mini_height,
                        resizable = "h")

        # Add a range overlay to the miniplot that is hooked up to the range
        # of the main price_plot
        range_tool = RangeSelection(miniplot)
        miniplot.tools.append(range_tool)
        range_overlay = RangeSelectionOverlay(miniplot, metadata_name="selections")
        miniplot.overlays.append(range_overlay)
        range_tool.on_trait_change(self._range_selection_handler, "selection")

        # Attach a handler that sets the tool when the plot's index range changes
        self.range_tool = range_tool
        price_plot.index_range.on_trait_change(self._plot_range_handler, "updated")

        return price_plot, miniplot
    def __init__(self, **traits):
        super(HistDemo, self).__init__(**traits)
        img = cv.imread("lena.jpg")
        gray_img = cv.Mat()
        cv.cvtColor(img, gray_img, cv.CV_BGR2GRAY)
        self.img = gray_img
        self.img2 = self.img.clone()
        result = cv.MatND()

        r = cv.vector_float32([0, 256])
        ranges = cv.vector_vector_float32([r, r])

        cv.calcHist(
            cv.vector_Mat([self.img]),
            channels=cv.vector_int([0, 1]),
            mask=cv.Mat(),
            hist=result,
            histSize=cv.vector_int([256]),
            ranges=ranges,
        )

        data = ArrayPlotData(x=np.arange(0, len(result[:])), y=result[:])
        self.plot = Plot(data, padding=10)
        line = self.plot.plot(("x", "y"))[0]
        self.select_tool = RangeSelection(line, left_button_selects=True)
        line.tools.append(self.select_tool)
        self.select_tool.on_trait_change(self._selection_changed, "selection")
        line.overlays.append(RangeSelectionOverlay(component=line))

        cv.imshow("Hist Demo", self.img)

        self.timer = Timer(50, self.on_timer)
Пример #8
0
    def __init__(self, **kwargs):
        super(VariableMeshPannerView, self).__init__(**kwargs)
        # Create the plot
        self.add_trait("field", DelegatesTo("vm_plot"))

        plot = self.vm_plot.plot
        img_plot = self.vm_plot.img_plot

        if self.use_tools:
            plot.tools.append(PanTool(img_plot))
            zoom = ZoomTool(component=img_plot,
                            tool_mode="box",
                            always_on=False)
            plot.overlays.append(zoom)
            imgtool = ImageInspectorTool(img_plot)
            img_plot.tools.append(imgtool)
            overlay = ImageInspectorOverlay(component=img_plot,
                                            image_inspector=imgtool,
                                            bgcolor="white",
                                            border_visible=True)
            img_plot.overlays.append(overlay)

        image_value_range = DataRange1D(self.vm_plot.fid)
        cbar_index_mapper = LinearMapper(range=image_value_range)
        self.colorbar = ColorBar(index_mapper=cbar_index_mapper,
                                 plot=img_plot,
                                 padding_right=40,
                                 resizable='v',
                                 width=30)

        self.colorbar.tools.append(
            PanTool(self.colorbar, constrain_direction="y", constrain=True))
        zoom_overlay = ZoomTool(self.colorbar,
                                axis="index",
                                tool_mode="range",
                                always_on=True,
                                drag_button="right")
        self.colorbar.overlays.append(zoom_overlay)

        # create a range selection for the colorbar
        range_selection = RangeSelection(component=self.colorbar)
        self.colorbar.tools.append(range_selection)
        self.colorbar.overlays.append(
            RangeSelectionOverlay(component=self.colorbar,
                                  border_color="white",
                                  alpha=0.8,
                                  fill_color="lightgray"))

        # we also want to the range selection to inform the cmap plot of
        # the selection, so set that up as well
        range_selection.listeners.append(img_plot)

        self.full_container = HPlotContainer(padding=30)
        self.container = OverlayPlotContainer(padding=0)
        self.full_container.add(self.colorbar)
        self.full_container.add(self.container)
        self.container.add(self.vm_plot.plot)
Пример #9
0
    def __init__(self, **traits):
        super(SelectionDemo, self).__init__(**traits)
        x = np.linspace(-140, 140, 1000)
        y = np.sin(x) * x**3
        y /= np.max(y)
        data = ArrayPlotData(x=x, y=y)

        self.plot1 = plot1 = Plot(data, padding=25)
        self.line1 = line1 = plot1.plot(("x", "y"), type="line")[0]

        self.select_tool = select_tool = RangeSelection(line1)
        line1.tools.append(select_tool)
        select_tool.on_trait_change(self._selection_changed, "selection")

        line1.overlays.append(RangeSelectionOverlay(component=line1))

        self.plot2 = plot2 = Plot(data, padding=25)
        plot2.plot(("x", "y"), type="line")[0]

        self.plot = VPlotContainer(plot2, plot1)

        self.data = data
Пример #10
0
    def _create_complexspectrumplot(self, x, y1, y2):
        amplitudeplot = create_line_plot((x, y1), index_bounds=None, value_bounds=None,
                                         orientation='h', color='green', width=1.0, dash='solid',
                                         value_mapper_class=LinearMapper,
                                         bgcolor='white', border_visible=True,
                                         add_grid=False, add_axis=False, index_sort='ascending')
        add_default_axes(amplitudeplot, orientation='normal', htitle='Frequency [MHz]', vtitle='Amplitude')

        amplitudeplot.tools.append(PanTool(amplitudeplot, drag_button="right"))
        zoom = SimpleZoom(component=amplitudeplot, tool_mode="box", drag_button="left", always_on=True)
        amplitudeplot.overlays.append(zoom)

        phaseplot = create_line_plot((x, y2), index_bounds=None,
                                     value_bounds=None,
                                     orientation='h', color='red',
                                     width=1.0, dash='solid',
                                     value_mapper_class=LinearMapper,
                                     bgcolor='white', border_visible=True,
                                     add_grid=False, add_axis=False,
                                     index_sort='ascending')
        add_default_axes(phaseplot, orientation='normal',
                         htitle='Frequency [MHz]', vtitle='Unwrapped phase')

        #        phaseplot.tools.append(PanTool(phaseplot, drag_button="right"))
        zoom = SimpleZoom(component=phaseplot, tool_mode="box",
                          drag_button="left", always_on=True,
                          #                          enter_zoom_key=KeySpec('z')
        )
        phaseplot.overlays.append(zoom)
        self.rangeselect = RangeSelection(phaseplot, left_button_selects=False)
        self.rangeselect.on_trait_change(self.phase_center, "selection_completed")
        phaseplot.active_tool = self.rangeselect
        phaseplot.overlays.append(RangeSelectionOverlay(component=phaseplot))

        container = VPlotContainer(padding=40, padding_left=60, spacing=40)
        container.add(phaseplot)
        container.add(amplitudeplot)
        self.container = container
Пример #11
0
 def draw_colorbar(self):
     scatplot = self.scatplot
     cmap_renderer = scatplot.plots["my_plot"][0]
     selection = ColormappedSelectionOverlay(cmap_renderer,
                                             fade_alpha=0.35,
                                             selection_type="range")
     cmap_renderer.overlays.append(selection)
     if self.thresh is not None:
         cmap_renderer.color_data.metadata['selections'] = self.thresh
         cmap_renderer.color_data.metadata_changed = {
             'selections': self.thresh
         }
     # Create the colorbar, handing in the appropriate range and colormap
     colormap = scatplot.color_mapper
     colorbar = ColorBar(
         index_mapper=LinearMapper(range=DataRange1D(low=0.0, high=1.0)),
         orientation='v',
         resizable='v',
         width=30,
         padding=20)
     colorbar_selection = RangeSelection(component=colorbar)
     colorbar.tools.append(colorbar_selection)
     ovr = colorbar.overlays.append(
         RangeSelectionOverlay(component=colorbar,
                               border_color="white",
                               alpha=0.8,
                               fill_color="lightgray",
                               metadata_name='selections'))
     #ipshell('colorbar, colorbar_selection and ovr available:')
     self.cbar_selection = colorbar_selection
     self.cmap_renderer = cmap_renderer
     colorbar.plot = cmap_renderer
     colorbar.padding_top = scatplot.padding_top
     colorbar.padding_bottom = scatplot.padding_bottom
     self.colorbar = colorbar
     return colorbar
Пример #12
0
    def __init__(self):
        super(CyclesPlot, self).__init__()

        # Normally you'd pass in the data, but I'll hardwire things for this
        #    one-off plot.

        srecs = read_time_series_from_csv("./biz_cycles.csv", date_col=0, date_format="%Y-%m-%d")

        dt = srecs["Date"]

        # Industrial production compared with trend (plotted on value axis)
        iprod_vs_trend = srecs["Metric 1"]

        # Industrial production change in last 6 Months (plotted on index axis)
        iprod_delta = srecs["Metric 2"]

        self._dates = dt
        self._series1 = self._selected_s1 = iprod_delta
        self._series2 = self._selected_s2 = iprod_vs_trend

        end_x = np.array([self._selected_s1[-1]])
        end_y = np.array([self._selected_s2[-1]])

        plotdata = ArrayPlotData(
            x=self._series1,
            y=self._series2,
            dates=self._dates,
            selected_x=self._selected_s1,
            selected_y=self._selected_s2,
            endpoint_x=end_x,
            endpoint_y=end_y,
        )

        cycles = Plot(plotdata, padding=20)

        cycles.plot(("x", "y"), type="line", color=(0.2, 0.4, 0.5, 0.4))

        cycles.plot(
            ("selected_x", "selected_y"), type="line", marker="circle", line_width=3, color=(0.2, 0.4, 0.5, 0.9)
        )

        cycles.plot(
            ("endpoint_x", "endpoint_y"),
            type="scatter",
            marker_size=4,
            marker="circle",
            color=(0.2, 0.4, 0.5, 0.2),
            outline_color=(0.2, 0.4, 0.5, 0.6),
        )

        cycles.index_range = DataRange1D(low_setting=80.0, high_setting=120.0)

        cycles.value_range = DataRange1D(low_setting=80.0, high_setting=120.0)

        # dig down to use actual Plot object
        cyc_plot = cycles.components[0]

        # Add the labels in the quadrants
        cyc_plot.overlays.append(
            PlotLabel(
                "\nSlowdown" + 40 * " " + "Expansion",
                component=cyc_plot,
                font="swiss 24",
                color=(0.2, 0.4, 0.5, 0.6),
                overlay_position="inside top",
            )
        )

        cyc_plot.overlays.append(
            PlotLabel(
                "Downturn" + 40 * " " + "Recovery\n ",
                component=cyc_plot,
                font="swiss 24",
                color=(0.2, 0.4, 0.5, 0.6),
                overlay_position="inside bottom",
            )
        )

        timeline = Plot(plotdata, resizable="h", height=50, padding=20)
        timeline.plot(("dates", "x"), type="line", color=(0.2, 0.4, 0.5, 0.8), name="x")
        timeline.plot(("dates", "y"), type="line", color=(0.5, 0.4, 0.2, 0.8), name="y")

        # Snap on the tools
        zoomer = ZoomTool(
            timeline, drag_button="right", always_on=True, tool_mode="range", axis="index", max_zoom_out_factor=1.1
        )

        panner = PanTool(timeline, constrain=True, constrain_direction="x")

        # dig down to get Plot component I want
        x_plt = timeline.plots["x"][0]

        range_selection = RangeSelection(x_plt, left_button_selects=True)
        range_selection.on_trait_change(self.update_interval, "selection")

        x_plt.tools.append(range_selection)
        x_plt.overlays.append(RangeSelectionOverlay(x_plt))

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(fill_ratio=0.4, default_numlabels=5, default_numticks=10)
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = ScalesPlotAxis(timeline, orientation="bottom", tick_generator=tick_gen)

        # Hack to remove default axis - FIXME: how do I *replace* an axis?
        del (timeline.underlays[-2])

        timeline.overlays.append(bottom_axis)

        container = GridContainer(
            padding=20, fill_padding=True, bgcolor="lightgray", use_backbuffer=True, shape=(2, 1), spacing=(30, 30)
        )

        # add a central "x" and "y" axis

        x_line = LineInspector(cyc_plot, is_listener=True, color="gray", width=2)
        y_line = LineInspector(cyc_plot, is_listener=True, color="gray", width=2, axis="value")

        cyc_plot.overlays.append(x_line)
        cyc_plot.overlays.append(y_line)

        cyc_plot.index.metadata["selections"] = 100.0
        cyc_plot.value.metadata["selections"] = 100.0

        container.add(cycles)
        container.add(timeline)

        container.title = "Business Cycles"

        self.plot = container
    def _create_plot_component(self):

        # Create a plot data object and give it this data
        self.pd = ArrayPlotData()
        self.pd.set_data("imagedata", self.data[self.data_name])

        # Create the plot
        self.tplot = Plot(self.pd, default_origin="top left")
        self.tplot.x_axis.orientation = "top"
        self.tplot.img_plot(
            "imagedata",
            name="my_plot",
            #xbounds=(0,10),
            #ybounds=(0,10),
            colormap=jet)

        # Tweak some of the plot properties
        self.tplot.title = "Matrix"
        self.tplot.padding = 50

        # Right now, some of the tools are a little invasive, and we need the
        # actual CMapImage object to give to them
        self.my_plot = self.tplot.plots["my_plot"][0]

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

        # my custom tool to get the connection information
        self.custtool = CustomTool(self.tplot)
        self.tplot.tools.append(self.custtool)

        # Create the colorbar, handing in the appropriate range and colormap
        colormap = self.my_plot.color_mapper
        self.colorbar = ColorBar(
            index_mapper=LinearMapper(range=colormap.range),
            color_mapper=colormap,
            plot=self.my_plot,
            orientation='v',
            resizable='v',
            width=30,
            padding=20)

        self.colorbar.padding_top = self.tplot.padding_top
        self.colorbar.padding_bottom = self.tplot.padding_bottom

        # create a range selection for the colorbar
        self.range_selection = RangeSelection(component=self.colorbar)
        self.colorbar.tools.append(self.range_selection)
        self.colorbar.overlays.append(
            RangeSelectionOverlay(component=self.colorbar,
                                  border_color="white",
                                  alpha=0.8,
                                  fill_color="lightgray"))

        # we also want to the range selection to inform the cmap plot of
        # the selection, so set that up as well
        self.range_selection.listeners.append(self.my_plot)

        # Create a container to position the plot and the colorbar side-by-side
        container = HPlotContainer(use_backbuffer=True)
        container.add(self.tplot)
        container.add(self.colorbar)
        container.bgcolor = "white"

        return container
Пример #14
0
 def selecting_middle_up(self, event):
     RangeSelection.selected_left_up(self,event)
Пример #15
0
 def moving_middle_up(self, event):
     RangeSelection.moving_left_up(self,event)
Пример #16
0
 def selected_middle_down(self, event):
     RangeSelection.selected_left_down(self,event)
Пример #17
0
 def selected_left_down(self, event):
     RangeSelection.selected_left_down(self,event)
     if self.event_state == "moving":
         self.event_state = "selected"
Пример #18
0
    def setup_plots(self):
        '''
        
        Args: 
        Returns:
        Raises:
        '''
        ext = self.extension

        if ext == "S2":
            color = "green"
        else:
            color = "blue"

        self.create_plot("AAE " + ext, ylabel="[ ]", color=color)
        self.create_plot("ARE " + ext, ylabel="[ ]", color=color)
        self.create_plot("Jerk " + ext, ylabel="[m/s2/s]", color=color)
        self.create_plot("SI " + ext, ylabel="[ ]", color=color)
        self.create_plot("VI " + ext, ylabel="[ ]", color=color)

        p = self.plots["VI " + ext]

        null_ds = ArrayDataSource([])
        self.time_plot = LinePlot(
            index=self.time_src,
            value=null_ds,
            index_mapper=LinearMapper(range=DataRange1D(self.time_src)),
            value_mapper=LinearMapper(range=DataRange1D(null_ds)),
            color="black",
            border_visible=True,
            bgcolor="white",
            height=10,
            resizable="h",
            padding_top=50,
            padding_bottom=40,
            padding_left=50,
            padding_right=20)
        self.ticker = ScalesTickGenerator()
        self.x_axis = LabelAxis(self.time_plot,
                                orientation="bottom",
                                title="Time [sec]",
                                label_rotation=0)
        #self.x_axis = PlotAxis(self.time_plot, orientation="bottom", tick_generator = self.ticker, title="Time [sec]")
        self.time_plot.underlays.append(self.x_axis)
        self.container.add(self.time_plot)

        # Add a range overlay to the miniplot that is hooked up to the range
        # of the main price_plot
        range_tool = RangeSelection(self.time_plot)
        self.time_plot.tools.append(range_tool)
        range_overlay = RangeSelectionOverlay(self.time_plot,
                                              metadata_name="selections")
        self.time_plot.overlays.append(range_overlay)
        range_tool.on_trait_change(self._range_selection_handler, "selection")
        self.range_tool = range_tool

        p.plot_conactory.index_range.on_trait_change(self._plot_range_handler,
                                                     "updated")
        self.zoom_overlay = ZoomOverlay(source=self.time_plot,
                                        destination=p.plot_conactory)
        self.container.overlays.append(self.zoom_overlay)
Пример #19
0
class TraceViewer(HasTraits):
    """
    Allows visualization of a single trace and spectral analysis.
    """
    # Load Panel Items
    gpr_type = Enum('HUBRA', 'CBAND', 'FIMBUL', label='GPR type')
    file = Str()
    dir = Str()
    browse = Button(label='...')
    sample_min = Int(0, label="Sample min/max")
    sample_max = Int(-1)
    trace_no = Int(0)
    trace_max = Int(-1, label="Max:")
    show_button = Button(label="Show")
    show = Bool(False)
    # Processing Panel Items
    removegate_button = Button(label="Remove Gating")
    removegate_keep = Bool(False)
    compensate_button = Button(label="Compensate Spreading")
    compensate_keep = Bool(False)
    compensate_power = Bool(False, label='Power')
    compensate_h0 = Float(label="h0")
    place_holder = Str("")
    # Spectrum Panel Items
    Nfft_button = Button(label="Get #samples")
    Nfft_edit = Int(32768, label="#FFT")
    spectrum_button = Button(label="Spectrum")
    cspectrum_button = Button(label="Complex Spectrum")
    clac_spectrum = Bool(False)
    zphi_button = Button(label="Phase-center",
                         enabled_when="calc_spectrum is True")
    freq_min_edit = Float(500.0, label="Freq. range")
    freq_max_edit = Float(3000.0)
    # Status Panel
    status_txt = Str("TraceViewer started ...")
    # Plot Panel Items
    container = Instance(BasePlotContainer)
    rangeselect = Instance(RangeSelection)
    #
    #    load_panel = VGrid(
    #                       Item(name='file'), Item(name='browse', show_label=False),
    #                       Item(name='sample_min'), Item(name='sample_max', show_label=False),
    #                       Item(name='trace_no'), Item(name='trace_max', style='readonly'),
    #                       Item(name='show_button', show_label=False),
    #                       show_border=True, label="Choose data file and range")

    load_panel = VGroup(Item(name='gpr_type'),
                        VGrid(
                            Item(name='file'),
                            Item(name='browse', show_label=False),
                            Item(name='sample_min'),
                            Item(name='sample_max', show_label=False),
                            Item(name='trace_no'),
                            Item(name='trace_max', style='readonly'),
                            Item(name='show_button', show_label=False)),
                        show_border=True, label="Choose data file and range")

    proc_panel = VGrid(
        Item(name='removegate_keep', show_label=False),
        Item(name='removegate_button', show_label=False),
        Item(name='place_holder', show_label=False,
             style='readonly'),
        Item(name='compensate_keep', show_label=False),
        Item(name='compensate_button', show_label=False),
        Item(name='compensate_h0', show_label=True),
        Item(name='compensate_power', show_label=True),
        show_border=True, columns=3, label="Processing steps"
    )

    spec_panel = VGrid(
        Item(name='Nfft_button', show_label=False),
        Item(name='Nfft_edit', show_label=True),
        Item(name='place_holder', show_label=False,
             style='readonly'),
        Item(name='spectrum_button', show_label=False),
        Item(name='place_holder', show_label=False,
             style='readonly'),
        Item(name='place_holder', show_label=False,
             style='readonly'),
        Item(name='cspectrum_button', show_label=False),
        Item(name='place_holder', show_label=False,
             style='readonly'),
        Item(name='place_holder', show_label=False,
             style='readonly'),
        Item(name='zphi_button', show_label=False),
        Item(name='freq_min_edit', show_label=True),
        Item(name='freq_max_edit', show_label=False),
        show_border=True, columns=3, label="Spectrum"
    )

    status_panel = VGroup(
        Item(name='status_txt', show_label=False, editor=TextEditor(),
             style='readonly',
             full_size=False, height=200),
        show_border=True, label="Status"
    )

    view = View(HSplit(
        VGroup(
            load_panel, proc_panel, spec_panel, status_panel
        ),
        #                      '_',
        Item(name="container", show_label=False, editor=ComponentEditor())
        #                          visible_when="show==True")),
    ),
                icon=r"../src/recources/icons/edit-32.png",
                title="Trace Viewer",
                width=1000, height=0.9,
                resizable=True)

    def __init__(self, file="", dir=os.getcwd()):
        self.dir = dir
        self.file = file

    def _create_traceplot(self, y=None):
        x = self.x
        if y == None:
            y = self.y
        traceplot = create_line_plot((x, y), index_bounds=None, value_bounds=None,
                                     orientation='v', color='blue', width=1.0, dash='solid',
                                     value_mapper_class=LinearMapper,
                                     bgcolor='transparent', border_visible=True,
                                     add_grid=False, add_axis=False, index_sort='ascending')
        add_default_axes(traceplot, orientation='flipped', vtitle='Time [ns]', htitle='Signal')
        traceplot.origin = "top left"
        traceplot.tools.append(PanTool(traceplot, drag_button="right"))
        zoom = SimpleZoom(component=traceplot, tool_mode="box", drag_button="left", always_on=True)
        traceplot.overlays.append(zoom)

        container = OverlayPlotContainer(padding=40, padding_left=60)
        container.add(traceplot)
        self.container = container

    def _create_spectrumplot(self, x, y):
        spectrumplot = create_line_plot((x, y), index_bounds=None, value_bounds=None,
                                        orientation='v', color='green', width=1.0, dash='solid',
                                        value_mapper_class=LinearMapper,
                                        bgcolor='transparent', border_visible=True,
                                        add_grid=False, add_axis=False, index_sort='ascending')
        add_default_axes(spectrumplot, orientation='flipped', vtitle='Frequency [MHz]', htitle='Amplitude')
        spectrumplot.origin = "top left"
        spectrumplot.tools.append(PanTool(spectrumplot, drag_button="right"))
        zoom = SimpleZoom(component=spectrumplot, tool_mode="box", drag_button="left", always_on=True)
        spectrumplot.overlays.append(zoom)

        container = OverlayPlotContainer(padding=40, padding_left=60)
        container.add(spectrumplot)
        self.container = container

    def _create_complexspectrumplot(self, x, y1, y2):
        amplitudeplot = create_line_plot((x, y1), index_bounds=None, value_bounds=None,
                                         orientation='h', color='green', width=1.0, dash='solid',
                                         value_mapper_class=LinearMapper,
                                         bgcolor='white', border_visible=True,
                                         add_grid=False, add_axis=False, index_sort='ascending')
        add_default_axes(amplitudeplot, orientation='normal', htitle='Frequency [MHz]', vtitle='Amplitude')

        amplitudeplot.tools.append(PanTool(amplitudeplot, drag_button="right"))
        zoom = SimpleZoom(component=amplitudeplot, tool_mode="box", drag_button="left", always_on=True)
        amplitudeplot.overlays.append(zoom)

        phaseplot = create_line_plot((x, y2), index_bounds=None,
                                     value_bounds=None,
                                     orientation='h', color='red',
                                     width=1.0, dash='solid',
                                     value_mapper_class=LinearMapper,
                                     bgcolor='white', border_visible=True,
                                     add_grid=False, add_axis=False,
                                     index_sort='ascending')
        add_default_axes(phaseplot, orientation='normal',
                         htitle='Frequency [MHz]', vtitle='Unwrapped phase')

        #        phaseplot.tools.append(PanTool(phaseplot, drag_button="right"))
        zoom = SimpleZoom(component=phaseplot, tool_mode="box",
                          drag_button="left", always_on=True,
                          #                          enter_zoom_key=KeySpec('z')
        )
        phaseplot.overlays.append(zoom)
        self.rangeselect = RangeSelection(phaseplot, left_button_selects=False)
        self.rangeselect.on_trait_change(self.phase_center, "selection_completed")
        phaseplot.active_tool = self.rangeselect
        phaseplot.overlays.append(RangeSelectionOverlay(component=phaseplot))

        container = VPlotContainer(padding=40, padding_left=60, spacing=40)
        container.add(phaseplot)
        container.add(amplitudeplot)
        self.container = container

    def _file_changed(self):
        try:
            from tables import openFile, NoSuchNodeError

            h5file = openFile(os.path.join(self.dir, self.file), mode='r')
            try:
                sample_max, trace_max = h5file.root.data.traces.shape
                self.sample_max = int(sample_max)
                self.trace_max = int(trace_max)
            except NoSuchNodeError:
                self.sample_max, self.trace_max = h5file.root.profile.traces.shape
            h5file.close()
        except IOError:
            print "The chosen file has an unknown format."

    def _browse_fired(self):
        file, dir = wxOpenFile(self.dir, multi=False)
        self.dir = dir
        self.file = file

    def _show_button_fired(self):
        gpr = eval(self.gpr_type + '()')
        gpr.readH5(os.path.join(self.dir, self.file),
                   self.trace_no, self.trace_no + 1,
                   self.sample_min, self.sample_max)
        gpr.gatefreq = 1523123.0
        self.x = gpr.t
        self.y = gpr.data[:, 0]
        self.r = gpr.r
        self.deltaT = gpr.deltaT
        self.gpr = gpr
        self._create_traceplot()
        self.status_txt = "%s\nTrace %i from file %s displayed" % (self.status_txt, self.trace_no, self.file)
        self.clac_spectrum = False

    def _removegate_button_fired(self):
        self.gpr.removeGating()
        if self.removegate_keep:
            self.y = self.gpr.data[:, 0]
            self._create_traceplot()
            self.status_txt = "%s\nGating gain removed permanently" % (self.status_txt)
        else:
            y = self.gpr.data[:, 0]
            self._create_traceplot(y)
            self.status_txt = "%s\nGating gain removed in plot" % (self.status_txt)

    def _compensate_button_fired(self):
        print self.gpr.data.shape
        print self.gpr.r.shape
        self.gpr.compensateVolSpread(h0=self.compensate_h0, ba=50.0,
                                     power=self.compensate_power)
        if self.compensate_keep:
            self.y = self.gpr.data[:, 0]
            self._create_traceplot()
            self.status_txt = "%s\nSpreading corrected permanently" % (self.status_txt)
        else:
            y = self.gpr.data[:, 0]
            self._create_traceplot(y)
            self.status_txt = "%s\nSpreading corrected in plot" % (self.status_txt)

    def _Nfft_button_fired(self):
        self.Nfft_edit = self.y.size

    def _spectrum_button_fired(self):
        Nfft = self.y.size
        freq = fftfreq(Nfft, self.deltaT)
        Y = abs(fft(self.y)) ** 2
        x = freq[0:Nfft / 2] * 1e-6
        y = Y[0:Nfft / 2]
        self._create_spectrumplot(x, y)

    def _cspectrum_button_fired(self):
        #        Nfft = self.y.size
        Nfft = self.Nfft_edit
        freq = fftfreq(Nfft, self.deltaT)
        #        c0 = 299792458.0
        #        k = 2*pi*freq[0:Nfft/2]/(c0/sqrt(1.8))
        Y = ifft(self.y, Nfft)
        f = freq[0:Nfft / 2] * 1e-6  # [MHz]
        y1 = abs(Y)[0:Nfft / 2]
        mag = y1 / y1.max()  # normalized amplitude spectrum
        pha = np.unwrap(np.angle(Y)[0:Nfft / 2])  # unwrapped phase spectrum

        self.freq = f
        self.pha = pha
        self._create_complexspectrumplot(f, mag, pha)
        self.clac_spectrum = True

    def _zphi_button_fired(self):
        c0 = 299792458.0
        smaller = self.freq > self.freq_min_edit
        larger = self.freq < self.freq_max_edit
        mask = smaller * larger
        p1 = np.polyfit(self.freq[mask] * 1e6, self.pha[mask], 1)

        self.status_txt = "%s\nPhase center = %5.2f m" % \
                          (self.status_txt, -p1[0] * c0 / (4 * np.pi))

    def _get_index(self):
        smaller = self.freq > self.rangeselect.selection[0]
        larger = self.freq < self.rangeselect.selection[1]
        ndx = smaller * larger
        return ndx

    def phase_center(self):
        c0 = 299792458.0
        if self.rangeselect.selection is not None:
            #        mask = mag>0.04
            mask = self._get_index()
            p1 = np.polyfit(self.freq[mask] * 1e6, self.pha[mask], 1)
            self.status_txt = "%s\nPhase center = %5.2f m" % \
                              (self.status_txt, -p1[0] * c0 / (4 * np.pi))
Пример #20
0
 def normal_right_down(self,event):
     self.downwindow = event.window
     if self.left_button_selects and event.right_down:
         return
     else:
         return RangeSelection.normal_right_down(self,event)
Пример #21
0
 def normal_left_down(self,event):
     self.downwindow = event.window
     return RangeSelection.normal_left_down(self,event)
Пример #22
0
    def __init__(self):
        super(CyclesPlot, self).__init__()

        # Normally you'd pass in the data, but I'll hardwire things for this
        #    one-off plot.

        srecs = read_time_series_from_csv("./biz_cycles2.csv",
                                          date_col=0,
                                          date_format="%Y-%m-%d")

        dt = srecs["Date"]

        # Industrial production compared with trend (plotted on value axis)
        iprod_vs_trend = srecs["Metric 1"]

        # Industrial production change in last 6 Months (plotted on index axis)
        iprod_delta = srecs["Metric 2"]

        self._dates = dt
        self._series1 = self._selected_s1 = iprod_delta
        self._series2 = self._selected_s2 = iprod_vs_trend

        end_x = np.array([self._selected_s1[-1]])
        end_y = np.array([self._selected_s2[-1]])

        plotdata = ArrayPlotData(x=self._series1,
                                 y=self._series2,
                                 dates=self._dates,
                                 selected_x=self._selected_s1,
                                 selected_y=self._selected_s2,
                                 endpoint_x=end_x,
                                 endpoint_y=end_y)

        cycles = Plot(plotdata, padding=20)

        cycles.plot(("x", "y"), type="line", color=(.2, .4, .5, .4))

        cycles.plot(("selected_x", "selected_y"),
                    type="line",
                    marker="circle",
                    line_width=3,
                    color=(.2, .4, .5, .9))

        cycles.plot(("endpoint_x", "endpoint_y"),
                    type="scatter",
                    marker_size=4,
                    marker="circle",
                    color=(.2, .4, .5, .2),
                    outline_color=(.2, .4, .5, .6))

        cycles.index_range = DataRange1D(low_setting=80., high_setting=120.)

        cycles.value_range = DataRange1D(low_setting=80., high_setting=120.)

        # dig down to use actual Plot object
        cyc_plot = cycles.components[0]

        # Add the labels in the quadrants
        cyc_plot.overlays.append(
            PlotLabel("\nSlowdown" + 40 * " " + "Expansion",
                      component=cyc_plot,
                      font="swiss 24",
                      color=(.2, .4, .5, .6),
                      overlay_position="inside top"))

        cyc_plot.overlays.append(
            PlotLabel("Downturn" + 40 * " " + "Recovery\n ",
                      component=cyc_plot,
                      font="swiss 24",
                      color=(.2, .4, .5, .6),
                      overlay_position="inside bottom"))

        timeline = Plot(plotdata, resizable='h', height=50, padding=20)
        timeline.plot(("dates", "x"),
                      type="line",
                      color=(.2, .4, .5, .8),
                      name='x')
        timeline.plot(("dates", "y"),
                      type="line",
                      color=(.5, .4, .2, .8),
                      name='y')

        # Snap on the tools
        zoomer = ZoomTool(timeline,
                          drag_button="right",
                          always_on=True,
                          tool_mode="range",
                          axis="index",
                          max_zoom_out_factor=1.1)

        panner = PanTool(timeline, constrain=True, constrain_direction="x")

        # dig down to get Plot component I want
        x_plt = timeline.plots['x'][0]

        range_selection = RangeSelection(x_plt, left_button_selects=True)
        range_selection.on_trait_change(self.update_interval, 'selection')

        x_plt.tools.append(range_selection)
        x_plt.overlays.append(RangeSelectionOverlay(x_plt))

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(
            fill_ratio=0.4,
            default_numlabels=5,
            default_numticks=10,
        )
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = ScalesPlotAxis(timeline,
                                     orientation="bottom",
                                     tick_generator=tick_gen)

        # Hack to remove default axis - FIXME: how do I *replace* an axis?
        del (timeline.underlays[-2])

        timeline.overlays.append(bottom_axis)

        container = GridContainer(padding=20,
                                  fill_padding=True,
                                  bgcolor="lightgray",
                                  use_backbuffer=True,
                                  shape=(2, 1),
                                  spacing=(30, 30))

        # add a central "x" and "y" axis

        x_line = LineInspector(cyc_plot,
                               is_listener=True,
                               color="gray",
                               width=2)
        y_line = LineInspector(cyc_plot,
                               is_listener=True,
                               color="gray",
                               width=2,
                               axis="value")

        cyc_plot.overlays.append(x_line)
        cyc_plot.overlays.append(y_line)

        cyc_plot.index.metadata["selections"] = 100.0
        cyc_plot.value.metadata["selections"] = 100.0

        container.add(cycles)
        container.add(timeline)

        container.title = "Business Cycles"

        self.plot = container
Пример #23
0
    def __init__(self, **kw):
        super(MLabChacoPlot, self).__init__(**kw)
        
        self.prices = get_data()
        x = self.prices['Date']
        pd = ArrayPlotData(index = x)
        pd.set_data("y", self.prices["Crude Supply"])

        # Create some line plots of some of the data
        plot = Plot(pd, bgcolor="none", padding=30, border_visible=True, 
                     overlay_border=True, use_backbuffer=False)
        #plot.legend.visible = True
        plot.plot(("index", "y"), name="Crude Price", color=(.3, .3, .8, .8))
        #plot.tools.append(PanTool(plot))

        plot.tools.append(PanTool(plot, constrain=True, drag_button="right",
                                  constrain_direction="x"))

        range_plt = plot.plots['Crude Price'][0]

        range_selection = RangeSelection(range_plt, left_button_selects=True)
        range_selection.on_trait_change(self.update_interval, 'selection')
        range_plt.tools.append(range_selection)
        range_plt.overlays.append(RangeSelectionOverlay(range_plt))


        zoom = ZoomTool(component=plot, tool_mode="range", always_on=False,
                        axis="index", max_zoom_out_factor=1.0,)
        plot.overlays.append(zoom)

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(fill_ratio=0.4,
                                        default_numlabels=5,
                                        default_numticks=10,)
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = ScalesPlotAxis(plot, orientation="bottom",
                                     tick_generator=tick_gen,
                                     label_color="white",
                                     line_color="white")

        # Hack to remove default axis - FIXME: how do I *replace* an axis?
        del(plot.underlays[-2])

        plot.overlays.append(bottom_axis)

        # Create the mlab test mesh and get references to various parts of the
        # VTK pipeline
        f = mlab.figure(size=(700,500))
        self.m = mlab.points3d(self.prices['Gasoline Supply'], self.prices['Jet Fuel Supply'], self.prices['Distillate Supply'], self.prices['Crude Supply'])
        
        # Add another glyph module to render the full set of points
        g2 = Glyph()
        g2.glyph.glyph_source.glyph_source.glyph_type = "circle"
        g2.glyph.glyph_source.glyph_source.filled = True
        g2.actor.property.opacity = 0.75
        self.m.module_manager.source.add_module(g2)
        
        # Set a bunch of properties on the scene to make things look right
        self.m.module_manager.scalar_lut_manager.lut_mode = 'PuBuGn'
        self.m.glyph.mask_points.random_mode = False
        self.m.glyph.mask_points.on_ratio = 1
        self.m.scene.isometric_view()
        self.m.scene.background = (.9, 0.95, 1.0)
        
        scene = mlab.gcf().scene
        render_window = scene.render_window
        renderer = scene.renderer
        rwi = scene.interactor

        plot.resizable = ""
        plot.bounds = [600,120]
        plot.padding = 25
        plot.bgcolor = "white"
        plot.outer_position = [30,30]
        plot.tools.append(MoveTool(component=plot,drag_button="right"))

        container = OverlayPlotContainer(bgcolor = "transparent",
                        fit_window = True)
        container.add(plot)

        # Create the Enable Window
        window = EnableVTKWindow(rwi, renderer, 
                component=container,
                istyle_class = tvtk.InteractorStyleTrackballCamera, 
                bgcolor = "transparent",
                event_passthrough = True,
                )

        mlab.show()