Exemple #1
0
def _create_plot_component():

    # Create some x-y data series to plot
    x = linspace(-2.0, 10.0, 40)
    pd = ArrayPlotData(index = x, y0=jn(0,x))

    # Create some line plots of some of the data
    plot1 = Plot(pd, title="render_style = hold", padding=50, border_visible=True,
                 overlay_border = True)
    plot1.legend.visible = True
    lineplot = plot1.plot(("index", "y0"), name="j_0", color="red", render_style="hold")

    # Attach some tools to the plot
    attach_tools(plot1)

    # Create a second scatter plot of one of the datasets, linking its
    # range to the first plot
    plot2 = Plot(pd, range2d=plot1.range2d, title="render_style = connectedhold",
                 padding=50, border_visible=True, overlay_border=True)
    plot2.plot(('index', 'y0'), color="blue", render_style="connectedhold")
    attach_tools(plot2)

    # Create a container and add our plots
    container = HPlotContainer()
    container.add(plot1)
    container.add(plot2)
    return container
Exemple #2
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, title="Line Plot", padding=50, border_visible=True)
    plot1.legend.visible = True
    plot1.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red")
    plot1.plot(("index", "y3"), name="j_3", color="blue")

    # 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, title="Scatter plot", padding=50,
                 border_visible=True)
    plot2.plot(('index', 'y3'), type="scatter", color="blue", marker="circle")

    # Create a container and add our plots
    container = HPlotContainer()
    container.add(plot1)
    container.add(plot2)

    return container
Exemple #3
0
def _create_plot_component():
    numpoints = 100
    low = -5
    high = 15.0
    x = arange(low, high, (high - low) / numpoints)

    container = HPlotContainer(resizable="hv", bgcolor="lightgray", fill_padding=True, padding=10)
    # container = VPlotContainer(resizable = "hv", bgcolor="lightgray",
    #                            fill_padding=True, padding = 10)

    # Plot some bessel functions
    value_range = None
    for i in range(10):
        y = jn(i, x)
        plot = create_line_plot((x, y), color=tuple(COLOR_PALETTE[i]), width=2.0, orientation="v")
        # orientation="h")
        plot.origin_axis_visible = True
        plot.origin = "top left"
        plot.padding_left = 10
        plot.padding_right = 10
        plot.border_visible = True
        plot.bgcolor = "white"
        if value_range is None:
            value_range = plot.value_mapper.range
        else:
            plot.value_range = value_range
            value_range.add(plot.value)
        if i % 2 == 1:
            plot.line_style = "dash"
        container.add(plot)

    container.padding_top = 50
    container.overlays.append(PlotLabel("More Bessels", component=container, font="swiss 16", overlay_position="top"))

    return container
Exemple #4
0
    def draw( self ):
        """Draw data."""
        if len(self.fitResults) == 0:
            return

        #if not hasattr( self, 'subplot1' ):
        #    self.subplot1 = self.figure.add_subplot( 211 )
        #    self.subplot2 = self.figure.add_subplot( 212 )

        a, ed = numpy.histogram(self.fitResults['tIndex'], self.Size[0]/2)

        #self.subplot1.cla()
        #self.subplot1.plot(ed[:-1], a, color='b' )
        #self.subplot1.set_xticks([0, ed.max()])
        #self.subplot1.set_yticks([0, a.max()])
        #self.subplot2.cla()
        #self.subplot2.plot(ed[:-1], numpy.cumsum(a), color='g' )
        #self.subplot2.set_xticks([0, ed.max()])
        #self.subplot2.set_yticks([0, a.sum()])

        plot1 = create_line_plot(ed[:,-1], a, color = 'blue', bgcolor="white",
                                add_grid=True, add_axis=True)

        plot2 = create_line_plot(ed[:,-1], numpy.cumsum(a), color = 'green', bgcolor="white",
                                add_grid=True, add_axis=True)
        container = HPlotContainer(spacing=20, padding=50, bgcolor="lightgray")
        container.add(plot1)
        container.add(plot2)
        return container
Exemple #5
0
def _create_plot_component(obj):
    # Setup the spectrum plot
    frequencies = linspace(0.0, float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2)
    obj.spectrum_data = ArrayPlotData(frequency=frequencies)
    empty_amplitude = zeros(NUM_SAMPLES/2)
    obj.spectrum_data.set_data('amplitude', empty_amplitude)

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

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

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

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

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

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

    return c2
Exemple #6
0
    def get_plot(self):
        pixel_sizes = self.data_source.voxel_sizes
        shape = self.data.shape
        m = min(pixel_sizes)
        s = [int(d*sz/m) for d, sz in zip(shape, pixel_sizes)]
        if 1: # else physical aspect ratio is enabled
            ss = max(s)/4
            s = [max(s,ss) for s in s]
        plot_sizes = dict (xy = (s[2], s[1]), xz = (s[2], s[0]), zy = (s[0],s[1]), zz=(s[0],s[0]))

        plots = GridContainer(shape=(2,2), spacing=(3, 3), padding = 50, aspect_ratio=1)
        pxy = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['xy'],
                   x_axis=PlotAxis (orientation='top'),
                   )
        pxz = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['xz'],
                   )
        pzy = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['zy'],
                   #orientation = 'v',  # cannot use 'v' because of img_plot assumes row-major ordering
                   x_axis=PlotAxis(orientation='top'), 
                   y_axis=PlotAxis(orientation='right'),
                   )
        pzz = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['zz'])

        plots.add(pxy, pzy, pxz, pzz)

        self.plots =  dict(xy = pxy.img_plot('xy', colormap=bone)[0],
                           xz = pxz.img_plot('xz', colormap=bone)[0],
                           zy = pzy.img_plot('zy', colormap=bone)[0],
                           zz = pzz.img_plot('zz')[0],
                           xyp = pxy.plot(('z_x', 'z_y'), type='scatter', color='orange', marker='circle', marker_size=3, 
                                          selection_marker_size = 3, selection_marker='circle')[0],
                           xzp = pxz.plot(('y_x', 'y_z'), type='scatter', color='orange', marker='circle', marker_size=3,
                                          selection_marker_size = 3, selection_marker='circle')[0],
                           zyp = pzy.plot(('x_z', 'x_y'), type='scatter', color='orange', marker='circle', marker_size=3,
                                          selection_marker_size = 3, selection_marker='circle')[0],
                           )

        for p in ['xy', 'xz', 'zy']:
            self.plots[p].overlays.append(ZoomTool(self.plots[p]))
            self.plots[p].tools.append(PanTool(self.plots[p], drag_button='right'))

            imgtool = ImageInspectorTool(self.plots[p])
            self.plots[p].tools.append(imgtool)
            overlay = ImageInspectorOverlay(component=self.plots[p],
                                            bgcolor = 'white',
                                            image_inspector=imgtool)
            self.plots['zz'].overlays.append(overlay)

            self.plots[p+'p'].tools.append (ScatterInspector(self.plots[p+'p'], selection_mode = 'toggle'))

        self.plots['xyp'].index.on_trait_change (self._xyp_metadata_handler, 'metadata_changed')
        self.plots['xzp'].index.on_trait_change (self._xzp_metadata_handler, 'metadata_changed')
        self.plots['zyp'].index.on_trait_change (self._zyp_metadata_handler, 'metadata_changed')

        plot = HPlotContainer()
        # todo: add colormaps
        plot.add(plots)
        return plot
Exemple #7
0
    def _createWindow(self):

        container = HPlotContainer(resizable = "hv", bgcolor="lightgray",
        #container = Container(resizable = "hv", bgcolor="lightgray",
                                   fill_padding=True, padding = 10)
        container.add(self._createConfigurationPane())
        container.add(self._createResultsPane())
        #container.add(self._create_plot_component())
        return container
Exemple #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)
Exemple #9
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
Exemple #10
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
    plot = Plot(pd, title="Line Plot", padding=50, border_visible=True)
    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.x_grid.line_color = "black"
    plot.y_grid.line_color = "black"
    xmin, xmax = 1.0, 6.0
    ymin, ymax = 0.2, 0.80001
    plot.x_grid.set(data_min = xmin, data_max = xmax,
            transverse_bounds = (ymin, ymax),
            transverse_mapper = plot.y_mapper)

    plot.y_grid.set(data_min = ymin, data_max = ymax,
            transverse_bounds = (xmin, xmax),
            transverse_mapper = plot.x_mapper)

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

    # A second plot whose vertical grid lines are clipped to the jn(3) function
    def my_bounds_func(ticks):
        """ Returns y_low and y_high for each grid tick in the array **ticks** """
        tmp = array([zeros(len(ticks)),jn(3, ticks)]).T
        return tmp

    func_plot = Plot(pd, padding=50, border_visible=True)
    func_plot.plot(("index", "y3"), color="red")
    func_plot.x_grid.set(transverse_bounds = my_bounds_func,
                    transverse_mapper = func_plot.y_mapper,
                    line_color="black")
    func_plot.tools.append(PanTool(func_plot))

    container = HPlotContainer()
    container.add(plot)
    container.add(func_plot)

    return container
Exemple #11
0
 def __init__(self):
     x, y = np.ogrid[-2*np.pi:2*np.pi:256j, -2*np.pi:2*np.pi:256j]
     self.img_data = np.sin(x)*y
     #self.img_mask = np.zeros((len(x), len(y[0]), 4), dtype=np.uint8)
     #self.img_mask[:, :, 3] = 255
     self.img_index = np.array(list((np.broadcast(y, x))))
     
     plotdata = ArrayPlotData(img_data=self.img_data, mask_data=self.img_data) 
     plot1 = Plot(plotdata, padding=10) 
     img_plot = plot1.img_plot("img_data",
         xbounds=(np.min(x), np.max(x)),
         ybounds=(np.min(y), np.max(y)))[0]
    
     self.lasso = LassoSelection(img_plot)
     img_plot.tools.append(self.lasso)
     self.ll = LassoOverlay(img_plot, lasso_selection=self.lasso)
     img_plot.overlays.append(self.ll)
     self.lasso.on_trait_change(self._selection_changed, 'selection_completed')
     
     plot2 = Plot(plotdata, padding=10)
     plot2.img_plot("mask_data")
    
     self.plot = HPlotContainer(plot1, plot2)
     self.plot1 = plot1
     self.plot2 = plot2
     self.plotdata = plotdata
Exemple #12
0
    def __init__(self, **traits):
        super(LassoDemoPlot, self).__init__(**traits)
        x = np.random.random(N)
        y = np.random.random(N)
        x2 = np.array([])
        y2 = np.array([])

        data = ArrayPlotData(x=x, y=y, x2=x2, y2=y2)

        plot1 = Plot(data, padding=10)
        scatter_plot1 = plot1.plot(("x", "y"),
                                   type="scatter",
                                   marker="circle",
                                   color="blue")[0]

        self.lasso = LassoSelection(scatter_plot1,
                                    incremental_select=True,
                                    selection_datasource=scatter_plot1.index)
        self.lasso.on_trait_change(self._selection_changed,
                                   'selection_changed')
        scatter_plot1.tools.append(self.lasso)
        scatter_plot1.overlays.append(
            LassoOverlay(scatter_plot1, lasso_selection=self.lasso))

        plot2 = Plot(data, padding=10)
        plot2.index_range = plot1.index_range
        plot2.value_range = plot1.value_range
        plot2.plot(("x2", "y2"), type="scatter", marker="circle", color="red")

        self.plot = HPlotContainer(plot1, plot2)
        self.plot2 = plot2
        self.data = data
Exemple #13
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
Exemple #14
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 test_valign(self):
     container = HPlotContainer(bounds=[300,200], valign="center")
     comp1 = StaticPlotComponent([200,100])
     container.add(comp1)
     container.do_layout()
     self.failUnlessEqual(comp1.position, [0,50])
     container.valign="top"
     container.do_layout(force=True)
     self.failUnlessEqual(comp1.position, [0,100])
     return
Exemple #16
0
def _create_plot_component(obj):
    # Setup the spectrum plot
    frequencies = linspace(0.0, MAX_FREQ, num=MAX_FREQN)
    obj.spectrum_data = ArrayPlotData(frequency=frequencies)
    empty_amplitude = zeros(MAX_FREQN)
    obj.spectrum_data.set_data("amplitude", empty_amplitude)

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

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

    obj.time_plot = Plot(obj.time_data)
    obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue", alpha=0.5)
    obj.time_plot.plot(("time", "amplitude_1"), name="Time", color="red", alpha=0.5)

    obj.time_plot.padding = 50
    obj.time_plot.title = "Time"
    obj.time_plot.index_axis.title = "Time (seconds)"
    obj.time_plot.value_axis.title = "Amplitude"
    time_range = obj.time_plot.plots.values()[0][0].value_mapper.range
    time_range.low = -1
    time_range.high = 1

    # Spectrogram plot
    spectrogram_data = zeros((MAX_FREQN, SPECTROGRAM_LENGTH))
    obj.spectrogram_plotdata = ArrayPlotData()
    obj.spectrogram_plotdata.set_data("imagedata", spectrogram_data)
    spectrogram_plot = Plot(obj.spectrogram_plotdata)
    max_time = float(SPECTROGRAM_LENGTH * NUM_SAMPLES) / SAMPLING_RATE
    # max_freq = float(SAMPLING_RATE / 2)
    max_freq = float(MAX_FREQ)
    spectrogram_plot.img_plot(
        "imagedata", name="Spectrogram", xbounds=(0, max_time), ybounds=(0, max_freq), colormap=jet
    )
    range_obj = spectrogram_plot.plots["Spectrogram"][0].value_mapper.range
    range_obj.high = 2  # brightness of specgram
    range_obj.low = 0.0
    range_obj.edit_traits()
    spectrogram_plot.title = "Spectrogram"
    obj.spectrogram_plot = spectrogram_plot

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

    return container
Exemple #17
0
 def activate_template(self):
     """ Converts all contained 'TDerived' objects to real objects using the
         template traits of the object. This method must be overridden in
         subclasses.
         
         Returns
         -------
         None
     """
     plots = [
         p for p in [self.scatter_plot_1.plot, self.scatter_plot_2.plot]
         if p is not None
     ]
     if len(plots) == 2:
         self.plot = HPlotContainer(spacing=self.spacing)
         self.plot.add(*plots)
     elif len(plots) == 1:
         self.plot = plots[0]
Exemple #18
0
def _create_plot_component(obj):
    # Setup the spectrum plot
    frequencies = linspace(0.0, float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2)
    obj.spectrum_data = ArrayPlotData(frequency=frequencies)
    empty_amplitude = zeros(NUM_SAMPLES/2)
    obj.spectrum_data.set_data('amplitude', empty_amplitude)

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

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

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

    # Spectrogram plot
    spectrogram_data = zeros(( NUM_SAMPLES/2, SPECTROGRAM_LENGTH))
    obj.spectrogram_plotdata = ArrayPlotData()
    obj.spectrogram_plotdata.set_data('imagedata', spectrogram_data)
    spectrogram_plot = Plot(obj.spectrogram_plotdata)
    max_time = float(SPECTROGRAM_LENGTH * NUM_SAMPLES) / SAMPLING_RATE
    max_freq = float(SAMPLING_RATE / 2)
    spectrogram_plot.img_plot('imagedata',
                              name='Spectrogram',
                              xbounds=(0, max_time),
                              ybounds=(0, max_freq),
                              colormap=jet,
                              )
    range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range
    range_obj.high = 5
    range_obj.low = 0.0
    spectrogram_plot.title = 'Spectrogram'
    obj.spectrogram_plot = spectrogram_plot

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

    return container
    def __init__(self):
        # Create the data and the PlotData object
        x = linspace(-14, 14, 100)
        y = sin(x) * x**3
        plotdata = ArrayPlotData(x = x, y = y)
        # Create the scatter plot
        scatter = Plot(plotdata)
        scatter.plot(("x", "y"), type="scatter", color="blue")
        # Create the line plot
        line = Plot(plotdata)
        line.plot(("x", "y"), type="line", color="blue")
        # Create a horizontal container and put the two plots inside it
        container = HPlotContainer(scatter, line)
        container.spacing = 0
        scatter.padding_right = 0
        line.padding_left = 0
        line.y_axis.orientation = "right"

        self.plot = container
Exemple #20
0
def _create_plot_component():

    # Create the index
    numpoints = 100
    low = -5
    high = 15.0
    x = arange(low, high, (high-low)/numpoints)
    plotdata = ArrayPlotData(x=x, y1=jn(0,x), y2=jn(1,x))

    # Create the left plot
    left_plot = Plot(plotdata)
    left_plot.x_axis.title = "X"
    left_plot.y_axis.title = "j0(x)"
    renderer = left_plot.plot(("x", "y1"), type="line", color="blue",
                              width=2.0)[0]
    renderer.overlays.append(LineInspector(renderer, axis='value',
                                            write_metadata=True,
                                            is_listener=True))
    renderer.overlays.append(LineInspector(renderer, axis="index",
                                            write_metadata=True,
                                            is_listener=True))
    left_plot.overlays.append(ZoomTool(left_plot, tool_mode="range"))
    left_plot.tools.append(PanTool(left_plot))

    # Create the right plot
    right_plot = Plot(plotdata)
    right_plot.index_range = left_plot.index_range
    right_plot.orientation = "v"
    right_plot.x_axis.title = "j1(x)"
    right_plot.y_axis.title = "X"
    renderer2 = right_plot.plot(("x","y2"), type="line", color="red", width=2.0)[0]
    renderer2.index = renderer.index
    renderer2.overlays.append(LineInspector(renderer2, write_metadata=True, is_listener=True))
    renderer2.overlays.append(LineInspector(renderer2, axis="value", is_listener=True))
    right_plot.overlays.append(ZoomTool(right_plot, tool_mode="range"))
    right_plot.tools.append(PanTool(right_plot))

    container = HPlotContainer(background="lightgray")
    container.add(left_plot)
    container.add(right_plot)

    return container
Exemple #21
0
 def __init__(self):
     super(ContainerExample, self).__init__()
     x = linspace(-14, 14, 100)
     y = sin(x) * x**3
     plotdata = ArrayPlotData(x=x, y=y)
     scatter = Plot(plotdata)
     scatter.plot(("x", "y"), type="scatter", color="blue")
     line = Plot(plotdata)
     line.plot(("x", "y"), type="line", color="blue")
     container = HPlotContainer(scatter, line)
     self.plot = container
Exemple #22
0
    def _create_window(self):

        # 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, title="Line Plot", padding=50, border_visible=True, 
                     overlay_border=True)
        plot1.legend.visible = True
        plot1.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red")
        plot1.plot(("index", "y3"), name="j_3", color="blue")

        # Create a container and add our plots
        container = HPlotContainer()
        container.add(plot1)

        # Return a window containing our plots
        return Window(self, -1, component=container)
Exemple #23
0
def _create_plot_component():
    # Create the index
    numpoints = 100
    low = -5
    high = 15.0
    x = arange(low, high, (high - low) / numpoints)
    plotdata = ArrayPlotData(x=x, y1=jn(0, x), y2=jn(1, x))
    # Create the left plot
    left_plot = Plot(plotdata)
    left_plot.x_axis.title = 'X'
    left_plot.y_axis.title = 'j0(x)'
    renderer = left_plot.plot(('x', 'y1'), type='line', color='blue',
                              width=2.0)[0]
    renderer.overlays.append(LineInspector(renderer, axis='value',
                             write_metadata=True, is_listener=True))
    renderer.overlays.append(LineInspector(renderer, axis='index',
                             write_metadata=True, is_listener=True))
    left_plot.overlays.append(ZoomTool(left_plot, tool_mode='range'))
    left_plot.tools.append(PanTool(left_plot))
    # Create the right plot
    right_plot = Plot(plotdata)
    right_plot.index_range = left_plot.index_range
    right_plot.orientation = 'v'
    right_plot.x_axis.title = 'j1(x)'
    right_plot.y_axis.title = 'X'
    renderer2 = right_plot.plot(('x', 'y2'), type='line', color='red',
                                width=2.0)[0]
    renderer2.index = renderer.index
    renderer2.overlays.append(LineInspector(renderer2,
                              write_metadata=True, is_listener=True))
    renderer2.overlays.append(LineInspector(renderer2, axis='value',
                              is_listener=True))
    right_plot.overlays.append(ZoomTool(right_plot, tool_mode='range'))
    right_plot.tools.append(PanTool(right_plot))
    container = HPlotContainer(background='lightgray')
    container.add(left_plot)
    container.add(right_plot)

    right_plot = Plot(plotdata)
    right_plot.index_range = left_plot.index_range
    right_plot.orientation = 'v'
    right_plot.x_axis.title = 'j1(x)'
    right_plot.y_axis.title = 'X'
    renderer2 = right_plot.plot(('x', 'y2'), type='line', color='red',
                                width=2.0)[0]
    renderer2.index = renderer.index
    renderer2.overlays.append(LineInspector(renderer2,
                              write_metadata=True, is_listener=True))
    renderer2.overlays.append(LineInspector(renderer2, axis='value',
                              is_listener=True))
    right_plot.overlays.append(ZoomTool(right_plot, tool_mode='range'))
    right_plot.tools.append(PanTool(right_plot))
    container.add(right_plot)

    return container
    def _create_window(self, title, xtitle, x, ytitle, y, z):
        '''
        - Left-drag pans the plot.
    	- Mousewheel up and down zooms the plot in and out.
        - Pressing "z" brings up the Zoom Box, and you can click-drag a rectangular
        region to zoom.  If you use a sequence of zoom boxes, pressing alt-left-arrow
        and alt-right-arrow moves you forwards and backwards through the "zoom
        history".
        '''
        self._plotname = title
        # Create window
        self.data = ArrayPlotData()
        self.plot = Plot(self.data)      
        self.update_plot(x, y, z)
        self.plot.title = title
        self.plot.x_axis.title = xtitle
        self.plot.y_axis.title = ytitle
        
        cmap_renderer = self.plot.plots[self._plotname][0]
        
        # Create colorbar
        self._create_colorbar()
        self._colorbar.plot = cmap_renderer
        self._colorbar.padding_top = self.plot.padding_top
        self._colorbar.padding_bottom = self.plot.padding_bottom
        
        # Add some tools
        self.plot.tools.append(PanTool(self.plot, constrain_key="shift"))
        self.plot.overlays.append(ZoomTool(component=self.plot, tool_mode="box", always_on=False))
        # selection = ColormappedSelectionOverlay(cmap_renderer, fade_alpha=0.35, selection_type="mask")
        # cmap_renderer.overlays.append(selection)
        
        # Create a container to position the plot and the colorbar side-by-side
        container = HPlotContainer(use_backbuffer = True)
        container.add(self.plot)
        container.add(self._colorbar)
        self.container = container

        # Return a window containing our plot container
        return Window(self, -1, component=container)
Exemple #25
0
def _create_plot_component():

    # Create some data
    numpts = 1000
    x = sort(random(numpts))
    y = random(numpts)
    color = exp(-(x**2 + y**2))

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

    # Create the plot
    plot = Plot(pd)
    plot.plot(("index", "value", "color"),
              type="cmap_scatter",
              name="my_plot",
              color_mapper=jet,
              marker = "square",
              fill_alpha = 0.5,
              marker_size = 6,
              outline_color = "black",
              border_visible = True,
              bgcolor = "white")

    # Tweak some of the plot properties
    plot.title = "Colormapped Scatter Plot"
    plot.padding = 50
    plot.x_grid.visible = False
    plot.y_grid.visible = False
    plot.x_axis.font = "modern 16"
    plot.y_axis.font = "modern 16"

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

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot, constrain_key="shift"))
    zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
    plot.overlays.append(zoom)
    selection = ColormappedSelectionOverlay(cmap_renderer, fade_alpha=0.35,
                                            selection_type="mask")
    cmap_renderer.overlays.append(selection)

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

    # Create a container to position the plot and the colorbar side-by-side
    container = HPlotContainer(use_backbuffer = True)
    container.add(plot)
    container.add(colorbar)
    container.bgcolor = "lightgray"
    return container
Exemple #26
0
    def _ScanPlotContainer_default(self):
        ScanImage = self.ScanImage
        ScanImage.x_mapper.domain_limits = (self.x_range[0],self.x_range[1])
        ScanImage.y_mapper.domain_limits = (self.y_range[0],self.y_range[1])
        ScanImage.overlays.append(self.zoom_tool)
        ScanImage.overlays.append(self.cursor)
        
        colormap = ScanImage.color_mapper
        colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                            color_mapper=colormap,
                            plot=self.ScanPlot,
                            orientation='v',
                            resizable='v',
                            width=20,
                            height=400,
                            padding=50)

        container = HPlotContainer()
        container.add(self.ScanPlot)
        container.add(colorbar)

        return container
    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)
 def __init__(self):
     super(IMUGloveDisplay, self).__init__()
     x = linspace(-14, 14, 100)
     y = sin(x) * x**3
     plotdata = ArrayPlotData(x=x, y=y)
     scatter = Plot(plotdata)
     scatter.plot(("x", "y"), type="scatter", color="blue")
     line = Plot(plotdata)
     line.plot(("x", "y"), type="line", color="blue")
     container = HPlotContainer(scatter, line)
     #scatter.title = "sin(x) * x^3"
     #line.title = 'line plot'
     self.plot = container
     self.InitGlove()
Exemple #29
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 activate_template ( self ):
        """ Converts all contained 'TDerived' objects to real objects using the
            template traits of the object. This method must be overridden in
            subclasses.

            Returns
            -------
            None
        """
        plots = [ p for p in [ self.scatter_plot_1.plot,
                               self.scatter_plot_2.plot ] if p is not None ]
        if len( plots ) == 2:
            self.plot = HPlotContainer( spacing = self.spacing )
            self.plot.add( *plots )
        elif len( plots ) == 1:
            self.plot = plots[0]
    def _create_window(self, **kw):
        self._colormap = default_colormaps.jet       
        
        self.data = ArrayPlotData()
        self.plot = Plot(self.data)

        x = linspace(-10, 10, 101)
        y = linspace(-10, 10, 101)
        z = zeros((101,101))

        self.set_data(x, y, z, **kw)
        
        # self.set_data(x,y,z)        
        self._create_colorbar()
        self.container = HPlotContainer(use_backbuffer=True)
        self.container.add(self.plot)
        self.container.add(self._colorbar)
        
        return Window(self, -1, component=self.container)
 def test_stack_nonresize(self):
     # Assuming resizable='' for all plot containers and components
     container = HPlotContainer(bounds=[300,100])
     comp1 = StaticPlotComponent([100,70])
     comp2 = StaticPlotComponent([90,80])
     comp3 = StaticPlotComponent([80,90])
     container.add(comp1, comp2, comp3)
     container.do_layout()
     self.assert_tuple(container.get_preferred_size(), (270,90))
     self.assert_tuple(container.bounds, (300,100))
     self.assert_tuple(comp1.position, (0,0))
     self.assert_tuple(comp2.position, (100,0))
     self.assert_tuple(comp3.position, (190,0))
     return
 def test_stack_one_resize(self):
     "Checks stacking with 1 resizable component thrown in"
     container = HPlotContainer(bounds=[300,100])
     comp1 = StaticPlotComponent([100,70])
     comp2 = StaticPlotComponent([90,80])
     comp3 = StaticPlotComponent([80,90], resizable='hv')
     comp4 = StaticPlotComponent([40,50])
     container.add(comp1, comp2, comp3, comp4)
     container.do_layout()
     self.assert_tuple(container.get_preferred_size(), (230,80))
     self.assert_tuple(container.bounds, (300,100))
     self.assert_tuple(comp1.position, (0,0))
     self.assert_tuple(comp2.position, (100,0))
     self.assert_tuple(comp3.position, (190,0))
     self.assert_tuple(comp4.position, (260,0))
     return
Exemple #34
0
    def _object_index_changed(self):
        """Handle object index slider changing."""
        try:
            self.current_object = self.current_image[self.object_index - 1]

            # Display
            sil = self.current_object.image
            self._update_img_plot('sil_plot', sil, 'Extracted mask')

            # .T to get major axis horizontal
            rotated = self.current_object.aligned_version.image.T
            self._update_img_plot('rotated_plot', rotated, 'Aligned mask')

            self.image_plots = HPlotContainer(self.sil_plot,
                                              self.rotated_plot,
                                              valign="top",
                                              bgcolor="transparent")

            self._update_spline_plot()

        except IndexError:
            self.current_object = None
    def __init__(self):
        #读入图像
        img = cv.imread("lena_full.jpg")
        img2 = cv.Mat()
        cv.cvtColor(img, img2, cv.CV_BGR2GRAY)
        img = cv.Mat()
        cv.resize(img2, img, cv.Size(N, N))
        self.fimg = fft.fft2(img[:])  # 图像的频域信号
        mag_img = np.log10(np.abs(self.fimg))

        # 创建计算用图像
        filtered_img = np.zeros((N, N), dtype=np.float)
        self.mask = np.zeros((N, N), dtype=np.float)
        self.mask_img = cv.asMat(self.mask)  # 在self.mask上绘制多边形用的图像

        # 创建数据源
        self.data = ArrayPlotData(mag_img=fft.fftshift(mag_img),
                                  filtered_img=filtered_img,
                                  mask_img=self.mask)

        # 创建三个图像绘制框以及容器
        meg_plot, img = self.make_image_plot("mag_img")
        mask_plot, _ = self.make_image_plot("mask_img")
        filtered_plot, _ = self.make_image_plot("filtered_img")
        self.plot = HPlotContainer(meg_plot, mask_plot, filtered_plot)

        # 创建套索工具
        lasso_selection = LassoSelection(component=img)
        lasso_overlay = LassoOverlay(lasso_selection=lasso_selection,
                                     component=img,
                                     selection_alpha=0.3)
        img.tools.append(lasso_selection)
        img.overlays.append(lasso_overlay)
        self.lasso_selection = lasso_selection

        # 监听套索工具的事件、开启时钟事件
        lasso_selection.on_trait_change(self.lasso_updated,
                                        "disjoint_selections")
        self.timer = Timer(50, self.on_timer)
Exemple #36
0
 def _container_default(self):
     #image_container = OverlayPlotContainer(padding=20,
     #                                         use_backbuffer=True,
     #                                         unified_draw=True)
     #image_container.add(self.plot)
     container = HPlotContainer(padding=40,
                                fill_padding=True,
                                bgcolor="white",
                                use_backbuffer=False)
     inner_cont = VPlotContainer(padding=0, use_backbuffer=True)
     #        container = HPlotContainer(bgcolor = "white", use_backbuffer=False)
     #        inner_cont = VPlotContainer(use_backbuffer=True)
     inner_cont.add(self.h_plot)
     inner_cont.add(self.plot)
     container.add(inner_cont)
     container.add(self.v_plot)
     return container
Exemple #37
0
    def _create_window(self, title, xtitle, x, ytitle, y, z):
        '''
        - Left-drag pans the plot.
    	- Mousewheel up and down zooms the plot in and out.
        - Pressing "z" brings up the Zoom Box, and you can click-drag a rectangular
        region to zoom.  If you use a sequence of zoom boxes, pressing alt-left-arrow
        and alt-right-arrow moves you forwards and backwards through the "zoom
        history".
        '''
        self._plotname = title
        # Create window
        self.data = ArrayPlotData()
        self.plot = Plot(self.data)
        self.update_plot(x, y, z)
        self.plot.title = title
        self.plot.x_axis.title = xtitle
        self.plot.y_axis.title = ytitle

        cmap_renderer = self.plot.plots[self._plotname][0]

        # Create colorbar
        self._create_colorbar()
        self._colorbar.plot = cmap_renderer
        self._colorbar.padding_top = self.plot.padding_top
        self._colorbar.padding_bottom = self.plot.padding_bottom

        # Add some tools
        self.plot.tools.append(PanTool(self.plot, constrain_key="shift"))
        self.plot.overlays.append(
            ZoomTool(component=self.plot, tool_mode="box", always_on=False))
        # selection = ColormappedSelectionOverlay(cmap_renderer, fade_alpha=0.35, selection_type="mask")
        # cmap_renderer.overlays.append(selection)

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

        # Return a window containing our plot container
        return Window(self, -1, component=container)
Exemple #38
0
    def create_plot_component(self):
        color_range_max_value = 10

        # gripper right cos field
        x_axis = numpy.array(
            range(self.arch._gripper_right_cos_field.
                  get_output_dimension_sizes()[0]))
        self._gripper_right_cos_field_plotdata = ArrayPlotData(
            x=x_axis, y=self.arch._gripper_right_cos_field.get_activation())
        self._gripper_right_cos_field_plot = Plot(
            self._gripper_right_cos_field_plotdata)
        self._gripper_right_cos_field_plot.title = 'gripper right cos'
        self._gripper_right_cos_field_plot.plot(("x", "y"),
                                                name='gripper_right_cos',
                                                type="line",
                                                color="blue")
        range_self = self._gripper_right_cos_field_plot.plots[
            'gripper_right_cos'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # gripper left cos field
        x_axis = numpy.array(
            range(
                self.arch._gripper_left_cos_field.get_output_dimension_sizes()
                [0]))
        self._gripper_left_cos_field_plotdata = ArrayPlotData(
            x=x_axis, y=self.arch._gripper_left_cos_field.get_activation())
        self._gripper_left_cos_field_plot = Plot(
            self._gripper_left_cos_field_plotdata)
        self._gripper_left_cos_field_plot.title = 'gripper left cos'
        self._gripper_left_cos_field_plot.plot(("x", "y"),
                                               name='gripper_left_cos',
                                               type="line",
                                               color="blue")
        range_self = self._gripper_left_cos_field_plot.plots[
            'gripper_left_cos'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # find red color intention field
        x_axis = numpy.array(
            range(self.arch._find_color.get_intention_field().
                  get_output_dimension_sizes()[0]))
        self._find_color_intention_field_plotdata = ArrayPlotData(
            x=x_axis,
            y=self.arch._find_color.get_intention_field().get_activation())
        self._find_color_intention_field_plot = Plot(
            self._find_color_intention_field_plotdata)
        self._find_color_intention_field_plot.title = 'find color int'
        self._find_color_intention_field_plot.plot(("x", "y"),
                                                   name='find_color_int',
                                                   type="line",
                                                   color="blue")
        range_self = self._find_color_intention_field_plot.plots[
            'find_color_int'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # find green color intention field
        x_axis = numpy.array(
            range(self.arch._find_color_ee.get_intention_field().
                  get_output_dimension_sizes()[0]))
        self._find_color_ee_intention_field_plotdata = ArrayPlotData(
            x=x_axis,
            y=self.arch._find_color_ee.get_intention_field().get_activation())
        self._find_color_ee_intention_field_plot = Plot(
            self._find_color_ee_intention_field_plotdata)
        self._find_color_ee_intention_field_plot.title = 'find color ee int'
        self._find_color_ee_intention_field_plot.plot(("x", "y"),
                                                      name='find_color_ee_int',
                                                      type="line",
                                                      color="blue")
        range_self = self._find_color_ee_intention_field_plot.plots[
            'find_color_ee_int'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # camera
        self._camera_field_plotdata = ArrayPlotData()
        self._camera_field_plotdata.set_data(
            'imagedata',
            self.arch._camera_field.get_activation().max(2).transpose())
        self._camera_field_plot = Plot(self._camera_field_plotdata)
        self._camera_field_plot.title = 'camera'
        self._camera_field_plot.img_plot(
            'imagedata',
            name='camera_field',
            xbounds=(0, self.arch._camera_field_sizes[0] - 1),
            ybounds=(0, self.arch._camera_field_sizes[1] - 1),
            colormap=jet,
        )
        range_self = self._camera_field_plot.plots['camera_field'][
            0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # color space red
        self._color_space_field_plotdata = ArrayPlotData()
        self._color_space_field_plotdata.set_data(
            'imagedata',
            self.arch._color_space_field.get_activation().max(1).transpose())
        self._color_space_field_plot = Plot(self._color_space_field_plotdata)
        self._color_space_field_plot.title = 'color space'
        self._color_space_field_plot.img_plot(
            'imagedata',
            name='color_space_field',
            xbounds=(0, self.arch._color_space_field_sizes[0] - 1),
            ybounds=(0, self.arch._color_space_field_sizes[2] - 1),
            colormap=jet,
        )
        range_self = self._color_space_field_plot.plots['color_space_field'][
            0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # color space green
        self._color_space_ee_field_plotdata = ArrayPlotData()
        self._color_space_ee_field_plotdata.set_data(
            'imagedata',
            self.arch._color_space_ee_field.get_activation().max(
                2).transpose())
        self._color_space_ee_field_plot = Plot(
            self._color_space_ee_field_plotdata)
        self._color_space_ee_field_plot.title = 'color space ee'
        self._color_space_ee_field_plot.img_plot(
            'imagedata',
            name='color_space_ee_field',
            xbounds=(0, self.arch._color_space_ee_field_sizes[0] - 1),
            ybounds=(0, self.arch._color_space_ee_field_sizes[1] - 1),
            colormap=jet,
        )
        range_self = self._color_space_ee_field_plot.plots[
            'color_space_ee_field'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # spatial target
        self._spatial_target_field_plotdata = ArrayPlotData()
        self._spatial_target_field_plotdata.set_data(
            'imagedata',
            self.arch._spatial_target_field.get_activation().transpose())
        self._spatial_target_field_plot = Plot(
            self._spatial_target_field_plotdata)
        self._spatial_target_field_plot.title = 'spatial target'
        self._spatial_target_field_plot.img_plot(
            'imagedata',
            name='spatial_target_field',
            xbounds=(0, self.arch._spatial_target_field_sizes[0] - 1),
            ybounds=(0, self.arch._spatial_target_field_sizes[1] - 1),
            colormap=jet,
        )
        range_self = self._spatial_target_field_plot.plots[
            'spatial_target_field'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # move head intention
        self._move_head_intention_field_plotdata = ArrayPlotData()
        self._move_head_intention_field_plotdata.set_data(
            'imagedata',
            self.arch._move_head.get_intention_field().get_activation().
            transpose())
        self._move_head_intention_field_plot = Plot(
            self._move_head_intention_field_plotdata)
        self._move_head_intention_field_plot.title = 'move head int'
        self._move_head_intention_field_plot.img_plot(
            'imagedata',
            name='move_head_intention_field',
            xbounds=(0, self.arch._move_head_field_sizes[0] - 1),
            ybounds=(0, self.arch._move_head_field_sizes[1] - 1),
            colormap=jet,
        )
        range_self = self._move_head_intention_field_plot.plots[
            'move_head_intention_field'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # move head cos
        self._move_head_cos_field_plotdata = ArrayPlotData()
        self._move_head_cos_field_plotdata.set_data(
            'imagedata',
            self.arch._move_head.get_cos_field().get_activation().transpose())
        self._move_head_cos_field_plot = Plot(
            self._move_head_cos_field_plotdata)
        self._move_head_cos_field_plot.title = 'move head cos'
        self._move_head_cos_field_plot.img_plot(
            'imagedata',
            name='move_head_cos_field',
            xbounds=(0, self.arch._move_head_field_sizes[0] - 1),
            ybounds=(0, self.arch._move_head_field_sizes[1] - 1),
            colormap=jet,
        )
        range_self = self._move_head_cos_field_plot.plots[
            'move_head_cos_field'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # move right arm intention
        self._move_right_arm_intention_field_plotdata = ArrayPlotData()
        self._move_right_arm_intention_field_plotdata.set_data(
            'imagedata',
            self.arch._move_right_arm_intention_field.get_activation().
            transpose())
        self._move_right_arm_intention_field_plot = Plot(
            self._move_right_arm_intention_field_plotdata)
        self._move_right_arm_intention_field_plot.title = 'move right arm int'
        self._move_right_arm_intention_field_plot.img_plot(
            'imagedata',
            name='move_right_arm_intention_field',
            xbounds=(0, self.arch._move_arm_field_sizes[0] - 1),
            ybounds=(0, self.arch._move_arm_field_sizes[1] - 1),
            colormap=jet,
        )
        range_self = self._move_right_arm_intention_field_plot.plots[
            'move_right_arm_intention_field'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # move right arm cos
        self._move_right_arm_cos_field_plotdata = ArrayPlotData()
        self._move_right_arm_cos_field_plotdata.set_data(
            'imagedata',
            self.arch._move_arm_cos_field.get_activation().transpose())
        self._move_right_arm_cos_field_plot = Plot(
            self._move_right_arm_cos_field_plotdata)
        self._move_right_arm_cos_field_plot.title = 'move right arm cos'
        self._move_right_arm_cos_field_plot.img_plot(
            'imagedata',
            name='move_right_arm_cos_field',
            xbounds=(0, self.arch._move_arm_field_sizes[0] - 1),
            ybounds=(0, self.arch._move_arm_field_sizes[1] - 1),
            colormap=jet,
        )
        range_self = self._move_right_arm_cos_field_plot.plots[
            'move_right_arm_cos_field'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # visual servoing right intention
        self._visual_servoing_right_intention_field_plotdata = ArrayPlotData()
        self._visual_servoing_right_intention_field_plotdata.set_data(
            'imagedata',
            self.arch._visual_servoing_right.get_intention_field().
            get_activation().transpose())
        self._visual_servoing_right_intention_field_plot = Plot(
            self._visual_servoing_right_intention_field_plotdata)
        self._visual_servoing_right_intention_field_plot.title = 'visual servoing right int'
        self._visual_servoing_right_intention_field_plot.img_plot(
            'imagedata',
            name='visual_servoing_right_intention_field',
            xbounds=(0, self.arch._visual_servoing_field_sizes[0] - 1),
            ybounds=(0, self.arch._visual_servoing_field_sizes[1] - 1),
            colormap=jet,
        )
        range_self = self._visual_servoing_right_intention_field_plot.plots[
            'visual_servoing_right_intention_field'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        # visual servoing right cos
        self._visual_servoing_right_cos_field_plotdata = ArrayPlotData()
        self._visual_servoing_right_cos_field_plotdata.set_data(
            'imagedata',
            self.arch._visual_servoing_right.get_cos_field().get_activation().
            transpose())
        self._visual_servoing_right_cos_field_plot = Plot(
            self._visual_servoing_right_cos_field_plotdata)
        self._visual_servoing_right_cos_field_plot.title = 'visual servoing right cos'
        self._visual_servoing_right_cos_field_plot.img_plot(
            'imagedata',
            name='visual_servoing_right_cos_field',
            xbounds=(0, self.arch._visual_servoing_field_sizes[0] - 1),
            ybounds=(0, self.arch._visual_servoing_field_sizes[1] - 1),
            colormap=jet,
        )
        range_self = self._visual_servoing_right_cos_field_plot.plots[
            'visual_servoing_right_cos_field'][0].value_mapper.range
        range_self.high = color_range_max_value
        range_self.low = -color_range_max_value

        self._container = VPlotContainer()
        self._hcontainer_top = HPlotContainer()
        self._hcontainer_bottom = HPlotContainer()
        self._hcontainer_bottom.add(self._camera_field_plot)
        self._hcontainer_bottom.add(self._color_space_field_plot)
        self._hcontainer_bottom.add(self._spatial_target_field_plot)
        self._hcontainer_bottom.add(self._move_head_intention_field_plot)
        self._hcontainer_bottom.add(self._move_right_arm_intention_field_plot)
        #        self._hcontainer_bottom.add(self._find_color_intention_field_plot)
        #        self._hcontainer_bottom.add(self._gripper_right_intention_field_plot)

        self._hcontainer_top.add(self._color_space_ee_field_plot)
        self._hcontainer_top.add(
            self._visual_servoing_right_intention_field_plot)
        self._hcontainer_top.add(self._visual_servoing_right_cos_field_plot)
        self._hcontainer_top.add(self._move_head_cos_field_plot)
        self._hcontainer_top.add(self._move_right_arm_cos_field_plot)
        #        self._hcontainer_top.add(self._gripper_right_cos_field_plot)

        self._container.add(self._hcontainer_bottom)
        self._container.add(self._hcontainer_top)
class ColorPlot(BasePlot): 
    def __init__(self, parent, **kw):

        self._cbar_axis_format = kw.pop('cbar_axis_format', '')
        self._plotname = kw.pop('plotname', 'color_plot')
        
        # TODO: enables via kws
        
        BasePlot.__init__(self, parent, **kw)

        # defaults from cyclops config
        import cyclops
        if cyclops.config.has_key('plot_colors'):
            cmap = cyclops.config['plot_colors'].get('colorplot_cmap', 
                DEFAULT_CMAP)
            self.set_colormap_by_name(cmap)


    ### public methods

    def enable_colorbar_panning(self):
        self._colorbar.tools.append(PanTool(self._colorbar,
                                            constrain_direction='y',
                                            constrain=True))

    def enable_colorbar_zooming(self):
        zoom_overlay = ZoomTool(self._colorbar, axis='index', tool_mode='range',
                                always_on=True, drag_button='right')
        self._colorbar.overlays.append(zoom_overlay)
        
    def set_colormap_by_name(self, colormap):
        if hasattr(default_colormaps, colormap):
            self._colormap = getattr(default_colormaps, colormap)
            value_range = self.plot.color_mapper.range
            self.plot.color_mapper = self._colormap(value_range)
            self._colorbar.color_mapper = self._colormap(value_range)
            self.container.request_redraw()
            
    def set_colormap(self, colormap):
        self._colormap = colormap
        value_range = self.plot.color_mapper.range
        self.plot.color_mapper = self._colormap(value_range)
        self._container.request_redraw()

    def set_data(self, x, y, z, **kw):
        self.data.set_data('2d_data', z)
        if self.plot.plots.has_key(self._plotname):
            self.plot.delplot(self._plotname)

        # determine correct bounds
        xstep = (x.max() - x.min())/(len(x)-1)
        ystep = (y.max() - y.min())/(len(y)-1)
        x0, x1 = x.min() - xstep/2, x.max() + xstep/2
        y0, y1 = y.min() - ystep/2, y.max() + ystep/2
        
        self.plot.img_plot('2d_data',
                           name = self._plotname,
                           xbounds = (x0, x1),
                           ybounds = (y0, y1),
                           colormap = self._colormap, **kw)[0]

        # if we have a cursor, need to redraw
        if hasattr(self, 'crosshair'):
            #pos = self.crosshair.cursor_pos
            self.enable_crosshair('color_plot')
            #self.crosshair.cursor_pos = pos
        

    ### private methods

    def _create_window(self, **kw):
        self._colormap = default_colormaps.jet       
        
        self.data = ArrayPlotData()
        self.plot = Plot(self.data)

        x = linspace(-10, 10, 101)
        y = linspace(-10, 10, 101)
        z = zeros((101,101))

        self.set_data(x, y, z, **kw)
        
        # self.set_data(x,y,z)        
        self._create_colorbar()
        self.container = HPlotContainer(use_backbuffer=True)
        self.container.add(self.plot)
        self.container.add(self._colorbar)
        
        return Window(self, -1, component=self.container)

    def _create_colorbar(self):
        cmap = self.plot.color_mapper
        self._colorbar = ColorBar(index_mapper=LinearMapper(range=cmap.range),
                                  color_mapper=cmap,
                                  orientation='v',
                                  resizable='v',
                                  width=30,
                                  padding=30,
                                  axis_visible=False)
        self._colorbar.plot = self.plot
        self._colorbar.padding_top = self.plot.padding_top
        self._colorbar.padding_bottom = self.plot.padding_bottom

        # create an axis as well
        kwargs = {'orientation' : 'left',
                  'title' : 'z'}
        if self._cbar_axis_format != '' :
            f = lambda val: ('%s' % self._cbar_axis_format) % val
            kwargs['tick_label_formatter'] = f
        
        self.colorbar_axis = PlotAxis(self._colorbar, **kwargs)
        self._colorbar.underlays.append(self.colorbar_axis)
Exemple #40
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.  "
 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
    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
Exemple #43
0
    def get_plot(self):
        pixel_sizes = self.data_source.voxel_sizes
        shape = self.data.shape
        m = min(pixel_sizes)
        s = [int(d * sz / m) for d, sz in zip(shape, pixel_sizes)]
        if 1:  # else physical aspect ratio is enabled
            ss = max(s) / 4
            s = [max(s, ss) for s in s]
        plot_sizes = dict(xy=(s[2], s[1]),
                          xz=(s[2], s[0]),
                          zy=(s[0], s[1]),
                          zz=(s[0], s[0]))

        plots = GridContainer(shape=(2, 2),
                              spacing=(3, 3),
                              padding=50,
                              aspect_ratio=1)
        pxy = Plot(
            self.plotdata,
            padding=1,
            fixed_preferred_size=plot_sizes['xy'],
            x_axis=PlotAxis(orientation='top'),
        )
        pxz = Plot(
            self.plotdata,
            padding=1,
            fixed_preferred_size=plot_sizes['xz'],
        )
        pzy = Plot(
            self.plotdata,
            padding=1,
            fixed_preferred_size=plot_sizes['zy'],
            #orientation = 'v',  # cannot use 'v' because of img_plot assumes row-major ordering
            x_axis=PlotAxis(orientation='top'),
            y_axis=PlotAxis(orientation='right'),
        )
        pzz = Plot(self.plotdata,
                   padding=1,
                   fixed_preferred_size=plot_sizes['zz'])

        plots.add(pxy, pzy, pxz, pzz)

        self.plots = dict(
            xy=pxy.img_plot('xy', colormap=bone)[0],
            xz=pxz.img_plot('xz', colormap=bone)[0],
            zy=pzy.img_plot('zy', colormap=bone)[0],
            zz=pzz.img_plot('zz')[0],
            xyp=pxy.plot(('z_x', 'z_y'),
                         type='scatter',
                         color='orange',
                         marker='circle',
                         marker_size=3,
                         selection_marker_size=3,
                         selection_marker='circle')[0],
            xzp=pxz.plot(('y_x', 'y_z'),
                         type='scatter',
                         color='orange',
                         marker='circle',
                         marker_size=3,
                         selection_marker_size=3,
                         selection_marker='circle')[0],
            zyp=pzy.plot(('x_z', 'x_y'),
                         type='scatter',
                         color='orange',
                         marker='circle',
                         marker_size=3,
                         selection_marker_size=3,
                         selection_marker='circle')[0],
        )

        for p in ['xy', 'xz', 'zy']:
            self.plots[p].overlays.append(ZoomTool(self.plots[p]))
            self.plots[p].tools.append(
                PanTool(self.plots[p], drag_button='right'))

            imgtool = ImageInspectorTool(self.plots[p])
            self.plots[p].tools.append(imgtool)
            overlay = ImageInspectorOverlay(component=self.plots[p],
                                            bgcolor='white',
                                            image_inspector=imgtool)
            self.plots['zz'].overlays.append(overlay)

            self.plots[p + 'p'].tools.append(
                ScatterInspector(self.plots[p + 'p'], selection_mode='toggle'))

        self.plots['xyp'].index.on_trait_change(self._xyp_metadata_handler,
                                                'metadata_changed')
        self.plots['xzp'].index.on_trait_change(self._xzp_metadata_handler,
                                                'metadata_changed')
        self.plots['zyp'].index.on_trait_change(self._zyp_metadata_handler,
                                                'metadata_changed')

        plot = HPlotContainer()
        # todo: add colormaps
        plot.add(plots)
        return plot
    def __init__(self):
        #The delegates views don't work unless we caller the superclass __init__
        super(CursorTest, self).__init__()

        container = HPlotContainer(padding=0, spacing=20)
        self.plot = container
        #a subcontainer for the first plot.
        #I'm not sure why this is required. Without it, the layout doesn't work right.
        subcontainer = OverlayPlotContainer(padding=40)
        container.add(subcontainer)

        #make some data
        index = numpy.linspace(-10,10,512)
        value = numpy.sin(index)

        #create a LinePlot instance and add it to the subcontainer
        line = create_line_plot([index, value], add_grid=True,
                                add_axis=True, index_sort='ascending',
                                orientation = 'h')
        subcontainer.add(line)

        #here's our first cursor.
        csr = CursorTool(line,
                        drag_button="left",
                        color='blue')
        self.cursor1 = csr
        #and set it's initial position (in data-space units)
        csr.current_position = 0.0, 0.0

        #this is a rendered component so it goes in the overlays list
        line.overlays.append(csr)

        #some other standard tools
        line.tools.append(PanTool(line, drag_button="right"))
        line.overlays.append(ZoomTool(line))

        #make some 2D data for a colourmap plot
        xy_range = (-5, 5)
        x = numpy.linspace(xy_range[0], xy_range[1] ,100)
        y = numpy.linspace(xy_range[0], xy_range[1] ,100)
        X,Y = numpy.meshgrid(x, y)
        Z = numpy.sin(X)*numpy.arctan2(Y,X)

        #easiest way to get a CMapImagePlot is to use the Plot class
        ds = ArrayPlotData()
        ds.set_data('img', Z)

        img = Plot(ds, padding=40)
        cmapImgPlot = img.img_plot("img",
                     xbounds = xy_range,
                     ybounds = xy_range,
                     colormap = jet)[0]

        container.add(img)

        #now make another cursor
        csr2 = CursorTool(cmapImgPlot,
                           drag_button='left',
                           color='white',
                           line_width=2.0
                           )
        self.cursor2 = csr2

        csr2.current_position = 1.0, 1.5

        cmapImgPlot.overlays.append(csr2)

        #add some standard tools. Note, I'm assigning the PanTool to the
        #right mouse-button to avoid conflicting with the cursors
        cmapImgPlot.tools.append(PanTool(cmapImgPlot, drag_button="right"))
        cmapImgPlot.overlays.append(ZoomTool(cmapImgPlot))
def _create_plot_component():
    # Create a scalar field to colormap# Create a scalar field to colormap
    xbounds = (-2*pi, 2*pi, 600)
    ybounds = (-1.5*pi, 1.5*pi, 300)
    xs = linspace(*xbounds)
    ys = linspace(*ybounds)
    x, y = meshgrid(xs,ys)
    z = jn(2, x)*y*x

    # Create a plot data obect and give it this data
    pd = ArrayPlotData()
    pd.set_data("imagedata", z)

    # Create the plot
    plot = Plot(pd)
    plot.img_plot("imagedata",
                  name="my_plot",
                  xbounds=xbounds[:2],
                  ybounds=ybounds[:2],
                  colormap=jet)

    # Tweak some of the plot properties
    plot.title = "Selectable Image Plot"
    plot.padding = 50

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

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

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

    # create a range selection for the colorbar
    range_selection = RangeSelection(component=colorbar)
    colorbar.tools.append(range_selection)
    colorbar.overlays.append(RangeSelectionOverlay(component=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(my_plot)

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

    #my_plot.set_value_selection((-1.3, 6.9))

    return container
Exemple #46
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)
class PlotUI(HasTraits):

    #Traits view definitions:
    traits_view = View(
        Group(Item('container',
                   editor=ComponentEditor(size=(800,600)),
                   show_label=False)),
        buttons=NoButtons,
        resizable=True)

    plot_edit_view = View(
        Group(Item('num_levels'),
              Item('colormap')),
              buttons=["OK","Cancel"])


    num_levels = Int(15)
    colormap = Enum(color_map_name_dict.keys())

    #---------------------------------------------------------------------------
    # Private Traits
    #---------------------------------------------------------------------------

    _image_index = Instance(GridDataSource)
    _image_value = Instance(ImageData)

    _cmap = Trait(jet, Callable)

    #---------------------------------------------------------------------------
    # Public View interface
    #---------------------------------------------------------------------------

    def __init__(self, *args, **kwargs):
        super(PlotUI, self).__init__(*args, **kwargs)
        self.create_plot()

    def create_plot(self):

        # Create the mapper, etc
        self._image_index = GridDataSource(array([]),
                                          array([]),
                                          sort_order=("ascending","ascending"))
        image_index_range = DataRange2D(self._image_index)
        self._image_index.on_trait_change(self._metadata_changed,
                                          "metadata_changed")

        self._image_value = ImageData(data=array([]), value_depth=1)
        image_value_range = DataRange1D(self._image_value)



        # Create the contour plots
        self.polyplot = ContourPolyPlot(index=self._image_index,
                                        value=self._image_value,
                                        index_mapper=GridMapper(range=
                                            image_index_range),
                                        color_mapper=\
                                            self._cmap(image_value_range),
                                        levels=self.num_levels)

        self.lineplot = ContourLinePlot(index=self._image_index,
                                        value=self._image_value,
                                        index_mapper=GridMapper(range=
                                            self.polyplot.index_mapper.range),
                                        levels=self.num_levels)


        # Add a left axis to the plot
        left = PlotAxis(orientation='left',
                        title= "y",
                        mapper=self.polyplot.index_mapper._ymapper,
                        component=self.polyplot)
        self.polyplot.overlays.append(left)

        # Add a bottom axis to the plot
        bottom = PlotAxis(orientation='bottom',
                          title= "x",
                          mapper=self.polyplot.index_mapper._xmapper,
                          component=self.polyplot)
        self.polyplot.overlays.append(bottom)


        # Add some tools to the plot
        self.polyplot.tools.append(PanTool(self.polyplot,
                                           constrain_key="shift"))
        self.polyplot.overlays.append(ZoomTool(component=self.polyplot,
                                            tool_mode="box", always_on=False))
        self.polyplot.overlays.append(LineInspector(component=self.polyplot,
                                               axis='index_x',
                                               inspect_mode="indexed",
                                               write_metadata=True,
                                               is_listener=False,
                                               color="white"))
        self.polyplot.overlays.append(LineInspector(component=self.polyplot,
                                               axis='index_y',
                                               inspect_mode="indexed",
                                               write_metadata=True,
                                               color="white",
                                               is_listener=False))

        # Add these two plots to one container
        contour_container = OverlayPlotContainer(padding=20,
                                                 use_backbuffer=True,
                                                 unified_draw=True)
        contour_container.add(self.polyplot)
        contour_container.add(self.lineplot)


        # Create a colorbar
        cbar_index_mapper = LinearMapper(range=image_value_range)
        self.colorbar = ColorBar(index_mapper=cbar_index_mapper,
                                 plot=self.polyplot,
                                 padding_top=self.polyplot.padding_top,
                                 padding_bottom=self.polyplot.padding_bottom,
                                 padding_right=40,
                                 resizable='v',
                                 width=30)

        self.pd = ArrayPlotData(line_index = array([]),
                                line_value = array([]),
                                scatter_index = array([]),
                                scatter_value = array([]),
                                scatter_color = array([]))

        self.cross_plot = Plot(self.pd, resizable="h")
        self.cross_plot.height = 100
        self.cross_plot.padding = 20
        self.cross_plot.plot(("line_index", "line_value"),
                             line_style="dot")
        self.cross_plot.plot(("scatter_index","scatter_value","scatter_color"),
                             type="cmap_scatter",
                             name="dot",
                             color_mapper=self._cmap(image_value_range),
                             marker="circle",
                             marker_size=8)

        self.cross_plot.index_range = self.polyplot.index_range.x_range

        self.pd.set_data("line_index2", array([]))
        self.pd.set_data("line_value2", array([]))
        self.pd.set_data("scatter_index2", array([]))
        self.pd.set_data("scatter_value2", array([]))
        self.pd.set_data("scatter_color2", array([]))

        self.cross_plot2 = Plot(self.pd, width = 140, orientation="v", resizable="v", padding=20, padding_bottom=160)
        self.cross_plot2.plot(("line_index2", "line_value2"),
                             line_style="dot")
        self.cross_plot2.plot(("scatter_index2","scatter_value2","scatter_color2"),
                             type="cmap_scatter",
                             name="dot",
                             color_mapper=self._cmap(image_value_range),
                             marker="circle",
                             marker_size=8)

        self.cross_plot2.index_range = self.polyplot.index_range.y_range



        # Create a container and add components
        self.container = HPlotContainer(padding=40, fill_padding=True,
                                        bgcolor = "white", use_backbuffer=False)
        inner_cont = VPlotContainer(padding=0, use_backbuffer=True)
        inner_cont.add(self.cross_plot)
        inner_cont.add(contour_container)
        self.container.add(self.colorbar)
        self.container.add(inner_cont)
        self.container.add(self.cross_plot2)


    def update(self, model):
        self.minz = model.minz
        self.maxz = model.maxz
        self.colorbar.index_mapper.range.low = self.minz
        self.colorbar.index_mapper.range.high = self.maxz
        self._image_index.set_data(model.xs, model.ys)
        self._image_value.data = model.zs
        self.pd.set_data("line_index", model.xs)
        self.pd.set_data("line_index2", model.ys)
        self.container.invalidate_draw()
        self.container.request_redraw()


    #---------------------------------------------------------------------------
    # Event handlers
    #---------------------------------------------------------------------------

    def _metadata_changed(self, old, new):
        """ This function takes out a cross section from the image data, based
        on the line inspector selections, and updates the line and scatter
        plots."""

        self.cross_plot.value_range.low = self.minz
        self.cross_plot.value_range.high = self.maxz
        self.cross_plot2.value_range.low = self.minz
        self.cross_plot2.value_range.high = self.maxz
        if self._image_index.metadata.has_key("selections"):
            x_ndx, y_ndx = self._image_index.metadata["selections"]
            if y_ndx and x_ndx:
                self.pd.set_data("line_value",
                                 self._image_value.data[y_ndx,:])
                self.pd.set_data("line_value2",
                                 self._image_value.data[:,x_ndx])
                xdata, ydata = self._image_index.get_data()
                xdata, ydata = xdata.get_data(), ydata.get_data()
                self.pd.set_data("scatter_index", array([xdata[x_ndx]]))
                self.pd.set_data("scatter_index2", array([ydata[y_ndx]]))
                self.pd.set_data("scatter_value",
                    array([self._image_value.data[y_ndx, x_ndx]]))
                self.pd.set_data("scatter_value2",
                    array([self._image_value.data[y_ndx, x_ndx]]))
                self.pd.set_data("scatter_color",
                    array([self._image_value.data[y_ndx, x_ndx]]))
                self.pd.set_data("scatter_color2",
                    array([self._image_value.data[y_ndx, x_ndx]]))
        else:
            self.pd.set_data("scatter_value", array([]))
            self.pd.set_data("scatter_value2", array([]))
            self.pd.set_data("line_value", array([]))
            self.pd.set_data("line_value2", array([]))

    def _colormap_changed(self):
        self._cmap = color_map_name_dict[self.colormap]
        if hasattr(self, "polyplot"):
            value_range = self.polyplot.color_mapper.range
            self.polyplot.color_mapper = self._cmap(value_range)
            value_range = self.cross_plot.color_mapper.range
            self.cross_plot.color_mapper = self._cmap(value_range)
            # FIXME: change when we decide how best to update plots using
            # the shared colormap in plot object
            self.cross_plot.plots["dot"][0].color_mapper = self._cmap(value_range)
            self.cross_plot2.plots["dot"][0].color_mapper = self._cmap(value_range)
            self.container.request_redraw()

    def _num_levels_changed(self):
        if self.num_levels > 3:
            self.polyplot.levels = self.num_levels
            self.lineplot.levels = self.num_levels
Exemple #48
0
class ScatterPlot2(Template):

    #-- Template Traits --------------------------------------------------------

    # The title of the plot:
    title = TStr('Dual Scatter Plots')

    # The type of marker to use.  This is a mapped trait using strings as the
    # keys:
    marker = marker_trait(template='copy', event='update')

    # The pixel size of the marker (doesn't include the thickness of the
    # outline):
    marker_size = TRange(1, 5, 1, event='update')

    # The thickness, in pixels, of the outline to draw around the marker.  If
    # this is 0, no outline will be drawn.
    line_width = TRange(0.0, 5.0, 1.0)

    # The fill color of the marker:
    color = TColor('red', event='update')

    # The color of the outline to draw around the marker
    outline_color = TColor('black', event='update')

    # The amount of space between plots:
    spacing = TRange(0.0, 20.0, 0.0)

    # The contained scatter plots:
    scatter_plot_1 = TInstance(ScatterPlot, ())
    scatter_plot_2 = TInstance(ScatterPlot, ())

    #-- Derived Traits ---------------------------------------------------------

    plot = TDerived

    #-- Traits UI Views --------------------------------------------------------

    # The scatter plot view:
    template_view = View(VGroup(
        Item('title',
             show_label=False,
             style='readonly',
             editor=ThemedTextEditor(theme=Theme('@GBB', alignment='center'))),
        Item('plot',
             show_label=False,
             resizable=True,
             editor=EnableEditor(),
             item_theme=Theme('@GF5', margins=0))),
                         resizable=True)

    # The scatter plot options view:
    options_view = View(
        VGroup(
            VGroup(Label('Scatter Plot Options',
                         item_theme=Theme('@GBB', alignment='center')),
                   show_labels=False),
            VGroup(Item('title', editor=TextEditor()),
                   Item('marker'),
                   Item('marker_size', editor=ThemedSliderEditor()),
                   Item('line_width',
                        label='Line Width',
                        editor=ThemedSliderEditor()),
                   Item('spacing', editor=ThemedSliderEditor()),
                   Item('color', label='Fill Color'),
                   Item('outline_color', label='Outline Color'),
                   group_theme=Theme('@GF5', margins=(-5, -1)),
                   item_theme=Theme('@G0B', margins=0))))

    #-- ITemplate Interface Implementation -------------------------------------

    def activate_template(self):
        """ Converts all contained 'TDerived' objects to real objects using the
            template traits of the object. This method must be overridden in
            subclasses.
            
            Returns
            -------
            None
        """
        plots = [
            p for p in [self.scatter_plot_1.plot, self.scatter_plot_2.plot]
            if p is not None
        ]
        if len(plots) == 2:
            self.plot = HPlotContainer(spacing=self.spacing)
            self.plot.add(*plots)
        elif len(plots) == 1:
            self.plot = plots[0]

    #-- Default Values ---------------------------------------------------------

    def _scatter_plot_1_default(self):
        """ Returns the default value for the first scatter plot.
        """
        result = ScatterPlot()
        result.index.description = 'Shared Plot Index'
        result.value.description += ' 1'

        return result

    def _scatter_plot_2_default(self):
        """ Returns the default value for the second scatter plot.
        """
        result = ScatterPlot(index=self.scatter_plot_1.index)
        result.value.description += ' 2'
        result.value.optional = True

        return result

    #-- Trait Event Handlers ---------------------------------------------------

    def _update_changed(self, name, old, new):
        """ Handles a plot option being changed. 
        """
        setattr(self.scatter_plot_1, name, new)
        setattr(self.scatter_plot_2, name, new)
        self.plot = Undefined

    def _spacing_changed(self, spacing):
        """ Handles the spacing between plots being changed.
        """
        self.plot = Undefined
Exemple #49
0
    def __init__(self,xdata=None,ydata=None,weights=None,model=None,
                 include_models=None,exclude_models=None,fittype=None,**traits):
        """

        :param xdata: the first dimension of the data to be fit
        :type xdata: array-like
        :param ydata: the second dimension of the data to be fit
        :type ydata: array-like
        :param weights:
            The weights to apply to the data. Statistically interpreted as inverse
            errors (*not* inverse variance). May be any of the following forms:

            * None for equal weights
            * an array of points that must match `ydata`
            * a 2-sequence of arrays (xierr,yierr) such that xierr matches the
              `xdata` and yierr matches `ydata`
            * a function called as f(params) that returns an array of weights
              that match one of the above two conditions

        :param model: the initial model to use to fit this data
        :type model:
            None, string, or :class:`pymodelfit.core.FunctionModel1D`
            instance.
        :param include_models:
            With `exclude_models`, specifies which models should be available in
            the "new model" dialog (see `models.list_models` for syntax).
        :param exclude_models:
            With `include_models`, specifies which models should be available in
            the "new model" dialog (see `models.list_models` for syntax).
        :param fittype:
            The fitting technique for the initial fit (see
            :class:`pymodelfit.core.FunctionModel`).
        :type fittype: string

        kwargs are passed in as any additional traits to apply to the
        application.

        """

        self.modelpanel = View(Label('empty'),kind='subpanel',title='model editor')

        self.tmodel = TraitedModel(model)

        if model is not None and fittype is not None:
            self.tmodel.model.fittype = fittype

        if xdata is None or ydata is None:
            if not hasattr(self.tmodel.model,'data') or self.tmodel.model.data is None:
                raise ValueError('data not provided and no data in model')
            if xdata is None:
                xdata = self.tmodel.model.data[0]
            if ydata is None:
                ydata = self.tmodel.model.data[1]
            if weights is None:
                weights = self.tmodel.model.data[2]

        self.on_trait_change(self._paramsChanged,'tmodel.paramchange')

        self.modelselector = NewModelSelector(include_models,exclude_models)

        self.data = [xdata,ydata]


        if weights is None:
            self.weights = np.ones_like(xdata)
            self.weighttype = 'equal'
        else:
            self.weights = np.array(weights,copy=True)
            self.savews = True

        weights1d = self.weights
        while len(weights1d.shape)>1:
            weights1d = np.sum(weights1d**2,axis=0)

        pd = ArrayPlotData(xdata=self.data[0],ydata=self.data[1],weights=weights1d)
        self.plot = plot = Plot(pd,resizable='hv')

        self.scatter = plot.plot(('xdata','ydata','weights'),name='data',
                         color_mapper=_cmapblack if self.weights0rem else _cmap,
                         type='cmap_scatter', marker='circle')[0]

        self.errorplots = None

        if not isinstance(model,FunctionModel1D):
            self.fitmodel = True

        self.updatemodelplot = False #force plot update - generates xmod and ymod
        plot.plot(('xmod','ymod'),name='model',type='line',line_style='dash',color='black',line_width=2)
        del plot.x_mapper.range.sources[-1]  #remove the line plot from the x_mapper source so only the data is tied to the scaling

        self.on_trait_change(self._rangeChanged,'plot.index_mapper.range.updated')

        self.pantool = PanTool(plot,drag_button='left')
        plot.tools.append(self.pantool)
        self.zoomtool = ZoomTool(plot)
        self.zoomtool.prev_state_key = KeySpec('a')
        self.zoomtool.next_state_key = KeySpec('s')
        plot.overlays.append(self.zoomtool)

        self.scattertool = None
        self.scatter.overlays.append(ScatterInspectorOverlay(self.scatter,
                        hover_color = "black",
                        selection_color="black",
                        selection_outline_color="red",
                        selection_line_width=2))


        self.colorbar = colorbar = ColorBar(index_mapper=LinearMapper(range=plot.color_mapper.range),
                                            color_mapper=plot.color_mapper.range,
                                            plot=plot,
                                            orientation='v',
                                            resizable='v',
                                            width = 30,
                                            padding = 5)
        colorbar.padding_top = plot.padding_top
        colorbar.padding_bottom = plot.padding_bottom
        colorbar._axis.title = 'Weights'

        self.plotcontainer = container = HPlotContainer(use_backbuffer=True)
        container.add(plot)
        container.add(colorbar)

        super(FitGui,self).__init__(**traits)

        self.on_trait_change(self._scale_change,'plot.value_scale,plot.index_scale')

        if weights is not None and len(weights)==2:
            self.weightsChanged() #update error bars