def _create_window(self):
        ts = touchstone.read("../tests/data/deemb_mom.s2p")
        ts = ts.recombine([1, 2])

        circles_source = np.vstack(ts.stability_circle_source()).T
        circles_load = np.vstack(ts.stability_circle_load()).T

        container = OverlayPlotContainer(padding=50, fill_padding=True, bgcolor="lightgray", use_backbuffer=True)

        self.data = ArrayPlotData(
            f=ts.freqs,
            s11=ts.get_parameter(1, 1),
            s12=ts.get_parameter(1, 2),
            s21=ts.get_parameter(2, 1),
            s22=ts.get_parameter(2, 2),
            circles_source=circles_source,
            circles_load=circles_load,
        )
        self.plot = SmithPlot(self.data, title="Smith plot")

        self.plot.plot(("f", "s11"), color="auto", line_width=2.0)
        self.plot.plot(("f", "s22"), color="auto", line_width=2.0)
        # self.plot.plot(("f", "s21"), color="auto", line_width=2.0)
        # self.plot.plot(("f", "s12"), color="auto", line_width=2.0)

        self.plot.plot_circle(("f", "circles_source"), color="auto", line_width=2.0)
        self.plot.plot_circle(("f", "circles_load"), color="auto", line_width=2.0)

        container.add(self.plot)

        self.plot.tools.append(PanTool(self.plot))
        zoom = SimpleZoom(self.plot, tool_mode="box", always_on=False)
        self.plot.overlays.append(zoom)

        return Window(self, -1, component=container)
    def slice_plot( self, anat, coefs, **traits ):

        p  = Plot( self.plot_data, default_origin = 'bottom left' )
        p2 = Plot( self.plot_data, default_origin = 'bottom left' )

        p.x_axis.visible = False; p2.x_axis.visible = False
        p.y_axis.visible = False; p2.y_axis.visible = False

        bounds = self.plot_data.get_data(anat).shape
        asp    = float( bounds[1] ) / float( bounds[0] )

        p.img_plot( anat,
#                    xbounds  = np.linspace( 0, 1, bounds[1] + 1 ),
#                    ybounds  = np.linspace( 0, 1, bounds[0] + 1 ),
                    colormap = chaco_colormaps.gray )
        
        p2.img_plot( coefs,
#                     xbounds  = np.linspace( 0, 1, bounds[1] + 1 ),
#                     ybounds  = np.linspace( 0, 1, bounds[0] + 1 ),
#                     bgcolor = 'transparent',
                     colormap = self.cmap,
                     interpolation = 'nearest')

#        p.aspect_ratio = asp; p2.aspect_ratio = asp
        p.aspect_ratio = asp; p2.aspect_ratio = asp

        subplot = OverlayPlotContainer( )

        subplot.add( p )
        subplot.add( p2 )

        return subplot 
Exemple #3
0
    def _container_default(self):
        self.plot = None

        # Create the data and datasource objects
        # In order for the date axis to work, the index data points need to
        # be in units of seconds since the epoch.  This is because we are using
        # the CalendarScaleSystem, whose formatters interpret the numerical values
        # as seconds since the epoch.
        numpoints = 500
        index = create_dates(numpoints)

        returns = random.lognormal(0.00, 0.04, size=numpoints)
        average = 100.0 * cumprod(returns)
        high = average + abs(random.normal(0, 20.0, size=numpoints))
        low = average - abs(random.normal(0, 20.0, size=numpoints))
        delta = high - low
        open = low + delta * random.uniform(0.05, 0.95, size=numpoints)
        close = low + delta * random.uniform(0.05, 0.95, size=numpoints)
        price = vstack((open, high, low, close, average))

        time_ds = ArrayDataSource(index)
        price_ds = PriceDataSource(price, sort_order="none")

        # Create the price plot
        price_plot = self._create_plot(time_ds, price_ds)
        self.plot = price_plot

        container = OverlayPlotContainer(padding=35)
        container.add(price_plot)
        return container
 def __init__(self, **traits):
     super(ContainerExample, self).__init__(**traits)
     x = np.linspace(-14, 14, 100)
     y = np.sin(x) * x**3 / 1000
     data = ArrayPlotData(x=x, y=y)
     
     
     p1 = Plot(data, padding=30)
     p1.plot(("x", "y"), type="scatter", color="blue")
     p1.plot(("x", "y"), type="line", color="blue")
     
     p2 = Plot(data, padding=30)
     p2.plot(("x", "y"), type="line", color="blue")
     p2.set(bounds = [200, 100], position = [70,150],  
     bgcolor = (0.9,0.9,0.9), unified_draw=True, resizable="")
     
     p3 = Plot(data, padding=30)
     p3.plot(("x", "y"), type="line", color="blue", line_width=2.0)
     
     p4 = Plot(data,  padding=30)
     p4.plot(("x", "y"), type="scatter", color="red", marker="circle")
     
     c1 = OverlayPlotContainer(p1, p2) 
     
     c1.fixed_preferred_size = p3.get_preferred_size() 
     c2 = HPlotContainer(c1, p3) 
     c3 = VPlotContainer(p4, c2) 
     
     self.plot = c3
 def test_basics(self):
     container = OverlayPlotContainer(resizable='', bounds=[100.0,200.0])
     self.assert_tuple(container.get_preferred_size(), (100.0,200.0))
     self.assertEquals(container._layout_needed, True)
     container.do_layout()
     self.assertEquals(container._layout_needed, False)
     return
Exemple #6
0
    def __init__(self, **traits):
        super(ContainerExample, self).__init__(**traits)
        x = np.linspace(-14, 14, 100)
        y = np.sin(x) * x**3 / 1000
        data = ArrayPlotData(x=x, y=y)

        p1 = Plot(data, padding=30)
        p1.plot(("x", "y"), type="scatter", color="blue")
        p1.plot(("x", "y"), type="line", color="blue")

        p2 = Plot(data, padding=30)
        p2.plot(("x", "y"), type="line", color="blue")
        p2.set(bounds=[200, 100],
               position=[70, 150],
               bgcolor=(0.9, 0.9, 0.9),
               unified_draw=True,
               resizable="")

        p3 = Plot(data, padding=30)
        p3.plot(("x", "y"), type="line", color="blue", line_width=2.0)

        p4 = Plot(data, padding=30)
        p4.plot(("x", "y"), type="scatter", color="red", marker="circle")

        c1 = OverlayPlotContainer(p1, p2)

        c1.fixed_preferred_size = p3.get_preferred_size()
        c2 = HPlotContainer(c1, p3)
        c3 = VPlotContainer(p4, c2)

        self.plot = c3
    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))
Exemple #8
0
def _create_plot_component():

    container = OverlayPlotContainer(padding = 50, fill_padding = True,
                                     bgcolor = "lightgray", use_backbuffer=True)

    # Create the initial X-series of data
    numpoints = 100
    low = -5
    high = 15.0
    x = arange(low, high+0.001, (high-low)/numpoints)

    # Plot some bessel functions
    plots = {}
    broadcaster = BroadcasterTool()
    for i in range(4):
        y = jn(i, x)
        plot = create_line_plot((x,y), color=tuple(COLOR_PALETTE[i]), width=2.0)
        plot.index.sort_order = "ascending"
        plot.bgcolor = "white"
        plot.border_visible = True
        if i == 0:
            add_default_grids(plot)
            add_default_axes(plot)

        # Create a pan tool and give it a reference to the plot it should
        # manipulate, but don't attach it to the plot.  Instead, attach it to
        # the broadcaster.
        pan = PanTool(plot)
        broadcaster.tools.append(pan)

        container.add(plot)
        plots["Bessel j_%d"%i] = plot

    # Add an axis on the right-hand side that corresponds to the second plot.
    # Note that it uses plot.value_mapper instead of plot0.value_mapper.
    plot1 = plots["Bessel j_1"]
    axis = PlotAxis(plot1, orientation="right")
    plot1.underlays.append(axis)

    # Add the broadcast tool to the container, instead of to an
    # individual plot
    container.tools.append(broadcaster)

    legend = Legend(component=container, padding=10, align="ur")
    legend.tools.append(LegendTool(legend, drag_button="right"))
    container.overlays.append(legend)

    # Set the list of plots on the legend
    legend.plots = plots

    # Add the title at the top
    container.overlays.append(PlotLabel("Bessel functions",
                              component=container,
                              font = "swiss 16",
                              overlay_position="top"))

    # Add the traits inspector tool to the container
    container.tools.append(TraitsTool(container))

    return container
 def test_min_size(self):
     container = OverlayPlotContainer(resizable='', bounds=[50.0,50.0])
     component = PlotComponent(resizable='', position=[50.0,60.0],
                               bounds=[100.0, 110.0])
     container.add(component)
     container.do_layout()
     self.assert_tuple(component.position, (50.0,60.0))
     self.assert_tuple(component.bounds, (100.0,110.0))
     return
Exemple #10
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)
Exemple #11
0
def _create_plot_component():

    container = OverlayPlotContainer(padding = 50, fill_padding = True,
                                     bgcolor = "lightgray", use_backbuffer=True)

    # Create the initial X-series of data
    numpoints = 100
    low = -5
    high = 15.0
    x = arange(low, high+0.001, (high-low)/numpoints)
    y = jn(0, x)
    plot = create_line_plot((x,y), color=tuple(COLOR_PALETTE[0]), width=2.0)
    plot.index.sort_order = "ascending"
    plot.bgcolor = "white"
    plot.border_visible = True
    add_default_grids(plot)
    add_default_axes(plot)

    # Add some tools
    plot.tools.append(PanTool(plot))
    zoom = ZoomTool(plot, tool_mode="box", always_on=False)
    plot.overlays.append(zoom)

    # Add a dynamic label.  This can be dragged and moved around using the
    # right mouse button.  Note the use of padding to offset the label
    # from its data point.
    label = DataLabel(component=plot, data_point=(x[40], y[40]),
                      label_position="top left", padding=40,
                      bgcolor = "lightgray",
                      border_visible=False)
    plot.overlays.append(label)
    tool = DataLabelTool(label, drag_button="right", auto_arrow_root=True)
    label.tools.append(tool)

    # Add some static labels.
    label2 = DataLabel(component=plot, data_point=(x[20], y[20]),
                       label_position="bottom right",
                       border_visible=False,
                       bgcolor="transparent",
                       marker_color="blue",
                       marker_line_color="transparent",
                       marker = "diamond",
                       arrow_visible=False)
    plot.overlays.append(label2)

    label3 = DataLabel(component=plot, data_point=(x[80], y[80]),
                       label_position="top", padding_bottom=20,
                       marker_color="transparent",
                       marker_size=8,
                       marker="circle",
                       arrow_visible=False)
    plot.overlays.append(label3)
    container.add(plot)

    return container
Exemple #12
0
def _create_plot_component():

    # Create some x-y data series to plot
    plot_area = OverlayPlotContainer(border_visible=True)
    container = HPlotContainer(padding=50, bgcolor="transparent")
    #container.spacing = 15

    x = linspace(-2.0, 10.0, 100)
    for i in range(5):
        color = tuple(COLOR_PALETTE[i])
        y = jn(i, x)
        renderer = create_line_plot((x, y), color=color)
        plot_area.add(renderer)
        #plot_area.padding_left = 20

        axis = PlotAxis(orientation="left", resizable="v",
                    mapper = renderer.y_mapper,
                    axis_line_color=color,
                    tick_color=color,
                    tick_label_color=color,
                    title_color=color,
                    bgcolor="transparent",
                    title = "jn_%d" % i,
                    border_visible = True,)
        axis.bounds = [60,0]
        axis.padding_left = 10
        axis.padding_right = 10

        container.add(axis)

        if i == 4:
            # Use the last plot's X mapper to create an X axis and a
            # vertical grid
            x_axis = PlotAxis(orientation="bottom", component=renderer,
                        mapper=renderer.x_mapper)
            renderer.overlays.append(x_axis)
            grid = PlotGrid(mapper=renderer.x_mapper, orientation="vertical",
                    line_color="lightgray", line_style="dot")
            renderer.underlays.append(grid)

    # Add the plot_area to the horizontal container
    container.add(plot_area)

    # Attach some tools to the plot
    broadcaster = BroadcasterTool()
    for plot in plot_area.components:
        broadcaster.tools.append(PanTool(plot))

    # Attach the broadcaster to one of the plots.  The choice of which
    # plot doesn't really matter, as long as one of them has a reference
    # to the tool and will hand events to it.
    plot.tools.append(broadcaster)

    return container
  def __init__(self, link):
    super(TrackingView, self).__init__()

    self.link = link
    self.link.add_callback(MSG_TRACKING_SNRS, self.tracking_snrs_callback)

    # ======= Line Plot =======

    self.plot_data = ArrayPlotData(t=[0.0])
    self.plot = Plot(self.plot_data, auto_colors=colours_list)
    self.plot.value_range.tight_bounds = False
    self.plot.value_range.low_setting = 0.0
    for n in range(TRACK_N_CHANNELS):
      self.plot_data.set_data('ch'+str(n), [0.0])
      self.plot.plot(('t', 'ch'+str(n)), type='line', color='auto')

    # ======= Bar Plot =======

    idxs = ArrayDataSource(range(1, len(self.snrs)+1))
    self.vals = ArrayDataSource(self.snrs, sort_order='none')
    # Create the index range
    index_range = DataRange1D(idxs, low=0.4, high=TRACK_N_CHANNELS+0.6)
    index_mapper = LinearMapper(range=index_range)
    # Create the value range
    value_range = DataRange1D(low=0.0, high=25.0)
    value_mapper = LinearMapper(range=value_range)

    plot = BarPlot(index=idxs, value=self.vals, 
                   index_mapper=index_mapper, value_mapper=value_mapper, 
                   line_color='blue', fill_color='blue', bar_width=0.8)

    container = OverlayPlotContainer(bgcolor = "white")
    plot.padding = 10
    plot.padding_left = 30
    plot.padding_bottom = 30
    container.add(plot)

    left_axis = PlotAxis(plot, orientation='left')
    bottom_axis = LabelAxis(plot, orientation='bottom',
                           labels = map(str, range(1, TRACK_N_CHANNELS+1)),
                           positions = range(1, TRACK_N_CHANNELS+1),
                           small_haxis_style=True)

    plot.underlays.append(left_axis)
    plot.underlays.append(bottom_axis)

    self.snr_bars = container

    self.python_console_cmds = {
      'track': self
    }
Exemple #14
0
    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
Exemple #15
0
def main():
    # 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
    plot = Plot(pd, bgcolor="none", padding=30, border_visible=True,
                 overlay_border=True, use_backbuffer=False)
    plot.legend.visible = True
    plot.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="auto")
    plot.plot(("index", "y3"), name="j_3", color="auto")
    plot.tools.append(PanTool(plot))
    zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
    plot.overlays.append(zoom)

    # Create the mlab test mesh and get references to various parts of the
    # VTK pipeline
    f = mlab.figure(size=(600,500))
    m = mlab.test_mesh()
    scene = mlab.gcf().scene
    render_window = scene.render_window
    renderer = scene.renderer
    rwi = scene.interactor

    plot.resizable = ""
    plot.bounds = [200,200]
    plot.padding = 25
    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.InteractorStyleSwitch,
            #istyle_class = tvtk.InteractorStyle,
            istyle_class = tvtk.InteractorStyleTrackballCamera,
            bgcolor = "transparent",
            event_passthrough = True,
            )

    mlab.show()
    return window, render_window
Exemple #16
0
def _create_draggable_plot_component(title, initial_values=None,  on_change_functor=None):

    container = OverlayPlotContainer(padding = 30, fill_padding = True,
                                     bgcolor = "lightgray", use_backbuffer=True)


    if initial_values:
        x = initial_values[0]
        y = initial_values[1]
    else:
        # Create the initial X-series of data
        numpoints = 30
        low = -5
        high = 15.0
        x = linspace(low, high, numpoints)
        y = jn(0, x)

    lineplot = create_line_plot((x, y), color=tuple(COLOR_PALETTE[0]),
                                width=2.0)
    lineplot.selected_color = 'none'

    scatter = ScatterPlot(
        index=lineplot.index,
        value=lineplot.value,
        index_mapper=lineplot.index_mapper,
        value_mapper=lineplot.value_mapper,
        color=tuple(COLOR_PALETTE[0]),
        marker_size=2,
        )
    scatter.index.sort_order = 'ascending'
    scatter.bgcolor = 'white'
    scatter.border_visible = True

    add_default_grids(scatter)
    add_default_axes(scatter)
    scatter.tools.append(PanTool(scatter, drag_button='right'))

    # The ZoomTool tool is stateful and allows drawing a zoom
    # box to select a zoom region.
    zoom = ZoomTool(scatter, tool_mode='box', always_on=False,
                    drag_button=None)
    scatter.overlays.append(zoom)

    point_dragging_tool = PointDraggingTool(scatter)
    point_dragging_tool.on_change_functor = on_change_functor
    scatter.tools.append(point_dragging_tool)

    container.add(lineplot)
    container.add(scatter)
    # Add the title at the top
    container.overlays.append(PlotLabel(title, component=container,
                              font='swiss 16', overlay_position='top'))

    container.mx = lineplot.index.get_data()
    container.my = lineplot.value.get_data()

    container.lineplot = lineplot
    return container
Exemple #17
0
    def _image_plot_container(self):
        plot = self.render_image()

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

        if self.numpeaks_img > 0:
            scatplot = self.render_scatplot()
            self.container.add(scatplot)
            colorbar = self.draw_colorbar()
            self.img_container.add(colorbar)
        return self.img_container
    def _plot_default(self):
        
        container = OverlayPlotContainer(bgcolor = "white")
        
        
        self.idx = ArrayDataSource( range(1, self.binsNum+1) )
        self.vals = ArrayDataSource(self.value_points, sort_order="none")
        
        index_range = DataRange1D(self.idx, low=0, high=self.binsNum+2 )
        index_mapper = LinearMapper(range=index_range)
    
        value_range = DataRange1D(low=0, high=self.value_points.max())
        value_mapper = LinearMapper(range=value_range)
    
        # Create the plot
        self.histPlot = BarPlot(index=self.idx, value=self.vals,
                        value_mapper=value_mapper,
                        index_mapper=index_mapper,
                        line_color='black',
                        fill_color=tuple(COLOR_PALETTE[1]),
                        bar_width=0.8, antialias=False)
        
        plots = [self.histPlot]
        
        for plot in plots:
            plot.padding = 50
            plot.padding_left = 80
            plot.padding_top = 30
            container.add(plot)
    
        left_axis = PlotAxis(plot, orientation='left',
                               title='Number / Probability',
                               positions = [num for num in self.value_points],
                               labels = ["%.2f" % num for num in self.value_points],
                               #small_haxis_style=True
                               )

        bottom_axis = LabelAxis(plot, orientation='bottom',
                               title='Values',
                               positions = range(1, self.binsNum+1),
                               labels = ["%.2f" % num for num in self.index_points],
                               )
    
        plot.underlays.append(left_axis)
        plot.underlays.append(bottom_axis)
           
        return container
Exemple #19
0
def _create_plot_component():

    container = OverlayPlotContainer(padding = 50, fill_padding = True,
                                     bgcolor = "lightgray", use_backbuffer=True)

    # Create the initial X-series of data
    numpoints = 30
    low = -5
    high = 15.0
    x = linspace(low, high, numpoints)
    y = jn(0, x)

    lineplot = create_line_plot((x,y), color=tuple(COLOR_PALETTE[0]), width=2.0)
    lineplot.selected_color = "none"
    scatter = ScatterPlot(index = lineplot.index,
                       value = lineplot.value,
                       index_mapper = lineplot.index_mapper,
                       value_mapper = lineplot.value_mapper,
                       color = tuple(COLOR_PALETTE[0]),
                       marker_size = 5)
    scatter.index.sort_order = "ascending"

    scatter.bgcolor = "white"
    scatter.border_visible = True

    add_default_grids(scatter)
    add_default_axes(scatter)

    scatter.tools.append(PanTool(scatter, drag_button="right"))

    # The ZoomTool tool is stateful and allows drawing a zoom
    # box to select a zoom region.
    zoom = ZoomTool(scatter, tool_mode="box", always_on=False, drag_button=None)
    scatter.overlays.append(zoom)

    scatter.tools.append(PointDraggingTool(scatter))

    container.add(lineplot)
    container.add(scatter)

    # Add the title at the top
    container.overlays.append(PlotLabel("Line Editor",
                              component=container,
                              font = "swiss 16",
                              overlay_position="top"))

    return container
Exemple #20
0
    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
Exemple #21
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")
    plot1.plot(("index", "y3"), name="j_3", color="blue")

    # Tweak some of the plot properties
    plot1.title = "Inset Plot"
    plot1.padding = 50

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

    # Create a second scatter plot of one of the datasets, linking its
    # range to the first plot
    plot2 = Plot(pd, range2d=plot1.range2d, padding=50)
    plot2.plot(('index', 'y3'), type="scatter", color="blue", marker="circle")
    plot2.set(resizable = "",
              bounds = [250, 250],
              position = [550,150],
              bgcolor = "white",
              border_visible = True,
              unified_draw = True
              )
    plot2.tools.append(PanTool(plot2))
    plot2.tools.append(MoveTool(plot2, drag_button="right"))
    zoom = ZoomTool(component=plot2, tool_mode="box", always_on=False)
    plot2.overlays.append(zoom)

    # Create a container and add our plots
    container = OverlayPlotContainer()
    container.add(plot1)
    container.add(plot2)
    return container
Exemple #22
0
def _create_plot_component(use_downsampling=False):

    container = OverlayPlotContainer(padding=40, bgcolor="lightgray",
                                     use_backbuffer = True,
                                     border_visible = True,
                                     fill_padding = True)

    numpoints = 100000
    low = -5
    high = 15.0
    x = arange(low, high+0.001, (high-low)/numpoints)

    # Plot some bessel functionsless ../en
    value_mapper = None
    index_mapper = None
    for i in range(10):
        y = jn(i, x)
        plot = create_line_plot((x,y), color=tuple(COLOR_PALETTE[i]), width=2.0)
        plot.use_downsampling = use_downsampling

        if value_mapper is None:
            index_mapper = plot.index_mapper
            value_mapper = plot.value_mapper
            add_default_grids(plot)
            add_default_axes(plot)
        else:
            plot.value_mapper = value_mapper
            value_mapper.range.add(plot.value)
            plot.index_mapper = index_mapper
            index_mapper.range.add(plot.index)
        if i%2 == 1:
            plot.line_style = "dash"
        plot.bgcolor = "white"
        container.add(plot)

    selection_overlay = RangeSelectionOverlay(component = plot)
    plot.tools.append(RangeSelection(plot))
    zoom = ZoomTool(plot, tool_mode="box", always_on=False)
    plot.overlays.append(selection_overlay)
    plot.overlays.append(zoom)

    return container
Exemple #23
0
def main():
    plot = create_plot()
    plot.bounds = [400,300]
    plot.outer_position = [30,30]
    plot.resizable = ""
    cmap_renderer = plot.plots["my_plot"][0]

    # Create the colorbar, handing in the appropriate range and colormap
    colorbar = create_colorbar(plot.color_mapper)
    colorbar.outer_position = [450,30]
    colorbar.plot = cmap_renderer
    colorbar.padding_top = plot.padding_top
    colorbar.padding_bottom = plot.padding_bottom

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

    start_vtk(container)
Exemple #24
0
def main():
    from enthought.tvtk.api import tvtk
    from enthought.mayavi import mlab
    from enthought.enable.vtk_backend.vtk_window import EnableVTKWindow

    f = mlab.figure(size=(900, 850))
    m = mlab.test_mesh()
    scene = mlab.gcf().scene
    render_window = scene.render_window
    renderer = scene.renderer
    rwi = scene.interactor

    # Create the plot
    timer_controller = TimerController()
    plots = create_plot_component(timer_controller)
    specplot, timeplot, spectrogram = plots

    for i, p in enumerate(plots):
        p.set(resizable="", bounds=[200, 200], outer_x=0, bgcolor="transparent")
        p.outer_y = i * 250
        p.tools.append(MoveTool(p, drag_button="right"))
        p.tools.append(PanTool(p))
        p.tools.append(ZoomTool(p))

    spectrogram.tools[-1].set(tool_mode="range", axis="value")
    spectrogram.tools[-2].set(constrain=True, constrain_direction="y")

    container = OverlayPlotContainer(bgcolor="transparent", fit_window=True)
    container.add(*plots)
    container.timer_callback = timer_controller.on_timer

    window = EnableVTKWindow(
        rwi,
        renderer,
        component=container,
        istyle_class=tvtk.InteractorStyleTrackballCamera,
        bgcolor="transparent",
        event_passthrough=True,
    )

    mlab.show()
Exemple #25
0
def _create_plot_component():

    container = OverlayPlotContainer(bgcolor = "white")
    plots = make_curves()
    for plot in plots:
        plot.padding = 50
        container.add(plot)

    left_axis = PlotAxis(plot, orientation='left')

    bottom_axis = LabelAxis(plot, orientation='bottom',
                           title='Categories',
                           positions = range(1, 10),
                           labels = ['a', 'b', 'c', 'd', 'e',
                                     'f', 'g', 'h', 'i'],
                           small_haxis_style=True)

    plot.underlays.append(left_axis)
    plot.underlays.append(bottom_axis)

    return container
    def _create_window(self):
        ts = touchstone.read('tests/data/deemb_mom.s2p')
        freqs = ts.freqs
        s11 = ts.get_parameter(1 ,1)

        container = OverlayPlotContainer(padding=50, fill_padding=True,
                                         bgcolor="lightgray",
                                         use_backbuffer=True)

        plot = create_smith_plot((freqs, s11), color=(0.0, 0.0, 1.0, 1),
                                 width=2.0)
        plot.bgcolor = "white"
        container.add(plot)

        # Add the title at the top
        container.overlays.append(PlotLabel("Smith Chart",
                                  component=container,
                                  font = "swiss 16",
                                  overlay_position="top"))

        return Window(self, -1, component=container)
def create_plot():

    container = OverlayPlotContainer(
        padding=50, fill_padding=True, bgcolor="lightgray")
    numpoints = 100

    low = -5

    high = 15.0

    x = arange(low, high + 0.001, (high - low) / numpoints)

    # Plot some bessel functions

    value_mapper = None

    index_mapper = None

    for i in range(10):

        y = jn(i, x)

        plot = create_line_plot((x, y),
                                color=(1.0 - i / 10.0, i / 10.0, 0, 1),
                                width=2.0,
                                index_sort="ascending")
        if i == 0:
            value_mapper = plot.value_mapper
            index_mapper = plot.index_mapper
            add_default_axes(plot)
            add_default_grids(plot)
        else:
            plot.value_mapper = value_mapper
            value_mapper.range.add(plot.value)
            plot.index_mapper = index_mapper
            index_mapper.range.add(plot.index)
        if i % 2 == 1:
            plot.line_style = "dash"
        container.add(plot)
    return container
 def test_multiple_min_size(self):
     comp1 = StaticPlotComponent([200, 50])
     comp2 = StaticPlotComponent([60, 300])
     container = OverlayPlotContainer(resizable='hv', bounds=[30,30])
     container.fit_components = "hv"
     container.add(comp1, comp2)
     container.do_layout()
     self.assert_tuple(container.get_preferred_size(), (200,300))
     self.assert_tuple(comp1.bounds, (200,50))
     self.assert_tuple(comp2.bounds, (60,300))
     return
    def test_fixed_size_component(self):
        container = OverlayPlotContainer(resizable='', bounds=[200.0,300.0])
        # non-resizable component
        component = PlotComponent(resizable='', position=[50.0,60.0], bounds=[100.0,110.0])
        self.assertEquals(container._layout_needed, True)
        container.do_layout()
        container.add(component)
        self.assertEquals(container._layout_needed, True)
        container.do_layout()
        self.assertEquals(container._layout_needed, False)

        # check the results of the layout
        self.assert_tuple(container.get_preferred_size(), (200.0,300.0))
        self.assert_tuple(component.position, (50.0,60.0))
        self.assert_tuple(component.bounds, (100.0,110.0))
        return
    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)
Exemple #31
0
    def _create_window(self):
        ts = touchstone.read('tests/data/deemb_mom.s2p')
        freqs = ts.freqs
        s11 = ts.get_parameter(1, 1)

        container = OverlayPlotContainer(padding=50,
                                         fill_padding=True,
                                         bgcolor="lightgray",
                                         use_backbuffer=True)

        plot = create_smith_plot((freqs, s11),
                                 color=(0.0, 0.0, 1.0, 1),
                                 width=2.0)
        plot.bgcolor = "white"
        container.add(plot)

        # Add the title at the top
        container.overlays.append(
            PlotLabel("Smith Chart",
                      component=container,
                      font="swiss 16",
                      overlay_position="top"))

        return Window(self, -1, component=container)
Exemple #32
0
def _create_plot_component():
    container = OverlayPlotContainer(bgcolor = "white")
    plots = make_curves()
    for plot in plots:
       plot.padding = 60
       container.add(plot)

    bottom_axis = PlotAxis(plot, orientation='bottom')

    label_list=['var a', 'var b', 'var c', 'var d', 'var e', 'var f',
                'var g', 'var h', 'var i']
    vertical_axis = LabelAxis(plot, orientation='left',
                            title='Categories',
                            positions = range(1, 10),
                            labels=label_list)
    vertical2_axis = LabelAxis(plot, orientation='right',
                               positions = range(1, 10),
                               labels=label_list)

    plot.underlays.append(vertical_axis)
    plot.underlays.append(vertical2_axis)
    plot.underlays.append(bottom_axis)

    return container
Exemple #33
0
    def rate_plot( self, rates, **traits ):

        rp = Plot( self.rate_data, default_origin = 'bottom left' )

        rp.x_axis.visible = False 
        rp.y_axis.visible = False 

        bounds = self.rate_data.get_data( rates ).shape

#        rp.img_plot( rates,
#                     xbounds  = np.linspace( 0, 1, bounds[1] + 1 ),
#                     ybounds  = np.linspace( 0, 1, bounds[0] + 1 ),
#                     colormap = chaco_colormaps.jet,
#                     interpolation = 'nearest')

        rp.contour_plot( rates,
                         type = 'line',
#                         xbounds  = np.linspace( 0, 1, bounds[1] + 1 ),
#                         ybounds  = np.linspace( 0, 1, bounds[0] + 1 ),
                         bgcolor  = 'black',
                         levels   = 15,
                         styles   = 'solid',
                         widths   = list( np.linspace( 4.0, 0.1, 15 )),
                         colors   = gmt_drywet )

        rp.aspect_ratio = 1

#        zoom = ZoomTool( rp, tool_mode = 'box', always_on = False )
#        rp.overlays.append(zoom)

#        rp.tools.append( PanTool( rp, constrain_key = 'shift' ) )
        
        subplot = OverlayPlotContainer( )
        subplot.add( rp )
        
        return subplot
Exemple #34
0
    def __init__(self, parent, id=-1, **kwargs):
        wx.Panel.__init__(self, parent, id=id, **kwargs)
        self.statusBar = self.GetTopLevelParent().statusBar

        self.container = OverlayPlotContainer(padding = 50, fill_padding = True,
            bgcolor = "lightgray", use_backbuffer=True)
        self.legend = Legend(component=self.container, padding=10, align="ur")
        #self.legend.tools.append(LegendTool(self.legend, drag_button="right"))
        self.container.overlays.append(self.legend)

        self.plot_window = Window(self, component=self.container)

        self.container.tools.append(TraitsTool(self.container))

        self.firstplot = True
        self._palette = ['red', 'blue', 'green', 'purple', 'yellow']
        self._current_palette_index = 0

        self._traces = []

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.plot_window.control, 1, wx.EXPAND)
        self.SetSizer(sizer)
        self.SetAutoLayout(True)
Exemple #35
0
    def _image_plot_container(self):
        plot = self.render_image()

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

        if self.numpeaks_img>0:
            scatplot = self.render_scatplot()
            self.container.add(scatplot)
            colorbar = self.draw_colorbar()
            self.img_container.add(colorbar)
        return self.img_container
Exemple #36
0
class TemplatePicker(HasTraits):
    template = Array
    CC = Array
    peaks = List
    zero = Int(0)
    tmp_size = Range(low=2, high=512, value=64, cols=4)
    max_pos_x = Int(1023)
    max_pos_y = Int(1023)
    top = Range(low='zero', high='max_pos_x', value=20, cols=4)
    left = Range(low='zero', high='max_pos_y', value=20, cols=4)
    is_square = Bool
    img_plot = Instance(Plot)
    tmp_plot = Instance(Plot)
    findpeaks = Button
    peak_width = Range(low=2, high=200, value=10)
    tab_selected = Event
    ShowCC = Bool
    img_container = Instance(Component)
    container = Instance(Component)
    colorbar = Instance(Component)
    numpeaks_total = Int(0)
    numpeaks_img = Int(0)
    OK_custom = OK_custom_handler
    cbar_selection = Instance(RangeSelection)
    cbar_selected = Event
    thresh = Trait(None, None, List, Tuple, Array)
    thresh_upper = Float(1.0)
    thresh_lower = Float(0.0)
    numfiles = Int(1)
    img_idx = Int(0)
    tmp_img_idx = Int(0)

    csr = Instance(BaseCursorTool)

    traits_view = View(HFlow(
        VGroup(Item("img_container",
                    editor=ComponentEditor(),
                    show_label=False),
               Group(
                   Spring(),
                   Item("ShowCC",
                        editor=BooleanEditor(),
                        label="Show cross correlation image")),
               label="Original image",
               show_border=True,
               trait_modified="tab_selected"),
        VGroup(
            Group(HGroup(
                Item("left", label="Left coordinate", style="custom"),
                Item("top", label="Top coordinate", style="custom"),
            ),
                  Item("tmp_size", label="Template size", style="custom"),
                  Item("tmp_plot",
                       editor=ComponentEditor(height=256, width=256),
                       show_label=False,
                       resizable=True),
                  label="Template",
                  show_border=True),
            Group(Item("peak_width", label="Peak width", style="custom"),
                  Group(
                      Spring(),
                      Item("findpeaks",
                           editor=ButtonEditor(label="Find Peaks"),
                           show_label=False),
                      Spring(),
                  ),
                  HGroup(
                      Item("thresh_lower",
                           label="Threshold Lower Value",
                           editor=TextEditor(evaluate=float,
                                             format_str='%1.4f')),
                      Item("thresh_upper",
                           label="Threshold Upper Value",
                           editor=TextEditor(evaluate=float,
                                             format_str='%1.4f')),
                  ),
                  HGroup(
                      Item("numpeaks_img",
                           label="Number of Cells selected (this image)",
                           style='readonly'),
                      Spring(),
                      Item("numpeaks_total", label="Total", style='readonly'),
                      Spring(),
                  ),
                  label="Peak parameters",
                  show_border=True),
        )),
                       buttons=[
                           Action(name='OK',
                                  enabled_when='numpeaks_total > 0'),
                           CancelButton
                       ],
                       title="Template Picker",
                       handler=OK_custom,
                       kind='livemodal',
                       key_bindings=key_bindings,
                       width=960,
                       height=600)

    def __init__(self, signal_instance):
        super(TemplatePicker, self).__init__()
        try:
            import cv
        except:
            print "OpenCV unavailable.  Can't do cross correlation without it.  Aborting."
            return None
        self.OK_custom = OK_custom_handler()
        self.sig = signal_instance
        if not hasattr(self.sig.mapped_parameters, "original_files"):
            self.sig.data = np.atleast_3d(self.sig.data)
            self.titles = [self.sig.mapped_parameters.name]
        else:
            self.numfiles = len(
                self.sig.mapped_parameters.original_files.keys())
            self.titles = self.sig.mapped_parameters.original_files.keys()
        tmp_plot_data = ArrayPlotData(
            imagedata=self.sig.data[self.top:self.top + self.tmp_size,
                                    self.left:self.left + self.tmp_size,
                                    self.img_idx])
        tmp_plot = Plot(tmp_plot_data, default_origin="top left")
        tmp_plot.img_plot("imagedata", colormap=jet)
        tmp_plot.aspect_ratio = 1.0
        self.tmp_plot = tmp_plot
        self.tmp_plotdata = tmp_plot_data
        self.img_plotdata = ArrayPlotData(
            imagedata=self.sig.data[:, :, self.img_idx])
        self.img_container = self._image_plot_container()

        self.crop_sig = None

    def render_image(self):
        plot = Plot(self.img_plotdata, default_origin="top left")
        img = plot.img_plot("imagedata", colormap=gray)[0]
        plot.title = "%s of %s: " % (self.img_idx + 1,
                                     self.numfiles) + self.titles[self.img_idx]
        plot.aspect_ratio = float(self.sig.data.shape[1]) / float(
            self.sig.data.shape[0])

        #if not self.ShowCC:
        csr = CursorTool(img,
                         drag_button='left',
                         color='white',
                         line_width=2.0)
        self.csr = csr
        csr.current_position = self.left, self.top
        img.overlays.append(csr)

        # attach the rectangle tool
        plot.tools.append(PanTool(plot, drag_button="right"))
        zoom = ZoomTool(plot,
                        tool_mode="box",
                        always_on=False,
                        aspect_ratio=plot.aspect_ratio)
        plot.overlays.append(zoom)
        self.img_plot = plot
        return plot

    def render_scatplot(self):
        peakdata = ArrayPlotData()
        peakdata.set_data("index", self.peaks[self.img_idx][:, 0])
        peakdata.set_data("value", self.peaks[self.img_idx][:, 1])
        peakdata.set_data("color", self.peaks[self.img_idx][:, 2])
        scatplot = Plot(peakdata,
                        aspect_ratio=self.img_plot.aspect_ratio,
                        default_origin="top left")
        scatplot.plot(
            ("index", "value", "color"),
            type="cmap_scatter",
            name="my_plot",
            color_mapper=jet(DataRange1D(low=0.0, high=1.0)),
            marker="circle",
            fill_alpha=0.5,
            marker_size=6,
        )
        scatplot.x_grid.visible = False
        scatplot.y_grid.visible = False
        scatplot.range2d = self.img_plot.range2d
        self.scatplot = scatplot
        self.peakdata = peakdata
        return scatplot

    def _image_plot_container(self):
        plot = self.render_image()

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

        if self.numpeaks_img > 0:
            scatplot = self.render_scatplot()
            self.container.add(scatplot)
            colorbar = self.draw_colorbar()
            self.img_container.add(colorbar)
        return self.img_container

    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

    @on_trait_change('ShowCC')
    def toggle_cc_view(self):
        if self.ShowCC:
            self.CC = cv_funcs.xcorr(
                self.sig.data[self.top:self.top + self.tmp_size,
                              self.left:self.left + self.tmp_size,
                              self.img_idx], self.sig.data[:, :, self.img_idx])
            self.img_plotdata.set_data("imagedata", self.CC)
        else:
            self.img_plotdata.set_data("imagedata",
                                       self.sig.data[:, :, self.img_idx])
        self.redraw_plots()

    @on_trait_change("img_idx")
    def update_img_depth(self):
        if self.ShowCC:
            self.CC = cv_funcs.xcorr(
                self.sig.data[self.top:self.top + self.tmp_size,
                              self.left:self.left + self.tmp_size,
                              self.img_idx], self.sig.data[:, :, self.img_idx])
            self.img_plotdata.set_data("imagedata", self.CC)
        else:
            self.img_plotdata.set_data("imagedata",
                                       self.sig.data[:, :, self.img_idx])
        self.img_plot.title = "%s of %s: " % (
            self.img_idx + 1, self.numfiles) + self.titles[self.img_idx]
        self.redraw_plots()

    @on_trait_change('tmp_size')
    def update_max_pos(self):
        max_pos_x = self.sig.data.shape[0] - self.tmp_size - 1
        if self.left > max_pos_x: self.left = max_pos_x
        self.max_pos_x = max_pos_x
        max_pos_y = self.sig.data.shape[1] - self.tmp_size - 1
        if self.top > max_pos_y: self.top = max_pos_y
        self.max_pos_y = max_pos_y
        return

    def increase_img_idx(self, info):
        if self.img_idx == (self.numfiles - 1):
            self.img_idx = 0
        else:
            self.img_idx += 1

    def decrease_img_idx(self, info):
        if self.img_idx == 0:
            self.img_idx = self.numfiles - 1
        else:
            self.img_idx -= 1

    @on_trait_change('left, top')
    def update_csr_position(self):
        self.csr.current_position = self.left, self.top

    @on_trait_change('csr:current_position')
    def update_top_left(self):
        self.left, self.top = self.csr.current_position

    @on_trait_change('left, top, tmp_size')
    def update_tmp_plot(self):
        self.tmp_plotdata.set_data(
            "imagedata",
            self.sig.data[self.top:self.top + self.tmp_size,
                          self.left:self.left + self.tmp_size, self.img_idx])
        grid_data_source = self.tmp_plot.range2d.sources[0]
        grid_data_source.set_data(np.arange(self.tmp_size),
                                  np.arange(self.tmp_size))
        self.tmp_img_idx = self.img_idx
        return

    @on_trait_change('left, top, tmp_size')
    def update_CC(self):
        if self.ShowCC:
            self.CC = cv_funcs.xcorr(
                self.sig.data[self.top:self.top + self.tmp_size,
                              self.left:self.left + self.tmp_size,
                              self.tmp_img_idx], self.sig.data[:, :,
                                                               self.img_idx])
            self.img_plotdata.set_data("imagedata", self.CC)
            grid_data_source = self.img_plot.range2d.sources[0]
            grid_data_source.set_data(np.arange(self.CC.shape[1]),
                                      np.arange(self.CC.shape[0]))
        if self.numpeaks_total > 0:
            self.peaks = [np.array([[0, 0, -1]])]

    @on_trait_change('cbar_selection:selection')
    def update_thresh(self):
        try:
            thresh = self.cbar_selection.selection
            self.thresh = thresh
            self.cmap_renderer.color_data.metadata['selections'] = thresh
            self.thresh_lower = thresh[0]
            self.thresh_upper = thresh[1]
            #cmap_renderer.color_data.metadata['selection_masks']=self.thresh
            self.cmap_renderer.color_data.metadata_changed = {
                'selections': thresh
            }
            self.container.request_redraw()
            self.img_container.request_redraw()
        except:
            pass

    @on_trait_change('thresh_upper,thresh_lower')
    def manual_thresh_update(self):
        self.thresh = [self.thresh_lower, self.thresh_upper]
        self.cmap_renderer.color_data.metadata['selections'] = self.thresh
        self.cmap_renderer.color_data.metadata_changed = {
            'selections': self.thresh
        }
        self.container.request_redraw()
        self.img_container.request_redraw()

    @on_trait_change('peaks,cbar_selection:selection,img_idx')
    def calc_numpeaks(self):
        try:
            thresh = self.cbar_selection.selection
            self.thresh = thresh
        except:
            thresh = []
        if thresh == [] or thresh == () or thresh == None:
            thresh = (0, 1)
        self.numpeaks_total = int(
            np.sum([
                np.sum(
                    np.ma.masked_inside(self.peaks[i][:, 2], thresh[0],
                                        thresh[1]).mask)
                for i in xrange(len(self.peaks))
            ]))
        try:
            self.numpeaks_img = int(
                np.sum(
                    np.ma.masked_inside(self.peaks[self.img_idx][:, 2],
                                        thresh[0], thresh[1]).mask))
        except:
            self.numpeaks_img = 0

    @on_trait_change('findpeaks')
    def locate_peaks(self):
        from hyperspy import peak_char as pc
        peaks = []
        for idx in xrange(self.numfiles):
            self.CC = cv_funcs.xcorr(
                self.sig.data[self.top:self.top + self.tmp_size,
                              self.left:self.left + self.tmp_size,
                              self.tmp_img_idx], self.sig.data[:, :, idx])
            # peak finder needs peaks greater than 1.  Multiply by 255 to scale them.
            pks = pc.two_dim_findpeaks(self.CC * 255,
                                       peak_width=self.peak_width,
                                       medfilt_radius=None)
            pks[:, 2] = pks[:, 2] / 255.
            peaks.append(pks)
        self.peaks = peaks

    def mask_peaks(self, idx):
        thresh = self.cbar_selection.selection
        if thresh == []:
            thresh = (0, 1)
        mpeaks = np.ma.asarray(self.peaks[idx])
        mpeaks[:, 2] = np.ma.masked_outside(mpeaks[:, 2], thresh[0], thresh[1])
        return mpeaks

    @on_trait_change("peaks")
    def redraw_plots(self):
        oldplot = self.img_plot
        self.container.remove(oldplot)
        newplot = self.render_image()
        self.container.add(newplot)
        self.img_plot = newplot

        try:
            # if these haven't been created before, this will fail.  wrap in try to prevent that.
            oldscat = self.scatplot
            self.container.remove(oldscat)
            oldcolorbar = self.colorbar
            self.img_container.remove(oldcolorbar)
        except:
            pass

        if self.numpeaks_img > 0:
            newscat = self.render_scatplot()
            self.container.add(newscat)
            self.scatplot = newscat
            colorbar = self.draw_colorbar()
            self.img_container.add(colorbar)
            self.colorbar = colorbar

        self.container.request_redraw()
        self.img_container.request_redraw()

    def crop_cells_stack(self):
        from eelslab.signals.aggregate import AggregateCells
        if self.numfiles == 1:
            self.crop_sig = self.crop_cells()
            return
        else:
            crop_agg = []
            for idx in xrange(self.numfiles):
                crop_agg.append(self.crop_cells(idx))
            self.crop_sig = AggregateCells(*crop_agg)
            return

    def crop_cells(self, idx=0):
        print "cropping cells..."
        from hyperspy.signals.image import Image
        # filter the peaks that are outside the selected threshold
        peaks = np.ma.compress_rows(self.mask_peaks(idx))
        tmp_sz = self.tmp_size
        data = np.zeros((tmp_sz, tmp_sz, peaks.shape[0]))
        if not hasattr(self.sig.mapped_parameters, "original_files"):
            parent = self.sig
        else:
            parent = self.sig.mapped_parameters.original_files[
                self.titles[idx]]
        for i in xrange(peaks.shape[0]):
            # crop the cells from the given locations
            data[:, :, i] = self.sig.data[peaks[i, 1]:peaks[i, 1] + tmp_sz,
                                          peaks[i,
                                                0]:peaks[i, 0] + tmp_sz, idx]
            crop_sig = Image({
                'data': data,
                'mapped_parameters': {
                    'name': 'Cropped cells from %s' % self.titles[idx],
                    'record_by': 'image',
                    'locations': peaks,
                    'parent': parent,
                }
            })
        return crop_sig
        # attach a class member that has the locations from which the images were cropped
        print "Complete.  "
Exemple #37
0
class VariableMeshPannerView(HasTraits):

    plot = Instance(Plot)
    spawn_zoom = Button
    vm_plot = Instance(VMImagePlot)
    use_tools = Bool(True)
    full_container = Instance(HPlotContainer)
    container = Instance(OverlayPlotContainer)

    traits_view = View(
        Group(Item('full_container',
                   editor=ComponentEditor(size=(512, 512)),
                   show_label=False),
              Item('field', show_label=False),
              orientation="vertical"),
        width=800,
        height=800,
        resizable=True,
        title="Pan and Scan",
    )

    def _vm_plot_default(self):
        return VMImagePlot(panner=self.panner)

    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)
Exemple #38
0
class PlotView(wx.Panel):
    def __init__(self, parent, id=-1, **kwargs):
        wx.Panel.__init__(self, parent, id=id, **kwargs)
        self.statusBar = self.GetTopLevelParent().statusBar

        self.container = OverlayPlotContainer(padding = 50, fill_padding = True,
            bgcolor = "lightgray", use_backbuffer=True)
        self.legend = Legend(component=self.container, padding=10, align="ur")
        #self.legend.tools.append(LegendTool(self.legend, drag_button="right"))
        self.container.overlays.append(self.legend)

        self.plot_window = Window(self, component=self.container)

        self.container.tools.append(TraitsTool(self.container))

        self.firstplot = True
        self._palette = ['red', 'blue', 'green', 'purple', 'yellow']
        self._current_palette_index = 0

        self._traces = []

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.plot_window.control, 1, wx.EXPAND)
        self.SetSizer(sizer)
        self.SetAutoLayout(True)

    def _next_color(self):
        if self._current_palette_index == len(self._palette):
            self._current_palette_index = 0
        self._current_palette_index += 1
        return self._palette[self._current_palette_index - 1]

    def add_plot(self, signal, sweep_point=None):
##        waveform = signal.get_waveform()
##        x = waveform.get_x()[-1][0].tolist()
##        y = np.real(waveform.get_y()[0].tolist())

        if sweep_point is None:
            sweep_point = signal.get_circuit()._sweep_set._points[0]

        trace = Trace(signal, self, self._next_color(), sweep_point)

        x_name = trace.index_label
        y_name = trace.label

        x = trace.get_indices()
        y = trace.get_values()
        if type(y[0]) == complex:
            y = [value.real for value in y]
        #print x_name, len(x)
        #print y_name, len(y)
        #print x
        #print y

        if self.firstplot:
            self.plotdata = ArrayPlotData()
            self.plotdata.set_data(x_name, x)
            self.plotdata.set_data(y_name, y)

            plot = Plot(self.plotdata)
            plot.padding = 1

            plot.bgcolor = "white"
            plot.border_visible = True
            add_default_grids(plot)
            add_default_axes(plot)

            plot.tools.append(PanTool(plot))

            # The ZoomTool tool is stateful and allows drawing a zoom
            # box to select a zoom region.
            zoom = CustomZoomTool(plot)
            plot.overlays.append(zoom)

            # The DragZoom tool just zooms in and out as the user drags
            # the mouse vertically.
            dragzoom = DragZoom(plot, drag_button="right")
            plot.tools.append(dragzoom)

            #~ # Add a legend in the upper right corner, and make it relocatable
            #~ self.legend = Legend(component=plot, padding=10, align="ur")
            #~ self.legend.tools.append(LegendTool(self.legend, drag_button="right"))
            #~ plot.overlays.append(self.legend)

            #~ self.legend.plots = {}

            self.firstplot = False

            self.container.add(plot)

            self.plot = plot

        else:
            self.plotdata.set_data(x_name, x)
            self.plotdata.set_data(y_name, y)

        #self.plot.plot(self.plotdata.list_data())
        pl = self.plot.plot( (x_name, y_name), name=trace.label, type="line",
            color=trace.color, line_style=trace.line_style,
            line_width=trace.line_width, marker=trace.marker,
            marker_size=trace.marker_size, marker_color=trace.marker_color)

        self.legend.plots[trace.label] = pl

        self.Refresh()