def _plot_default(self):
    plot = Plot(self.plotdata)
    plot.title = "Simplex on the Rosenbrock function"

    plot.img_plot("background",
                  name="background",
                  xbounds=(0,1.5),
                  ybounds=(0,1.5),
                  colormap=jet(DataRange1D(low=0,high=100)),
                  )

    plot.plot(("values_x", "values_y"), type="scatter", color="red")

    background = plot.plots["background"][0]

    colormap = background.color_mapper
    colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                        color_mapper=colormap,
                        plot=background,
                        orientation='v',
                        resizable='v',
                        width=30,
                        padding=20)
    colorbar.padding_top = plot.padding_top
    colorbar.padding_bottom = plot.padding_bottom

    container = HPlotContainer(use_backbuffer = True)
    container.add(plot)
    container.add(colorbar)
    container.bgcolor = "lightgray"
    return container
Beispiel #2
0
    def __init__(self, signal_instance):
        super(TemplatePicker, self).__init__()
        try:
            import cv
        except:
            try:
                import cv2.cv as 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.titles=[os.path.splitext(self.sig.mapped_parameters.title)[0]]
        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.img_idx,self.top:self.top+self.tmp_size,self.left:self.left+self.tmp_size])
        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
Beispiel #3
0
 def update_labeled_image_data(self):
     im = self.image_data.arrays.get('im')[:, :, 0]
     bw = get_cleared_binary_image(im)
     bx, by = get_region_bounds(bw)
     apd = ArrayPlotData(im=bw)
     for i in range(len(bx)):
         minc, maxc = bx[i]
         minr, maxr = by[i]
         key = "bb" + str(i)
         apd.update({key + 'topx': (minc, maxc),
                     key + 'topy': (maxr, maxr),
                     key + 'botx': (minc, maxc),
                     key + 'boty': (minr, minr),
                     key + 'leftx': (minc, minc),
                     key + 'lefty': (minr, maxr),
                     key + 'rightx': (maxc, maxc),
                     key + 'righty': (minr, maxr)})
     plot = Plot(apd)
     plot.img_plot('im', colormap=gray, origin='bottom left')
     for i in range((len(apd.arrays) - 1) / 8):
         key = 'bb' + str(i)
         plot.plot((key + 'topx', key + 'topy'), color='green',
                   line_width=3)
         plot.plot((key + 'botx', key + 'boty'), color='green',
                   line_width=3)
         plot.plot((key + 'leftx', key + 'lefty'), color='green',
                   line_width=3)
         plot.plot((key + 'rightx', key + 'righty'), color='green',
                   line_width=3)
     self.labeled_image_plot = plot
    def _plot_default(self):
        # Create a GridContainer to hold all of our plots: 2 rows, 4 columns:
        container = GridContainer(fill_padding=True,
                                  bgcolor="lightgray", use_backbuffer=True,
                                  shape=(2, 4))

        arrangements = [('top left', 'h'),
                        ('top right', 'h'),
                        ('top left', 'v'),
                        ('top right', 'v'),
                        ('bottom left', 'h'),
                        ('bottom right', 'h'),
                        ('bottom left', 'v'),
                        ('bottom right', 'v')]
        orientation_name = {'h': 'horizontal', 'v': 'vertical'}

        pd = ArrayPlotData(image=lena())
        # Plot some bessel functions and add the plots to our container
        for origin, orientation in arrangements:
            plot = Plot(pd, default_origin=origin, orientation=orientation)
            plot.img_plot('image')

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

            title = '{0}, {1}'
            plot.title = title.format(orientation_name[orientation],
                                      origin.replace(' ', '-'))

            # Add to the grid container
            container.add(plot)

        return container
Beispiel #5
0
    def plotImage(self, image, title, plot):
        '''plot one image
        image:     2d ndarray or ssp matrix
        title:     string, plot title
        plot:      plot instance to be update, if None, a plot instance will be created

        return:    plot instance'''
        if plot == None:
            pd = ArrayPlotData()
            pd.set_data('imagedata', image)
            plot = Plot(pd, default_origin = "bottom left")
            plot.title = title
            plot.bgcolor = 'white'
            if not title == 'Total Intensity':
                plot.x_axis.visible = False
                plot.y_axis.visible = False
                imgPlot = plot.img_plot("imagedata", colormap=jet, name='image')[0]
            # TODO: mess with color maps on else block    
            else:
                imgPlot = plot.img_plot("imagedata", colormap=jet, name='image')[0]

            self._appendTools(imgPlot, title)
        else:
            plot.data.set_data('imagedata', image)
            plot.title = title
        plot.aspect_ratio = float(image.shape[1]) / image.shape[0]
        plot.invalidate_draw()
        return plot
Beispiel #6
0
    def _hist2d_default(self):
        plot = Plot(self.hist2d_data, padding=(20, 0, 0, 40))
        plot.img_plot("H", xbounds=self.xedges, ybounds=self.yedges, colormap=jet)
        plot.index_axis.title = "Voxel dist."
        plot.value_axis.title = "Root Square Error"

        # Create a colorbar
        colormap = plot.color_mapper
        colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                            color_mapper=colormap,
                            plot=plot,
                            orientation='v',
                            resizable='v',
                            width=20,
                            padding=(20, 30, 0, 0))
        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, padding=0)
        container.add(colorbar)
        container.add(plot)
        container.bgcolor = "lightgray"

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

    obj.spectrum_plot = Plot(obj.spectrum_data)
    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
Beispiel #8
0
    def _create_window(self):
        # Create the model
        #try:
        #    self.model = model = BrainModel()
        #    cmap = bone
        #except SystemExit:
        #    sys.exit()
        #except:
        #    print "Unable to load BrainModel, using generated data cube."
        self.model = model = Model()
        cmap = jet
        self._update_model(cmap)

        datacube = self.colorcube

        # Create the plot
        self.plotdata = ArrayPlotData()
        self._update_images()

        # Center Plot
        centerplot = Plot(self.plotdata, padding=0)
        imgplot = centerplot.img_plot("xy",
                                xbounds=(model.xs[0], model.xs[-1]),
                                ybounds=(model.ys[0], model.ys[-1]),
                                colormap=cmap)[0]
        self._add_plot_tools(imgplot, "xy")
        self.center = imgplot

        # Right Plot
        rightplot = Plot(self.plotdata, width=150, resizable="v", padding=0)
        rightplot.value_range = centerplot.value_range
        imgplot = rightplot.img_plot("yz",
                                xbounds=(model.zs[0], model.zs[-1]),
                                ybounds=(model.ys[0], model.ys[-1]),
                                colormap=cmap)[0]
        self._add_plot_tools(imgplot, "yz")
        self.right = imgplot

        # Bottom Plot
        bottomplot = Plot(self.plotdata, height=150, resizable="h", padding=0)
        bottomplot.index_range = centerplot.index_range
        imgplot = bottomplot.img_plot("xz",
                                xbounds=(model.xs[0], model.xs[-1]),
                                ybounds=(model.zs[0], model.zs[-1]),
                                colormap=cmap)[0]
        self._add_plot_tools(imgplot, "xz")
        self.bottom = imgplot

        # Create Container and add all Plots
        container = GridPlotContainer(padding=20, fill_padding=True,
                                      bgcolor="white", use_backbuffer=True,
                                      shape=(2,2), spacing=(12,12))
        container.add(centerplot)
        container.add(rightplot)
        container.add(bottomplot)

        self.container = container
        return Window(self, -1, component=container)
 def __init__(self, x, all_agents):
     
     self.x = x
     self.all_agents = all_agents
     self.plotdata = ArrayPlotData(imagedata=self.x)
     plot = Plot(self.plotdata)
     plot.img_plot('imagedata')
     self.plot = plot
     self.sim_count = 0
 def _plot_default(self):
     x = np.linspace(0, 10, 51)
     y = np.linspace(0, 5, 51)
     X, Y = np.meshgrid(x, y)
     z = np.exp(-(X**2 + Y**2) / 100)
     plotdata = ArrayPlotData(zdata=z[:-1, :-1])
     plot = Plot(plotdata)
     plot.img_plot("zdata", xbounds=x, ybounds=y, colormap=jet)
     return plot
Beispiel #11
0
 def _image_plot_default(self):
     '''
     Default chaco plot object for the image plot.
     '''
     
     self.img_plotdata = ArrayPlotData(imagedata=self.table)
     p = Plot(self.img_plotdata)
     p.img_plot('imagedata')
     return p
 def _plot_default(self):
     plot = Plot(self.plot_data)
     plot.x_axis = None
     plot.y_axis = None
     plot.padding = 0
     self.tcm = TransformColorMapper.from_color_map(gray)
     self.tcm.unit_func = self.unit_map.function
     self.unit_map.on_trait_change(self.map_changed, 'function')
     plot.img_plot('image', colormap=self.tcm)
     return plot
Beispiel #13
0
 def _plot_default(self):
     julia = self.model.julia
     apd = ArrayPlotData(julia=julia[:-1,:-1])
     grid = np.linspace(-2, 2, self.model.resolution-1)
     X, Y = np.meshgrid(grid, grid)
     plot = Plot(apd)
     plot.aspect_ratio = 1.0
     plot.img_plot("julia", xbounds=X, ybounds=Y,
                   colormap=hot, interpolation='nearest')
     return plot
Beispiel #14
0
 def _julia_plot_default(self):
     img = self.julia_img
     plot_data = ArrayPlotData(img=img)
     julia_plot = Plot(plot_data)
     julia_plot.img_plot(
         "img",
         xbounds=self.julia_bounds_x,
         ybounds=self.julia_bounds_y,
         colormap=self.colormap,
     )
     return julia_plot
Beispiel #15
0
 def _image_default(self):
     container = VPlotContainer()
     soln_plot = Plot(self.soln_data)
     soln_plot.plot(("x", "y"), type='bar', fill_color='green',
                    bar_width=0.8)
     container.add(soln_plot)
     galaxy_plot = Plot(self.image_data)
     galaxy_plot.img_plot('im')
     container.add(galaxy_plot)
     container.add(self.cropped_image)
     return container
Beispiel #16
0
    def __init__(self):
        super(ImagePlot, self).__init__()

        x = linspace(0, 10, 50)
        y = linspace(0, 5, 50)
        xgrid, ygrid = meshgrid(x, y)
        z = exp(-1 * (xgrid * xgrid + ygrid * ygrid) / 100.0)
        plotdata = ArrayPlotData(imagedata=z)

        plot = Plot(plotdata)
        plot.img_plot("imagedata", colormap=jet)

        self.plot = plot
Beispiel #17
0
 def _plot_default(self):
     data = self.data < self.limit
     pd = self.pd = ArrayPlotData(imagedata=data,orig=self.data)
     plot1 = Plot(pd, default_origin='top left')
     plot2 = Plot(pd, default_origin='top left')
     img_plot1 = plot1.img_plot("imagedata",colormap=gray,padding=0)[0]
     img_plot2 = plot2.img_plot("orig",colormap=gray,padding=0)[0]
     container = HPlotContainer(plot1,plot2)
     container.spacing=0
     plot1.padding_right=0
     plot2.padding_left=0
     plot2.y_axis.orientation= 'right'
     return container
Beispiel #18
0
 def _plot_default(self):
     # Create the data and the PlotData object.  For a 2D plot, we need to
     # create a grid of X and Y points using meshgrid.
     x = linspace(0, 10, 51)
     y = linspace(0, 5, 51)
     X, Y = meshgrid(x, y)
     z = exp(-(X**2 + Y**2) / 100)
     plotdata = ArrayPlotData(zdata=z[:-1, :-1])
     # Create a Plot and associate it with the PlotData.
     plot = Plot(plotdata)
     # Create a line plot in the Plot
     plot.img_plot("zdata", xbounds=x, ybounds=y, colormap=jet)
     return plot
Beispiel #19
0
 def __init__(self):
     # Create the data and the PlotData object.  For a 2D plot, we need to
     # take the row of X points and Y points and create a grid from them
     # using meshgrid().
     x = linspace(0, 10, 50)
     y = linspace(0, 5, 50)
     xgrid, ygrid = meshgrid(x, y)
     z = exp(-(xgrid*xgrid + ygrid*ygrid) / 100)
     plotdata = ArrayPlotData(imagedata = z)
     # Create a Plot and associate it with the PlotData
     plot = Plot(plotdata)
     # Create an image plot in the Plot
     plot.img_plot("imagedata", colormap=jet)
     self.plot = plot
 def _main_plot_default(self):
     p = Plot(self.plot_data, default_origin='top left')
     p.padding = 0
     self.original_plot = p.img_plot('original_image', colormap=bone,
                                     alpha=self.original_alpha,
                                     bgcolor=self.background_color_)[0]
     self.canny_plot = p.img_plot('canny_plot_image',
                                  alpha=self.canny_alpha)[0]
     p.x_axis = None
     p.y_axis = None
     self.segments_overlay = SegmentsOverlay(component=self.canny_plot,
                                             image_size=self.image.canny_image.shape)
     p.overlays.append(self.segments_overlay)
     return p
Beispiel #21
0
 def _labeled_image_plot_default(self):
     plot = Plot(self.labeled_image_data)
     plot.img_plot('im', colormap=gray, origin='bottom left')
     for i in range((len(self.labeled_image_data.arrays) - 1) / 8):
         key = 'bb' + str(i)
         plot.plot((key + 'topx', key + 'topy'), color='green',
                   line_width=3)
         plot.plot((key + 'botx', key + 'boty'), color='green',
                   line_width=3)
         plot.plot((key + 'leftx', key + 'lefty'), color='green',
                   line_width=3)
         plot.plot((key + 'rightx', key + 'righty'), color='green',
                   line_width=3)
     return plot
Beispiel #22
0
    def _create_window(self):
        self.model = model = Model()
        self.cmap = jet
        #self._update_model(self.cmap)

        # Create the plot
        self.plotdata = ArrayPlotData()
        self._update_images()

        # Center Plot
        centerplot = Plot(self.plotdata, padding=0)
        imgplot = centerplot.img_plot("xy",
                                xbounds=(model.min_x, model.max_x),
                                ybounds=(model.min_y, model.max_y),
                                colormap=self.cmap)[0]
        self._add_plot_tools(imgplot, "xy")
        self.center = imgplot

        # Right Plot
        rightplot = Plot(self.plotdata, width=150, resizable="v", padding=0)
        rightplot.value_range = centerplot.value_range
        imgplot = rightplot.img_plot("yz",
                                xbounds=(model.min_z, model.max_z),
                                ybounds=(model.min_y, model.max_y),
                                colormap=self.cmap)[0]
        self._add_plot_tools(imgplot, "yz")
        self.right = imgplot

        # Bottom Plot.  Seismic plot axis1 (depth) down into earth 
        #               i.e. z is depth, to altitude.
        bottomplot = Plot(self.plotdata, height=150, resizable="h", 
                          padding=0, origin="top left")
        bottomplot.index_range = centerplot.index_range
        imgplot = bottomplot.img_plot("xz",
                                xbounds=(model.min_x, model.max_x),
                                ybounds=(model.min_z, model.max_z),
                                colormap=self.cmap)[0]
        self._add_plot_tools(imgplot, "xz")
        self.bottom = imgplot

        # Create Container and add all Plots
        container = GridPlotContainer(padding=20, fill_padding=True,
                                      bgcolor="white", use_backbuffer=True,
                                      shape=(2,2), spacing=(20,20))
        container.add(centerplot)
        container.add(rightplot)
        container.add(bottomplot)

        self.container = container
        return Window(self, -1, component=container)
Beispiel #23
0
class BaseViewer(HasTraits):
    reconstruction = Instance(Component)
    image = Array
    result = Array
    save_file = File(exists=False, auto_set=False, enter_set=True)
    save_button = Button('Save Result as .npy')

    def __init__(self, **kwargs):
        HasTraits.__init__(self, **kwargs)

    def _reconstruction_default(self):
        self.plot_data = ArrayPlotData(original=self.image,
                                       reconstruction=self.result)

        rows, cols = self.image.shape[:2]
        aspect = cols/float(rows)

        old = Plot(self.plot_data)
        old.img_plot('original', colormap=gray, origin='top left')
        old.title = 'Old'
        old.aspect_ratio = aspect

        self.new = Plot(self.plot_data)
        self.new.img_plot('reconstruction', colormap=gray, origin='top left')
        self.new.title = 'New'
        self.new.aspect_ratio = aspect

        container = HPlotContainer(bgcolor='none')
        container.add(old)
        container.add(self.new)

        return container

    def update_plot(self):
        self.plot_data.set_data('reconstruction', self.result)
        self.new.request_redraw()

    def _save_button_changed(self):
        try:
            np.save(self.save_file, self.result)
        except IOError as e:
            message('Could not save file: %s' % str(e))

        try:
            f = open(self.save_file + '.txt', 'w')
            f.write(str(self))
            f.close()
        except IOError:
            message('Could not save file: %s' % str(e))
    def _plot_default(self):
        # Create a scalar field to colormap
        xs = linspace(0, 10, 600)
        ys = linspace(0, 5, 600)
        x, y = meshgrid(xs, ys)
        z = exp(-(x ** 2 + y ** 2) / 100)

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

        # Create the plot
        plot = Plot(pd)
        plot.img_plot("imagedata", colormap=jet)
        return plot
Beispiel #25
0
    def _composite_plot_default(self):

        line_plot = Plot(self.plotdata)
        line_plot.plot(('x', 'y'), type='line', color='blue')

        img_plot = Plot(self.plotdata)
        img_plot.img_plot("zdata",
                          xbounds='x_range',
                          ybounds='y_range',
                          colormap=jet)

        cp = VPlotContainer()
        cp.add(img_plot)
        cp.add(line_plot)
        return cp
Beispiel #26
0
def _create_plot_component():
    # Create a scalar field to colormap
    xs = linspace(0, 10, 600)
    ys = linspace(0, 5, 600)
    x, y = meshgrid(xs,ys)
    z = exp(-(x**2+y**2)/100)

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

    # Create the plot
    plot = Plot(pd)
    img_plot = plot.img_plot("imagedata",
                             xbounds=(0, 10),
                             ybounds=(0, 5),
                             colormap=jet)[0]

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

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot))
    zoom = ZoomTool(component=img_plot, tool_mode="box", always_on=False)
    img_plot.overlays.append(zoom)
    return plot
Beispiel #27
0
def _create_plot_component():

    # Create some RGBA image data
    image = zeros((200,400,4), dtype=uint8)
    image[:,0:40,0] += 255     # Vertical red stripe
    image[0:25,:,1] += 255     # Horizontal green stripe; also yellow square
    image[-80:,-160:,2] += 255 # Blue square
    image[:,:,3] = 255

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

    # Create the plot
    plot = Plot(pd, default_origin="top left")
    plot.x_axis.orientation = "top"
    img_plot = plot.img_plot("imagedata")[0]

    # Tweak some of the plot properties
    plot.bgcolor = "white"

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

    imgtool = ImageInspectorTool(img_plot)
    img_plot.tools.append(imgtool)
    plot.overlays.append(ImageInspectorOverlay(component=img_plot,
                                               image_inspector=imgtool))
    return plot
Beispiel #28
0
def _create_plot_component():  # 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 = sin(x) * y

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

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

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

    lasso_selection = LassoSelection(component=img_plot)
    lasso_selection.on_trait_change(lasso_updated, "disjoint_selections")
    lasso_overlay = LassoOverlay(lasso_selection=lasso_selection, component=img_plot)
    img_plot.tools.append(lasso_selection)
    img_plot.overlays.append(lasso_overlay)
    return plot
Beispiel #29
0
def _create_plot_component():# 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 = sin(x)*y

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

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

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

    # 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)
    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)
    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))
Beispiel #31
0
def _create_plot_component():

    # Create a scalar field to colormap
    x_extents = (-2 * pi, 2 * pi)
    y_extents = (-1.5 * pi, 1.5 * pi)
    xs = linspace(-2 * pi, 2 * pi, 200)
    ys = linspace(-1.5 * pi, 1.5 * pi, 100)
    x, y = meshgrid(xs, ys)
    zs = sin(log(abs((x+1)**4)+0.05))*cos(y)*1.1*(-y) + \
            sin(((x+1)**2 + y**2)/4)

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

    # Create the left plot, a colormap and simple contours
    lplot = Plot(pd)
    lplot.img_plot("imagedata",
                   name="cm_plot",
                   xbounds=x_extents,
                   ybounds=y_extents,
                   colormap=gmt_drywet)
    lplot.contour_plot("imagedata",
                       type="line",
                       xbounds=x_extents,
                       ybounds=y_extents)

    # Tweak some of the plot properties
    lplot.title = "Colormap and contours"
    lplot.padding = 20
    lplot.bg_color = "white"
    lplot.fill_padding = True

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

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

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

    # Create the left plot, contours of varying color and width
    rplot = Plot(pd, range2d=lplot.range2d)
    rplot.contour_plot("imagedata",
                       type="line",
                       xbounds=x_extents,
                       ybounds=y_extents,
                       bgcolor="black",
                       levels=15,
                       styles="solid",
                       widths=list(linspace(4.0, 0.1, 15)),
                       colors=gmt_drywet)

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

    # Tweak some of the plot properties
    rplot.title = "Varying contour lines"
    rplot.padding = 20
    rplot.bg_color = "white"
    rplot.fill_padding = True

    # Create a container and add our plots
    container = HPlotContainer(padding=40,
                               fill_padding=True,
                               bgcolor="white",
                               use_backbuffer=True)
    container.add(colorbar)
    container.add(lplot)
    container.add(rplot)
    return container
class ConnectionMatrixViewer(HasTraits):

    tplot = Instance(Plot)
    plot = Instance(Component)
    custtool = Instance(CustomTool)
    colorbar = Instance(ColorBar)

    fro = Any
    to = Any
    data = None
    val = Float
    nodelabels = Any

    traits_view = View(
        Group(Item('plot',
                   editor=ComponentEditor(size=(800, 600)),
                   show_label=False),
              HGroup(
                  Item('fro', label="From", style='readonly', springy=True),
                  Item('to', label="To", style='readonly', springy=True),
                  Item('val', label="Value", style='readonly', springy=True),
              ),
              orientation="vertical"),
        Item('data_name', label="Edge key"),
        # handler=CustomHandler(),
        resizable=True,
        title="Connection Matrix Viewer")

    def __init__(self, nodelabels, matdict, **traits):
        """ Starts a matrix inspector
        
        Parameters
        ----------
        nodelables : list
            List of strings of labels for the rows of the matrix
        matdict : dictionary
            Keys are the edge type and values are NxN Numpy arrays """
        super(HasTraits, self).__init__(**traits)

        self.add_trait('data_name', Enum(matdict.keys()))

        self.data_name = matdict.keys()[0]
        self.data = matdict
        self.nodelables = nodelabels
        self.plot = self._create_plot_component()

        # set trait notification on customtool
        self.custtool.on_trait_change(self._update_fields, "xval")
        self.custtool.on_trait_change(self._update_fields, "yval")

    def _data_name_changed(self, old, new):
        self.pd.set_data("imagedata", self.data[self.data_name])
        #self.my_plot.set_value_selection((0, 2))
        self.tplot.title = "Connection Matrix for %s" % self.data_name

    def _update_fields(self):

        # map mouse location to array index
        frotmp = int(round(self.custtool.yval) - 1)
        totmp = int(round(self.custtool.xval) - 1)

        # check if within range
        sh = self.data[self.data_name].shape
        # assume matrix whose shape is (# of rows, # of columns)
        if frotmp >= 0 and frotmp < sh[0] and totmp >= 0 and totmp < sh[1]:
            row = " (index: %i" % (frotmp + 1) + ")"
            col = " (index: %i" % (totmp + 1) + ")"
            self.fro = " " + str(self.nodelables[frotmp]) + row
            self.to = " " + str(self.nodelables[totmp]) + col
            self.val = self.data[self.data_name][frotmp, totmp]

    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])

        # find dimensions
        xdim = self.data[self.data_name].shape[1]
        ydim = self.data[self.data_name].shape[0]

        # 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.5, xdim + 0.5),
                            ybounds=(0.5, ydim + 0.5),
                            colormap=jet)

        # Tweak some of the plot properties
        self.tplot.title = "Connection Matrix for %s" % self.data_name
        self.tplot.padding = 80

        # 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
Beispiel #33
0
    def __init__(self):

        super(ContainerExample, self).__init__()

        filenames = []
        for parameter in sys.argv[1:]:
            print("processing parameter", parameter)
            if parameter.find("=") == -1:
                print("no = in parameter", parameter, "must be a file name")
                filenames.append(parameter)
        if len(filenames) < 1:
            print("just to help me test, if there are no files in the list, ")
            print("I will append the file foldplot1.rsf")
            filenames.append('foldplot1.rsf')

        self.seis_data_0 = SeisData(filenames[0])
        self.cmap = jet

        self.displayParameters = DisplayParameters()

        self.slice_y = self.displayParameters.slice_y
        print("self.slice_y=", self.slice_y)
        self.arrayPlotData = ArrayPlotData()
        self._update_images()
        bottomplot = Plot(self.arrayPlotData, padding=0, origin="top left")
        imgplot = bottomplot.img_plot("xz",
                                      xbounds=(self.seis_data_0.axis_start[0],
                                               self.seis_data_0.axis_end[0]),
                                      ybounds=(self.seis_data_0.axis_start[2],
                                               self.seis_data_0.axis_end[2]),
                                      colormap=self.cmap)[0]
        self.bottom = imgplot

        print("x range=", self.seis_data_0.axis_start[0],
              self.seis_data_0.axis_end[0])
        print("z range=", self.seis_data_0.axis_start[2],
              self.seis_data_0.axis_end[2])
        #print "colormap.shape=',colormap.shape)
        x = linspace(-14, 14, 100)

        y = x**3
        plotdata = ArrayPlotData(x=x, y=y)

        scatter = Plot(plotdata, origin="top left")
        scatter.plot(("x", "y"), type="scatter", color='blue')
        scatter.title = "x**3"
        self.scatter = scatter
        #scatter.origin="top left"
        print("make container")
        container = HPlotContainer(bottomplot)
        print("container.add")
        container.add(scatter)
        #container.spacing = 0

        #        scatter.padding_right = 0

        #        line.padding_left = 0
        #        line.y_axis.orientation = "right"

        self.plot = bottomplot  #container
        # kls karl !! When I change plot = Instance(Plot) and this line to
        # self.plot=container I get no img_plotplot to
        #        self.plot.tools.append(CustomTool(self.plot))

        self.displayParameters = DisplayParameters()

        imgplot.tools.append(CustomTool(self.plot))
Beispiel #34
0
    def create_hplot(self, key=None, mini=False):
        if mini:
            hpc = HPlotContainer(bgcolor='darkgrey',
                                 height=MINI_HEIGHT,
                                 resizable='h',
                                 padding=0)
        else:
            hpc = HPlotContainer(bgcolor='lightgrey',
                                 padding=HPLOT_PADDING,
                                 resizable='hv')

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

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

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

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

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

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

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

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

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

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

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

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

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

        return hpc
 def _plot_default(self):
     plot = Plot(datasources={'image': self.plot_data})
     self.img_plot = plot.img_plot('image', origin='top left')[0]
     return plot
Beispiel #36
0
class TwoDimensionalPanel(Handler):
    images = Dict # Str -> Tuple(imgd, affine, tkr_affine)

    #original_current_image = Any #np.ndarray XxYxZ
    current_image = Any # np.ndarray XxYxZ
    #original_image is not allowed to be altered by thresholding.
    #current_image may be reset by copying original whenever threshold change
    current_affine = Any
    current_tkr_affine = Any

    xy_plane = Instance(Plot)
    xz_plane = Instance(Plot)
    yz_plane = Instance(Plot)
    
    pins = Dict # Str -> (Str -> 3-Tuple)
    pin_tolerance = DelegatesTo('info_panel')
    minimum_contrast = DelegatesTo('info_panel')
    maximum_contrast = DelegatesTo('info_panel')

    current_pin = Str(None)
    confirm_movepin_postproc_button = DelegatesTo('info_panel')
    confirm_movepin_internal_button = DelegatesTo('info_panel')
    add_electrode_button = DelegatesTo('info_panel')
    move_electrode_internally_event = Event
    move_electrode_postprocessing_event = Event
    add_electrode_event = Event
    track_cursor_button = DelegatesTo('info_panel')
    track_cursor_event = Event
    untrack_cursor_event = Event
    panel2d_closed_event = Event
    reset_image_button = DelegatesTo('info_panel')
    
    info_panel = Instance(InfoPanel, ())

    currently_showing_list = DelegatesTo('info_panel')
    currently_showing = DelegatesTo('info_panel')

    #later we will rename cursor to "coord"

    cursor = Tuple # 3-tuple

    null = Any # None

    _finished_plotting = Bool(False)

    traits_view = View(
        Group(
        HGroup(
            Item(name='xz_plane', editor=ComponentEditor(),
                height=400, width=400, show_label=False, resizable=True),
            Item(name='yz_plane', editor=ComponentEditor(),
                height=400, width=400, show_label=False, resizable=True),
        ),
        HGroup(
            Item(name='xy_plane', editor=ComponentEditor(),
                height=400, width=400, show_label=False, resizable=True),
            Item(name='info_panel', 
                    editor=InstanceEditor(), 
                style='custom',
            #Item(name='null', editor=NullEditor(),
                height=400, width=400, show_label=False, resizable=True),
        ),
        ),
        title='Contact 867-5309 for blobfish sales',
    )

    def map_cursor(self, cursor, affine, invert=False):
        x,y,z = cursor
        aff_to_use = np.linalg.inv(affine) if invert else affine
        mcursor, = apply_affine([cursor], aff_to_use)
        return tuple(map(lambda x: truncate(x, 2), mcursor))

    #def cut_data(self, data, mcursor):
    def cut_data(self, ndata, mcursor):
        xm,ym,zm = [int(np.round(c)) for c in mcursor]
        #xm, ym, zm = mcursor
        #yz_cut = np.rot90(data[xm,:,:].T)
        #xz_cut = np.rot90(data[:,ym,:].T)
        #xy_cut = np.rot90(data[:,:,zm].T)

        #ndata = data.copy()
        ndata[ndata < self.minimum_contrast] = self.minimum_contrast
        ndata[ndata > self.maximum_contrast] = self.maximum_contrast

        yz_cut = ndata[xm,:,:].T
        xz_cut = ndata[:,ym,:].T
        xy_cut = ndata[:,:,zm].T
        return xy_cut, xz_cut, yz_cut

    def load_img(self, imgf, reorient2std=False, image_name=None):
        self._finished_plotting = False

        img = nib.load(imgf)

        aff = np.dot(
            get_orig2std(imgf) if reorient2std else np.eye(4),
            img.get_affine())
        tkr_aff = np.dot(
            reorient_orig2std_tkr_mat if reorient2std else np.eye(4),
            get_vox2rasxfm(imgf, stem='vox2ras-tkr'))

        #from nilearn.image.resampling import reorder_img

        #img = reorder_img(uimg, resample='continuous')

        xsz, ysz, zsz = img.shape

        #print 'image coordinate transform', img.get_affine()

        imgd = img.get_data()
        if reorient2std:
            imgd = np.swapaxes(imgd, 1, 2)[:,:,::-1]

        #print 'image size', imgd.shape

        if image_name is None:
            from utils import gensym
            image_name = 'image%s'%gensym()

        self.images[image_name] = (imgd, aff, tkr_aff)
        self.currently_showing_list.append(
            NullInstanceHolder(name=image_name))
        self.currently_showing = self.currently_showing_list[-1]

        self.pins[image_name] = {}
        #self.current_pin = image_name

        self.show_image(image_name)

    @on_trait_change('currently_showing, minimum_contrast, maximum_contrast')
    def switch_image(self):
        self.show_image(self.currently_showing.name)

    @on_trait_change('reset_image_button')
    def center_image(self):
        x, y, z = self.current_image.shape

        for plane, (r,c) in zip((self.xy_plane, self.xz_plane, self.yz_plane),
                                ((x,y), (x,z), (y,z))):
            plane.index_mapper.range.low = 0
            plane.value_mapper.range.low = 0
            plane.index_mapper.range.high = r
            plane.value_mapper.range.high = c
    
    def show_image(self, image_name, xyz=None):
        # XYZ is given in pixel coordinates
        cur_img_t, self.current_affine, self.current_tkr_affine = (
            self.images[image_name])

        self.current_image = cur_img_t.copy()

        if xyz is None:
            xyz = tuple(np.array(self.current_image.shape) // 2)
        self.cursor = x,y,z = xyz
        xy_cut, xz_cut, yz_cut = self.cut_data(self.current_image, 
            self.cursor)

        xsz, ysz, zsz = self.current_image.shape

        xy_plotdata = ArrayPlotData()
        xy_plotdata.set_data('imagedata', xy_cut)
        xy_plotdata.set_data('cursor_x', np.array((x,)))
        xy_plotdata.set_data('cursor_y', np.array((y,)))

        xz_plotdata = ArrayPlotData()
        xz_plotdata.set_data('imagedata', xz_cut)
        xz_plotdata.set_data('cursor_x', np.array((x,)))
        xz_plotdata.set_data('cursor_z', np.array((z,)))

        yz_plotdata = ArrayPlotData()
        yz_plotdata.set_data('imagedata', yz_cut)
        yz_plotdata.set_data('cursor_y', np.array((y,)))
        yz_plotdata.set_data('cursor_z', np.array((z,)))

        self.xy_plane = Plot(xy_plotdata, bgcolor='black',
            #aspect_ratio=xsz/ysz)
            )
        self.xz_plane = Plot(xz_plotdata, bgcolor='black',
            #aspect_ratio=xsz/zsz)
            )
        self.yz_plane = Plot(yz_plotdata, bgcolor='black',
            #aspect_ratio=ysz/zsz)
            )

        self.xy_plane.img_plot('imagedata',name='brain',colormap=bone_cmap)
        self.xz_plane.img_plot('imagedata',name='brain',colormap=bone_cmap)
        self.yz_plane.img_plot('imagedata',name='brain',colormap=bone_cmap)

        self.xy_plane.plot(('cursor_x','cursor_y'), type='scatter', 
            color='red', marker='plus', size=3, name='cursor')
        self.xz_plane.plot(('cursor_x','cursor_z'), type='scatter',
            color='red', marker='plus', size=3, name='cursor')
        self.yz_plane.plot(('cursor_y','cursor_z'), type='scatter',
            color='red', marker='plus', size=3, name='cursor')

        self.xy_plane.tools.append(Click2DPanelTool(self, 'xy'))
        self.xz_plane.tools.append(Click2DPanelTool(self, 'xz'))
        self.yz_plane.tools.append(Click2DPanelTool(self, 'yz'))

        self.xy_plane.tools.append(ZoomTool( self.xy_plane ))
        self.xz_plane.tools.append(ZoomTool( self.xz_plane ))
        self.yz_plane.tools.append(ZoomTool( self.yz_plane ))

        #self.xy_plane.tools.append(PanTool( self.xy_plane ))
        #self.xz_plane.tools.append(PanTool( self.xz_plane ))
        #self.yz_plane.tools.append(PanTool( self.yz_plane ))

        self.info_panel.cursor = self.cursor
        self.info_panel.cursor_ras = self.map_cursor(self.cursor, 
            self.current_affine)
        self.info_panel.cursor_tkr = self.map_cursor(self.cursor,
            self.current_tkr_affine)
        self.info_panel.cursor_intensity = float(self.current_image[x,y,z])

        self._finished_plotting = True

        if image_name in self.pins:
            for pin in self.pins[image_name]:
                px, py, pz, pcolor = self.pins[image_name][pin]
                self.drop_pin(px,py,pz, name=pin, color=pcolor)

    def cursor_outside_image_dimensions(self, cursor, image=None):
        if image is None:
            image = self.current_image

        x, y, z = cursor

        x_sz, y_sz, z_sz = image.shape

        if not 0 <= x < x_sz:
            return True
        if not 0 <= y < y_sz:
            return True
        if not 0 <= z < z_sz:
            return True
        
        return False

    def move_cursor(self, x, y, z, suppress_cursor=False, suppress_ras=False,
            suppress_tkr=False):

        #it doesnt seem necessary for the instance variable cursor to exist
        #at all but this code isn't broken
        cursor = x,y,z

        if self.cursor_outside_image_dimensions(cursor):
            print ('Cursor %.2f %.2f %.2f outside image dimensions, doing '
                'nothing'%(x,y,z))
            return

        self.cursor = cursor

        xy_cut, xz_cut, yz_cut = self.cut_data(self.current_image, self.cursor)

        print 'clicked on point %.2f %.2f %.2f'%(x,y,z)

        self.xy_plane.data.set_data('imagedata', xy_cut)
        self.xz_plane.data.set_data('imagedata', xz_cut)
        self.yz_plane.data.set_data('imagedata', yz_cut)

        self.xy_plane.data.set_data('cursor_x', np.array((x,)))
        self.xy_plane.data.set_data('cursor_y', np.array((y,)))

        self.xz_plane.data.set_data('cursor_x', np.array((x,)))
        self.xz_plane.data.set_data('cursor_z', np.array((z,)))

        self.yz_plane.data.set_data('cursor_y', np.array((y,)))
        self.yz_plane.data.set_data('cursor_z', np.array((z,)))

        if not suppress_cursor:
            self.info_panel.cursor = tuple(
                map(lambda x:truncate(x, 2), self.cursor))
        if not suppress_ras:
            self.info_panel.cursor_ras = self.map_cursor(self.cursor,
                self.current_affine)
        if not suppress_tkr:
            self.info_panel.cursor_tkr = self.map_cursor(self.cursor,
                self.current_tkr_affine)
        self.info_panel.cursor_intensity = truncate(
            self.current_image[x,y,z],3)

        image_name = self.currently_showing.name

        if image_name in self.pins:
            for pin in self.pins[image_name]:
                px, py, pz, pcolor = self.pins[image_name][pin]
                self.drop_pin(px,py,pz, name=pin, color=pcolor)

        self.untrack_cursor_event = True

    def redraw(self):
        self.xz_plane.request_redraw()
        self.yz_plane.request_redraw()
        self.xy_plane.request_redraw()

    def drop_pin(self, x, y, z, name='pin', color='yellow', 
            image_name=None, ras_coords=False, alter_current_pin=True):
        '''
        XYZ is given in pixel space
        '''
        if ras_coords:
            #affine might not necessarily be from image currently on display
            _,_,affine = self.images[image_name]

            ras_pin = self.map_cursor((x,y,z), affine, invert=True)
            x,y,z = ras_pin

        if image_name is None:
            image_name = self.currently_showing.name

        cx, cy, cz = self.cursor

        tolerance = self.pin_tolerance

        if image_name == self.currently_showing.name:
            self.xy_plane.data.set_data('%s_x'%name, 
                np.array((x,) if np.abs(z - cz) < tolerance else ()))
            self.xy_plane.data.set_data('%s_y'%name, 
                np.array((y,) if np.abs(z - cz) < tolerance else ()))
            
            self.xz_plane.data.set_data('%s_x'%name, 
                np.array((x,) if np.abs(y - cy) < tolerance else ()))
            self.xz_plane.data.set_data('%s_z'%name, 
                np.array((z,) if np.abs(y - cy) < tolerance else ()))
        
            self.yz_plane.data.set_data('%s_y'%name, 
                np.array((y,) if np.abs(x - cx) < tolerance else ()))
            self.yz_plane.data.set_data('%s_z'%name, 
                np.array((z,) if np.abs(x - cx) < tolerance else ()))

            #if name not in self.pins[image_name]:
            if name not in self.xy_plane.plots:
                self.xy_plane.plot(('%s_x'%name,'%s_y'%name), type='scatter', 
                    color=color, marker='dot', size=3, name=name)
                self.xz_plane.plot(('%s_x'%name,'%s_z'%name), type='scatter',
                    color=color, marker='dot', size=3, name=name)
                self.yz_plane.plot(('%s_y'%name,'%s_z'%name), type='scatter',
                    color=color, marker='dot', size=3, name=name)

            self.redraw()

        self.pins[image_name][name] = (x,y,z,color)

        if alter_current_pin:
            self.current_pin = name

    def move_mouse(self, x, y, z):
        mouse = (x,y,z)

        if self.cursor_outside_image_dimensions(mouse):
            return

        self.info_panel.mouse = tuple(map(lambda x:truncate(x, 2), mouse))
        self.info_panel.mouse_ras = self.map_cursor(mouse,
            self.current_affine)
        self.info_panel.mouse_tkr = self.map_cursor(mouse, 
            self.current_tkr_affine)
        self.info_panel.mouse_intensity = truncate(
            self.current_image[x,y,z], 3)

    def _confirm_movepin_internal_button_fired(self):
        self.move_electrode_internally_event = True

    def _confirm_movepin_postproc_button_fired(self):
        self.move_electrode_postprocessing_event = True 

    def _add_electrode_button_fired(self):
        self.add_electrode_event = True

    def _track_cursor_button_fired(self):
        self.track_cursor_event = True

    def closed(self, info, is_ok):
        self.panel2d_closed_event = True

    #because these calls all call map_cursor, which changes the listener
    #variables they end up infinite looping.

    #to solve this we manage _finished_plotting manually
    #so that move_cursor is only called once when any listener is triggered
    @on_trait_change('info_panel:cursor_csvlist')
    def _listen_cursor(self):
        if self._finished_plotting and len(self.info_panel.cursor) == 3:
            self._finished_plotting = False
            x,y,z = self.info_panel.cursor
            self.move_cursor(x,y,z, suppress_cursor=True)
            self._finished_plotting = True

    @on_trait_change('info_panel:cursor_ras_csvlist')
    def _listen_cursor_ras(self):
        if self._finished_plotting and len(self.info_panel.cursor_ras) == 3:
            self._finished_plotting = False
            x,y,z = self.map_cursor(self.info_panel.cursor_ras,
                self.current_affine, invert=True)
            self.move_cursor(x,y,z, suppress_ras=True)
            self._finished_plotting = True

    @on_trait_change('info_panel:cursor_tkr_csvlist')
    def _listen_cursor_tkr(self):
        if self._finished_plotting and len(self.info_panel.cursor_tkr) == 3:
            self._finished_plotting = False
            x,y,z = self.map_cursor(self.info_panel.cursor_tkr,
                self.current_tkr_affine, invert=True)
            self.move_cursor(x,y,z, suppress_tkr=True)
            self._finished_plotting = True
Beispiel #37
0
class CameraWindow(HasTraits):
    """ CameraWindow class contains the relevant information and functions for a single camera window: image, zoom, pan
	important members:
		_plot_data  - contains image data to display (used by update_image)
		_plot - instance of Plot class to use with _plot_data
		_click_tool - instance of Clicker tool for the single camera window, to handle mouse processing
	"""
    _plot_data = Instance(ArrayPlotData)
    _plot = Instance(Plot)
    _click_tool = Instance(Clicker)
    rclicked = Int(0)

    cam_color = ''

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

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

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

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

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

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

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

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

        # self._plot.request_redraw()

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

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

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

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

    def drawline(self, str_x, str_y, x1, y1, x2, y2, color1):
        """ drawline draws 1 line on the screen by using lineplot x1,y1->x2,y2
		parameters:
			str_x - label of x coordinate
			str_y - label of y coordinate
			x1,y1,x2,y2 - start and end coordinates of the line
			color1 - color of the line
		example usage:
			drawline("x_coord","y_coord",100,100,200,200,red)
			draws a red line 100,100->200,200
		"""
        self._plot_data.set_data(str_x, [x1, x2])
        self._plot_data.set_data(str_y, [y1, y2])
        self._plot.plot((str_x, str_y), type="line", color=color1)
Beispiel #38
0
class ChacoSlice(HasTraits):
    # Borrow the volume data from the parent
    plot_data = ArrayPlotData
    plot = Instance(Plot)
    origin = Enum("bottom left", "top left", "bottom right", "top right")
    top_slice = Int
    slice_number = Range(low=0, high_name="top_slice", value=0)
    slice_plane_visible = Bool(True)
    slice_opacity = Range(0.0,1.0,1.)
    plane = Enum("x","y","z")

    def __init__(self,**traits):
        super(ChacoSlice,self).__init__(**traits)
        self.plot_data = ArrayPlotData(imagedata=self.data_source())
        self.plot = Plot(self.plot_data,
                padding=1,
                fixed_preferred_size=(50,50),
                bgcolor="black"
                )
        aspect_ratio = 1
        self.renderer = self.plot.img_plot(
            "imagedata", name="plot1",
            colormap=gray,
            aspect_ratio=aspect_ratio)[0]
        
    def _slice_number_changed(self):
        #print self.plane, "slice changed to ",self.slice_number
        self.plot.data.set_data("imagedata",self.data_source())
        self.plot.request_redraw()

    def _origin_changed(self):
        self.renderer.origin = self.origin
        self.plot.request_redraw()
        
    def reset_aspect_ratio(self):
        x,y = self.get_extents()
        self.renderer.aspect_ratio = float(x)/y
        
    def get_extents(self):
        i,j,k = self.parent.extents
        if self.plane == "x":
            return j,k
        if self.plane == "y":
            return i,k
        if self.plane == "z":
            return i,j
        
    def data_source(self):
        # Link the appropriate view changer to the slice number change
        if self.plane == "x":
            return self.parent.volume_data[self.slice_number,:,:].T
        elif self.plane == "y":
            return self.parent.volume_data[:,self.slice_number,:].T
        elif self.plane == "z":
            return self.parent.volume_data[:,:,self.slice_number].T

    traits_view = View(
                    Group(
                        Item('plot', editor=ComponentEditor(),
                             height=100,width=100, show_label=False),
                        HGroup(
                            Item("slice_plane_visible"),
                            Item("slice_number", editor=RangeEditor(
                                    mode="slider",
                                    high_name = 'top_slice',
                                    low    = 0,
                                    format = "%i")),
                            show_labels=False),
                    show_labels=False,
                        ),
                    #width=100, height=200,
                    resizable=True
                    )
Beispiel #39
0
class CellCropController(BaseImageController):
    zero = Int(0)
    template_plot = Instance(BasePlotContainer)
    template_data = Instance(ArrayPlotData)
    template_size = Range(low=2, high=512, value=64, cols=4)
    template_top = Range(low='zero', high='max_pos_y', value=20, cols=4)
    template_left = Range(low='zero', high='max_pos_x', value=20, cols=4)
    peaks = Dict({})
    ShowCC = Bool(False)
    max_pos_x = Int(256)
    max_pos_y = Int(256)
    is_square = Bool(True)
    peak_width = Range(low=2, high=200, value=10)
    numpeaks_total = Int(0, cols=5)
    numpeaks_img = Int(0, cols=5)
    _session_id = String('')

    def __init__(self,
                 parent,
                 treasure_chest=None,
                 data_path='/rawdata',
                 *args,
                 **kw):
        super(CellCropController, self).__init__(parent, treasure_chest,
                                                 data_path, *args, **kw)

        if self.chest is not None:
            self.numfiles = len(self.nodes)
            if self.numfiles > 0:
                self.init_plot()

    def data_updated(self):
        # reinitialize data
        self.__init__(parent=self.parent,
                      treasure_chest=self.chest,
                      data_path=self.data_path)

    def init_plot(self):
        self.plotdata.set_data('imagedata', self.get_active_image())
        self.plot = self.get_scatter_overlay_plot(
            array_plot_data=self.plotdata,
            title=self.get_active_name(),
            tools=['csr', 'colorbar', 'zoom', 'pan'])
        # pick an initial template with default parameters
        self.template_data = ArrayPlotData()
        self.template_plot = Plot(self.template_data,
                                  default_origin="top left")
        self.template_data.set_data(
            'imagedata',
            self.get_active_image()[self.template_top:self.template_top +
                                    self.template_size,
                                    self.template_left:self.template_left +
                                    self.template_size])
        self.template_plot.img_plot('imagedata', title="Template")
        self.template_plot.aspect_ratio = 1  #square templates
        self.template_filename = self.get_active_name()
        self._get_max_positions()

    @on_trait_change("selected_index, ShowCC")
    def update_image(self):
        if self.ShowCC:
            CC = cv_funcs.xcorr(self.template_data.get_data('imagedata'),
                                self.get_active_image())
            self.plotdata.set_data("imagedata", CC)
            self.plot = self.get_scatter_overlay_plot(
                array_plot_data=self.plotdata,
                title=self.get_active_name(),
                tools=['csr', 'zoom', 'pan', 'colorbar'],
            )
            self.plot.aspect_ratio = (float(CC.shape[1]) / CC.shape[0])
            self.set_plot_title("Cross correlation of " +
                                self.get_active_name())
            grid_data_source = self._base_plot.range2d.sources[0]
            grid_data_source.set_data(np.arange(CC.shape[1]),
                                      np.arange(CC.shape[0]))
        else:
            self.plotdata.set_data("imagedata", self.get_active_image())
            self.plot = self.get_scatter_overlay_plot(
                array_plot_data=self.plotdata,
                title=self.get_active_name(),
                tools=['csr', 'zoom', 'pan', 'colorbar'],
            )
            self.plot.aspect_ratio = (float(self.get_active_image().shape[1]) /
                                      self.get_active_image().shape[0])
            self.set_plot_title(self.get_active_name())
            grid_data_source = self._base_plot.range2d.sources[0]
            grid_data_source.set_data(
                np.arange(self.get_active_image().shape[1]),
                np.arange(self.get_active_image().shape[0]))

    def update_CC(self):
        if self.ShowCC:
            CC = cv_funcs.xcorr(self.template_data.get_data('imagedata'),
                                self.get_active_image())
            self.plotdata.set_data("imagedata", CC)

    @on_trait_change('template_left, template_top, template_size')
    def update_template_data(self):
        self.template_data.set_data(
            'imagedata',
            self.get_active_image()[self.template_top:self.template_top +
                                    self.template_size,
                                    self.template_left:self.template_left +
                                    self.template_size])
        self.template_filename = self.get_active_name()
        if self.numpeaks_total > 0:
            print "clearing peaks"
            self.peaks = {}
        # when template data changes, we should check whether to update the
        #    cross correlation plot, which depends on the template
        self.update_CC()

    @on_trait_change('selected_index, template_size')
    def _get_max_positions(self):
        max_pos_x = self.get_active_image().shape[-1] - self.template_size - 1
        if max_pos_x > 0:
            self.max_pos_x = int(max_pos_x)
        max_pos_y = self.get_active_image().shape[-2] - self.template_size - 1
        if max_pos_y > 0:
            self.max_pos_y = int(max_pos_y)

    @on_trait_change('template_left, template_top')
    def update_csr_position(self):
        if self.template_left > 0:
            self._csr.current_position = self.template_left, self.template_top
        pass

    @on_trait_change('_csr:current_position')
    def update_top_left(self):
        if self._csr.current_position[0] > 0 or self._csr.current_position[
                1] > 0:
            if self._csr.current_position[0] > self.max_pos_x:
                if self._csr.current_position[1] < self.max_pos_y:
                    self.template_top = self._csr.current_position[1]
                else:
                    self._csr.current_position = self.max_pos_x, self.max_pos_y
            elif self._csr.current_position[1] > self.max_pos_y:
                self.template_left, self.template_top = self._csr.current_position[
                    0], self.max_pos_y
            else:
                self.template_left, self.template_top = self._csr.current_position

    @on_trait_change('_colorbar_selection:selection')
    def update_thresh(self):
        try:
            thresh = self._colorbar_selection.selection
            self.thresh = thresh
            scatter_renderer = self._scatter_plot.plots['scatter_plot'][0]
            scatter_renderer.color_data.metadata['selections'] = thresh
            self.thresh_lower = thresh[0]
            self.thresh_upper = thresh[1]
            scatter_renderer.color_data.metadata_changed = {
                'selections': thresh
            }
            self.plot.request_redraw()
        except:
            pass

    @on_trait_change('thresh_upper,thresh_lower')
    def manual_thresh_update(self):
        self.thresh = [self.thresh_lower, self.thresh_upper]
        scatter_renderer = self._scatter_plot.plots['scatter_plot'][0]
        scatter_renderer.color_data.metadata['selections'] = self.thresh
        scatter_renderer.color_data.metadata_changed = {
            'selections': self.thresh
        }
        self.plot.request_redraw()

    @on_trait_change('peaks, _colorbar_selection:selection, selected_index')
    def calc_numpeaks(self):
        try:
            thresh = self._colorbar_selection.selection
            self.thresh = thresh
        except:
            thresh = []
        if thresh == [] or thresh == () or thresh == None:
            thresh = (-1, 1)
        self.numpeaks_total = int(
            np.sum([
                np.sum(
                    np.ma.masked_inside(self.peaks[image_id][:, 2], thresh[0],
                                        thresh[1]).mask)
                for image_id in self.peaks.keys()
            ]))
        try:
            self.numpeaks_img = int(
                np.sum(
                    np.ma.masked_inside(
                        self.peaks[self.get_active_name()][:, 2], thresh[0],
                        thresh[1]).mask))
        except:
            self.numpeaks_img = 0

    @on_trait_change('peaks, selected_index')
    def update_scatter_plot(self):
        data = self.plotdata.get_data('imagedata')
        aspect_ratio = (float(data.shape[1]) / data.shape[0])
        if self.get_active_name() in self.peaks:
            self.plotdata.set_data("index",
                                   self.peaks[self.get_active_name()][:, 1])
            self.plotdata.set_data("value",
                                   self.peaks[self.get_active_name()][:, 0])
            self.plotdata.set_data("color",
                                   self.peaks[self.get_active_name()][:, 2])
            self.plot = self.get_scatter_overlay_plot(
                array_plot_data=self.plotdata,
                tools=['zoom', 'pan', 'colorbar'])
            scatter_renderer = self._scatter_plot.plots['scatter_plot'][0]
            scatter_renderer.color_data.metadata['selections'] = self.thresh
            scatter_renderer.color_data.metadata_changed = {
                'selections': self.thresh
            }
        else:
            if 'index' in self.plotdata.arrays:
                self.plotdata.del_data('index')
                # value will implicitly exist if value exists.
                self.plotdata.del_data('value')
            if 'color' in self.plotdata.arrays:
                self.plotdata.del_data('color')
            self.plot = self.get_scatter_overlay_plot(
                array_plot_data=self.plotdata, )

    def locate_peaks(self):
        peaks = {}
        for idx in xrange(self.numfiles):
            self.set_active_index(idx)
            CC = cv_funcs.xcorr(self.template_data.get_data("imagedata"),
                                self.get_active_image())
            #
            pks = pc.two_dim_findpeaks((CC - CC.min()) * 255, xc_filter=False)
            pks[:, 2] = pks[:, 2] / 255 + CC.min()
            peaks[self.get_active_name()] = pks
        self.peaks = peaks

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

    def crop_cells(self):
        rows = self.chest.root.cell_description.nrows
        if rows > 0:
            # remove the table
            self.chest.remove_node('/cell_description')
            try:
                # remove the table of peak characteristics - they are not valid.
                self.chest.remove_node('/cell_peaks')
            except:
                pass
            # recreate it
            self.chest.create_table('/', 'cell_description', CellsTable)
            # remove all existing entries in the data group
            for node in self.chest.list_nodes('/cells'):
                self.chest.remove_node('/cells/' + node.name)
        # store the template
        template_data = self.template_data.get_data('imagedata')
        self.parent.add_cell_data(template_data, name="template")
        # TODO: set attribute that tells where the template came from
        row = self.chest.root.cell_description.row
        files = []
        for idx in xrange(self.numfiles):
            # filter the peaks that are outside the selected threshold
            self.set_active_index(idx)
            active_image = self.get_active_image()
            peaks = np.ma.compress_rows(self.mask_peaks(
                self.get_active_name()))
            files.append(self.get_active_name())
            tmp_sz = self.template_size
            data = np.zeros((peaks.shape[0], tmp_sz, tmp_sz),
                            dtype=active_image.dtype)
            if data.shape[0] > 0:
                for i in xrange(peaks.shape[0]):
                    # store the peak in the table
                    row['file_idx'] = i
                    row['input_data'] = self.data_path
                    row['filename'] = self.get_active_name()
                    row['x_coordinate'] = peaks[i, 0]
                    row['y_coordinate'] = peaks[i, 1]
                    row.append()
                    # crop the cells from the given locations
                    data[i, :, :] = active_image[
                        int(peaks[i, 0]):int(peaks[i, 0] + tmp_sz),
                        int(peaks[i, 1]):int(peaks[i, 1] + tmp_sz)]
                self.chest.root.cell_description.flush()
                self.parent.add_cell_data(data, name=self.get_active_name())
                # insert the data (one 3d array per file)
                self.chest.set_node_attr(
                    '/cell_description', 'threshold',
                    (self.thresh_lower, self.thresh_upper))
                self.chest.set_node_attr(
                    '/cell_description', 'template_position',
                    (self.template_left, self.template_top))
                self.chest.set_node_attr('/cell_description',
                                         'template_filename',
                                         self.template_filename)
                self.chest.set_node_attr('/cell_description', 'template_size',
                                         (self.template_size))

                self.chest.root.cell_description.flush()
                self.chest.flush()
        average_data = np.average(data, axis=0).squeeze()
        self.parent.add_cell_data(average_data, name="average")
        row = self.chest.root.cell_description.row
        row['file_idx'] = 0
        row['input_data'] = self.data_path
        row['filename'] = "average"
        row['x_coordinate'] = 0
        row['y_coordinate'] = 0
        row.append()
        self.chest.root.cell_description.flush()
        self.parent.update_cell_data()
        self.parent.add_image_data(average_data, "average")
        self.log_action(action="crop cells",
                        files=files,
                        thresh=self.thresh,
                        template_position=(self.template_left,
                                           self.template_top),
                        template_size=self.template_size,
                        template_filename=self.template_filename)
        Application.instance().end_session(self._session_id)
class ResultExplorer(HasTraits):

    # source of result data
    Beamformer = Instance(BeamformerBase)

    # traits for the plots
    plot_data = Instance(ArrayPlotData, transient=True)

    # the map
    map_plot = Instance(Plot, transient=True)
    imgp = Instance(ImagePlot, transient=True)

    # map interpolation
    interpolation = DelegatesTo('imgp', transient=True)

    # the colorbar for the map
    colorbar = Instance(ColorBar, transient=True)

    # the spectrum
    spec_plot = Instance(Plot, transient=True)

    # the main container for the plots
    plot_container = Instance(BasePlotContainer, transient=True)

    # zoom and integration box tool for map plot
    zoom = Instance(RectZoomSelect, transient=True)

    # selection of freqs
    synth = Instance(FreqSelector, transient=True)

    # cursor tool for spectrum plot
    cursor = Instance(BaseCursorTool, transient=True)

    # dynamic range of the map
    drange = Instance(DataRange1D, transient=True)

    # dynamic range of the spectrum plot
    yrange = Instance(DataRange1D, transient=True)

    # set if plots are invalid
    invalid = Bool(False, transient=True)

    # remember the last valid result
    last_valid_digest = Str(transient=True)

    # starts calculation thread
    start_calc = Button(transient=True)

    # signals end of calculation
    calc_ready = Event(transient=True)

    # calculation thread
    CThread = Instance(Thread, transient=True)

    # is calculation active ?
    running = Bool(False, transient=True)
    rmesg = Property(depends_on='running')

    # automatic recalculation ?
    automatic = Bool(False, transient=True)

    # picture
    pict = File(filter=['*.png', '*.jpg'],
                desc="name of picture file",
                transient=True)

    pic_x_min = Float(-1.0, desc="minimum  x-value picture plane")

    pic_y_min = Float(-0.75, desc="minimum  y-value picture plane")

    pic_scale = Float(400, desc="maximum  x-value picture plane")

    pic_flag = Bool(False, desc="show picture ?")

    view = View(
        HSplit(
            VGroup(
                HFlow(Item('synth{}', style='custom', width=0.8),
                      Item('start_calc{Recalc}', enabled_when='invalid'),
                      show_border=True),
                TGroup(
                    Item('plot_container{}', editor=ComponentEditor()),
                    dock='vertical',
                ),
            ),
            Tabbed(
                [Item('Beamformer', style='custom'), '-<>[Beamform]'],
                [
                    Item('Beamformer',
                         style='custom',
                         editor=InstanceEditor(view=fview)), '-<>[Data]'
                ],
            ),
            #                ['invalid{}~','last_valid_digest{}~',
            #                'calc_ready','running',
            #                '|'],
            dock='vertical'),  #HSplit
        statusbar=[StatusItem(name='rmesg', width=0.5)],
        #            icon= ImageResource('py.ico'),
        title="Beamform Result Explorer",
        resizable=True,
        menubar=MenuBarManager(
            MenuManager(
                MenuManager(Action(name='Open', action='load'),
                            Action(name='Save as', action='save_as'),
                            name='&Project'),
                MenuManager(Action(name='VI logger csv',
                                   action='import_time_data'),
                            Action(name='Pulse mat',
                                   action='import_bk_mat_data'),
                            Action(name='td file', action='import_td'),
                            name='&Import'),
                MenuManager(Action(name='NI-DAQmx', action='import_nidaqmx'),
                            name='&Acquire'),
                Action(name='R&un script', action='run_script'),
                Action(name='E&xit', action='_on_close'),
                name='&File',
            ),
            MenuManager(
                Group(
                    Action(name='&Delay+Sum',
                           style='radio',
                           action='set_Base',
                           checked=True),
                    Action(name='&Eigenvalue', style='radio',
                           action='set_Eig'),
                    Action(name='&Capon', style='radio', action='set_Capon'),
                    Action(name='M&usic', style='radio', action='set_Music'),
                    Action(name='D&amas', style='radio', action='set_Damas'),
                    Action(name='Clea&n', style='radio', action='set_Clean'),
                    Action(name='C&lean-SC',
                           style='radio',
                           action='set_Cleansc'),
                    Action(name='&Orthogonal',
                           style='radio',
                           action='set_Ortho'),
                    Action(name='&Functional',
                           style='radio',
                           action='set_Functional'),
                    Action(name='C&MF', style='radio', action='set_CMF'),
                ),
                Separator(),
                Action(name='Auto &recalc',
                       style='toggle',
                       checked_when='automatic',
                       action='toggle_auto'),
                name='&Options',
            ),
            MenuManager(
                Group(
                    #                            Action(name='&Frequency', action='set_Freq'),
                    Action(name='&Interpolation method', action='set_interp'),
                    Action(name='&Map dynamic range', action='set_drange'),
                    Action(name='&Plot dynamic range', action='set_yrange'),
                    Action(name='Picture &underlay', action='set_pic'),
                ),
                name='&View',
            ),
        ))  #View

    # init the app
    def __init__(self, **kwtraits):
        super(ResultExplorer, self).__init__(**kwtraits)
        # containers
        bgcolor = "sys_window"  #(212/255.,208/255.,200/255.) # Windows standard background
        self.plot_container = container = VPlotContainer(use_backbuffer=True,
                                                         padding=0,
                                                         fill_padding=False,
                                                         valign="center",
                                                         bgcolor=bgcolor)
        subcontainer = HPlotContainer(use_backbuffer=True,
                                      padding=0,
                                      fill_padding=False,
                                      halign="center",
                                      bgcolor=bgcolor)
        # freqs
        self.synth = FreqSelector(parent=self)
        # data source
        self.plot_data = pd = ArrayPlotData()
        self.set_result_data()
        self.set_pict()
        # map plot
        self.map_plot = Plot(pd, padding=40)
        self.map_plot.img_plot("image", name="image")
        imgp = self.map_plot.img_plot("map_data", name="map", colormap=jet)[0]
        self.imgp = imgp
        t1 = self.map_plot.plot(("xpoly", "ypoly"),
                                name="sector",
                                type="polygon")
        t1[0].face_color = (0, 0, 0, 0)  # set face color to transparent
        # map plot tools and overlays
        imgtool = ImageInspectorTool(imgp)
        imgp.tools.append(imgtool)
        overlay = ImageInspectorOverlay(component=imgp,
                                        image_inspector=imgtool,
                                        bgcolor="white",
                                        border_visible=True)
        self.map_plot.overlays.append(overlay)
        self.zoom = RectZoomSelect(self.map_plot,
                                   drag_button='right',
                                   always_on=True,
                                   tool_mode='box')
        self.map_plot.overlays.append(self.zoom)
        self.map_plot.tools.append(PanTool(self.map_plot))
        # colorbar
        colormap = imgp.color_mapper
        self.drange = colormap.range
        self.drange.low_setting = "track"
        self.colorbar = cb = ColorBar(
            index_mapper=LinearMapper(range=colormap.range),
            color_mapper=colormap,
            plot=self.map_plot,
            orientation='v',
            resizable='v',
            width=10,
            padding=20)
        # colorbar tools and overlays
        range_selection = RangeSelection(component=cb)
        cb.tools.append(range_selection)
        cb.overlays.append(
            RangeSelectionOverlay(component=cb,
                                  border_color="white",
                                  alpha=0.8,
                                  fill_color=bgcolor))
        range_selection.listeners.append(imgp)
        # spectrum plot
        self.spec_plot = Plot(pd, padding=25)
        px = self.spec_plot.plot(("freqs", "spectrum"),
                                 name="spectrum",
                                 index_scale="log")[0]
        self.yrange = self.spec_plot.value_range
        px.index_mapper = MyLogMapper(range=self.spec_plot.index_range)
        # spectrum plot tools
        self.cursor = CursorTool(
            px)  #, drag_button="left", color='blue', show_value_line=False)
        px.overlays.append(self.cursor)
        self.cursor.current_position = 0.3, 0.5
        px.index_mapper.map_screen(0.5)
        #        self.map_plot.tools.append(SaveTool(self.map_plot, filename='pic.png'))

        # layout
        self.set_map_details()
        self.reset_sector()
        subcontainer.add(self.map_plot)
        subcontainer.add(self.colorbar)
        #        subcontainer.tools.append(SaveTool(subcontainer, filename='pic.png'))
        container.add(self.spec_plot)
        container.add(subcontainer)
        container.tools.append(SaveTool(container, filename='pic.pdf'))
        self.last_valid_digest = self.Beamformer.ext_digest

    def _get_rmesg(self):
        if self.running:
            return "Running ..."
        else:
            return "Ready."

    @on_trait_change('Beamformer.ext_digest')
    def invalidate(self):
        if self.last_valid_digest != "" and self.Beamformer.ext_digest != self.last_valid_digest:
            self.invalid = True

    def _start_calc_fired(self):
        if self.CThread and self.CThread.isAlive():
            pass
        else:
            self.CThread = CalcThread()
            self.CThread.b = self.Beamformer
            self.CThread.caller = self
            self.CThread.start()

    def _calc_ready_fired(self):
        f = self.Beamformer.freq_data
        low, high = f.freq_range
        print low, high
        fr = f.fftfreq()
        if self.synth.synth_freq < low:
            self.synth.synth_freq = fr[1]
        if self.synth.synth_freq > high:
            self.synth.synth_freq = fr[-2]
        self.set_result_data()
        self.set_map_details()
        self.plot_container.request_redraw()
        self.map_plot.request_redraw()

    @on_trait_change('invalid')
    def activate_plot(self):
        self.plot_container.visible = not self.invalid
        self.plot_container.request_redraw()
        if self.invalid and self.automatic:
            self._start_calc_fired()

    @on_trait_change('cursor.current_position')
    def update_synth_freq(self):
        self.synth.synth_freq = self.cursor.current_position[0]

    def reset_sector(self):
        g = self.Beamformer.grid
        if self.zoom:
            self.zoom.x_min = g.x_min
            self.zoom.y_min = g.y_min
            self.zoom.x_max = g.x_max
            self.zoom.y_max = g.y_max

    @on_trait_change(
        'zoom.box,synth.synth_freq,synth.synth_type,drange.+,yrange.+')
    def set_result_data(self):
        if self.invalid:
            return
        if self.cursor:
            self.cursor.current_position = self.synth.synth_freq, 0
        pd = self.plot_data
        if not pd:
            return
        g = self.Beamformer.grid
        try:
            map_data = self.Beamformer.synthetic(self.synth.synth_freq,
                                                 self.synth.synth_type_).T
            map_data = L_p(map_data)
        except:
            map_data = arange(0, 19.99, 20. / g.size).reshape(g.shape)
        pd.set_data("map_data", map_data)
        f = self.Beamformer.freq_data
        if self.zoom and self.zoom.box:
            sector = self.zoom.box
        else:
            sector = (g.x_min, g.y_min, g.x_max, g.y_max)
        pd.set_data("xpoly", array(sector)[[0, 2, 2, 0]])
        pd.set_data("ypoly", array(sector)[[1, 1, 3, 3]])
        ads = pd.get_data("freqs")
        if not ads:
            freqs = ArrayDataSource(f.fftfreq()[f.ind_low:f.ind_high],
                                    sort_order='ascending')
            pd.set_data("freqs", freqs)
        else:
            ads.set_data(f.fftfreq()[f.ind_low:f.ind_high],
                         sort_order='ascending')
        self.synth.enumerate()
        try:
            spectrum = self.Beamformer.integrate(sector)[f.ind_low:f.ind_high]
            spectrum = L_p(spectrum)
        except:
            spectrum = f.fftfreq()[f.ind_low:f.ind_high]
        pd.set_data("spectrum", spectrum)

    @on_trait_change('pic+')
    def set_map_details(self):
        if self.invalid:
            return
        mp = self.map_plot
        # grid
        g = self.Beamformer.grid
        xs = linspace(g.x_min, g.x_max, g.nxsteps)
        ys = linspace(g.y_min, g.y_max, g.nysteps)
        mp.range2d.sources[1].set_data(xs,
                                       ys,
                                       sort_order=('ascending', 'ascending'))
        mp.aspect_ratio = (xs[-1] - xs[0]) / (ys[-1] - ys[0])
        yl, xl = self.plot_data.get_data("image").shape[0:2]
        xp = (self.pic_x_min, self.pic_x_min + xl * 1.0 / self.pic_scale)
        yp = (self.pic_y_min, self.pic_y_min + yl * 1.0 / self.pic_scale)
        mp.range2d.sources[0].set_data(xp,
                                       yp,
                                       sort_order=('ascending', 'ascending'))
        mp.range2d.low_setting = (g.x_min, g.y_min)
        mp.range2d.high_setting = (g.x_max, g.y_max)

        # dynamic range
        map = mp.plots["map"][0]
        #map.color_mapper.range.low_setting="track"
        # colormap
        map.color_mapper._segmentdata['alpha'] = [(0.0, 0.0, 0.0),
                                                  (0.001, 0.0, 1.0),
                                                  (1.0, 1.0, 1.0)]
        map.color_mapper._recalculate()
        mp.request_redraw()

    @on_trait_change('pict')
    def set_pict(self):
        pd = self.plot_data
        if not pd:
            return
        try:
            imgd = ImageData.fromfile(self.pict)._data[::-1]
        except:
            imgd = ImageData()
            imgd.set_data(255 * ones((2, 2, 3), dtype='uint8'))
            imgd = imgd._data
        pd.set_data("image", imgd)

    def save_as(self):
        dlg = FileDialog(action='save as', wildcard='*.rep')
        dlg.open()
        if dlg.filename != '':
            fi = file(dlg.filename, 'w')
            dump(self, fi)
            fi.close()

    def load(self):
        dlg = FileDialog(action='open', wildcard='*.rep')
        dlg.open()
        if dlg.filename != '':
            fi = file(dlg.filename, 'rb')
            s = load(fi)
            self.copy_traits(s)
            fi.close()

    def run_script(self):
        dlg = FileDialog(action='open', wildcard='*.py')
        dlg.open()
        if dlg.filename != '':
            #~ try:
            rx = self
            b = rx.Beamformer
            script = dlg.path
            execfile(dlg.path)
            #~ except:
            #~ pass

    def import_time_data(self):
        t = self.Beamformer.freq_data.time_data
        ti = csv_import()
        ti.from_file = 'C:\\tyto\\array\\07.03.2007 16_45_59,203.txt'
        ti.configure_traits(kind='modal')
        t.name = ""
        ti.get_data(t)

    def import_bk_mat_data(self):
        t = self.Beamformer.freq_data.time_data
        ti = bk_mat_import()
        ti.from_file = 'C:\\work\\1_90.mat'
        ti.configure_traits(kind='modal')
        t.name = ""
        ti.get_data(t)

    def import_td(self):
        t = self.Beamformer.freq_data.time_data
        ti = td_import()
        ti.from_file = 'C:\\work\\x.td'
        ti.configure_traits(kind='modal')
        t.name = ""
        ti.get_data(t)

    def import_nidaqmx(self):
        t = self.Beamformer.freq_data.time_data
        ti = nidaq_import()
        ti.configure_traits(kind='modal')
        t.name = ""
        ti.get_data(t)

    def set_Base(self):
        b = self.Beamformer
        self.Beamformer = BeamformerBase(freq_data=b.freq_data,
                                         grid=b.grid,
                                         mpos=b.mpos,
                                         c=b.c,
                                         env=b.env)
        self.invalid = True

    def set_Eig(self):
        b = self.Beamformer
        self.Beamformer = BeamformerEig(freq_data=b.freq_data,
                                        grid=b.grid,
                                        mpos=b.mpos,
                                        c=b.c,
                                        env=b.env)
        self.invalid = True

    def set_Capon(self):
        b = self.Beamformer
        self.Beamformer = BeamformerCapon(freq_data=b.freq_data,
                                          grid=b.grid,
                                          mpos=b.mpos,
                                          c=b.c,
                                          env=b.env)
        self.invalid = True

    def set_Music(self):
        b = self.Beamformer
        self.Beamformer = BeamformerMusic(freq_data=b.freq_data,
                                          grid=b.grid,
                                          mpos=b.mpos,
                                          c=b.c,
                                          env=b.env)
        self.invalid = True

    def set_Damas(self):
        b = self.Beamformer
        self.Beamformer = BeamformerDamas(beamformer=BeamformerBase(
            freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env))
        self.invalid = True

    def set_Cleansc(self):
        b = self.Beamformer
        self.Beamformer = BeamformerCleansc(freq_data=b.freq_data,
                                            grid=b.grid,
                                            mpos=b.mpos,
                                            c=b.c,
                                            env=b.env)
        self.invalid = True

    def set_Ortho(self):
        b = self.Beamformer
        self.Beamformer = BeamformerOrth(beamformer=BeamformerEig(
            freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env))
        self.Beamformer.n = 10
        self.invalid = True

    def set_Functional(self):
        b = self.Beamformer
        self.Beamformer = BeamformerFunctional(freq_data=b.freq_data,
                                               grid=b.grid,
                                               mpos=b.mpos,
                                               c=b.c,
                                               env=b.env)
        self.invalid = True

    def set_Clean(self):
        b = self.Beamformer
        self.Beamformer = BeamformerClean(beamformer=BeamformerBase(
            freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env))
        self.invalid = True

    def set_CMF(self):
        b = self.Beamformer
        self.Beamformer = BeamformerCMF(freq_data=b.freq_data,
                                        grid=b.grid,
                                        mpos=b.mpos,
                                        c=b.c,
                                        env=b.env)
        self.invalid = True

    def toggle_auto(self):
        self.automatic = not self.automatic

    def set_interp(self):
        self.configure_traits(kind='live', view=interpview)

    def set_drange(self):
        self.drange.configure_traits(kind='live', view=drangeview)

    def set_yrange(self):
        self.yrange.configure_traits(kind='live', view=drangeview)

    def set_pic(self):
        self.configure_traits(kind='live', view=picview)
Beispiel #41
0
    def __init__(self):

        super(ContainerExample, self).__init__()

        filenames = []
        for parameter in sys.argv[1:]:
            print("processing parameter", parameter)
            if parameter.find("=") == -1:
                print("no = in parameter", parameter, "must be a file name")
                filenames.append(parameter)
        if len(filenames) < 1:
            print("just to help me test, if there are no files in the list, ")
            print("I will append the file foldplot1.rsf")
            filenames.append('foldplot1.rsf')

        self.seis_data_0 = SeisData(filenames[0])
        self.cmap = jet

        self.displayParameters = DisplayParameters()

        self.slice_y = self.displayParameters.slice_y

        print("self.slice_y=", self.slice_y)
        self.arrayPlotData = ArrayPlotData()
        self._update_images()

        x_extents = (self.seis_data_0.axis_start[1],
                     self.seis_data_0.axis_end[1])
        y_extents = (self.seis_data_0.axis_start[2],
                     self.seis_data_0.axis_end[2])
        bottomplot = Plot(self.arrayPlotData, origin="top left")
        self.bottomplot = bottomplot
        imgplot = bottomplot.img_plot("xz",
                                      xbounds=x_extents,
                                      ybounds=y_extents,
                                      colormap=self.cmap)[0]
        self.bottom = imgplot

        plotright = Plot(self.arrayPlotData,
                         origin="top left",
                         range2d=bottomplot.range2d)
        imgplotright = plotright.img_plot("xz",
                                          xbounds=x_extents,
                                          ybounds=y_extents,
                                          colormap=self.cmap)[0]
        self.right = imgplotright

        container = HPlotContainer(fill_padding=True,
                                   bgcolor="white",
                                   use_backbuffer=True)
        container.add(bottomplot)
        container.add(plotright)

        self.plot = container

        self.displayParameters = DisplayParameters()
        self.slice_y = self.displayParameters.slice_y

        imgplot.tools.append(CustomTool(imgplot))
        imgplot.tools.append(PanTool(imgplot, constrain_key="shift"))
        imgplot.overlays.append(
            ZoomTool(component=imgplot, tool_mode="box", always_on=False))
        imgplotright.tools.append(PanTool(imgplotright, constrain_key="shift"))
        imgplotright.overlays.append(
            ZoomTool(component=self.right, tool_mode="box", always_on=False))
Beispiel #42
0
class DVMatrix(DataView):
    conn_mat = Any
    xa = Instance(ColorfulAxis)
    ya = Instance(ColorfulAxis)

    def __init__(self, ds, **kwargs):
        super(DVMatrix, self).__init__(ds, **kwargs)
        if self.ds.adj is not None: self.chaco_gen()
        else: self.empty_gen()

    def supply_adj(self):
        self.conn_mat.data.set_data('imagedata', self.ds.adj_thresdiag)

    ########################################################################
    # GEN METHODS
    ########################################################################

    def chaco_gen(self):
        self.conn_mat = Plot(ArrayPlotData(imagedata=self.ds.adj_thresdiag))

        cm = ColorMapper.from_palette_array(
            self.ds.opts.connmat_map._pl(xrange(256)))
        self.conn_mat.img_plot('imagedata', name='connmatplot', colormap=cm)

        self.conn_mat.tools.append(ZoomTool(self.conn_mat))
        self.conn_mat.tools.append(PanTool(self.conn_mat))
        self.xa = ColorfulAxis(self.conn_mat, self.ds.node_colors, 'x')
        self.ya = ColorfulAxis(self.conn_mat, self.ds.node_colors, 'y')
        self.conn_mat.underlays = [self.xa, self.ya]

    def empty_gen(self):
        from chaco.api import Greys
        img = np.zeros((self.ds.nr_labels, self.ds.nr_labels))
        self.conn_mat = Plot(ArrayPlotData(imagedata=img))

        cm = ColorMapper.from_palette_array(
            self.ds.opts.connmat_map._pl(xrange(256)))
        self.conn_mat.img_plot('imagedata', name='connmatplot', colormap=cm)

        self.conn_mat.tools.append(ZoomTool(self.conn_mat))
        self.conn_mat.tools.append(PanTool(self.conn_mat))
        self.xa = ColorfulAxis(self.conn_mat, self.ds.node_colors, 'x')
        self.ya = ColorfulAxis(self.conn_mat, self.ds.node_colors, 'y')
        self.conn_mat.underlays = [self.xa, self.ya]

    ########################################################################
    # DRAW METHODS
    ########################################################################

    def draw_surfs(self):
        NotImplemented

    def draw_nodes(self):
        mat = self.ds.scalar_display_settings.connmat

        if self.ds.display_mode == 'scalar' and mat:
            scalars = self.ds.node_scalars[mat]
            scalars = (scalars - np.min(scalars)) / (np.max(scalars) -
                                                     np.min(scalars))
            colors = list(self.ds.opts.scalar_map._pl(scalars))
        else:
            colors = self.ds.node_colors

        self.xa.colors = colors
        self.ya.colors = colors
        self.conn_mat.request_redraw()

    def draw_conns(self, new_edges=None):
        NotImplemented

    def center(self):
        for ax in (self.xa, self.ya):
            ax.mapper.range.high_setting = self.ds.nr_labels
            ax.mapper.range.low_setting = 0

    def change_colormap(self):
        self.conn_mat.color_mapper = ColorMapper.from_palette_array(
            self.ds.opts.connmat_map._pl(xrange(256)))
        self.conn_mat.request_redraw()

    ########################################################################
    # I/O
    ########################################################################

    #takes a SnapshotParameters
    def snapshot(self, params):
        gc = PlotGraphicsContext(self.conn_mat.outer_bounds, dpi=params.dpi)
        gc.render_component(self.conn_mat)
        gc.save(params.savefile)
Beispiel #43
0
    def _create_window(self):
        # Create the model
        #try:
        #    self.model = model = BrainModel()
        #    cmap = bone
        #except SystemExit:
        #    sys.exit()
        #except:
        #    print "Unable to load BrainModel, using generated data cube."
        self.model = model = Model()
        cmap = jet
        self._update_model(cmap)

        datacube = self.colorcube

        # Create the plot
        self.plotdata = ArrayPlotData()
        self._update_images()

        # Center Plot
        centerplot = Plot(self.plotdata, padding=0)
        imgplot = centerplot.img_plot("xy",
                                      xbounds=(model.xs[0], model.xs[-1]),
                                      ybounds=(model.ys[0], model.ys[-1]),
                                      colormap=cmap)[0]
        self._add_plot_tools(imgplot, "xy")
        self.center = imgplot

        # Right Plot
        rightplot = Plot(self.plotdata, width=150, resizable="v", padding=0)
        rightplot.value_range = centerplot.value_range
        imgplot = rightplot.img_plot("yz",
                                     xbounds=(model.zs[0], model.zs[-1]),
                                     ybounds=(model.ys[0], model.ys[-1]),
                                     colormap=cmap)[0]
        self._add_plot_tools(imgplot, "yz")
        self.right = imgplot

        # Bottom Plot
        bottomplot = Plot(self.plotdata, height=150, resizable="h", padding=0)
        bottomplot.index_range = centerplot.index_range
        imgplot = bottomplot.img_plot("xz",
                                      xbounds=(model.xs[0], model.xs[-1]),
                                      ybounds=(model.zs[0], model.zs[-1]),
                                      colormap=cmap)[0]
        self._add_plot_tools(imgplot, "xz")
        self.bottom = imgplot

        # Create Container and add all Plots
        container = GridPlotContainer(padding=20,
                                      fill_padding=True,
                                      bgcolor="white",
                                      use_backbuffer=True,
                                      shape=(2, 2),
                                      spacing=(12, 12))
        container.add(centerplot)
        container.add(rightplot)
        container.add(bottomplot)

        self.container = container
        return Window(self, -1, component=container)
Beispiel #44
0
class Bullseye(HasTraits):
    plots = Instance(GridPlotContainer)
    abplots = Instance(VPlotContainer)
    screen = Instance(Plot)
    horiz = Instance(Plot)
    vert = Instance(Plot)
    asum = Instance(Plot)
    bsum = Instance(Plot)

    process = Instance(Process)

    colormap = Enum("gray", "jet", "hot", "prism")
    invert = Bool(True)

    label = None
    gridm = None
    grid = None

    traits_view = View(HGroup(VGroup(
        HGroup(
            VGroup(
                Item("object.process.x", label="Centroid x",
                    format_str=u"%.4g µm",
                    tooltip="horizontal beam position relative to chip "
                    "center"),
                Item("object.process.a", label="Major 4sig",
                    format_str=u"%.4g µm",
                    tooltip="major axis beam width 4 sigma ~ 1/e^2 width"),
                Item("object.process.t", label="Rotation",
                    format_str=u"%.4g°",
                    tooltip="angle between horizontal an major axis"),
                #Item("object.process.black", label="Black",
                #    format_str=u"%.4g",
                #    tooltip="background black level"),
            ), VGroup(
                Item("object.process.y", label="Centroid y",
                    format_str=u"%.4g µm",
                    tooltip="vertical beam position relative to chip "
                    "center"),
                Item("object.process.b", label="Minor 4sig",
                    format_str=u"%.4g µm",
                    tooltip="major axis beam width 4 sigma ~ 1/e^2 width"),
                #Item("object.process.d", label="Mean width",
                #    format_str=u"%.4g µm",
                #    tooltip="mean beam width 4 sigma ~ 1/e^2 width"),
                #Item("object.process.e", label="Ellipticity",
                #    format_str=u"%.4g",
                #    tooltip="ellipticity minor-to-major width ratio"),
                #Item("object.process.peak", label="Peak",
                #    format_str=u"%.4g",
                #    tooltip="peak pixel level"),
                Item("object.process.include_radius", label="Include radius",
                    format_str=u"%.4g µm",
                    tooltip="energy inclusion radius according to ignore "
                    "level, used to crop before taking moments"),
            ),
            style="readonly",
        ), VGroup(
            Item("object.process.capture.shutter",
                tooltip="exposure time per frame in seconds"),
            Item("object.process.capture.gain",
                tooltip="analog camera gain in dB"),
            Item("object.process.capture.framerate",
                tooltip="frames per second to attempt, may be limited by "
                "shutter time and processing speed"),
            Item("object.process.capture.average",
                tooltip="number of subsequent images to boxcar average"),
            Item("object.process.background",
                tooltip="background intensity percentile to subtract "
                "from image"),
            Item("object.process.ignore",
                tooltip="fraction of total intensity to ignore for "
                "cropping, determines include radius"),
            Item("object.process.crops",
                tooltip="fraction of total intensity to ignore for "
                "cropping, determines include radius"),
        ), HGroup(
            Item("object.process.active",
                tooltip="capture and processing running"),
            Item("object.process.capture.auto_shutter",
                tooltip="adjust the shutter time to "
                "yield acceptably exposed frames with peak values "
                "between .25 and .75"),
            Item("object.process.track",
                tooltip="adjust the region of interest to track the "
                "beam center, the size is not adjusted"),
            Item("object.process.capture.dark",
                tooltip="capture a dark image and subtract it from "
                "subsequent images, reset if gain or shutter change"),
        ), HGroup(
            UItem("colormap", tooltip="image colormap"),
            Item("invert", tooltip="invert the colormap"),
        ), UItem("abplots", editor=ComponentEditor(),
                width=-200, height=-300, resizable=False,
                tooltip="line sums (red), moments (blue) and "
                "2-sigma markers (green) along the major and minor axes",
        ),
    ), UItem("plots", editor=ComponentEditor(), width=800,
            tooltip="top right: beam image with 2-sigma and 6-sigma "
            "radius ellipses and axis markers (green). top left and bottom "
            "right: vertial and horizontal line sums (red), moments "
            "(blue) and 2-sigma markers (green). bottom left: beam data "
            "from moments"),
    layout="split",
    ), resizable=True, title=u"Bullseye ― Beam Profiler", width=1000)

    def __init__(self, **k):
        super(Bullseye, self).__init__(**k)
        self.data = ArrayPlotData()
        self.process.initialize()
        self.setup_plots()
        self.update_data()
        self.populate_plots()

        self.on_trait_change(self.update_data, "process.new_data",
                dispatch="fast_ui")

    def setup_plots(self):
        self.screen = Plot(self.data,
                resizable="hv", padding=0, bgcolor="lightgray",
                border_visible=False)
        self.screen.index_grid.visible = False
        self.screen.value_grid.visible = False
        px = self.process.capture.pixelsize
        w, h = self.process.capture.width, self.process.capture.height
        # value_range last, see set_range()
        self.screen.index_range.low_setting = -w/2*px
        self.screen.index_range.high_setting = w/2*px
        self.screen.value_range.low_setting = -h/2*px
        self.screen.value_range.high_setting = h/2*px

        self.horiz = Plot(self.data,
                resizable="h", padding=0, height=100,
                bgcolor="lightgray", border_visible=False)
        self.horiz.value_mapper.range.low_setting = \
                -.1*self.process.capture.maxval
        self.horiz.index_range = self.screen.index_range
        self.vert = Plot(self.data, orientation="v",
                resizable="v", padding=0, width=100,
                bgcolor="lightgray", border_visible=False)
        for p in self.horiz, self.vert:
            p.index_axis.visible = False
            p.value_axis.visible = False
            p.index_grid.visible = True
            p.value_grid.visible = False
        self.vert.value_mapper.range.low_setting = \
                -.1*self.process.capture.maxval
        self.vert.index_range = self.screen.value_range

        #self.vert.value_range = self.horiz.value_range

        self.mini = Plot(self.data,
                width=100, height=100, resizable="", padding=0,
                bgcolor="lightgray", border_visible=False)
        self.mini.index_axis.visible = False
        self.mini.value_axis.visible = False
        self.label = PlotLabel(component=self.mini,
                overlay_position="inside left", font="modern 10",
                text=self.process.text)
        self.mini.overlays.append(self.label)

        self.plots = GridPlotContainer(shape=(2, 2), padding=0,
                spacing=(5, 5), use_backbuffer=True,
                bgcolor="lightgray")
        self.plots.component_grid = [[self.vert, self.screen],
                                     [self.mini, self.horiz ]]

        self.screen.overlays.append(ZoomTool(self.screen,
            x_max_zoom_factor=1e2, y_max_zoom_factor=1e2,
            x_min_zoom_factor=0.5, y_min_zoom_factor=0.5,
            zoom_factor=1.2))
        self.screen.tools.append(PanTool(self.screen))
        self.plots.tools.append(SaveTool(self.plots,
            filename="bullseye.pdf"))

        self.asum = Plot(self.data,
                padding=0, height=100, bgcolor="lightgray",
                title="major axis", border_visible=False)
        self.bsum = Plot(self.data,
                padding=0, height=100, bgcolor="lightgray",
                title="minor axis", border_visible=False)
        for p in self.asum, self.bsum:
            p.value_axis.visible = False
            p.value_grid.visible = False
            p.title_font = "modern 10"
            p.title_position = "left"
            p.title_angle = 90
        # lock scales
        #self.bsum.value_range = self.asum.value_range
        #self.bsum.index_range = self.asum.index_range

        self.abplots = VPlotContainer(padding=20, spacing=20,
                use_backbuffer=True,bgcolor="lightgray",
                fill_padding=True)
        self.abplots.add(self.bsum, self.asum)

    def populate_plots(self):
        self.screenplot = self.screen.img_plot("img",
                xbounds="xbounds", ybounds="ybounds",
                interpolation="nearest",
                colormap=color_map_name_dict[self.colormap],
                )[0]
        self.set_invert()
        self.grid = self.screenplot.index
        self.gridm = self.screenplot.index_mapper
        t = ImageInspectorTool(self.screenplot)
        self.screen.tools.append(t)
        self.screenplot.overlays.append(ImageInspectorOverlay(
            component=self.screenplot, image_inspector=t,
            border_size=0, bgcolor="transparent", align="ur",
            tooltip_mode=False, font="modern 10"))

        self.horiz.plot(("x", "imx"), type="line", color="red")
        self.vert.plot(("y", "imy"), type="line", color="red")
        self.horiz.plot(("x", "gx"), type="line", color="blue")
        self.vert.plot(("y", "gy"), type="line", color="blue")
        self.asum.plot(("a", "ima"), type="line", color="red")
        self.bsum.plot(("b", "imb"), type="line", color="red")
        self.asum.plot(("a", "ga"), type="line", color="blue")
        self.bsum.plot(("b", "gb"), type="line", color="blue")

        for p in [("ell1_x", "ell1_y"), ("ell3_x", "ell3_y"),
                ("a_x", "a_y"), ("b_x", "b_y")]:
            self.screen.plot(p, type="line", color="green", alpha=.5)

        for r, s in [("x", self.horiz), ("y", self.vert),
                ("a", self.asum), ("b", self.bsum)]:
            for p in "0 p m".split():
                q = ("%s%s_mark" % (r, p), "%s_bar" % r)
                s.plot(q, type="line", color="green")

    def __del__(self):
        self.close()

    def close(self):
        self.process.active = False

    @on_trait_change("colormap")
    def set_colormap(self):
        p = self.screenplot
        m = color_map_name_dict[self.colormap]
        p.color_mapper = m(p.value_range)
        self.set_invert()
        p.request_redraw()

    @on_trait_change("invert")
    def set_invert(self):
        p = self.screenplot
        if self.invert:
            a, b = self.process.capture.maxval, 0
        else:
            a, b = 0, self.process.capture.maxval
        p.color_mapper.range.low_setting = a
        p.color_mapper.range.high_setting = b

    # TODO: bad layout for one frame at activation, track
    # value_range seems to be updated after index_range, take this
    @on_trait_change("screen.value_range.updated")
    def set_range(self):
        if self.gridm is not None:
            #enforce data/screen aspect ratio 1
            sl, sr, sb, st = self.gridm.screen_bounds
            dl, db = self.gridm.range.low
            dr, dt = self.gridm.range.high
            #dsdx = float(sr-sl)/(dr-dl)
            dsdy = float(st-sb)/(dt-db)
            #dt_new = db+(st-sb)/dsdx
            if dsdy:
                dr_new = dl+(sr-sl)/dsdy
                self.gridm.range.x_range.high_setting = dr_new
        l, r = self.screen.index_range.low, self.screen.index_range.high
        b, t = self.screen.value_range.low, self.screen.value_range.high
        px = self.process.capture.pixelsize
        self.process.capture.roi = [l, b, r-l, t-b]

    def update_data(self):
        if self.label is not None:
            self.label.text = self.process.text
        upd = self.process.data
        self.data.arrays.update(upd)
        self.data.data_changed = {"changed": upd.keys()}
        if self.grid is not None:
            self.grid.set_data(upd["xbounds"], upd["ybounds"])
Beispiel #45
0
class CameraImage(HasTraits):

    data = Array()
    data_store = Instance(ArrayPlotData)
    plot = Instance(Plot)
    hud_overlay = Instance(PlotLabel)

    # Number of steps of 90 degrees to rotate the image before
    # displaying it - must be between 0 and 3
    rotate = Range(0, 3)

    # Colormap to use for display; None means use the image's natural
    # colors (if RGB data) or grayscale (if monochrome). Setting @cmap
    # to a value coerces the image to monochrome.
    cmap = Enum(None, gray, bone, pink, jet, isoluminant, awesome)

    view = View(Item('plot', show_label=False, editor=ComponentEditor()))

    def __init__(self, **traits):
        super(CameraImage, self).__init__(**traits)
        self._dims = (200, 320)
        self.data_store = ArrayPlotData(image=self.data)
        self._hud = dict()
        self.plot = Plot(self.data_store)
        # Draw the image
        renderers = self.plot.img_plot('image',
                                       name='camera_image',
                                       colormap=fix(gray, (0, 255)))
        self._image = renderers[0]
        self.plot.aspect_ratio = float(self._dims[1]) / self._dims[0]

        self.hud_overlay = PlotLabel(text='',
                                     component=self.plot,
                                     hjustify='left',
                                     overlay_position='inside bottom',
                                     color='white')
        self.plot.overlays.append(self.hud_overlay)

    def _data_default(self):
        return N.zeros(self._dims, dtype=N.uint8)

    def _data_changed(self, value):
        bw = (len(value.shape) == 2)
        if not bw and self.cmap is not None:
            # Selecting a colormap coerces the image to monochrome
            # Use standard NTSC conversion formula
            value = N.array(0.2989 * value[..., 0] + 0.5870 * value[..., 1] +
                            0.1140 * value[..., 2])
        value = N.rot90(value, self.rotate)
        self.data_store['image'] = self.data = value

        if self._dims != self.data.shape:
            # Redraw the axes if the image is a different size
            self.plot.delplot('camera_image')
            self._dims = self.data.shape
            renderers = self.plot.img_plot('image',
                                           name='camera_image',
                                           colormap=self._get_cmap_function())
            # colormap is ignored if image is RGB or RGBA
            self._image = renderers[0]

        # Make sure the aspect ratio is correct, even after resize
        self.plot.aspect_ratio = float(self._dims[1]) / self._dims[0]

    def _get_cmap_function(self):
        return fix(gray if self.cmap is None else self.cmap,
                   (0, 65535 if self.data.dtype == N.uint16 else 255))

    def _cmap_changed(self, old_value, value):
        # Must redraw the plot if data was RGB
        if old_value is None or value is None:
            self._data_changed(self.data)

        cmap_func = self._get_cmap_function()
        self._image.color_mapper = cmap_func(self._image.value_range)

    def hud(self, key, text):
        if text is None:
            self._hud.pop(key, None)
        else:
            self._hud[key] = text

        # Do the heads-up display
        text = ''
        for key in sorted(self._hud.keys()):
            text += self._hud[key] + '\n\n'
        self.hud_overlay.text = text
Beispiel #46
0
    def create_plot_component(self):
        if not self.data.size:
            return

        self.pd = ArrayPlotData()
        self.shape = self.data.shape
        self.pd.set_data("imagedata", self.data)
        self.pd.set_data("left_line", self.data[:, self.shape[0]//2])
        self.pd.set_data("top_line", self.data[self.shape[1]//2,:])

        plot = Plot(self.pd)
        cmap = default_colormaps.color_map_name_dict[self.colormap]

        if self.rev_cmap:
            cmap = default_colormaps.reverse(cmap)

        drange = DataRange1D(ImageData(data=self.data, value_depth=1))



        self.ccmap = cmap_constant_range(cmap, drange)(drange)

            #from copy import copy
        self.img_plot = plot.img_plot("imagedata",
                                 colormap=cmap,
                                 #xbounds=self.xbounds,
                                 #ybounds=self.ybounds,
                                 )[0]
        self.cmap = self.img_plot.value_mapper
        if not self.autoscale:
            self.img_plot.value_mapper = self.ccmap
        # Tweak some of the plot properties
        plot.title = self.title
        plot.padding = 10

        # 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)

        csr = CursorTool(self.img_plot,
                          drag_button='right',
                          color='white',
                          line_width=2.0
                          )
        self.cursor = csr

        csr.current_index = self.shape[0]//2, self.shape[1]//2
        self.img_plot.overlays.append(csr)

        imgtool = ImageInspectorTool(self.img_plot)
        self.img_plot.tools.append(imgtool)

        overlay = ImageInspectorOverlay(component=self.img_plot, image_inspector=imgtool,
                                        bgcolor="white", border_visible=True)

        self.img_plot.overlays.append(overlay)
        self.plot = plot

        self.cross_plot = Plot(self.pd,resizable='h')
        self.cross_plot.height = 40
        self.cross_plot.padding = 15
        self.cross_plot.plot("top_line",
                             line_style="dot")


        self.cross_plot.index_range = self.img_plot.index_range.x_range


        self.cross_plot2 = Plot(self.pd, width=40, orientation="v",
                                padding=15, padding_bottom=10, resizable='v')
        self.cross_plot2.plot("left_line",
                              line_style="dot")


        self.cross_plot2.index_range = self.img_plot.index_range.y_range

        # Create a container and add components
        #self.container = HPlotContainer(padding=10, fill_padding=False,
        #                                bgcolor="none", use_backbuffer=False)
        #inner_cont = VPlotContainer(padding=0, use_backbuffer=True, bgcolor="none")
        #inner_cont.add(self.plot)
        #inner_cont.add(self.cross_plot)
        self.container = GridPlotContainer(padding=20, fill_padding=False,
                                      bgcolor="none", use_backbuffer=True,
                                      shape=(2, 2), spacing=(12, 20))

        #self.container.add(self.colorbar)
        self.container.add(self.plot)
        self.container.add(self.cross_plot2)
        self.container.add(self.cross_plot)
Beispiel #47
0
    def __init__(self):

        super(ContainerExample, self).__init__()

        # make a list of the files names on the command line
        # command line entries without = are assumed to be files
        filenames = []
        for parameter in sys.argv[1:]:
            print "processing parameter", parameter
            if parameter.find("=") == -1:
                print "no = in parameter", parameter, "must be a file name"
                filenames.append(parameter)
        if len(filenames) < 1:
            print "just to help me test, if there are no files in the list, "
            print "I will append the file foldplot1.rsf"
            filenames.append('foldplot1.rsf')

        # there should be a try while these files are opened to identify
        # bad file names and make error messages.

        self.seis_data = []
        for filename in filenames:
            print "  "
            print "+++++++++++++++++++++++++++++++++++++++++++"
            print "+++++++++++++++++++++++++++++++++++++++++++"
            print "open the file", filename
            self.seis_data.append(SeisData(filename))

        # kls files should be tested to make sure they are all same shape
        print "number files=", len(filenames)
        self.displayParameters = DisplayParameters()
        self.cmap = jet  # kls this should come from display parameters

        self.slice_y = self.displayParameters.slice_y  # kls this should be pointer

        print "self.slice_y=", self.slice_y
        self.arrayPlotDatas = []
        for filename in filenames:
            self.arrayPlotDatas.append(ArrayPlotData())
        self._update_images()

        x_extents = (self.seis_data[0].axis_start[1],
                     self.seis_data[0].axis_end[1])
        y_extents = (self.seis_data[0].axis_start[2],
                     self.seis_data[0].axis_end[2])
        bottomplot = Plot(self.arrayPlotDatas[0], origin="top left")
        self.bottomplot = bottomplot
        imgplot = bottomplot.img_plot("xz",
                                      xbounds=x_extents,
                                      ybounds=y_extents,
                                      colormap=self.cmap)[0]
        self.bottom = imgplot

        plotright = Plot(self.arrayPlotDatas[1],
                         origin="top left",
                         range2d=bottomplot.range2d)
        imgplotright = plotright.img_plot("xz",
                                          xbounds=x_extents,
                                          ybounds=y_extents,
                                          colormap=self.cmap)[0]
        self.right = imgplotright

        container = HPlotContainer(fill_padding=True,
                                   bgcolor="white",
                                   use_backbuffer=True)
        container.add(bottomplot)
        container.add(plotright)

        self.plot = container

        self.displayParameters = DisplayParameters()
        self.slice_y = self.displayParameters.slice_y

        imgplot.tools.append(CustomTool(imgplot))
        imgplot.tools.append(PanTool(imgplot, constrain_key="shift"))
        imgplot.overlays.append(
            ZoomTool(component=imgplot, tool_mode="box", always_on=False))
        imgplotright.tools.append(PanTool(imgplotright, constrain_key="shift"))
        imgplotright.overlays.append(
            ZoomTool(component=self.right, tool_mode="box", always_on=False))
Beispiel #48
0
    def _get_plot_cmap(self):

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

        numpoints = self.data.shape[1]

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

        x_bounds = (index_x[0], index_x[-1], len(index_x))
        y_bounds = (1, self.data.shape[0], self.data.shape[0])
        # Create a plot data obect and give it this data
        pd = ArrayPlotData()
        pd.set_data("imagedata", self.data)

        plot = Plot(pd)

        plot.img_plot("imagedata",
                      name="corr_plot",
                      origin="top left",
                      xbounds=x_bounds[:2],
                      ybounds=y_bounds[:2],
                      colormap=jet,
                      padding_left=25)

        corr_plot = plot.plots['corr_plot'][0]

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

        corr_plot.overlays.append(bottom_axis)

        corr_plot.tools.append(
            PanTool(corr_plot,
                    constrain=True,
                    constrain_direction="x",
                    constrain_key="shift"))
        corr_plot.overlays.append(
            ZoomTool(
                corr_plot,
                drag_button="right",
                always_on=True,
                tool_mode="range",
                axis="index",
                max_zoom_out_factor=10.0,
            ))

        # Create the colorbar, handing in the appropriate range and colormap
        colorbar = ColorBar(
            index_mapper=LinearMapper(range=corr_plot.color_mapper.range),
            color_mapper=corr_plot.color_mapper,
            plot=corr_plot,
            orientation='v',
            resizable='v',
            width=30,
            padding_top=corr_plot.padding_top,
            padding_bottom=corr_plot.padding_bottom,
            padding_left=50,
            padding_right=5)

        #colorbar.plot = corr_plot
        #colorbar.padding_top = corr_plot.padding_top
        #colorbar.padding_bottom = corr_plot.padding_bottom

        # Add pan and zoom tools to the colorbar
        pan_tool = PanTool(colorbar, constrain_direction="y", constrain=True)
        colorbar.tools.append(pan_tool)

        zoom_overlay = ZoomTool(colorbar,
                                axis="index",
                                tool_mode="range",
                                always_on=False,
                                drag_button=None)
        colorbar.overlays.append(zoom_overlay)

        # Create a container to position the plot and the colorbar side-by-side
        container = HPlotContainer(corr_plot,
                                   colorbar,
                                   use_backbuffer=True,
                                   bgcolor="transparent",
                                   spacing=9,
                                   padding=30)

        container.overlays.append(
            PlotLabel(self.p_title,
                      component=container,
                      overlay_position="outside top",
                      font="modern 16"))

        container.overlays.append(
            PlotLabel(self.y_lbl,
                      component=container,
                      angle=90.0,
                      overlay_position="outside left",
                      font="modern 12"))

        container.padding_bottom = 50

        return container
Beispiel #49
0
    def create_plot_component(self):# Create a scalar field to colormap
        # Create the plot
        self.pd = ArrayPlotData()
        self.pd.set_data("imagedata", self.fxydata())
        plot = Plot(self.pd)
        cmap = default_colormaps.color_map_name_dict[self.colormap]
        if self.rev_cmap:
            cmap = default_colormaps.reverse(cmap)
        img_plot = plot.img_plot("imagedata",
                                 xbounds = self.xbounds,
                                 ybounds = self.ybounds,
                                 colormap=cmap,

                                 )[0]

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

        # 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)

        csr = CursorTool(img_plot,
                          drag_button='left',
                          color='white',
                          line_width=2.0
                          )
        self.cursor = csr

        csr.current_position = np.mean(self.xbounds), np.mean(self.ybounds)
        img_plot.overlays.append(csr)

        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)
        colorbar = ColorBar(index_mapper=LinearMapper(range=plot.color_mapper.range),
                            color_mapper=plot.color_mapper,
                            orientation='v',
                            resizable='v',
                            width=30,
                            padding=20)
        colorbar.plot = plot
        colorbar.padding_top = plot.padding_top + 10
        colorbar.padding_bottom = plot.padding_bottom

        # Add pan and zoom tools to the colorbar
        colorbar.tools.append(PanTool(colorbar, constrain_direction="y", constrain=True))
        zoom_overlay = ZoomTool(colorbar, axis="index", tool_mode="range",
                                always_on=True, drag_button="right")
        colorbar.overlays.append(zoom_overlay)

        # Create a container to position the plot and the colorbar side-by-side
        container = HPlotContainer(plot, colorbar, use_backbuffer=True, bgcolor="transparent",)
        container.overlays.append(overlay)
        #self.plot = plot
        self.plot = container
Beispiel #50
0
    def _plot(self, x, y, z, scale):
        pd = ArrayPlotData()
        pd.set_data("imagedata", z)
        plot = Plot(pd, padding_left=60, fill_padding=True)
        plot.bgcolor = 'white'
        cmap = fix(jet, (0, z.max()))
        origin = 'bottom left' # origin = 'top left' # to flip y-axis
        plot.img_plot("imagedata", name="surface2d",
                      xbounds=(np.min(x), np.max(x)),
                      ybounds=(1.0, y[-1,-1]),
                      colormap=cmap, hide_grids=True, interpolation='nearest',
                      origin=origin,
                      )
        plot.default_origin = origin
        plot.x_axis.title = u'Angle (2\u0398)'

        tick_font = settings.tick_font
        plot.x_axis.title_font = settings.axis_title_font
        plot.y_axis.title_font = settings.axis_title_font
        plot.x_axis.tick_label_font = tick_font
        plot.y_axis.tick_label_font = tick_font
        plot.y_axis.title = "Dataset"
        plot.y_axis.tick_interval = 1.0
        actual_plot = plot.plots["surface2d"][0]

        self.plot_zoom_tool = ClickUndoZoomTool(
            plot, tool_mode="box", always_on=True, pointer="cross",
            drag_button=settings.zoom_button,
            undo_button=settings.undo_button,
            x_min_zoom_factor=-np.inf, y_min_zoom_factor=-np.inf,
        )
        plot.overlays.append(self.plot_zoom_tool)
        plot.tools.append(TraitsTool(plot))

        # Add a color bar
        colormap = actual_plot.color_mapper
        colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                        color_mapper=colormap,
                        plot=actual_plot,
                        orientation='v',
                        resizable='v',
                        width=30,
                        padding=40,
                        padding_top=50,
                        fill_padding=True)

        colorbar._axis.title_font = settings.axis_title_font
        colorbar._axis.tick_label_font = settings.tick_font
        # Add pan and zoom tools to the colorbar
        self.colorbar_zoom_tool = ClickUndoZoomTool(colorbar,
                                                    axis="index",
                                                    tool_mode="range",
                                                    always_on=True,
                                                    drag_button=settings.zoom_button,
                                                    undo_button=settings.undo_button)
        pan_tool = PanToolWithHistory(colorbar,
                                      history_tool=self.colorbar_zoom_tool,
                                      constrain_direction="y", constrain=True,
                                      drag_button=settings.pan_button)
        colorbar.tools.append(pan_tool)
        colorbar.overlays.append(self.colorbar_zoom_tool)

        # Add a label to the top of the color bar
        colorbar_label = PlotLabel(
            u'Intensity\n{:^9}'.format('(' + get_value_scale_label(scale) + ')'),
            component=colorbar,
            font=settings.axis_title_font,
        )
        colorbar.overlays.append(colorbar_label)
        colorbar.tools.append(TraitsTool(colorbar))

        # Add the plot and colorbar side-by-side
        container = HPlotContainer(use_backbuffer=True)
        container.add(plot)
        container.add(colorbar)
        return container
Beispiel #51
0
def create_plot_component(obj):
    # Setup the spectrum plot
    frequencies = linspace(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 = list(
        obj.spectrum_plot.plots.values())[0][0].value_mapper.range
    spec_range.low = 0.0
    spec_range.high = 5.0
    obj.spectrum_plot.index_axis.title = 'Frequency (hz)'
    obj.spectrum_plot.value_axis.title = 'Amplitude'

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

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

    # Spectrogram plot
    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)
    spectrogram_time = linspace(0.0,
                                float(SPECTROGRAM_LENGTH * NUM_SAMPLES) /
                                float(SAMPLING_RATE),
                                num=SPECTROGRAM_LENGTH)
    spectrogram_freq = linspace(0.0,
                                float(SAMPLING_RATE / 2),
                                num=NUM_SAMPLES / 2)
    xbounds = (spectrogram_time[0], spectrogram_time[-1])
    ybounds = (spectrogram_freq[0], spectrogram_freq[-1])
    spectrogram_plot.img_plot(
        'imagedata',
        name='Spectrogram',
        xbounds=xbounds,
        ybounds=ybounds,
        colormap=viridis,
    )
    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

    return obj.spectrum_plot, obj.time_plot, obj.spectrogram_plot
Beispiel #52
0
 def _forest_plot_default(self):
     plot = Plot(self.plot_data)
     plot.img_plot("forest_image")
     plot.bounds = [0., 2.0]
     return plot
Beispiel #53
0
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
Beispiel #54
0
    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))
Beispiel #55
0
class ImagePlot(HasTraits):

    #create UI interface
    plot = Instance(GridPlotContainer)
    LineScans = Instance(GridPlotContainer)
    value = Str
    saved = Bool(True)
    filedir = Str
    filename = Str
    path = Str
    xLo = Str
    xHi = Str
    yLo = Str
    yHi = Str
    Cmin = Str
    Cmax = Str
    Cmin2 = Str
    Cmax2 = Str
    loaded = False

    Rtrue = Bool(True)
    R2true = Bool(False)
    Fluortrue = Bool(False)
    #Catch variables
    bounds = []
    xLow = []
    yLow = []
    xHigh = []
    yHigh = []

    vscale = None
    notes = Str

    #UI buttons
    reload_button = Button("Reload")
    save_plot_button = Button("Save Plots..")
    save_LineScans_button = Button("Save LineScans..")
    load_button = Button("Load")
    load1_button =Button("Load 1")
    load2_button =Button("Load 2")
    load3_button =Button("Load 3")
    load4_button =Button("Load 4")
    catch_bounds = Button("Catch Bounds")
    to_csv = Button("Generate .CSV")
    scale_set = Button("Set Scale")
    reset = Button("Reset")
    nextfile = Button("Next")
    prevfile = Button("Prev")
    flatten = Button("Flatten")
    readline = Button("LineScan")
    colormap = Button("ApplyColorMap")
    genfilelist = Button("Generate File List")
    out_to_mat = Button("Generate .mat")
    special = Button("Special")

    presmooth = Bool
    plot1button = Bool
    plot2button = Bool
    plot3button = Bool
    plot4button = Bool
    fastline = Str
    slowline = Str

    fastscanline = 0
    slowscanline = 0

    fastline  = str(fastscanline)
    slowline  = str(slowscanline)

    fastlinevar = Str
    fastlinemean = Str
    fastlinemax = Str
    fastlinemin = Str
    slowlinevar = Str
    slowlinemean = Str
    slowlinemax = Str
    slowlinemin = Str

    x_f = Bool(label = "Fast Axis x:")
    y_f = Bool(label = "y:")
    z_f = Bool(label = "z:")
    x_s = Bool(label = "Slow Axis x:")
    y_s = Bool(label = "y:")
    z_s = Bool(label = "z:")
    xbounds=None
    ybounds=None



    #wildcard patterns
    file_wildcard = Str("zis File (*.zis)|*.zis|All files|*")
    file_wildcard2 = Str("png File (*.png)|*.png|All files|*")
    file_wildcard3 = Str("mat File (*.mat)|*.mat|All files|*")
    fastlinevars = Group(   Item('fastlinevar'),
                            Item('fastlinemean'),
                            Item('fastlinemax'),
                            Item('fastlinemin'),show_border=True)
    slowlinevars = Group(   Item('slowlinevar'),
                            Item('slowlinemean'),
                            Item('slowlinemax'),
                            Item('slowlinemin'),show_border=True)
    linescangroup = HGroup(Item('LineScans', editor=ComponentEditor(),show_label=False),
                        VGroup(
                            Item(name="plte", style = 'simple'),
                            HGroup(
                            Item('slowline'),
                            Item('fastline'),),
                            UItem('readline'),
                            fastlinevars,
                            slowlinevars
                            ),label = "LineScan")
    colorgroup = VGroup(HGroup(
                            Item('Cmin',width = -50),
                            Item('Cmax',width = -50),
                            Item('Cmin2',width = -50),
                            Item('Cmax2',width = -50),
                            ),
                        HGroup(
                            UItem('colormap'),
                            UItem('genfilelist'),
                            UItem('out_to_mat'),
                            UItem('special'),
                            ),
                        show_border =True)

    tabs = Group(Item('plot', editor=ComponentEditor(),show_label=False),
                linescangroup,
                Item('notes', style = 'custom', width=.1), layout = "tabbed")
    plta = Enum("R", "Phase", "R0","R/R0","Fluor", "X", "Y")
    pltb = Enum("R", "Phase", "R0","R/R0","Fluor", "X", "Y")
    pltc = Enum("R", "Phase", "R0","R/R0","Fluor", "X", "Y")
    pltd = Enum("R", "Phase", "R0","R/R0","Fluor", "X", "Y")
    plte = Enum("R", "Phase", "R0","R/R0","Fluor", "X", "Y")

    lefttop = Group(
                VGroup(
                    HGroup(
                        Item('value', label = "File", width = 300),
                        Item('presmooth'),
                        ),
                    HGroup(
                        UItem('save_plot_button'),
                        UItem('save_LineScans_button'),
                        UItem('load_button'),
                        UItem('nextfile'),
                        UItem('prevfile'),
                        ),
                    HGroup(
                    Item(name="plta", style = 'simple'),
                    Item(name="pltb", style = 'simple'),
                    Item(name="pltc", style = 'simple'),
                    Item(name="pltd", style = 'simple'),
                    UItem('reload_button'),
                    ),
                    ),
                )

    righttop = Group(
                    VGroup(
                        HGroup(
                            Item('xLo',width = -50, height = 25),
                            Item('xHi',width = -50),
                            Item('yLo',width = -50, height = 25),
                            Item('yHi',width = -50),
                            ),
                        HGroup(
                            UItem('flatten'),
                            UItem('catch_bounds'),
                            UItem('scale_set'),
                        ),
                        HGroup(
                            UItem("load1_button"),
                            UItem("load2_button"),
                            UItem("load3_button"),
                            UItem("load4_button"),
                        ),
                    ),
                show_border = True)

    traits_view = View(
            VGroup(
                    HGroup(
                        lefttop,
                        righttop,
                        colorgroup,
                    ),
                    tabs,
            ),
            width=1200, height=700, resizable=True, title="Scan Image Reconstruction")


    #USED DICTIONARY
    plotA = {"plot": plta, "data" : "", "shape" : "", "range" : np.zeros((2,2))}
    plotB = {"plot": pltb, "data" : "", "shape" : "", "range" : np.zeros((2,2))}
    plotC = {"plot": pltc, "data" : "", "shape" : "", "range" : np.zeros((2,2))}
    plotD = {"plot": pltd, "data" : "", "shape" : "", "range" : np.zeros((2,2))}
    plotE = {"plot": plte, "data" : "", "shape" : "", "range" : np.zeros((2,2))}

    def _Rtrue_changed(self):
        if self.Rtrue:
            self.R2true = False
            self.Fluortrue = False
    def _R2true_changed(self):
        if self.R2true:
            self.Rtrue = False
            self.Fluortrue = False
    def _Fluortrue_changed(self):
        if self.Fluortrue:
            self.Rtrue = False
            self.R2true = False
    def _plot1button_changed(self):
        if self.plot1button:
            self.plot2button = False
            self.plot3button = False
            self.plot4button = False
            self._plot2()
    def _plot2button_changed(self):
        if self.plot2button:
            self.plot1button=False
            self.plot3button = False
            self.plot4button = False
            self._plot2()
    def _plot3button_changed(self):
        if self.plot3button:
            self.plot1button=False
            self.plot2button = False
            self.plot4button = False
            self._plot2()
    def _plot4button_changed(self):
        if self.plot4button:
            self.plot1button=False
            self.plot2button = False
            self.plot3button = False
            self._plot2()

    def _colormap_fired(self):
        self.plot1.color_mapper.range.low = float(self.Cmin)
        self.plot1.color_mapper.range.high = float(self.Cmax)

        self.plot2.color_mapper.range.low = float(self.Cmin2)
        self.plot2.color_mapper.range.high = float(self.Cmax2)

        self.plot4.color_mapper.range.low = float(self.Cmin)
        self.plot4.color_mapper.range.high = float(self.Cmax)

        if self.plot1button or self.plot3button or self.plot4button:
            self.plot1lines.color_mapper.range.low = float(self.Cmin)
            self.plot1lines.color_mapper.range.high = float(self.Cmax)
        if self.plot2button:
            self.plot1lines.color_mapper.range.low = float(self.Cmin2)
            self.plot1lines.color_mapper.range.high = float(self.Cmax2)

        #self._plot()
        print "Color Mapped"
    def _scale_set_fired(self):

        self.plot1.range2d.x_range.low = float(self.xLo)
        self.plot1.range2d.x_range.high = float(self.xHi)
        self.plot1.range2d.y_range.low = float(self.yLo)
        self.plot1.range2d.y_range.high = float(self.yHi)

        self.plot2.range2d.x_range.low = float(self.xLo)
        self.plot2.range2d.x_range.high = float(self.xHi)
        self.plot2.range2d.y_range.low = float(self.yLo)
        self.plot2.range2d.y_range.high = float(self.yHi)

        self.plot3.range2d.x_range.low = float(self.xLo)
        self.plot3.range2d.x_range.high = float(self.xHi)
        self.plot3.range2d.y_range.low = float(self.yLo)
        self.plot3.range2d.y_range.high = float(self.yHi)

        self.plot4.range2d.x_range.low = float(self.xLo)
        self.plot4.range2d.x_range.high = float(self.xHi)
        self.plot4.range2d.y_range.low = float(self.yLo)
        self.plot4.range2d.y_range.high = float(self.yHi)

        self.plot1lines.range2d.x_range.low = float(self.xLo)/self.plotE["range"][0][1]*self.plotE["shape"][0]
        self.plot1lines.range2d.x_range.high = float(self.xHi)/self.plotE["range"][0][1]*self.plotE["shape"][0]
        self.plot1lines.range2d.y_range.low = float(self.yLo)/self.plotE["range"][1][1]*self.plotE["shape"][1]
        self.plot1lines.range2d.y_range.high = float(self.yHi)/self.plotE["range"][1][1]*self.plotE["shape"][1]

        self.slow_plot.range2d.x_range.low = float(self.xLo)
        self.slow_plot.range2d.x_range.high = float(self.xHi)
        self.fast_plot.range2d.x_range.low = float(self.yLo)
        self.fast_plot.range2d.x_range.high = float(self.yHi)


    def _reset_fired(self):
        self.vscale = None
        self.Cmin = ""
        self.Cmax = ""
        self._refresh()
    def _value_changed(self):
        #self.saved = False
        self.value = self.value

    def _refresh(self):
        try: self._plot()
        except: print "Option will be applied when plotting"

    def _readline_fired(self):

        #select which line to scan (this should be input as int value of line number until changed)

        self.fastscanline = int(self.fastline)#float(self.slowline)*float(self.dataset["range"][0][1])/self.dataset["shape"][0])
        self.slowscanline = int(self.slowline)#float(self.fastline)*float(self.dataset["range"][1][1])/self.dataset["shape"][1])

        slowstart = int(float(self.xLo)/float(self.plotE["range"][0][1])*self.plotE["shape"][0])
        slowend = int(float(self.xHi)/float(self.plotE["range"][0][1])*self.plotE["shape"][0]-1)
        faststart = int(float(self.yLo)/float(self.plotE["range"][1][1])*self.plotE["shape"][1])
        fastend = int(float(self.yHi)/float(self.plotE["range"][1][1])*(self.plotE["shape"][1])-1)

        fastarray = np.array(self._image_value.data[:,int(self.slowline)])
        slowarray = np.array(self._image_value.data[int(self.fastline),:])

        self.pd.set_data("line_value2",
                                 self._image_value.data[:,self.fastscanline])
        self.pd.set_data("line_value",
                                 self._image_value.data[self.slowscanline,:])

        self.fastlinevar = str(np.std(fastarray))
        self.fastlinemean = str(np.mean(fastarray))
        self.fastlinemax = str(np.amax(fastarray))
        self.fastlinemin = str(np.amin(fastarray))
        self.slowlinevar = str(np.std(slowarray))
        self.slowlinemean = str(np.mean(slowarray))
        self.slowlinemax = str(np.amax(slowarray))
        self.slowlinemin = str(np.amin(slowarray))

        self.slow_plot.title = "Slowline : " + str(self.fastscanline)
        self.fast_plot.title = "Fastline : " + str(self.fastscanline)


    def _flatten_fired(self):
        self._flatten()

    def _out_to_mat_fired(self):
        dialog = FileDialog(default_filename = self.filename+"_MATLAB_Phase"+str(self.plotA["notes"]["start"][2]), action="save as", wildcard=self.file_wildcard3)
        dialog.open()
        if dialog.return_code == OK:
            savefiledir = dialog.directory
            savefilename = dialog.filename
            path = os.path.join(savefiledir, savefilename)
            dataset = {self.plotA, self.plotB, self.plotC, self.plotD}
            scio.savemat(path, dataset, True)

    def _flatten(self):
        y=0
        x=0
        for line in self.plotA['data']:
            x_axis = np.arange(0,int(len(line)))
            y_axis = np.array(line)
            slope,intercept,r_value,p_value,std_err = stats.linregress(x_axis,y_axis)
            x=0
            for point in line:
                self.plotA['data'][y,x] = point - (slope*x + intercept)
                x+=1
            y+=1

        y=0
        x=0
        for line in self.plotB['data']:
            x_axis = np.arange(0,int(len(line)))
            y_axis = np.array(line)
            slope,intercept,r_value,p_value,std_err = stats.linregress(x_axis,y_axis)
            x=0
            for point in line:
                self.plotB['data'][y,x] = point - (slope*x + intercept)
                x+=1
            y+=1
        y=0
        x=0
        for line in self.plotC['data']:
            x_axis = np.arange(0,int(len(line)))
            y_axis = np.array(line)
            slope,intercept,r_value,p_value,std_err = stats.linregress(x_axis,y_axis)
            x=0
            for point in line:
                self.plotC['data'][y,x] = point - (slope*x + intercept)
                x+=1
            y+=1
        y=0
        x=0
        for line in self.plotD['data']:
            x_axis = np.arange(0,int(len(line)))
            y_axis = np.array(line)
            slope,intercept,r_value,p_value,std_err = stats.linregress(x_axis,y_axis)
            x=0
            for point in line:
                self.plotD['data'][y,x] = point - (slope*x + intercept)
                x+=1
            y+=1
        self._plot()
        print "Flattened"



    def _catch_bounds_fired(self):
        try:
            self.xLow = float(self.plot1.range2d.x_range.low)
            self.xHigh = float(self.plot1.range2d.x_range.high)
            self.yLow = float(self.plot1.range2d.y_range.low)
            self.yHigh = float(self.plot1.range2d.y_range.high)

            self.xLo = str(self.xLow)
            self.xHi = str(self.xHigh)
            self.yLo = str(self.yLow)
            self.yHi = str(self.yHigh)
        except: print "Please plot first"

    def _save_plot_button_fired(self):
        dialog = FileDialog(default_filename = self.filename+"_Plots_", action="save as", wildcard=self.file_wildcard2)
        dialog.open()
        if dialog.return_code == OK:
            savefiledir = dialog.directory
            savefilename = dialog.filename
            path = os.path.join(savefiledir, savefilename)
            #self.plot.do_layout(force=True)
            plot_gc = PlotGraphicsContext(self.plot.outer_bounds)
            plot_gc.render_component(self.plot)
            plot_gc.save(path)

    def _save_LineScans_button_fired(self):
        dialog = FileDialog(default_filename = self.filename+"_LineScan_", action="save as", wildcard=self.file_wildcard2)
        dialog.open()
        if dialog.return_code == OK:
            savefiledir = dialog.directory
            savefilename = dialog.filename
            path = os.path.join(savefiledir, savefilename)
            self.LineScans.do_layout(force=True)
            plot_gc = PlotGraphicsContext(self.LineScans.outer_bounds)
            plot_gc.render_component(self.LineScans)
            plot_gc.save(path)




    def _load_button_fired(self):
        dialog = FileDialog(action="open", wildcard=self.file_wildcard)
        dialog.open()
        if dialog.return_code == OK:
            self.value = dialog.filename
            title = self.value
            self.path = dialog.path
            self.filedir = dialog.directory
            self.allfiles =[]

            for filenames in os.walk(self.filedir):
                for files in filenames:
                    for afile in files:
                        if ".zis" in str(afile):
                            if ".png" not in str(afile)and ".mat" not in str(afile):
                                self.allfiles.append(self.filedir+"\\"+afile)
            self.filename = dialog.filename
            self.saved = True
            self.loaded = True
            self._loader(self.path)
            self._plot()

    def _nextfile_fired(self):
        if self.loaded:
            nextone = False
            path2=self.path
##            self.allfiles =[]
##            for filenames in os.walk(self.filedir):
##                for files in filenames:
##                    for afile in files:
##                        if ".zis" in str(afile):
##                            if ".png" not in str(afile):
##                                self.allfiles.append(self.filedir+"\\"+afile)
            for afile in self.allfiles:
                if nextone == True:
                    self.path = afile
                    junk,self.value = afile.split(self.filedir+"\\")
                    self.filename =self.value
                    self._loader(self.path)
                    self._plot()
                    nextone=False
                    break
                if afile == path2:
                    nextone = True


    def _prevfile_fired(self):
        if self.loaded:
            nextone = False
            path2=self.path
            for afile in self.allfiles:
                if afile == path2:
                    self.path = prevfile
                    junk,self.value = prevfile.split(self.filedir+"\\")
                    self.filename = self.value
                    self._loader(self.path)
                    self._plot()
                    break
                prevfile = afile

    def _genfilelist_fired(self):
        if self.loaded:
            event = {'trial': 0 , "settings" : "", "notes": "", "time": ""}
            eventlist = {"Description": "", "0" : event}
            i=1
            for afile in self.allfiles:
                #grab file name
                junk,currentfilename = afile.split(self.filedir+"\\")
                print "Working on file : " + currentfilename
                #unpickle file and grab data
                try:
                    currentfile = open(afile,'rb')
                    data = pickle.load(currentfile)
                    currentfile.close()

                    foldername,time = currentfilename.split("_")
                    time,junk = time.split(".")
                    settings = data['settings']['scan']
                    strsettings = ""
                    for key, value in settings.iteritems() :
                        strsettings += str(key) + " " + str(value)+ "\n"
                    newtrial = {'trial': i, "settings" : strsettings, "notes": "", "time": time}
                    eventlist[str(i)] = newtrial

                    i +=1
                except:
                    print "\tcorrupt file, skipping"
            settings = ""
            strsettings =""
            newtrial = ""

            #save data to data logger compatible file
            a = os.getcwd() + "/eventlist_"+foldername
            if not os.path.isdir(a):
                print "made"
                os.makedirs(a)
            b = a+ "/filelist.log"
            f1 = open(b, "w")
            pickle.dump(eventlist, f1)
            f1.close()

            print "File Write Complete"
        else:
            print "Please load a folder first"

    def _reload_button_fired(self):
        self._loader(self.path)
        self._plot()
    #-----------------------------------------------
    # Private API
    #-----------------------------------------------

    def _plot(self):
        print "...plotting"
        self.notes = ""
        for key, value in self.plotA["notes"].iteritems() :
            self.notes += str(key) + " " + str(value)+ "\n"

        self.container1 = GridPlotContainer(shape = (2,4), spacing = (0,0), use_backbuffer=True,
	                                     valign = 'top', bgcolor = 'white')

        print"\t assigning data"
        self.plotdata1 = ArrayPlotData(imagedata = self.plotA["data"])
        self.plotdata2 = ArrayPlotData(imagedata = self.plotB["data"])
        self.plotdata3 = ArrayPlotData(imagedata = self.plotC["data"])
        self.plotdata4 = ArrayPlotData(imagedata = self.plotD["data"])



        print"\t calling names"
        self.plot1 = Plot(self.plotdata1, title = self.plotA["plot"]+ str(self.plotA["notes"]["start"]))
        self.plot2 = Plot(self.plotdata2, title = self.plotB["plot"])
        self.plot3 = Plot(self.plotdata3, title = self.plotC["plot"])
        self.plot4 = Plot(self.plotdata4, title = self.plotD["plot"])


        self.plot1.img_plot("imagedata", xbounds = (self.plotA["range"][0][0],self.plotA["range"][0][1]), ybounds = (self.plotA["range"][1][0],self.plotA["range"][1][1]))
        self.plot2.img_plot("imagedata", xbounds = (self.plotB["range"][0][0],self.plotB["range"][0][1]), ybounds = (self.plotB["range"][1][0],self.plotB["range"][1][1]))
        self.plot3.img_plot("imagedata", xbounds = (self.plotC["range"][0][0],self.plotC["range"][0][1]), ybounds = (self.plotC["range"][1][0],self.plotC["range"][1][1]))
        self.plot4.img_plot("imagedata", xbounds = (self.plotD["range"][0][0],self.plotD["range"][0][1]), ybounds = (self.plotD["range"][1][0],self.plotD["range"][1][1]))



#        self.scale = Str(self.plot3.color_mapper.high)
#        plot1.index_axis.title = str(f) + ' (um)'

##ADD TOOLS
        self.plot1.tools.append(PanTool(self.plot1))
        zoom1 = ZoomTool(component=self.plot1, tool_mode="box", always_on=False)
        self.plot1.overlays.append(zoom1)

        self.plot2.tools.append(PanTool(self.plot2))
        zoom2 = ZoomTool(component=self.plot2, tool_mode="box", always_on=False)
        self.plot2.overlays.append(zoom2)

        self.plot3.tools.append(PanTool(self.plot3))
        zoom3 = ZoomTool(component=self.plot3, tool_mode="box", always_on=False)
        self.plot3.overlays.append(zoom3)

        self.plot4.tools.append(PanTool(self.plot4))
        zoom4 = ZoomTool(component=self.plot4, tool_mode="box", always_on=False)
        self.plot4.overlays.append(zoom4)

##ADD COLORBARS
        self.colorbar1 = ColorBar(index_mapper=LinearMapper(range=self.plot1.color_mapper.range),
                        color_mapper=self.plot1.color_mapper,
                        orientation='v',
                        resizable='v',
                        width=20,
                        padding=5)
        self.colorbar1.plot = self.plot1
        self.colorbar1.padding_left = 45
        self.colorbar1.padding_right= 5

        self.colorbar2 = ColorBar(index_mapper=LinearMapper(range=self.plot2.color_mapper.range),
                        color_mapper=self.plot2.color_mapper,
                        orientation='v',
                        resizable='v',
                        width=20,
                        padding=5)
        self.colorbar2.plot = self.plot2
        self.colorbar2.padding_left = 10

        self.colorbar3 = ColorBar(index_mapper=LinearMapper(range=self.plot3.color_mapper.range),
                        color_mapper=self.plot3.color_mapper,
                        orientation='v',
                        resizable='v',
                        width=20,
                        padding=5)
        self.colorbar3.plot = self.plot3
        self.colorbar3.padding_left = 45
        self.colorbar3.padding_right= 5

        self.colorbar4 = ColorBar(index_mapper=LinearMapper(range=self.plot4.color_mapper.range),
                        color_mapper=self.plot4.color_mapper,
                        orientation='v',
                        resizable='v',
                        width=20,
                        padding=5)
        self.colorbar4.plot = self.plot4
        self.colorbar4.padding_left = 15



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

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

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

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


        self.container1.add(self.colorbar1)
        self.container1.add(self.plot1)
        self.container1.add(self.plot2)
        self.container1.add(self.colorbar2)
        self.container1.add(self.colorbar3)
        self.container1.add(self.plot3)
        self.container1.add(self.plot4)
        self.container1.add(self.colorbar4)

        self.plot1.padding_right = 5
        self.plot2.padding_left = 5
        self.plot1.padding_bottom = 15
        self.plot2.padding_bottom = 15
        self.plot3.padding_top = 15
        self.plot4.padding_top = 15
        self.plot1.x_axis.orientation = "top"
        self.plot2.x_axis.orientation = "top"
        self.plot2.y_axis.orientation = "right"
        self.plot3.padding_right = 5
        self.plot4.padding_left = 5
        self.plot4.y_axis.orientation = "right"

        self.colorbar1.padding_top = self.plot1.padding_top
        self.colorbar1.padding_bottom = self.plot1.padding_bottom
        self.colorbar2.padding_top = self.plot2.padding_top
        self.colorbar2.padding_bottom = self.plot2.padding_bottom
        self.colorbar3.padding_top = self.plot3.padding_top
        self.colorbar3.padding_bottom = self.plot3.padding_bottom
        self.colorbar4.padding_top = self.plot4.padding_top
        self.colorbar4.padding_bottom = self.plot4.padding_bottom

        imgtool = ImageInspectorTool(self.plot1)
        self.plot1.tools.append(imgtool)
        overlay = ImageInspectorOverlay(component=self.plot1, image_inspector=imgtool,
                                    bgcolor="white", border_visible=True)
        self.plot1.overlays.append(overlay)

        self.plot = self.container1

        self._plot2()




#######line plots##############################################################################################

    def _plot2(self):

        print"...plotting line scans"
        title = str(self.plotE['plot']) + str(self.plotE["notes"]["start"])
        self.plotdata5 = ArrayPlotData(imagedata = self.plotE['data'])



        self._image_index = GridDataSource(array([]),
                                          array([]),
                                          sort_order=("ascending","ascending"))

        self.xs = linspace(self.plotE["range"][0][0], self.plotE["range"][0][1], self.plotE["shape"][0])
        self.ys = linspace(self.plotE["range"][1][0], self.plotE["range"][1][1], self.plotE["shape"][1])

        self._image_index.set_data(self.xs, self.ys)

        image_index_range = DataRange2D(self._image_index)


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

        s = ""
        f = ""
        if self.x_s: s = "X"
        if self.y_s: s = "Y"
        if self.z_s: s = "Z"
        if self.x_f: f = "X"
        if self.y_f: f = "Y"
        if self.z_f: f = "Z"


        self.plot1lines = Plot(self.plotdata5,  title = title)
        self.plot1lines.img_plot("imagedata", xbounds = (self.plotE["range"][0][0],self.plotE["range"][0][1]), ybounds = (self.plotE["range"][1][0],self.plotE["range"][1][1]), colormap=jet)
        img_plot = self.plot1lines.img_plot("imagedata")[0]
        imgtool = ImageInspectorTool(img_plot)
        img_plot.tools.append(imgtool)
        overlay = ImageInspectorOverlay(component=img_plot, image_inspector=imgtool,
                                    bgcolor="white", border_visible=True)
        self.plot1lines.overlays.append(overlay)
##ADD TOOLS

        self.plot1lines.tools.append(PanTool(self.plot1lines))
        zoom1 = ZoomTool(component=self.plot1lines, tool_mode="box", always_on=False)
        self.plot1lines.overlays.append(zoom1)

        self.plot1lines.overlays.append(LineInspector(component=self.plot1lines,
                                               axis='index_x',
                                               inspect_mode="indexed",
                                               write_metadata=True,
                                               is_listener=False,
                                               #constrain_key="right",
                                               color="white"))
        self.plot1lines.overlays.append(LineInspector(component=self.plot1lines,
                                               axis='index_y',
                                               inspect_mode="indexed",
                                               write_metadata=True,
                                               color="white",
                                               is_listener=False))




##ADD COLORBAR

        self.colorbar5  = ColorBar(index_mapper=LinearMapper(range=self.plot1lines.color_mapper.range),
                        color_mapper=self.plot1lines.color_mapper,
                        orientation='v',
                        resizable='v',
                        width=20,
                        padding=5)
        self.colorbar5.plot = self.plot1lines


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

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



        self.slow_plot = Plot(self.pd,   title = "Slowline : " + self.slowline)
        self.slow_plot.plot(("line_index", "line_value"),
                             line_style='solid')

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

        self.fast_plot = Plot(self.pd,   title = "Fastline : " + self.fastline)
        self.fast_plot.plot(("line_index2", "line_value2"),
                             line_style='solid')


        self.pd.set_data("line_index", self.xs)
        self.pd.set_data("line_index2", self.ys)
        self.pd.set_data("line_value",
                                 self._image_value.data[self.fastscanline,:])
        self.pd.set_data("line_value2",
                                 self._image_value.data[:,self.slowscanline])

        self.colorbar5.padding= 0
        self.colorbar5.padding_left = 15
        #self.colorbar5.height = 400
        self.colorbar5.padding_top =50
        self.colorbar5.padding_bottom = 0
        self.colorbar5.padding_right = 25
        self.colorbar5.padding_left = 50

        self.plot1lines.width = 300
        self.plot1lines.padding_top = 50

        self.plot1lines.index_axis.title = 'fast axis (um)'
        self.plot1lines.value_axis.title = 'slow axis (um)'

        self.slow_plot.width = 100
        self.slow_plot.padding_right = 20

        self.fast_plot.width = 100
        self.fast_plot.padding_right = 20

        self.container2 = GridPlotContainer(shape = (1,2), spacing = ((0,0)), use_backbuffer=True,
	                                     valign = 'top', halign = 'center', bgcolor = 'white')
        self.container3 = GridPlotContainer(shape = (2,1), spacing = (0,0), use_backbuffer=True,
	                                     valign = 'top', halign = 'center', bgcolor = 'grey')
        self.container4 = GridPlotContainer(shape = (1,2), spacing = (0,0), use_backbuffer=True,
	                                     valign = 'top', halign = 'center', bgcolor = 'grey')

        self.container2.add(self.colorbar5)
        self.container3.add(self.fast_plot)
        self.container3.add(self.slow_plot)
        self.container4.add(self.container3)
        self.container4.add(self.plot1lines)
        self.container2.add(self.container4)
        self.LineScans = self.container2

        self._readline_fired()
        self._scale_set_fired()

    def _load_file(self,i):
        file = open(str(i),'rb')
        print "\n\n" + str(i)   + " is open"
        self.data = pickle.load(file)
        file.close()
        print "\nfile.closed"
        return
    #########################################################
    def _special_fired(self):
        #load stitch
        print "All resolutions must be the same"
        a,b = 2,3 #raw_input("\tset rows and cols: ")
        size = 512 #raw_input("\tsize:")
        self.stitchdataA = np.zeros((size*a, size*b))
        self.stitchdataB = np.zeros((size*a, size*b))
        i = 1
        col = 0
        while i < a*b:
            j = 1
            row = 0
            while j < b:
                self._load_file(self._single_load())
                self.plotA['plot'] = self.plta
                self.plotA = self._pick_plots(self.plotA)
                print col*size, row*size
                self.stitchdataA[col*size : col*self.plotA["shape"][0], row*size : row*self.plotA["shape"][1]] = self.plotA
                row = row+1
                j = j+1
                i = i+1
            col = col+1


        i = 1
        col = 0
        while i < a*b:
            j = 1
            row = 0
            while j < b:
                self._load_file(self._single_load())
                self.plotB['plot'] = self.pltb
                self.plotB = self._pick_plots(self.plotB)
                self.stitchdataB[col*size : col*self.plotB["shape"][0], row*size : row*self.plotB["shape"][1]] = self.plotB
                row = row+1
                j = j+1
                i = i+1
            col = col+1

        self.plotA["data"] = self.stitchdataA
        self.plotB["data"] = self.stitchdataB
        self.plotC["data"] = self.stitchdataA
        self.plotD["data"] = self.stitchdataB
        self.plotA["range"][0][0] = 0
        self.plotA["range"][1][0] = 0
        self.plotA["range"][0][1] = size*a
        self.plotA["range"][1][1] = size*b
        self.plotA["shape"] = (size*b, size*a)
        self._plot()

        gc.collect()
        return

    ########################################################

    def _pick_plots(self, plotdata):
        #plotA = Enum("R", "Phase", "R0","R/R0","Fluor", "X", "Y")
        print "...loading plot"
        #gather shape info
        plotdata["notes"] = self.data['settings']['scan']
        print "\t filling shapes"
        for x in xrange(3):
            if plotdata["notes"]['axes'][x] == 0:
                fast = plotdata["notes"]['npoints'][x]
                plotdata["range"][0][1] = plotdata["notes"]["fast_axis_range"]
            if plotdata["notes"]['axes'][x] == 1:
                slow = plotdata["notes"]['npoints'][x]
                plotdata["range"][1][1] = plotdata["notes"]['range'][x]

        plotdata["shape"] =(fast,slow)

        print "\t filling data"
        data =np.zeros((fast,slow))
        try:
            if plotdata['plot']== "R":
                print "\t\tplotting R"
                data = np.sqrt(np.multiply(np.array(self.data['data']['lia_x']["0"]),np.array(self.data['data']['lia_x']["0"])) + np.multiply(np.array(self.data['data']['lia_y']["0"]),np.array(self.data['data']['lia_y']["0"])))
            if plotdata['plot'] == "Phase":
                print "\t\tplotting Phase"
                data = np.arctan2(np.array(self.data['data']['lia_y']["0"]),np.array(self.data['data']['lia_x']["0"]))
            if plotdata['plot']== "R0":
                print "\t\tplotting R0"
                data = np.sqrt(np.multiply(np.array(self.data['data']['lia_x']["3"]),np.array(self.data['data']['lia_x']["3"])) + np.multiply(np.array(self.data['data']['lia_y']["3"]),np.array(self.data['data']['lia_y']["3"])))
            if plotdata['plot']== "R/R0":
                print "\t\tplotting R/R0"
                data = np.sqrt(np.multiply(np.array(self.data['data']['lia_x']["0"]),np.array(self.data['data']['lia_x']["0"])) + np.multiply(np.array(self.data['data']['lia_y']["0"]),np.array(self.data['data']['lia_y']["0"])))/np.sqrt(np.multiply(np.array(self.data['data']['lia_x']["3"]),np.array(self.data['data']['lia_x']["3"])) + np.multiply(np.array(self.data['data']['lia_y']["3"]),np.array(self.data['data']['lia_y']["3"])))
            if plotdata['plot']== "Fluor":
                print "\t\tplotting Fluor"
                data = np.array(self.data['data']['dio2'])
            if plotdata['plot']=="X":
                print "\t\tplotting X"
                data = np.array(self.data['data']['lia_x']["0"])
            if plotdata['plot']=="Y":
                print "\t\tplotting Y"
                data = np.array(self.data['data']['lia_y']["0"])
        except:
            print "Process failed-- check dropdown assignments"

        data.shape = (plotdata["shape"])
        plotdata['data'] = data
        return plotdata

    def _single_load(self):
        dialog = FileDialog(action="open", wildcard=self.file_wildcard)
        dialog.open()
        if dialog.return_code == OK:
            return dialog.path



    def _loader(self, i):
    #open file with specified path unpickle and prepare to pass to dictionary

        self._load_file(i)

      #--APPLY LOGIC CONDITIONS TO DATA AND ASSIGN TO PLOTING 2D ARRAYS

        self.plotA['plot'] = self.plta
        self.plotB['plot'] = self.pltb
        self.plotC['plot'] = self.pltc
        self.plotD['plot'] = self.pltd
        self.plotE['plot'] = self.plte

        self.plotA = self._pick_plots(self.plotA)
        self.plotB = self._pick_plots(self.plotB)
        self.plotC = self._pick_plots(self.plotC)
        self.plotD = self._pick_plots(self.plotD)
        self.plotE = self._pick_plots(self.plotE)


        if self.xLo == "":
            print "...populating ranges"
            self.xLo = str(self.plotA["range"][0][0])
            self.xHi = str(self.plotA["range"][0][1])
            self.yLo = str(self.plotA["range"][1][0])
            self.yHi = str(self.plotA["range"][1][1])

        gc.collect()
        return

    def _load1_button_fired(self):
    #open file with specified path unpickle and prepare to pass to dictionary

        self._load_file(self._single_load())

      #--APPLY LOGIC CONDITIONS TO DATA AND ASSIGN TO PLOTING 2D ARRAYS

        self.plotA['plot'] = self.plta

        self.plotA = self._pick_plots(self.plotA)
        gc.collect()
        self._plot()
        return

    def _load2_button_fired(self):
    #open file with specified path unpickle and prepare to pass to dictionary

        self._load_file(self._single_load())

      #--APPLY LOGIC CONDITIONS TO DATA AND ASSIGN TO PLOTING 2D ARRAYS

        self.plotB['plot'] = self.pltb

        self.plotB = self._pick_plots(self.plotB)
        gc.collect()
        self._plot()
        return

    def _load3_button_fired(self):
    #open file with specified path unpickle and prepare to pass to dictionary

        self._load_file(self._single_load())

      #--APPLY LOGIC CONDITIONS TO DATA AND ASSIGN TO PLOTING 2D ARRAYS

        self.plotC['plot'] = self.pltc

        self.plotC = self._pick_plots(self.plotC)
        gc.collect()
        self._plot()
        return

    def _load4_button_fired(self):
    #open file with specified path unpickle and prepare to pass to dictionary

        self._load_file(self._single_load())

      #--APPLY LOGIC CONDITIONS TO DATA AND ASSIGN TO PLOTING 2D ARRAYS

        self.plotD['plot'] = self.pltd

        self.plotD = self._pick_plots(self.plotD)
        gc.collect()
        self._plot()
        return
Beispiel #56
0
def make_plots(self, n_dfe_taps):
    """ Create the plots used by the PyBERT GUI."""

    post_chnl_str = "Channel"
    post_tx_str = "Channel + Tx Preemphasis"
    post_ctle_str = "Channel + Tx Preemphasis + CTLE (+ AMI DFE)"
    post_dfe_str = "Channel + Tx Preemphasis + CTLE (+ AMI DFE) + PyBERT DFE"

    plotdata = self.plotdata

    # - DFE tab
    plot2 = Plot(plotdata, padding_left=75)
    plot2.plot(("t_ns", "ui_ests"), type="line", color="blue")
    plot2.title = "CDR Adaptation"
    plot2.index_axis.title = "Time (ns)"
    plot2.value_axis.title = "UI (ps)"

    plot9 = Plot(
        plotdata,
        auto_colors=["red", "orange", "yellow", "green", "blue", "purple"],
        padding_left=75,
    )
    for i in range(n_dfe_taps):
        plot9.plot(
            ("tap_weight_index", "tap%d_weights" % (i + 1)),
            type="line",
            color="auto",
            name="tap%d" % (i + 1),
        )
    plot9.title = "DFE Adaptation"
    plot9.tools.append(
        PanTool(plot9,
                constrain=True,
                constrain_key=None,
                constrain_direction="x"))
    zoom9 = ZoomTool(plot9, tool_mode="range", axis="index", always_on=False)
    plot9.overlays.append(zoom9)
    plot9.legend.visible = True
    plot9.legend.align = "ul"

    plot_clk_per_hist = Plot(plotdata, padding_left=75)
    plot_clk_per_hist.plot(("clk_per_hist_bins", "clk_per_hist_vals"),
                           type="line",
                           color="blue")
    plot_clk_per_hist.title = "CDR Clock Period Histogram"
    plot_clk_per_hist.index_axis.title = "Clock Period (ps)"
    plot_clk_per_hist.value_axis.title = "Bin Count"

    plot_clk_per_spec = Plot(plotdata, padding_left=75)
    plot_clk_per_spec.plot(("clk_freqs", "clk_spec"),
                           type="line",
                           color="blue")
    plot_clk_per_spec.title = "CDR Clock Period Spectrum"
    plot_clk_per_spec.index_axis.title = "Frequency (bit rate)"
    plot_clk_per_spec.value_axis.title = "|H(f)| (dB mean)"
    plot_clk_per_spec.value_range.low_setting = -10
    zoom_clk_per_spec = ZoomTool(plot_clk_per_spec,
                                 tool_mode="range",
                                 axis="index",
                                 always_on=False)
    plot_clk_per_spec.overlays.append(zoom_clk_per_spec)

    container_dfe = GridPlotContainer(shape=(2, 2),
                                      spacing=(PLOT_SPACING, PLOT_SPACING))
    container_dfe.add(plot2)
    container_dfe.add(plot9)
    container_dfe.add(plot_clk_per_hist)
    container_dfe.add(plot_clk_per_spec)
    self.plots_dfe = container_dfe
    self._dfe_plot = plot9

    # - EQ Tune tab
    # plot_h_tune = Plot(plotdata, padding_left=75)
    plot_h_tune = Plot(plotdata, padding_bottom=75)
    plot_h_tune.plot(("t_ns_chnl", "ctle_out_h_tune"),
                     type="line",
                     color="blue")
    plot_h_tune.plot(("t_ns_chnl", "clocks_tune"), type="line", color="gray")
    plot_h_tune.title = "Channel + Tx Preemphasis + CTLE (+ AMI DFE) + Ideal DFE"
    plot_h_tune.index_axis.title = "Time (ns)"
    plot_h_tune.y_axis.title = "Pulse Response (V)"
    zoom_tune = ZoomTool(plot_h_tune,
                         tool_mode="range",
                         axis="index",
                         always_on=False)
    plot_h_tune.overlays.append(zoom_tune)
    self.plot_h_tune = plot_h_tune

    # - Impulse Responses tab
    plot_h_chnl = Plot(plotdata, padding_left=75)
    plot_h_chnl.plot(("t_ns_chnl", "chnl_h"),
                     type="line",
                     color="blue",
                     name="Incremental")
    plot_h_chnl.title = post_chnl_str
    plot_h_chnl.index_axis.title = "Time (ns)"
    plot_h_chnl.y_axis.title = "Impulse Response (V/ns)"
    plot_h_chnl.legend.visible = True
    plot_h_chnl.legend.align = "ur"
    zoom_h = ZoomTool(plot_h_chnl,
                      tool_mode="range",
                      axis="index",
                      always_on=False)
    plot_h_chnl.overlays.append(zoom_h)

    plot_h_tx = Plot(plotdata, padding_left=75)
    plot_h_tx.plot(("t_ns_chnl", "tx_out_h"),
                   type="line",
                   color="red",
                   name="Cumulative")
    plot_h_tx.title = post_tx_str
    plot_h_tx.index_axis.title = "Time (ns)"
    plot_h_tx.y_axis.title = "Impulse Response (V/ns)"
    plot_h_tx.legend.visible = True
    plot_h_tx.legend.align = "ur"
    plot_h_tx.index_range = plot_h_chnl.index_range  # Zoom x-axes in tandem.

    plot_h_ctle = Plot(plotdata, padding_left=75)
    plot_h_ctle.plot(("t_ns_chnl", "ctle_out_h"),
                     type="line",
                     color="red",
                     name="Cumulative")
    plot_h_ctle.title = post_ctle_str
    plot_h_ctle.index_axis.title = "Time (ns)"
    plot_h_ctle.y_axis.title = "Impulse Response (V/ns)"
    plot_h_ctle.legend.visible = True
    plot_h_ctle.legend.align = "ur"
    plot_h_ctle.index_range = plot_h_chnl.index_range  # Zoom x-axes in tandem.

    plot_h_dfe = Plot(plotdata, padding_left=75)
    plot_h_dfe.plot(("t_ns_chnl", "dfe_out_h"),
                    type="line",
                    color="red",
                    name="Cumulative")
    plot_h_dfe.title = post_dfe_str
    plot_h_dfe.index_axis.title = "Time (ns)"
    plot_h_dfe.y_axis.title = "Impulse Response (V/ns)"
    plot_h_dfe.legend.visible = True
    plot_h_dfe.legend.align = "ur"
    plot_h_dfe.index_range = plot_h_chnl.index_range  # Zoom x-axes in tandem.

    container_h = GridPlotContainer(shape=(2, 2),
                                    spacing=(PLOT_SPACING, PLOT_SPACING))
    container_h.add(plot_h_chnl)
    container_h.add(plot_h_tx)
    container_h.add(plot_h_ctle)
    container_h.add(plot_h_dfe)
    self.plots_h = container_h

    # - Step Responses tab
    plot_s_chnl = Plot(plotdata, padding_left=75)
    plot_s_chnl.plot(("t_ns_chnl", "chnl_s"),
                     type="line",
                     color="blue",
                     name="Incremental")
    plot_s_chnl.title = post_chnl_str
    plot_s_chnl.index_axis.title = "Time (ns)"
    plot_s_chnl.y_axis.title = "Step Response (V)"
    plot_s_chnl.legend.visible = True
    plot_s_chnl.legend.align = "lr"
    zoom_s = ZoomTool(plot_s_chnl,
                      tool_mode="range",
                      axis="index",
                      always_on=False)
    plot_s_chnl.overlays.append(zoom_s)

    plot_s_tx = Plot(plotdata, padding_left=75)
    plot_s_tx.plot(("t_ns_chnl", "tx_s"),
                   type="line",
                   color="blue",
                   name="Incremental")
    plot_s_tx.plot(("t_ns_chnl", "tx_out_s"),
                   type="line",
                   color="red",
                   name="Cumulative")
    plot_s_tx.title = post_tx_str
    plot_s_tx.index_axis.title = "Time (ns)"
    plot_s_tx.y_axis.title = "Step Response (V)"
    plot_s_tx.legend.visible = True
    plot_s_tx.legend.align = "lr"
    plot_s_tx.index_range = plot_s_chnl.index_range  # Zoom x-axes in tandem.

    plot_s_ctle = Plot(plotdata, padding_left=75)
    plot_s_ctle.plot(("t_ns_chnl", "ctle_s"),
                     type="line",
                     color="blue",
                     name="Incremental")
    plot_s_ctle.plot(("t_ns_chnl", "ctle_out_s"),
                     type="line",
                     color="red",
                     name="Cumulative")
    plot_s_ctle.title = post_ctle_str
    plot_s_ctle.index_axis.title = "Time (ns)"
    plot_s_ctle.y_axis.title = "Step Response (V)"
    plot_s_ctle.legend.visible = True
    plot_s_ctle.legend.align = "lr"
    plot_s_ctle.index_range = plot_s_chnl.index_range  # Zoom x-axes in tandem.

    plot_s_dfe = Plot(plotdata, padding_left=75)
    plot_s_dfe.plot(("t_ns_chnl", "dfe_s"),
                    type="line",
                    color="blue",
                    name="Incremental")
    plot_s_dfe.plot(("t_ns_chnl", "dfe_out_s"),
                    type="line",
                    color="red",
                    name="Cumulative")
    plot_s_dfe.title = post_dfe_str
    plot_s_dfe.index_axis.title = "Time (ns)"
    plot_s_dfe.y_axis.title = "Step Response (V)"
    plot_s_dfe.legend.visible = True
    plot_s_dfe.legend.align = "lr"
    plot_s_dfe.index_range = plot_s_chnl.index_range  # Zoom x-axes in tandem.

    container_s = GridPlotContainer(shape=(2, 2),
                                    spacing=(PLOT_SPACING, PLOT_SPACING))
    container_s.add(plot_s_chnl)
    container_s.add(plot_s_tx)
    container_s.add(plot_s_ctle)
    container_s.add(plot_s_dfe)
    self.plots_s = container_s

    # - Pulse Responses tab
    plot_p_chnl = Plot(plotdata, padding_left=75)
    plot_p_chnl.plot(("t_ns_chnl", "chnl_p"),
                     type="line",
                     color="blue",
                     name="Incremental")
    plot_p_chnl.title = post_chnl_str
    plot_p_chnl.index_axis.title = "Time (ns)"
    plot_p_chnl.y_axis.title = "Pulse Response (V)"
    plot_p_chnl.legend.visible = True
    plot_p_chnl.legend.align = "ur"
    zoom_p = ZoomTool(plot_p_chnl,
                      tool_mode="range",
                      axis="index",
                      always_on=False)
    plot_p_chnl.overlays.append(zoom_p)

    plot_p_tx = Plot(plotdata, padding_left=75)
    plot_p_tx.plot(("t_ns_chnl", "tx_out_p"),
                   type="line",
                   color="red",
                   name="Cumulative")
    plot_p_tx.title = post_tx_str
    plot_p_tx.index_axis.title = "Time (ns)"
    plot_p_tx.y_axis.title = "Pulse Response (V)"
    plot_p_tx.legend.visible = True
    plot_p_tx.legend.align = "ur"
    plot_p_tx.index_range = plot_p_chnl.index_range  # Zoom x-axes in tandem.

    plot_p_ctle = Plot(plotdata, padding_left=75)
    plot_p_ctle.plot(("t_ns_chnl", "ctle_out_p"),
                     type="line",
                     color="red",
                     name="Cumulative")
    plot_p_ctle.title = post_ctle_str
    plot_p_ctle.index_axis.title = "Time (ns)"
    plot_p_ctle.y_axis.title = "Pulse Response (V)"
    plot_p_ctle.legend.visible = True
    plot_p_ctle.legend.align = "ur"
    plot_p_ctle.index_range = plot_p_chnl.index_range  # Zoom x-axes in tandem.

    plot_p_dfe = Plot(plotdata, padding_left=75)
    plot_p_dfe.plot(("t_ns_chnl", "dfe_out_p"),
                    type="line",
                    color="red",
                    name="Cumulative")
    plot_p_dfe.title = post_dfe_str
    plot_p_dfe.index_axis.title = "Time (ns)"
    plot_p_dfe.y_axis.title = "Pulse Response (V)"
    plot_p_dfe.legend.visible = True
    plot_p_dfe.legend.align = "ur"
    plot_p_dfe.index_range = plot_p_chnl.index_range  # Zoom x-axes in tandem.

    container_p = GridPlotContainer(shape=(2, 2),
                                    spacing=(PLOT_SPACING, PLOT_SPACING))
    container_p.add(plot_p_chnl)
    container_p.add(plot_p_tx)
    container_p.add(plot_p_ctle)
    container_p.add(plot_p_dfe)
    self.plots_p = container_p

    # - Frequency Responses tab
    plot_H_chnl = Plot(plotdata, padding_left=75)
    plot_H_chnl.plot(("f_GHz", "chnl_H"),
                     type="line",
                     color="blue",
                     name="Original Impulse",
                     index_scale="log")
    plot_H_chnl.plot(("f_GHz", "chnl_trimmed_H"),
                     type="line",
                     color="red",
                     name="Trimmed Impulse",
                     index_scale="log")
    plot_H_chnl.title = post_chnl_str
    plot_H_chnl.index_axis.title = "Frequency (GHz)"
    plot_H_chnl.y_axis.title = "Frequency Response (dB)"
    plot_H_chnl.index_range.low_setting = 0.01
    plot_H_chnl.index_range.high_setting = 40.0
    plot_H_chnl.legend.visible = True
    plot_H_chnl.legend.align = "ll"

    plot_H_tx = Plot(plotdata, padding_left=75)
    plot_H_tx.plot(("f_GHz", "tx_H"),
                   type="line",
                   color="blue",
                   name="Incremental",
                   index_scale="log")
    plot_H_tx.plot(("f_GHz", "tx_out_H"),
                   type="line",
                   color="red",
                   name="Cumulative",
                   index_scale="log")
    plot_H_tx.title = post_tx_str
    plot_H_tx.index_axis.title = "Frequency (GHz)"
    plot_H_tx.y_axis.title = "Frequency Response (dB)"
    plot_H_tx.index_range.low_setting = 0.01
    plot_H_tx.index_range.high_setting = 40.0
    plot_H_tx.legend.visible = True
    plot_H_tx.legend.align = "ll"

    plot_H_ctle = Plot(plotdata, padding_left=75)
    plot_H_ctle.plot(("f_GHz", "ctle_H"),
                     type="line",
                     color="blue",
                     name="Incremental",
                     index_scale="log")
    plot_H_ctle.plot(("f_GHz", "ctle_out_H"),
                     type="line",
                     color="red",
                     name="Cumulative",
                     index_scale="log")
    plot_H_ctle.title = post_ctle_str
    plot_H_ctle.index_axis.title = "Frequency (GHz)"
    plot_H_ctle.y_axis.title = "Frequency Response (dB)"
    plot_H_ctle.index_range.low_setting = 0.01
    plot_H_ctle.index_range.high_setting = 40.0
    plot_H_ctle.value_range.low_setting = -40.0
    plot_H_ctle.legend.visible = True
    plot_H_ctle.legend.align = "ll"

    plot_H_chnl.value_range = plot_H_ctle.value_range
    plot_H_tx.value_range = plot_H_ctle.value_range

    plot_H_dfe = Plot(plotdata, padding_left=75)
    plot_H_dfe.plot(("f_GHz", "dfe_H"),
                    type="line",
                    color="blue",
                    name="Incremental",
                    index_scale="log")
    plot_H_dfe.plot(("f_GHz", "dfe_out_H"),
                    type="line",
                    color="red",
                    name="Cumulative",
                    index_scale="log")
    plot_H_dfe.title = post_dfe_str
    plot_H_dfe.index_axis.title = "Frequency (GHz)"
    plot_H_dfe.y_axis.title = "Frequency Response (dB)"
    plot_H_dfe.index_range.low_setting = 0.01
    plot_H_dfe.index_range.high_setting = 40.0
    plot_H_dfe.value_range = plot_H_ctle.value_range
    plot_H_dfe.legend.visible = True
    plot_H_dfe.legend.align = "ll"

    container_H = GridPlotContainer(shape=(2, 2),
                                    spacing=(PLOT_SPACING, PLOT_SPACING))
    container_H.add(plot_H_chnl)
    container_H.add(plot_H_tx)
    container_H.add(plot_H_ctle)
    container_H.add(plot_H_dfe)
    self.plots_H = container_H

    # - Outputs tab
    plot_out_chnl = Plot(plotdata, padding_left=75)
    # plot_out_chnl.plot(("t_ns", "ideal_signal"), type="line", color="lightgrey")
    plot_out_chnl.plot(("t_ns", "chnl_out"), type="line", color="blue")
    plot_out_chnl.title = post_chnl_str
    plot_out_chnl.index_axis.title = "Time (ns)"
    plot_out_chnl.y_axis.title = "Output (V)"
    plot_out_chnl.tools.append(
        PanTool(plot_out_chnl,
                constrain=True,
                constrain_key=None,
                constrain_direction="x"))
    zoom_out_chnl = ZoomTool(plot_out_chnl,
                             tool_mode="range",
                             axis="index",
                             always_on=False)
    plot_out_chnl.overlays.append(zoom_out_chnl)

    plot_out_tx = Plot(plotdata, padding_left=75)
    plot_out_tx.plot(("t_ns", "tx_out"), type="line", color="blue")
    plot_out_tx.title = post_tx_str
    plot_out_tx.index_axis.title = "Time (ns)"
    plot_out_tx.y_axis.title = "Output (V)"
    plot_out_tx.index_range = plot_out_chnl.index_range  # Zoom x-axes in tandem.

    plot_out_ctle = Plot(plotdata, padding_left=75)
    plot_out_ctle.plot(("t_ns", "ctle_out"), type="line", color="blue")
    plot_out_ctle.title = post_ctle_str
    plot_out_ctle.index_axis.title = "Time (ns)"
    plot_out_ctle.y_axis.title = "Output (V)"
    plot_out_ctle.index_range = plot_out_chnl.index_range  # Zoom x-axes in tandem.

    plot_out_dfe = Plot(plotdata, padding_left=75)
    plot_out_dfe.plot(("t_ns", "dfe_out"), type="line", color="blue")
    plot_out_dfe.title = post_dfe_str
    plot_out_dfe.index_axis.title = "Time (ns)"
    plot_out_dfe.y_axis.title = "Output (V)"
    plot_out_dfe.index_range = plot_out_chnl.index_range  # Zoom x-axes in tandem.

    container_out = GridPlotContainer(shape=(2, 2),
                                      spacing=(PLOT_SPACING, PLOT_SPACING))
    container_out.add(plot_out_chnl)
    container_out.add(plot_out_tx)
    container_out.add(plot_out_ctle)
    container_out.add(plot_out_dfe)
    self.plots_out = container_out

    # - Eye Diagrams tab
    seg_map = dict(
        red=[
            (0.00, 0.00, 0.00),  # black
            (0.00001, 0.00, 0.00),  # blue
            (0.15, 0.00, 0.00),  # cyan
            (0.30, 0.00, 0.00),  # green
            (0.45, 1.00, 1.00),  # yellow
            (0.60, 1.00, 1.00),  # orange
            (0.75, 1.00, 1.00),  # red
            (0.90, 1.00, 1.00),  # pink
            (1.00, 1.00, 1.00),  # white
        ],
        green=[
            (0.00, 0.00, 0.00),  # black
            (0.00001, 0.00, 0.00),  # blue
            (0.15, 0.50, 0.50),  # cyan
            (0.30, 0.50, 0.50),  # green
            (0.45, 1.00, 1.00),  # yellow
            (0.60, 0.50, 0.50),  # orange
            (0.75, 0.00, 0.00),  # red
            (0.90, 0.50, 0.50),  # pink
            (1.00, 1.00, 1.00),  # white
        ],
        blue=[
            (0.00, 0.00, 0.00),  # black
            (1e-18, 0.50, 0.50),  # blue
            (0.15, 0.50, 0.50),  # cyan
            (0.30, 0.00, 0.00),  # green
            (0.45, 0.00, 0.00),  # yellow
            (0.60, 0.00, 0.00),  # orange
            (0.75, 0.00, 0.00),  # red
            (0.90, 0.50, 0.50),  # pink
            (1.00, 1.00, 1.00),  # white
        ],
    )
    clr_map = ColorMapper.from_segment_map(seg_map)
    self.clr_map = clr_map

    plot_eye_chnl = Plot(plotdata, padding_left=75)
    plot_eye_chnl.img_plot("eye_chnl", colormap=clr_map)
    plot_eye_chnl.y_direction = "normal"
    plot_eye_chnl.components[0].y_direction = "normal"
    plot_eye_chnl.title = post_chnl_str
    plot_eye_chnl.x_axis.title = "Time (ps)"
    plot_eye_chnl.x_axis.orientation = "bottom"
    plot_eye_chnl.y_axis.title = "Signal Level (V)"
    plot_eye_chnl.x_grid.visible = True
    plot_eye_chnl.y_grid.visible = True
    plot_eye_chnl.x_grid.line_color = "gray"
    plot_eye_chnl.y_grid.line_color = "gray"

    plot_eye_tx = Plot(plotdata, padding_left=75)
    plot_eye_tx.img_plot("eye_tx", colormap=clr_map)
    plot_eye_tx.y_direction = "normal"
    plot_eye_tx.components[0].y_direction = "normal"
    plot_eye_tx.title = post_tx_str
    plot_eye_tx.x_axis.title = "Time (ps)"
    plot_eye_tx.x_axis.orientation = "bottom"
    plot_eye_tx.y_axis.title = "Signal Level (V)"
    plot_eye_tx.x_grid.visible = True
    plot_eye_tx.y_grid.visible = True
    plot_eye_tx.x_grid.line_color = "gray"
    plot_eye_tx.y_grid.line_color = "gray"

    plot_eye_ctle = Plot(plotdata, padding_left=75)
    plot_eye_ctle.img_plot("eye_ctle", colormap=clr_map)
    plot_eye_ctle.y_direction = "normal"
    plot_eye_ctle.components[0].y_direction = "normal"
    plot_eye_ctle.title = post_ctle_str
    plot_eye_ctle.x_axis.title = "Time (ps)"
    plot_eye_ctle.x_axis.orientation = "bottom"
    plot_eye_ctle.y_axis.title = "Signal Level (V)"
    plot_eye_ctle.x_grid.visible = True
    plot_eye_ctle.y_grid.visible = True
    plot_eye_ctle.x_grid.line_color = "gray"
    plot_eye_ctle.y_grid.line_color = "gray"

    plot_eye_dfe = Plot(plotdata, padding_left=75)
    plot_eye_dfe.img_plot("eye_dfe", colormap=clr_map)
    plot_eye_dfe.y_direction = "normal"
    plot_eye_dfe.components[0].y_direction = "normal"
    plot_eye_dfe.title = post_dfe_str
    plot_eye_dfe.x_axis.title = "Time (ps)"
    plot_eye_dfe.x_axis.orientation = "bottom"
    plot_eye_dfe.y_axis.title = "Signal Level (V)"
    plot_eye_dfe.x_grid.visible = True
    plot_eye_dfe.y_grid.visible = True
    plot_eye_dfe.x_grid.line_color = "gray"
    plot_eye_dfe.y_grid.line_color = "gray"

    container_eye = GridPlotContainer(shape=(2, 2),
                                      spacing=(PLOT_SPACING, PLOT_SPACING))
    container_eye.add(plot_eye_chnl)
    container_eye.add(plot_eye_tx)
    container_eye.add(plot_eye_ctle)
    container_eye.add(plot_eye_dfe)
    self.plots_eye = container_eye

    # - Jitter Distributions tab
    plot_jitter_dist_chnl = Plot(plotdata, padding_left=75)
    plot_jitter_dist_chnl.plot(("jitter_bins", "jitter_chnl"),
                               type="line",
                               color="blue",
                               name="Measured")
    plot_jitter_dist_chnl.plot(("jitter_bins", "jitter_ext_chnl"),
                               type="line",
                               color="red",
                               name="Extrapolated")
    plot_jitter_dist_chnl.title = post_chnl_str
    plot_jitter_dist_chnl.index_axis.title = "Time (ps)"
    plot_jitter_dist_chnl.value_axis.title = "Count"
    plot_jitter_dist_chnl.legend.visible = True
    plot_jitter_dist_chnl.legend.align = "ur"

    plot_jitter_dist_tx = Plot(plotdata, padding_left=75)
    plot_jitter_dist_tx.plot(("jitter_bins", "jitter_tx"),
                             type="line",
                             color="blue",
                             name="Measured")
    plot_jitter_dist_tx.plot(("jitter_bins", "jitter_ext_tx"),
                             type="line",
                             color="red",
                             name="Extrapolated")
    plot_jitter_dist_tx.title = post_tx_str
    plot_jitter_dist_tx.index_axis.title = "Time (ps)"
    plot_jitter_dist_tx.value_axis.title = "Count"
    plot_jitter_dist_tx.legend.visible = True
    plot_jitter_dist_tx.legend.align = "ur"

    plot_jitter_dist_ctle = Plot(plotdata, padding_left=75)
    plot_jitter_dist_ctle.plot(("jitter_bins", "jitter_ctle"),
                               type="line",
                               color="blue",
                               name="Measured")
    plot_jitter_dist_ctle.plot(("jitter_bins", "jitter_ext_ctle"),
                               type="line",
                               color="red",
                               name="Extrapolated")
    plot_jitter_dist_ctle.title = post_ctle_str
    plot_jitter_dist_ctle.index_axis.title = "Time (ps)"
    plot_jitter_dist_ctle.value_axis.title = "Count"
    plot_jitter_dist_ctle.legend.visible = True
    plot_jitter_dist_ctle.legend.align = "ur"

    plot_jitter_dist_dfe = Plot(plotdata, padding_left=75)
    plot_jitter_dist_dfe.plot(("jitter_bins", "jitter_dfe"),
                              type="line",
                              color="blue",
                              name="Measured")
    plot_jitter_dist_dfe.plot(("jitter_bins", "jitter_ext_dfe"),
                              type="line",
                              color="red",
                              name="Extrapolated")
    plot_jitter_dist_dfe.title = post_dfe_str
    plot_jitter_dist_dfe.index_axis.title = "Time (ps)"
    plot_jitter_dist_dfe.value_axis.title = "Count"
    plot_jitter_dist_dfe.legend.visible = True
    plot_jitter_dist_dfe.legend.align = "ur"

    container_jitter_dist = GridPlotContainer(shape=(2, 2),
                                              spacing=(PLOT_SPACING,
                                                       PLOT_SPACING))
    container_jitter_dist.add(plot_jitter_dist_chnl)
    container_jitter_dist.add(plot_jitter_dist_tx)
    container_jitter_dist.add(plot_jitter_dist_ctle)
    container_jitter_dist.add(plot_jitter_dist_dfe)
    self.plots_jitter_dist = container_jitter_dist

    # - Jitter Spectrums tab
    plot_jitter_spec_chnl = Plot(plotdata)
    plot_jitter_spec_chnl.plot(("f_MHz", "jitter_spectrum_chnl"),
                               type="line",
                               color="blue",
                               name="Total")
    plot_jitter_spec_chnl.plot(("f_MHz", "jitter_ind_spectrum_chnl"),
                               type="line",
                               color="red",
                               name="Data Independent")
    plot_jitter_spec_chnl.plot(("f_MHz", "thresh_chnl"),
                               type="line",
                               color="magenta",
                               name="Pj Threshold")
    plot_jitter_spec_chnl.title = post_chnl_str
    plot_jitter_spec_chnl.index_axis.title = "Frequency (MHz)"
    plot_jitter_spec_chnl.value_axis.title = "|FFT(TIE)| (dBui)"
    plot_jitter_spec_chnl.tools.append(
        PanTool(plot_jitter_spec_chnl,
                constrain=True,
                constrain_key=None,
                constrain_direction="x"))
    zoom_jitter_spec_chnl = ZoomTool(plot_jitter_spec_chnl,
                                     tool_mode="range",
                                     axis="index",
                                     always_on=False)
    plot_jitter_spec_chnl.overlays.append(zoom_jitter_spec_chnl)
    plot_jitter_spec_chnl.legend.visible = True
    plot_jitter_spec_chnl.legend.align = "lr"

    plot_jitter_spec_tx = Plot(plotdata)
    plot_jitter_spec_tx.plot(("f_MHz", "jitter_spectrum_tx"),
                             type="line",
                             color="blue",
                             name="Total")
    plot_jitter_spec_tx.plot(("f_MHz", "jitter_ind_spectrum_tx"),
                             type="line",
                             color="red",
                             name="Data Independent")
    plot_jitter_spec_tx.plot(("f_MHz", "thresh_tx"),
                             type="line",
                             color="magenta",
                             name="Pj Threshold")
    plot_jitter_spec_tx.title = post_tx_str
    plot_jitter_spec_tx.index_axis.title = "Frequency (MHz)"
    plot_jitter_spec_tx.value_axis.title = "|FFT(TIE)| (dBui)"
    plot_jitter_spec_tx.value_range.low_setting = -40.0
    plot_jitter_spec_tx.index_range = plot_jitter_spec_chnl.index_range  # Zoom x-axes in tandem.
    plot_jitter_spec_tx.legend.visible = True
    plot_jitter_spec_tx.legend.align = "lr"

    plot_jitter_spec_chnl.value_range = plot_jitter_spec_tx.value_range

    plot_jitter_spec_ctle = Plot(plotdata)
    plot_jitter_spec_ctle.plot(("f_MHz", "jitter_spectrum_ctle"),
                               type="line",
                               color="blue",
                               name="Total")
    plot_jitter_spec_ctle.plot(("f_MHz", "jitter_ind_spectrum_ctle"),
                               type="line",
                               color="red",
                               name="Data Independent")
    plot_jitter_spec_ctle.plot(("f_MHz", "thresh_ctle"),
                               type="line",
                               color="magenta",
                               name="Pj Threshold")
    plot_jitter_spec_ctle.title = post_ctle_str
    plot_jitter_spec_ctle.index_axis.title = "Frequency (MHz)"
    plot_jitter_spec_ctle.value_axis.title = "|FFT(TIE)| (dBui)"
    plot_jitter_spec_ctle.index_range = plot_jitter_spec_chnl.index_range  # Zoom x-axes in tandem.
    plot_jitter_spec_ctle.legend.visible = True
    plot_jitter_spec_ctle.legend.align = "lr"
    plot_jitter_spec_ctle.value_range = plot_jitter_spec_tx.value_range

    plot_jitter_spec_dfe = Plot(plotdata)
    plot_jitter_spec_dfe.plot(("f_MHz_dfe", "jitter_spectrum_dfe"),
                              type="line",
                              color="blue",
                              name="Total")
    plot_jitter_spec_dfe.plot(("f_MHz_dfe", "jitter_ind_spectrum_dfe"),
                              type="line",
                              color="red",
                              name="Data Independent")
    plot_jitter_spec_dfe.plot(("f_MHz_dfe", "thresh_dfe"),
                              type="line",
                              color="magenta",
                              name="Pj Threshold")
    plot_jitter_spec_dfe.title = post_dfe_str
    plot_jitter_spec_dfe.index_axis.title = "Frequency (MHz)"
    plot_jitter_spec_dfe.value_axis.title = "|FFT(TIE)| (dBui)"
    plot_jitter_spec_dfe.index_range = plot_jitter_spec_chnl.index_range  # Zoom x-axes in tandem.
    plot_jitter_spec_dfe.legend.visible = True
    plot_jitter_spec_dfe.legend.align = "lr"
    plot_jitter_spec_dfe.value_range = plot_jitter_spec_tx.value_range

    container_jitter_spec = GridPlotContainer(shape=(2, 2),
                                              spacing=(PLOT_SPACING,
                                                       PLOT_SPACING))
    container_jitter_spec.add(plot_jitter_spec_chnl)
    container_jitter_spec.add(plot_jitter_spec_tx)
    container_jitter_spec.add(plot_jitter_spec_ctle)
    container_jitter_spec.add(plot_jitter_spec_dfe)
    self.plots_jitter_spec = container_jitter_spec

    # - Bathtub Curves tab
    plot_bathtub_chnl = Plot(plotdata)
    plot_bathtub_chnl.plot(("jitter_bins", "bathtub_chnl"),
                           type="line",
                           color="blue")
    plot_bathtub_chnl.value_range.high_setting = 0
    plot_bathtub_chnl.value_range.low_setting = -18
    plot_bathtub_chnl.value_axis.tick_interval = 3
    plot_bathtub_chnl.title = post_chnl_str
    plot_bathtub_chnl.index_axis.title = "Time (ps)"
    plot_bathtub_chnl.value_axis.title = "Log10(P(Transition occurs inside.))"

    plot_bathtub_tx = Plot(plotdata)
    plot_bathtub_tx.plot(("jitter_bins", "bathtub_tx"),
                         type="line",
                         color="blue")
    plot_bathtub_tx.value_range.high_setting = 0
    plot_bathtub_tx.value_range.low_setting = -18
    plot_bathtub_tx.value_axis.tick_interval = 3
    plot_bathtub_tx.title = post_tx_str
    plot_bathtub_tx.index_axis.title = "Time (ps)"
    plot_bathtub_tx.value_axis.title = "Log10(P(Transition occurs inside.))"

    plot_bathtub_ctle = Plot(plotdata)
    plot_bathtub_ctle.plot(("jitter_bins", "bathtub_ctle"),
                           type="line",
                           color="blue")
    plot_bathtub_ctle.value_range.high_setting = 0
    plot_bathtub_ctle.value_range.low_setting = -18
    plot_bathtub_ctle.value_axis.tick_interval = 3
    plot_bathtub_ctle.title = post_ctle_str
    plot_bathtub_ctle.index_axis.title = "Time (ps)"
    plot_bathtub_ctle.value_axis.title = "Log10(P(Transition occurs inside.))"

    plot_bathtub_dfe = Plot(plotdata)
    plot_bathtub_dfe.plot(("jitter_bins", "bathtub_dfe"),
                          type="line",
                          color="blue")
    plot_bathtub_dfe.value_range.high_setting = 0
    plot_bathtub_dfe.value_range.low_setting = -18
    plot_bathtub_dfe.value_axis.tick_interval = 3
    plot_bathtub_dfe.title = post_dfe_str
    plot_bathtub_dfe.index_axis.title = "Time (ps)"
    plot_bathtub_dfe.value_axis.title = "Log10(P(Transition occurs inside.))"

    container_bathtub = GridPlotContainer(shape=(2, 2),
                                          spacing=(PLOT_SPACING, PLOT_SPACING))
    container_bathtub.add(plot_bathtub_chnl)
    container_bathtub.add(plot_bathtub_tx)
    container_bathtub.add(plot_bathtub_ctle)
    container_bathtub.add(plot_bathtub_dfe)
    self.plots_bathtub = container_bathtub

    update_eyes(self)
Beispiel #57
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=.5)
    obj.time_plot.plot(("time", "amplitude_1"),
                       name="Time",
                       color="red",
                       alpha=.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()  #spawn a traits window
    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
Beispiel #58
0
def make_plots(self, n_dfe_taps):
    """ Create the plots used by the PyBERT GUI."""

    plotdata = self.plotdata

    # - DFE tab
    plot1 = Plot(plotdata)
    plot1.plot(("t_ns", "dfe_out"), type="line", color="blue")
    plot1.plot(("t_ns", "clocks"), type="line", color="green")
    plot1.plot(("t_ns", "lockeds"), type="line", color="red")
    plot1.title  = "DFE Output, Recovered Clocks, & Locked"
    plot1.index_axis.title = "Time (ns)"
    plot1.tools.append(PanTool(plot1, constrain=True, constrain_key=None, constrain_direction='x'))
    zoom1 = ZoomTool(plot1, tool_mode="range", axis='index', always_on=False)
    plot1.overlays.append(zoom1)

    plot2        = Plot(plotdata)
    plot2.plot(("t_ns", "ui_ests"), type="line", color="blue")
    plot2.title  = "CDR Adaptation"
    plot2.index_axis.title = "Time (ns)"
    plot2.value_axis.title = "UI (ps)"
    plot2.index_range = plot1.index_range # Zoom x-axes in tandem.

    plot3        = Plot(plotdata)
    plot3.plot(('f_MHz_dfe', 'jitter_rejection_ratio'), type="line", color="blue")
    plot3.title  = "CDR/DFE Jitter Rejection Ratio"
    plot3.index_axis.title = "Frequency (MHz)"
    plot3.value_axis.title = "Ratio (dB)"
    zoom3 = ZoomTool(plot3, tool_mode="range", axis='index', always_on=False)
    plot3.overlays.append(zoom3)

    plot4        = Plot(plotdata)
    plot4.plot(('auto_corr'), type="line", color="blue")
    plot4.title  = "Received to Transmitted Bits Correlation"
    plot4.index_axis.title = "Offset (bits)"
    plot4.value_axis.title = "Correlation"
    plot4.value_range.high_setting = 1
    plot4.value_range.low_setting  = 0
    zoom4 = ZoomTool(plot4, tool_mode="range", axis='index', always_on=False)
    plot4.overlays.append(zoom4)

    plot9 = Plot(plotdata, auto_colors=['red', 'orange', 'yellow', 'green', 'blue', 'purple'])
    for i in range(n_dfe_taps):
        plot9.plot(("tap_weight_index", "tap%d_weights" % (i + 1)), type="line", color="auto", name="tap%d"%(i+1))
    plot9.title  = "DFE Adaptation"
    plot9.tools.append(PanTool(plot9, constrain=True, constrain_key=None, constrain_direction='x'))
    zoom9 = ZoomTool(plot9, tool_mode="range", axis='index', always_on=False)
    plot9.overlays.append(zoom9)
    plot9.legend.visible = True
    plot9.legend.align = 'ul'

    plot_clk_per_hist = Plot(plotdata)
    plot_clk_per_hist.plot(('clk_per_hist_bins', 'clk_per_hist_vals'), type="line", color="blue")
    plot_clk_per_hist.title  = "CDR Clock Period Histogram"
    plot_clk_per_hist.index_axis.title = "Clock Period (ps)"
    plot_clk_per_hist.value_axis.title = "Bin Count"

    plot_clk_per_spec = Plot(plotdata)
    plot_clk_per_spec.plot(('clk_freqs', 'clk_spec'), type="line", color="blue")
    plot_clk_per_spec.title  = "CDR Clock Period Spectrum"
    plot_clk_per_spec.index_axis.title = "Frequency (bit rate)"
    plot_clk_per_spec.value_axis.title = "|H(f)| (dB mean)"
    plot_clk_per_spec.value_range.low_setting  = -10
    zoom_clk_per_spec = ZoomTool(plot_clk_per_spec, tool_mode="range", axis='index', always_on=False)
    plot_clk_per_spec.overlays.append(zoom_clk_per_spec)

    container_dfe = GridPlotContainer(shape=(2,2))
    container_dfe.add(plot2)
    container_dfe.add(plot9)
    container_dfe.add(plot_clk_per_hist)
    container_dfe.add(plot_clk_per_spec)
    self.plots_dfe = container_dfe

    # - EQ Tune tab
    plot_h_tune = Plot(plotdata)
    plot_h_tune.plot(("t_ns_chnl", "ctle_out_h_tune"), type="line", color="red",  name="Cumulative")
    plot_h_tune.plot(("t_ns_chnl", "ctle_out_g_tune"), type="line", color="gray")
    plot_h_tune.title            = "Channel + Tx Preemphasis + CTLE"
    plot_h_tune.index_axis.title = "Time (ns)"
    plot_h_tune.y_axis.title     = "Response"
    zoom_tune = ZoomTool(plot_h_tune, tool_mode="range", axis='index', always_on=False)
    plot_h_tune.overlays.append(zoom_tune)
    self.plot_h_tune = plot_h_tune

    # - Impulse Responses tab
    plot_h_chnl = Plot(plotdata)
    plot_h_chnl.plot(("t_ns_chnl", "chnl_h"), type="line", color="blue")
    plot_h_chnl.title            = "Channel"
    plot_h_chnl.index_axis.title = "Time (ns)"
    plot_h_chnl.y_axis.title     = "Impulse Response (V/ns)"
    zoom_h = ZoomTool(plot_h_chnl, tool_mode="range", axis='index', always_on=False)
    plot_h_chnl.overlays.append(zoom_h)

    plot_h_tx = Plot(plotdata)
    plot_h_tx.plot(("t_ns_chnl", "tx_out_h"), type="line", color="red",  name="Cumulative")
    plot_h_tx.title            = "Channel + Tx Preemphasis"
    plot_h_tx.index_axis.title = "Time (ns)"
    plot_h_tx.y_axis.title     = "Impulse Response (V/ns)"
    plot_h_tx.index_range = plot_h_chnl.index_range # Zoom x-axes in tandem.

    plot_h_ctle = Plot(plotdata)
    plot_h_ctle.plot(("t_ns_chnl", "ctle_out_h"), type="line", color="red",  name="Cumulative")
    plot_h_ctle.title            = "Channel + Tx Preemphasis + CTLE"
    plot_h_ctle.index_axis.title = "Time (ns)"
    plot_h_ctle.y_axis.title     = "Impulse Response (V/ns)"
    plot_h_ctle.index_range = plot_h_chnl.index_range # Zoom x-axes in tandem.

    plot_h_dfe = Plot(plotdata)
    plot_h_dfe.plot(("t_ns_chnl", "dfe_out_h"), type="line", color="red",  name="Cumulative")
    plot_h_dfe.title            = "Channel + Tx Preemphasis + CTLE + DFE"
    plot_h_dfe.index_axis.title = "Time (ns)"
    plot_h_dfe.y_axis.title     = "Impulse Response (V/ns)"
    plot_h_dfe.index_range = plot_h_chnl.index_range # Zoom x-axes in tandem.

    container_h = GridPlotContainer(shape=(2,2))
    container_h.add(plot_h_chnl)
    container_h.add(plot_h_tx)
    container_h.add(plot_h_ctle)
    container_h.add(plot_h_dfe)
    self.plots_h  = container_h

    # - Step Responses tab
    plot_s_chnl = Plot(plotdata)
    plot_s_chnl.plot(("t_ns_chnl", "chnl_s"), type="line", color="blue")
    plot_s_chnl.title            = "Channel"
    plot_s_chnl.index_axis.title = "Time (ns)"
    plot_s_chnl.y_axis.title     = "Step Response (V)"
    zoom_s = ZoomTool(plot_s_chnl, tool_mode="range", axis='index', always_on=False)
    plot_s_chnl.overlays.append(zoom_s)

    plot_s_tx = Plot(plotdata)
    plot_s_tx.plot(("t_ns_chnl", "tx_s"),     type="line", color="blue", name="Incremental")
    plot_s_tx.plot(("t_ns_chnl", "tx_out_s"), type="line", color="red",  name="Cumulative")
    plot_s_tx.title            = "Channel + Tx Preemphasis"
    plot_s_tx.index_axis.title = "Time (ns)"
    plot_s_tx.y_axis.title     = "Step Response (V)"
    plot_s_tx.legend.visible   = True
    plot_s_tx.legend.align     = 'lr'
    plot_s_tx.index_range = plot_s_chnl.index_range # Zoom x-axes in tandem.

    plot_s_ctle = Plot(plotdata)
    plot_s_ctle.plot(("t_ns_chnl", "ctle_s"),     type="line", color="blue", name="Incremental")
    plot_s_ctle.plot(("t_ns_chnl", "ctle_out_s"), type="line", color="red",  name="Cumulative")
    plot_s_ctle.title            = "Channel + Tx Preemphasis + CTLE"
    plot_s_ctle.index_axis.title = "Time (ns)"
    plot_s_ctle.y_axis.title     = "Step Response (V)"
    plot_s_ctle.legend.visible   = True
    plot_s_ctle.legend.align     = 'lr'
    plot_s_ctle.index_range = plot_s_chnl.index_range # Zoom x-axes in tandem.

    plot_s_dfe = Plot(plotdata)
    plot_s_dfe.plot(("t_ns_chnl", "dfe_s"),     type="line", color="blue", name="Incremental")
    plot_s_dfe.plot(("t_ns_chnl", "dfe_out_s"), type="line", color="red",  name="Cumulative")
    plot_s_dfe.title            = "Channel + Tx Preemphasis + CTLE + DFE"
    plot_s_dfe.index_axis.title = "Time (ns)"
    plot_s_dfe.y_axis.title     = "Step Response (V)"
    plot_s_dfe.legend.visible   = True
    plot_s_dfe.legend.align     = 'lr'
    plot_s_dfe.index_range = plot_s_chnl.index_range # Zoom x-axes in tandem.

    container_s = GridPlotContainer(shape=(2,2))
    container_s.add(plot_s_chnl)
    container_s.add(plot_s_tx)
    container_s.add(plot_s_ctle)
    container_s.add(plot_s_dfe)
    self.plots_s  = container_s

    # - Pulse Responses tab
    plot_p_chnl = Plot(plotdata)
    plot_p_chnl.plot(("t_ns_chnl", "chnl_p"), type="line", color="blue")
    plot_p_chnl.title            = "Channel"
    plot_p_chnl.index_axis.title = "Time (ns)"
    plot_p_chnl.y_axis.title     = "Pulse Response (V)"
    zoom_p = ZoomTool(plot_p_chnl, tool_mode="range", axis='index', always_on=False)
    plot_p_chnl.overlays.append(zoom_p)

    plot_p_tx = Plot(plotdata)
    plot_p_tx.plot(("t_ns_chnl", "tx_out_p"), type="line", color="red",  name="Cumulative")
    plot_p_tx.title            = "Channel + Tx Preemphasis"
    plot_p_tx.index_axis.title = "Time (ns)"
    plot_p_tx.y_axis.title     = "Pulse Response (V)"
    plot_p_tx.legend.align     = 'lr'
    plot_p_tx.index_range = plot_p_chnl.index_range # Zoom x-axes in tandem.

    plot_p_ctle = Plot(plotdata)
    plot_p_ctle.plot(("t_ns_chnl", "ctle_out_p"), type="line", color="red",  name="Cumulative")
    plot_p_ctle.title            = "Channel + Tx Preemphasis + CTLE"
    plot_p_ctle.index_axis.title = "Time (ns)"
    plot_p_ctle.y_axis.title     = "Pulse Response (V)"
    plot_p_ctle.legend.align     = 'lr'
    plot_p_ctle.index_range = plot_p_chnl.index_range # Zoom x-axes in tandem.

    plot_p_dfe = Plot(plotdata)
    plot_p_dfe.plot(("t_ns_chnl", "dfe_out_p"), type="line", color="red",  name="Cumulative")
    plot_p_dfe.title            = "Channel + Tx Preemphasis + CTLE + DFE"
    plot_p_dfe.index_axis.title = "Time (ns)"
    plot_p_dfe.y_axis.title     = "Pulse Response (V)"
    plot_p_dfe.legend.align     = 'lr'
    plot_p_dfe.index_range = plot_p_chnl.index_range # Zoom x-axes in tandem.

    container_p = GridPlotContainer(shape=(2,2))
    container_p.add(plot_p_chnl)
    container_p.add(plot_p_tx)
    container_p.add(plot_p_ctle)
    container_p.add(plot_p_dfe)
    self.plots_p  = container_p

    # - Frequency Responses tab
    plot_H_chnl = Plot(plotdata)
    plot_H_chnl.plot(("f_GHz", "chnl_H"), type="line", color="blue", index_scale='log')
    plot_H_chnl.title            = "Channel"
    plot_H_chnl.index_axis.title = "Frequency (GHz)"
    plot_H_chnl.y_axis.title     = "Frequency Response (dB)"
    plot_H_chnl.index_range.low_setting  = 0.01
    plot_H_chnl.index_range.high_setting = 40.

    plot_H_tx = Plot(plotdata)
    plot_H_tx.plot(("f_GHz", "tx_H"),     type="line", color="blue", name="Incremental", index_scale='log')
    plot_H_tx.plot(("f_GHz", "tx_out_H"), type="line", color="red",  name="Cumulative", index_scale='log')
    plot_H_tx.title            = "Channel + Tx Preemphasis"
    plot_H_tx.index_axis.title = "Frequency (GHz)"
    plot_H_tx.y_axis.title     = "Frequency Response (dB)"
    plot_H_tx.index_range.low_setting  = 0.01
    plot_H_tx.index_range.high_setting = 40.
    plot_H_tx.legend.visible   = True
    plot_H_tx.legend.align     = 'll'

    plot_H_ctle = Plot(plotdata)
    plot_H_ctle.plot(("f_GHz", "ctle_H"),     type="line", color="blue", name="Incremental", index_scale='log')
    plot_H_ctle.plot(("f_GHz", "ctle_out_H"), type="line", color="red",  name="Cumulative", index_scale='log')
    plot_H_ctle.title            = "Channel + Tx Preemphasis + CTLE"
    plot_H_ctle.index_axis.title = "Frequency (GHz)"
    plot_H_ctle.y_axis.title     = "Frequency Response (dB)"
    plot_H_ctle.index_range.low_setting  = 0.01
    plot_H_ctle.index_range.high_setting = 40.
    plot_H_ctle.value_range.low_setting  = -40.
    plot_H_ctle.legend.visible   = True
    plot_H_ctle.legend.align     = 'll'

    plot_H_chnl.value_range = plot_H_ctle.value_range 
    plot_H_tx.value_range   = plot_H_ctle.value_range 

    plot_H_dfe = Plot(plotdata)
    plot_H_dfe.plot(("f_GHz", "dfe_H"),     type="line", color="blue", name="Incremental", index_scale='log')
    plot_H_dfe.plot(("f_GHz", "dfe_out_H"), type="line", color="red",  name="Cumulative", index_scale='log')
    plot_H_dfe.title            = "Channel + Tx Preemphasis + CTLE + DFE"
    plot_H_dfe.index_axis.title = "Frequency (GHz)"
    plot_H_dfe.y_axis.title     = "Frequency Response (dB)"
    plot_H_dfe.index_range.low_setting  = 0.01
    plot_H_dfe.index_range.high_setting = 40.
    plot_H_dfe.value_range = plot_H_ctle.value_range 
    plot_H_dfe.legend.visible   = True
    plot_H_dfe.legend.align     = 'll'

    container_H = GridPlotContainer(shape=(2,2))
    container_H.add(plot_H_chnl)
    container_H.add(plot_H_tx)
    container_H.add(plot_H_ctle)
    container_H.add(plot_H_dfe)
    self.plots_H  = container_H

    # - Outputs tab
    plot_out_chnl = Plot(plotdata)
    plot_out_chnl.plot(("t_ns", "ideal_signal"), type="line", color="lightgrey")
    plot_out_chnl.plot(("t_ns", "chnl_out"),     type="line", color="blue")
    plot_out_chnl.title            = "Channel"
    plot_out_chnl.index_axis.title = "Time (ns)"
    plot_out_chnl.y_axis.title     = "Output (V)"
    zoom_out_chnl = ZoomTool(plot_out_chnl, tool_mode="range", axis='index', always_on=False)
    plot_out_chnl.overlays.append(zoom_out_chnl)

    plot_out_tx = Plot(plotdata)
    plot_out_tx.plot(("t_ns", "tx_out"), type="line", color="blue")
    plot_out_tx.title            = "Channel + Tx Preemphasis (Noise added here.)"
    plot_out_tx.index_axis.title = "Time (ns)"
    plot_out_tx.y_axis.title     = "Output (V)"
    plot_out_tx.index_range = plot_out_chnl.index_range # Zoom x-axes in tandem.

    plot_out_ctle = Plot(plotdata)
    plot_out_ctle.plot(("t_ns", "ctle_out"), type="line", color="blue")
    plot_out_ctle.title            = "Channel + Tx Preemphasis + CTLE"
    plot_out_ctle.index_axis.title = "Time (ns)"
    plot_out_ctle.y_axis.title     = "Output (V)"
    plot_out_ctle.index_range = plot_out_chnl.index_range # Zoom x-axes in tandem.

    plot_out_dfe = Plot(plotdata)
    plot_out_dfe.plot(("t_ns", "dfe_out"), type="line", color="blue")
    plot_out_dfe.title            = "Channel + Tx Preemphasis + CTLE + DFE"
    plot_out_dfe.index_axis.title = "Time (ns)"
    plot_out_dfe.y_axis.title     = "Output (V)"
    plot_out_dfe.index_range = plot_out_chnl.index_range # Zoom x-axes in tandem.

    container_out = GridPlotContainer(shape=(2,2))
    container_out.add(plot_out_chnl)
    container_out.add(plot_out_tx)
    container_out.add(plot_out_ctle)
    container_out.add(plot_out_dfe)
    self.plots_out  = container_out

    # - Eye Diagrams tab
    seg_map = dict(
        red = [
            (0.00, 0.00, 0.00), # black
            (0.00001, 0.00, 0.00), # blue
            (0.15, 0.00, 0.00), # cyan
            (0.30, 0.00, 0.00), # green
            (0.45, 1.00, 1.00), # yellow
            (0.60, 1.00, 1.00), # orange
            (0.75, 1.00, 1.00), # red
            (0.90, 1.00, 1.00), # pink
            (1.00, 1.00, 1.00) # white
        ],
        green = [
            (0.00, 0.00, 0.00), # black
            (0.00001, 0.00, 0.00), # blue
            (0.15, 0.50, 0.50), # cyan
            (0.30, 0.50, 0.50), # green
            (0.45, 1.00, 1.00), # yellow
            (0.60, 0.50, 0.50), # orange
            (0.75, 0.00, 0.00), # red
            (0.90, 0.50, 0.50), # pink
            (1.00, 1.00, 1.00) # white
        ],
        blue = [
            (0.00, 0.00, 0.00), # black
            (1e-18, 0.50, 0.50), # blue
            (0.15, 0.50, 0.50), # cyan
            (0.30, 0.00, 0.00), # green
            (0.45, 0.00, 0.00), # yellow
            (0.60, 0.00, 0.00), # orange
            (0.75, 0.00, 0.00), # red
            (0.90, 0.50, 0.50), # pink
            (1.00, 1.00, 1.00) # white
        ]
    )
    clr_map = ColorMapper.from_segment_map(seg_map)
    self.clr_map = clr_map

    plot_eye_chnl = Plot(plotdata)
    plot_eye_chnl.img_plot("eye_chnl", colormap=clr_map,)
    plot_eye_chnl.y_direction = 'normal'
    plot_eye_chnl.components[0].y_direction = 'normal'
    plot_eye_chnl.title  = "Channel"
    plot_eye_chnl.x_axis.title = "Time (ps)"
    plot_eye_chnl.x_axis.orientation = "bottom"
    plot_eye_chnl.y_axis.title = "Signal Level (V)"
    plot_eye_chnl.x_grid.visible = True
    plot_eye_chnl.y_grid.visible = True
    plot_eye_chnl.x_grid.line_color = 'gray'
    plot_eye_chnl.y_grid.line_color = 'gray'

    plot_eye_tx = Plot(plotdata)
    plot_eye_tx.img_plot("eye_tx", colormap=clr_map,)
    plot_eye_tx.y_direction = 'normal'
    plot_eye_tx.components[0].y_direction = 'normal'
    plot_eye_tx.title  = "Channel + Tx Preemphasis (Noise added here.)"
    plot_eye_tx.x_axis.title = "Time (ps)"
    plot_eye_tx.x_axis.orientation = "bottom"
    plot_eye_tx.y_axis.title = "Signal Level (V)"
    plot_eye_tx.x_grid.visible = True
    plot_eye_tx.y_grid.visible = True
    plot_eye_tx.x_grid.line_color = 'gray'
    plot_eye_tx.y_grid.line_color = 'gray'

    plot_eye_ctle = Plot(plotdata)
    plot_eye_ctle.img_plot("eye_ctle", colormap=clr_map,)
    plot_eye_ctle.y_direction = 'normal'
    plot_eye_ctle.components[0].y_direction = 'normal'
    plot_eye_ctle.title  = "Channel + Tx Preemphasis + CTLE"
    plot_eye_ctle.x_axis.title = "Time (ps)"
    plot_eye_ctle.x_axis.orientation = "bottom"
    plot_eye_ctle.y_axis.title = "Signal Level (V)"
    plot_eye_ctle.x_grid.visible = True
    plot_eye_ctle.y_grid.visible = True
    plot_eye_ctle.x_grid.line_color = 'gray'
    plot_eye_ctle.y_grid.line_color = 'gray'

    plot_eye_dfe = Plot(plotdata)
    plot_eye_dfe.img_plot("eye_dfe", colormap=clr_map,)
    plot_eye_dfe.y_direction = 'normal'
    plot_eye_dfe.components[0].y_direction = 'normal'
    plot_eye_dfe.title  = "Channel + Tx Preemphasis + CTLE + DFE"
    plot_eye_dfe.x_axis.title = "Time (ps)"
    plot_eye_dfe.x_axis.orientation = "bottom"
    plot_eye_dfe.y_axis.title = "Signal Level (V)"
    plot_eye_dfe.x_grid.visible = True
    plot_eye_dfe.y_grid.visible = True
    plot_eye_dfe.x_grid.line_color = 'gray'
    plot_eye_dfe.y_grid.line_color = 'gray'

    container_eye = GridPlotContainer(shape=(2,2))
    container_eye.add(plot_eye_chnl)
    container_eye.add(plot_eye_tx)
    container_eye.add(plot_eye_ctle)
    container_eye.add(plot_eye_dfe)
    self.plots_eye  = container_eye

    # - Jitter Distributions tab
    plot_jitter_dist_chnl        = Plot(plotdata)
    plot_jitter_dist_chnl.plot(('jitter_bins', 'jitter_chnl'),     type="line", color="blue", name="Measured")
    plot_jitter_dist_chnl.plot(('jitter_bins', 'jitter_ext_chnl'), type="line", color="red",  name="Extrapolated")
    plot_jitter_dist_chnl.title  = "Channel"
    plot_jitter_dist_chnl.index_axis.title = "Time (ps)"
    plot_jitter_dist_chnl.value_axis.title = "Count"
    plot_jitter_dist_chnl.legend.visible   = True
    plot_jitter_dist_chnl.legend.align     = 'ur'

    plot_jitter_dist_tx        = Plot(plotdata)
    plot_jitter_dist_tx.plot(('jitter_bins', 'jitter_tx'),     type="line", color="blue", name="Measured")
    plot_jitter_dist_tx.plot(('jitter_bins', 'jitter_ext_tx'), type="line", color="red",  name="Extrapolated")
    plot_jitter_dist_tx.title  = "Channel + Tx Preemphasis (Noise added here.)"
    plot_jitter_dist_tx.index_axis.title = "Time (ps)"
    plot_jitter_dist_tx.value_axis.title = "Count"
    plot_jitter_dist_tx.legend.visible   = True
    plot_jitter_dist_tx.legend.align     = 'ur'

    plot_jitter_dist_ctle        = Plot(plotdata)
    plot_jitter_dist_ctle.plot(('jitter_bins', 'jitter_ctle'),     type="line", color="blue", name="Measured")
    plot_jitter_dist_ctle.plot(('jitter_bins', 'jitter_ext_ctle'), type="line", color="red",  name="Extrapolated")
    plot_jitter_dist_ctle.title  = "Channel + Tx Preemphasis + CTLE"
    plot_jitter_dist_ctle.index_axis.title = "Time (ps)"
    plot_jitter_dist_ctle.value_axis.title = "Count"
    plot_jitter_dist_ctle.legend.visible   = True
    plot_jitter_dist_ctle.legend.align     = 'ur'

    plot_jitter_dist_dfe        = Plot(plotdata)
    plot_jitter_dist_dfe.plot(('jitter_bins', 'jitter_dfe'),     type="line", color="blue", name="Measured")
    plot_jitter_dist_dfe.plot(('jitter_bins', 'jitter_ext_dfe'), type="line", color="red",  name="Extrapolated")
    plot_jitter_dist_dfe.title  = "Channel + Tx Preemphasis + CTLE + DFE"
    plot_jitter_dist_dfe.index_axis.title = "Time (ps)"
    plot_jitter_dist_dfe.value_axis.title = "Count"
    plot_jitter_dist_dfe.legend.visible   = True
    plot_jitter_dist_dfe.legend.align     = 'ur'

    container_jitter_dist = GridPlotContainer(shape=(2,2))
    container_jitter_dist.add(plot_jitter_dist_chnl)
    container_jitter_dist.add(plot_jitter_dist_tx)
    container_jitter_dist.add(plot_jitter_dist_ctle)
    container_jitter_dist.add(plot_jitter_dist_dfe)
    self.plots_jitter_dist  = container_jitter_dist

    # - Jitter Spectrums tab
    plot_jitter_spec_chnl        = Plot(plotdata)
    plot_jitter_spec_chnl.plot(('f_MHz', 'jitter_spectrum_chnl'),     type="line", color="blue",    name="Total")
    plot_jitter_spec_chnl.plot(('f_MHz', 'jitter_ind_spectrum_chnl'), type="line", color="red",     name="Data Independent")
    plot_jitter_spec_chnl.plot(('f_MHz', 'thresh_chnl'),              type="line", color="magenta", name="Pj Threshold")
    plot_jitter_spec_chnl.title  = "Channel"
    plot_jitter_spec_chnl.index_axis.title = "Frequency (MHz)"
    plot_jitter_spec_chnl.value_axis.title = "|FFT(TIE)| (dBui)"
    plot_jitter_spec_chnl.tools.append(PanTool(plot_jitter_spec_chnl, constrain=True, constrain_key=None, constrain_direction='x'))
    zoom_jitter_spec_chnl = ZoomTool(plot_jitter_spec_chnl, tool_mode="range", axis='index', always_on=False)
    plot_jitter_spec_chnl.overlays.append(zoom_jitter_spec_chnl)
    plot_jitter_spec_chnl.legend.visible = True
    plot_jitter_spec_chnl.legend.align = 'lr'

    plot_jitter_spec_tx        = Plot(plotdata)
    plot_jitter_spec_tx.plot(('f_MHz', 'jitter_spectrum_tx'),     type="line", color="blue",    name="Total")
    plot_jitter_spec_tx.plot(('f_MHz', 'jitter_ind_spectrum_tx'), type="line", color="red",     name="Data Independent")
    plot_jitter_spec_tx.plot(('f_MHz', 'thresh_tx'),              type="line", color="magenta", name="Pj Threshold")
    plot_jitter_spec_tx.title  = "Channel + Tx Preemphasis (Noise added here.)"
    plot_jitter_spec_tx.index_axis.title = "Frequency (MHz)"
    plot_jitter_spec_tx.value_axis.title = "|FFT(TIE)| (dBui)"
    plot_jitter_spec_tx.value_range.low_setting  = -40.
    plot_jitter_spec_tx.tools.append(PanTool(plot_jitter_spec_tx, constrain=True, constrain_key=None, constrain_direction='x'))
    zoom_jitter_spec_tx = ZoomTool(plot_jitter_spec_tx, tool_mode="range", axis='index', always_on=False)
    plot_jitter_spec_tx.overlays.append(zoom_jitter_spec_tx)
    plot_jitter_spec_tx.legend.visible = True
    plot_jitter_spec_tx.legend.align = 'lr'

    plot_jitter_spec_chnl.value_range = plot_jitter_spec_tx.value_range 

    plot_jitter_spec_ctle        = Plot(plotdata)
    plot_jitter_spec_ctle.plot(('f_MHz', 'jitter_spectrum_ctle'),     type="line", color="blue",    name="Total")
    plot_jitter_spec_ctle.plot(('f_MHz', 'jitter_ind_spectrum_ctle'), type="line", color="red",     name="Data Independent")
    plot_jitter_spec_ctle.plot(('f_MHz', 'thresh_ctle'),              type="line", color="magenta", name="Pj Threshold")
    plot_jitter_spec_ctle.title  = "Channel + Tx Preemphasis + CTLE"
    plot_jitter_spec_ctle.index_axis.title = "Frequency (MHz)"
    plot_jitter_spec_ctle.value_axis.title = "|FFT(TIE)| (dBui)"
    plot_jitter_spec_ctle.tools.append(PanTool(plot_jitter_spec_ctle, constrain=True, constrain_key=None, constrain_direction='x'))
    zoom_jitter_spec_ctle = ZoomTool(plot_jitter_spec_ctle, tool_mode="range", axis='index', always_on=False)
    plot_jitter_spec_ctle.overlays.append(zoom_jitter_spec_ctle)
    plot_jitter_spec_ctle.legend.visible = True
    plot_jitter_spec_ctle.legend.align = 'lr'
    plot_jitter_spec_ctle.value_range = plot_jitter_spec_tx.value_range 

    plot_jitter_spec_dfe        = Plot(plotdata)
    plot_jitter_spec_dfe.plot(('f_MHz_dfe', 'jitter_spectrum_dfe'),     type="line", color="blue",    name="Total")
    plot_jitter_spec_dfe.plot(('f_MHz_dfe', 'jitter_ind_spectrum_dfe'), type="line", color="red",     name="Data Independent")
    plot_jitter_spec_dfe.plot(('f_MHz_dfe', 'thresh_dfe'),              type="line", color="magenta", name="Pj Threshold")
    plot_jitter_spec_dfe.title  = "Channel + Tx Preemphasis + CTLE + DFE"
    plot_jitter_spec_dfe.index_axis.title = "Frequency (MHz)"
    plot_jitter_spec_dfe.value_axis.title = "|FFT(TIE)| (dBui)"
    plot_jitter_spec_dfe.tools.append(PanTool(plot_jitter_spec_dfe, constrain=True, constrain_key=None, constrain_direction='x'))
    zoom_jitter_spec_dfe = ZoomTool(plot_jitter_spec_dfe, tool_mode="range", axis='index', always_on=False)
    plot_jitter_spec_dfe.overlays.append(zoom_jitter_spec_dfe)
    plot_jitter_spec_dfe.legend.visible = True
    plot_jitter_spec_dfe.legend.align = 'lr'
    plot_jitter_spec_dfe.value_range = plot_jitter_spec_tx.value_range 

    container_jitter_spec = GridPlotContainer(shape=(2,2))
    container_jitter_spec.add(plot_jitter_spec_chnl)
    container_jitter_spec.add(plot_jitter_spec_tx)
    container_jitter_spec.add(plot_jitter_spec_ctle)
    container_jitter_spec.add(plot_jitter_spec_dfe)
    self.plots_jitter_spec  = container_jitter_spec

    # - Bathtub Curves tab
    plot_bathtub_chnl = Plot(plotdata)
    plot_bathtub_chnl.plot(("jitter_bins", "bathtub_chnl"), type="line", color="blue")
    plot_bathtub_chnl.value_range.high_setting =   0
    plot_bathtub_chnl.value_range.low_setting  = -18
    plot_bathtub_chnl.value_axis.tick_interval =   3
    plot_bathtub_chnl.title             = "Channel"
    plot_bathtub_chnl.index_axis.title  = "Time (ps)"
    plot_bathtub_chnl.value_axis.title  = "Log10(P(Transition occurs inside.))"

    plot_bathtub_tx = Plot(plotdata)
    plot_bathtub_tx.plot(("jitter_bins", "bathtub_tx"), type="line", color="blue")
    plot_bathtub_tx.value_range.high_setting =   0
    plot_bathtub_tx.value_range.low_setting  = -18
    plot_bathtub_tx.value_axis.tick_interval =   3
    plot_bathtub_tx.title             = "Channel + Tx Preemphasis (Noise added here.)"
    plot_bathtub_tx.index_axis.title  = "Time (ps)"
    plot_bathtub_tx.value_axis.title  = "Log10(P(Transition occurs inside.))"

    plot_bathtub_ctle = Plot(plotdata)
    plot_bathtub_ctle.plot(("jitter_bins", "bathtub_ctle"), type="line", color="blue")
    plot_bathtub_ctle.value_range.high_setting =   0
    plot_bathtub_ctle.value_range.low_setting  = -18
    plot_bathtub_ctle.value_axis.tick_interval =   3
    plot_bathtub_ctle.title             = "Channel + Tx Preemphasis + CTLE"
    plot_bathtub_ctle.index_axis.title  = "Time (ps)"
    plot_bathtub_ctle.value_axis.title  = "Log10(P(Transition occurs inside.))"

    plot_bathtub_dfe = Plot(plotdata)
    plot_bathtub_dfe.plot(("jitter_bins", "bathtub_dfe"), type="line", color="blue")
    plot_bathtub_dfe.value_range.high_setting =   0
    plot_bathtub_dfe.value_range.low_setting  = -18
    plot_bathtub_dfe.value_axis.tick_interval =   3
    plot_bathtub_dfe.title             = "Channel + Tx Preemphasis + CTLE + DFE"
    plot_bathtub_dfe.index_axis.title  = "Time (ps)"
    plot_bathtub_dfe.value_axis.title  = "Log10(P(Transition occurs inside.))"

    container_bathtub = GridPlotContainer(shape=(2,2))
    container_bathtub.add(plot_bathtub_chnl)
    container_bathtub.add(plot_bathtub_tx)
    container_bathtub.add(plot_bathtub_ctle)
    container_bathtub.add(plot_bathtub_dfe)
    self.plots_bathtub  = container_bathtub

    update_eyes(self)
    return
Beispiel #59
0
class WorldMapPlot(HasTraits):

    ### Public Traits ##########################################################

    # The plot which will be displayed
    plot = Instance(Plot)

    # The URL which points to the world map image to be downloaded
    image_url = Str("http://eoimages.gsfc.nasa.gov/ve//2433/land_shallow_topo_2048.jpg")


    ### Private Traits #########################################################

    # The path to where the image exists on the filesystem
    image_path = Str()

    # The view
    traits_view = View(Item('plot', editor=ComponentEditor(),
                            width=800, height=400, show_label=False),
                       resizable=True)

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

    def __init__(self, **kw):
        super(WorldMapPlot, self).__init__(**kw)

        self._download_map_image()
        image = ImageData.fromfile(self.image_path)

        # For now, the locations are hardcoded, though this can be changed
        # eassily to take command line args, read from a file, or by other
        # means
        austin_loc = (30.16, -97.44)

        locations_x = numpy.array([austin_loc[1]])
        locations_y = numpy.array([austin_loc[0]])

        # transform each of the locations to the image data space, including
        # moving the origin from bottom left to top left
        locations_x = (locations_x + 180) * image.data.shape[1]/360
        locations_y = (locations_y*-1 + 90) * image.data.shape[0]/180

        # Create the plott data, adding the image and the locations
        plot_data = ArrayPlotData()
        plot_data.set_data("imagedata", image._data)
        plot_data.set_data("locations_x", locations_x)
        plot_data.set_data("locations_y", locations_y)

        # Create the plot with the origin as top left, which matches
        # how the image data is aligned
        self.plot = Plot(plot_data, default_origin="top left")
        self.plot.img_plot('imagedata')

        # Plot the locations as a scatter plot to be overlayed on top
        # of the map
        loc_plot = self.plot.plot(('locations_x',  'locations_y'),
                                    type='scatter', size=3, color='yellow',
                                    marker='dot')[0]

        loc_plot.x_mapper.range.high = image.data.shape[1]
        loc_plot.x_mapper.range.low = 0
        loc_plot.y_mapper.range.high = image.data.shape[0]
        loc_plot.y_mapper.range.low = -0

        # set up any tools, in this case just the zoom tool
        zoom = ZoomTool(component=self.plot, tool_mode="box", always_on=False)
        self.plot.overlays.append(zoom)

    #---------------------------------------------------------------------------
    # Protected interface
    #---------------------------------------------------------------------------

    def _download_map_image(self):
        """ Downloads a map from the image_url attribute. This is done
            primarily to keep the redistributable Chaco package as small
            as possible
        """
        example_dir = os.path.dirname(__file__)
        self.image_path = os.path.join(example_dir, 'data',
                                        os.path.split(self.image_url)[1])

        if not os.path.exists(self.image_path):
            print("Downloading map image")
            request.urlretrieve(self.image_url, self.image_path)
Beispiel #60
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=hot,
    )
    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