예제 #1
0
파일: viewer1D.py 프로젝트: amared/lulu
class Viewer1D(Viewer):
    image = Array
    result = Array

    def _reconstruction_default(self):
        rows, cols = self.image.shape[:2]
        self.plot_data = ArrayPlotData(original=self.image[0],
                                       reconstruction=self.result[0])

        aspect = cols/float(rows)

        old = Plot(self.plot_data)
        old.plot('original', )
        old.title = 'Old'

        self.new = Plot(self.plot_data)
        self.new.plot('reconstruction')
        self.new.title = 'New'

        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[0])
        self.new.request_redraw()
예제 #2
0
파일: display.py 프로젝트: mlange806/pyxda
    def plotHistogram(self, image, plot=None):
        if plot == None:
            pd = ArrayPlotData(y=np.array([0]), x=np.array([0]))
            plot = Plot(pd, padding=(70, 10, 0, 0))
            plot.plot(('x', 'y'), name='Histogram', type='bar', bar_width=5.0, color='auto')
            #plot.title = 'Histogram'
            plot.line_color = 'black'
            plot.bgcolor = "white"
            plot.fixed_preferred_size = (100, 30)
            add_default_grids(plot)
            plot.value_axis.title = "Histogram"
            self._appendHistogramTools(plot)
            '''
            plot.overlays.append(PlotAxis(plot, orientation='left'))
            plot.overlays.append(PlotAxis(plot, orientation='bottom'))
            '''
        else:
            data = np.histogram(image.data, bins=10000)
            index = np.delete(data[1], data[1].size-1)
            values = data[0]
            
            plot.index_range.low= np.min(index)
            plot.index_range.high = np.max(index)
            plot.value_range.low = 0
            plot.value_range.high = np.max(values)

            plot.data.set_data('x', index)
            plot.data.set_data('y', values)
        plot.request_redraw()
        return plot
예제 #3
0
class Viewer1D(Viewer):
    image = Array
    result = Array

    def _reconstruction_default(self):
        rows, cols = self.image.shape[:2]
        self.plot_data = ArrayPlotData(original=self.image[0],
                                       reconstruction=self.result[0])

        aspect = cols / float(rows)

        old = Plot(self.plot_data)
        old.plot('original', )
        old.title = 'Old'

        self.new = Plot(self.plot_data)
        self.new.plot('reconstruction')
        self.new.title = 'New'

        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[0])
        self.new.request_redraw()
예제 #4
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, 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))
예제 #5
0
파일: viewer.py 프로젝트: stefanv/lulu
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))
예제 #6
0
파일: display.py 프로젝트: mlange806/pyxda
 def plotRRMap(self, rr, rrchoice, plot=None):
     if plot == None:
         pd = ArrayPlotData(y=np.array([0]), x=np.array([0]))
         plot = Plot(pd, padding=(70, 5, 0, 0))
         self._setData(rr, plot)
         plot.plot(('x', 'y'), name='rrplot', type="scatter", color='green',
                   marker="circle", marker_size=6)
         #plot.title = 'rrplot'
         plot.value_axis.title = rrchoice
         #plot.y_axis.visible = False
         plot.bgcolor = 'white'
         plot.aspect_ratio = 2.5
         plot.fixed_preferred_size = (100, 50)
         #left, bottom = add_default_axes(plot)
         hgrid, vgrid = add_default_grids(plot)
         self._appendCMapTools(plot)
     else:
         self._setData(rr, plot)
     plot.request_redraw()
     return plot
예제 #7
0
class MyPlot(HasTraits):
    """ Displays a plot with a few buttons to control which overlay
        to display
    """
    plot = Instance(Plot)
    status_overlay = Instance(StatusLayer)

    error_button = Button('Error')
    warn_button = Button('Warning')
    no_problem_button = Button('No problem')

    traits_view = View( HGroup(UItem('error_button'),
                               UItem('warn_button'),
                               UItem('no_problem_button')),
                        UItem('plot', editor=ComponentEditor()),
                        width=700, height=600, resizable=True,        
                        )

    def __init__(self, index, data_series, **kw):
        super(MyPlot, self).__init__(**kw)

        plot_data = ArrayPlotData(index=index)
        plot_data.set_data('data_series', data_series)
        self.plot = Plot(plot_data)
        self.plot.plot(('index', 'data_series'))

    def _error_button_fired(self, event):
        """ removes the old overlay and replaces it with
            an error overlay
        """
        self.clear_status()

        self.status_overlay = ErrorLayer(component=self.plot,
                                            align='ul', scale_factor=0.25)
        self.plot.overlays.append(self.status_overlay)

        self.plot.request_redraw()

    def _warn_button_fired(self, event):
        """ removes the old overlay and replaces it with
            an warning overlay
        """
        self.clear_status()

        self.status_overlay = WarningLayer(component=self.plot,
                                            align='ur', scale_factor=0.25)
        self.plot.overlays.append(self.status_overlay)

        self.plot.request_redraw()

    def _no_problem_button_fired(self, event):
        """ removes the old overlay
        """
        self.clear_status()
        self.plot.request_redraw()

    def clear_status(self):
        if self.status_overlay in self.plot.overlays:
            # fade_out will remove the overlay when its done
            self.status_overlay.fade_out()
예제 #8
0
파일: canvas.py 프로젝트: 5n1p/chaco
def clone_plot(clonetool, drop_position):
    # A little sketchy...
    canvas = clonetool.component.container.component.component

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

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

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

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

    newplot.datasources = copy(oldplot.datasources)

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

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

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

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

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

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

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

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

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

    newplot._layout_needed = True

    clonetool.dest.add(newplot)
    newplot.invalidate_draw()
    newplot.request_redraw()
    canvas.request_redraw()
    return
예제 #9
0
def clone_plot(clonetool, drop_position):
    # A little sketchy...
    canvas = clonetool.component.container.component.component

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

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

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

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

    newplot.datasources = copy(oldplot.datasources)

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

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

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

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

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

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

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

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

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

    newplot._layout_needed = True

    clonetool.dest.add(newplot)
    newplot.invalidate_draw()
    newplot.request_redraw()
    canvas.request_redraw()
    return
예제 #10
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
예제 #11
0
class MainPlot(HasTraits):
    """Main class for the primary solar image and point-by-point spectra.
    
    Class creates image inspector tool object.
    
    Controls file saving.
    
    Main window that passes information on to source function plots
    """
    
    #Place to extend program for extra filetypes
    Name, fileExtension = os.path.splitext(FileLoadWindow.file_name_Ray)
    if fileExtension == '.ncdf':
	#Open .ncdf File to read
	RayFile = Rh15dout()
	RayFile.read_ray(FileLoadWindow.file_name_Ray)
	WavelengthData = RayFile.ray.wavelength
	IntensityData = RayFile.ray.intensity
    elif fileExtension == 'Alternate file type':
	pass
	#Add code here to read in new file type
    else:
	print "Ray File Extension Not Recognized"
    

    wave_ref = float(FileLoadWindow.Wave_Ref)
    intensityindex =  N.argmin(N.abs(WavelengthData[:]-wave_ref))
    #self.RayFile.read_ray('/sanhome/tiago/rhout/cb24bih/MgII/PRD/385_PRD_newatom/output_ray.ncdf')
    WavelengthIndex = Range(value = int(intensityindex), low = 0, high = WavelengthData.shape[0] - 1)
    WavelengthFine = Range(value = wave_ref, low = wave_ref - 0.1, high = wave_ref + 0.1)
    WavelengthView = Float(wave_ref)
    Wavelength = Range(value = wave_ref, low = float(N.min(WavelengthData[:])), high = float(N.max(WavelengthData[:])))
    save = Button('save')
    SaveFlag = Bool()
    VelocityView = Float()
    ViewPosition = Array()


    
    
    colormapminabs = float(N.min(IntensityData[:,:,intensityindex]))
    colormapmaxabs = float(N.max(IntensityData[:,:,intensityindex]))
    colormapmin = Range(low=colormapminabs, high=colormapmaxabs, value=colormapminabs)
    colormapmax = Range(low=colormapminabs, high=colormapmaxabs, value=colormapmaxabs)

    
    PrimaryPlotC = Instance(HPlotContainer)
    windowwidth = 1500
    ImageLock = Bool()
    colormap_list = Enum('jet', 'gist_gray', 'gist_heat', 'Blues', 'hot')
    Spectraplotzoom = Enum('Close', 'Far')
    Markercolor = Enum('white', 'green', 'yellow', 'red')

    
    traits_view = View(VGroup(Item('PrimaryPlotC', editor = ComponentEditor(), show_label = False, springy = True)),
		       Item('colormapmin', label = 'Minimum Intensity'), Item('colormapmax', label = 'Maximum Intensity'),
		       HGroup(Item('WavelengthIndex', label = 'Index', style = 'simple', editor = RangeEditor(mode = 'slider', low=0, high=WavelengthData.shape[0] - 1)), Item('WavelengthView', label = 'Wavelength')),
		       HGroup(Item('colormap_list', style = 'simple', label = 'Colormap'), Item('Spectraplotzoom', style = 'custom', label = 'Spectral Zoom Range'), Item('Markercolor', style = 'simple', label = 'Marker Color'), Item('VelocityView', label = 'Velocity (km/s)', style = 'readonly'), Item('ViewPosition', label = 'View Location', style = 'readonly'), Item('save', show_label = False)),
		       width = windowwidth, height = windowwidth/2.0 * 1.3, resizable = True, title = "Main Image Plot")

    #Array used for passing information to speactra line plto and also Source Function Plots.  Will be synced
    InspectorPosition = Array()

    def __init__(self):
	super(MainPlot, self).__init__()
	self.ImageLock = False
	self.SaveFlag = False
	
	self.create_PrimaryPlotC()
	
    def create_PrimaryPlotC(self):
	#Extracts the data for the main plot
        self.MainPlotData = self.IntensityData[:,:,self.intensityindex]
	self.markerplotdatax = []
	self.markerplotdatay = []
	self.SpectraMultiple = 1.0e+8
	WavelengthXPoints = [self.Wavelength, self.Wavelength]
	WavelengthYPoints = [N.min(self.IntensityData[:,:])*self.SpectraMultiple, N.max(self.IntensityData[:,:])*self.SpectraMultiple]
	WavelengthXPointsStatic = WavelengthXPoints
	WavelengthYPointsStatic = WavelengthYPoints

	AvgIntensity = N.mean(N.mean(self.IntensityData, axis = 0), axis = 0)
	print "mean computed-------------------"

        #Create main Plot (intensity plot)
        self.Mainplotdata = ArrayPlotData(Mainimagedata = self.MainPlotData, markerplotdatax = self.markerplotdatax, markerplotdatay = self.markerplotdatay)
        self.Mainplot = Plot(self.Mainplotdata)
        self.Main_img_plot = self.Mainplot.img_plot("Mainimagedata", colormap = jet)[0]
	
	#Create marker wneh x is pressed
	self.Mainplot.MarkerPlot = self.Mainplot.plot(("markerplotdatax","markerplotdatay"),type = 'line', color = 'white')

        #Create overlaid crosshairs for Main plot
        LineInspector1 = LineInspector(component = self.Main_img_plot,axis = 'index_x', write_metadata=True,is_listener = False,inspect_mode="indexed")            
        self.Main_img_plot.overlays.append(LineInspector1)
        LineInspector2 = LineInspector(component = self.Main_img_plot,axis = 'index_y', write_metadata=True,is_listener = False,inspect_mode="indexed")
        self.Main_img_plot.overlays.append(LineInspector2)

        #Create overlay tools and add them to main plot
        Main_imgtool = ImageInspectorTool(self.Main_img_plot)
        self.Main_img_plot.tools.append(Main_imgtool)
        Main_overlay = ImageInspectorOverlay(component = self.Main_img_plot, image_inspector = Main_imgtool, bgcolor = "white", border_visible = True)
        self.Main_img_plot.overlays.append(Main_overlay)

        #Sync up inspector position so it can be passed to the spectra plot
        Main_overlay.sync_trait('InspectorPosition', self, 'InspectorPosition', mutual = True)
	Main_imgtool.sync_trait('ImageLock', self, 'ImageLock')
	Main_imgtool.sync_trait('SaveFlag', self, 'SaveFlag')
	
	#Sync up max and min colormap value
	self.Main_img_plot.value_range.sync_trait('low', self, 'colormapmin', mutual = True)
	self.Main_img_plot.value_range.sync_trait('high', self, 'colormapmax', mutual = True)
	
        #Create spectra plot for a single column
	self.Spectraplotdata = ArrayPlotData(x = self.WavelengthData[:], y = (self.IntensityData[2,2] * self.SpectraMultiple), WavelengthXPointsStatic = WavelengthXPointsStatic, WavelengthYPointsStatic = WavelengthYPointsStatic, WavelengthXPoints = WavelengthXPoints, WavelengthYPoints = WavelengthYPoints, AvgIntensity = AvgIntensity * self.SpectraMultiple, is_listener = True)
        self.Spectraplot1 = Plot(self.Spectraplotdata)
        self.Spectraplot1.plot(("x","y"), type = "line", color = "blue")
        self.Spectraplot1.plot( ("WavelengthXPointsStatic","WavelengthYPointsStatic"), type = 'line', line_style = 'dash', color = 'green')
	self.Spectraplot1.plot( ("WavelengthXPoints","WavelengthYPoints"), type = 'line', line_style = 'dash', color = 'red')
	self.Spectraplot1.plot( ("x","AvgIntensity"), type = 'line', color = 'black')
        
	#Change Plot characteristics
	#Sets width around waveref to examine
	self.xlowspread = 1.
        self.xhighspread = 1.
        self.Spectraplot1.range2d.x_range.set_bounds(self.wave_ref - self.xlowspread, self.wave_ref + self.xhighspread)
        self.Spectraplot1.x_axis.title = "Wavelength (A)"
        self.Spectraplot1.y_axis.title = "Intensity (J s^-1 m^-2 Hz^-1 sr^-1)"
        self.rangearray = self.IntensityData[:,:]
        self.rangearray = self.rangearray[:,:,N.argmin(N.abs(self.WavelengthData[:]-(self.wave_ref-self.xlowspread))):N.argmin(N.abs(self.WavelengthData[:]-(self.wave_ref+self.xhighspread)))]
        self.Spectraplot1.range2d.y_range.set_bounds(N.min(self.rangearray[:,:])*self.SpectraMultiple, N.max(self.rangearray[:,:])   * self.SpectraMultiple)
	#self.Spectraplot1.range2d.y_range.set_bounds(N.min(self.rangearray[:,:])*self.SpectraMultiple, Scaling * (N.max(self.rangearray[:,:]) - N.min(self.rangearray[:,:])) + N.min(self.rangearray[:,:])  * self.SpectraMultiple)


        #add some standard tools. Note, I'm assigning the PanTool to the 
        #right mouse-button to avoid conflicting with the cursors
        self.Mainplot.tools.append(PanTool(self.Main_img_plot, drag_button="right"))
	self.Spectraplot1.tools.append(PanTool(self.Spectraplot1, drag_button="right"))
        self.Mainplot.overlays.append(ZoomTool(self.Main_img_plot))
        self.Spectraplot1.overlays.append(ZoomTool(self.Spectraplot1))

        #Changing interactive options
        zoom = ZoomTool(component=self.Mainplot, tool_mode="box", always_on=False)

        #Create Container for main plot                                  
        MainContainer = HPlotContainer(self.Mainplot, self.Spectraplot1, background = "lightgray", use_back_buffer = True)
        MainContainer.spacing = 25
        self.PrimaryPlotC = MainContainer
	

	
    def _InspectorPosition_changed(self):
	if self.ImageLock == True:
	    return
	
	if len(self.InspectorPosition) > 0:
	    xi = self.InspectorPosition[0]
	    yi = self.InspectorPosition[1]
	else:
	    xi = 0
	    yi = 0
	    return
	    
	self.ViewPosition = self.InspectorPosition    
	self.Spectraplotdata.set_data("y", self.IntensityData[self.InspectorPosition[0],self.InspectorPosition[1]] * self.SpectraMultiple)
	
    def _WavelengthIndex_changed(self):
	self.intensityindex = self.WavelengthIndex
	self.Wavelength = self.WavelengthData[self.intensityindex]
	self.WavelengthView = self.Wavelength
	self.WavelengthXPoints = [self.Wavelength, self.Wavelength]
	self.Spectraplotdata.set_data("WavelengthXPoints", self.WavelengthXPoints)
	self.intensityindex =  N.argmin(N.abs(self.WavelengthData[:]-float(self.Wavelength)))
	self.VelocityView = 299792.45 * (self.Wavelength - self.wave_ref)/self.wave_ref
	self.Mainplotdata.set_data("Mainimagedata", self.IntensityData[:,:,self.intensityindex])
	self.Mainplot.request_redraw()
	
    def _WavelengthView_changed(self):
	self.WavelengthIndex = int(N.argmin(N.abs(self.WavelengthData[:]-self.WavelengthView)))
	
	
    def _WavelengthFine_changed(self):
	self.Wavelength = self.WavelengthFine

    def _colormapmin_changed(self):
	self.Mainplot.request_redraw()
	
    def _colormapmax_changed(self):
	self.Spectraplot1.range2d.y_range.set_bounds(N.min(self.rangearray[:,:])*self.SpectraMultiple, self.colormapmax  * self.SpectraMultiple)
	self.Mainplot.request_redraw()
	
    def _colormap_list_changed(self):
	# get range of current colormap
	clr_range = self.Main_img_plot.color_mapper.range
	color_mapper = eval(self.colormap_list)(clr_range)
	self.Main_img_plot.color_mapper = color_mapper 
	self.Main_img_plot.request_redraw()
	    
    def _Spectraplotzoom_changed(self):
	if (self.Spectraplotzoom == 'Close'):
	    self.Spectraplot1.range2d.x_range.set_bounds(self.wave_ref - self.xlowspread, self.wave_ref + self.xhighspread)
	    self.Spectraplot1.range2d.y_range.set_bounds(N.min(self.rangearray[:,:])*self.SpectraMultiple, self.colormapmax  * self.SpectraMultiple)
	elif (self.Spectraplotzoom == 'Far'):
	    self.Spectraplot1.range2d.x_range.set_bounds(float(N.min(self.WavelengthData[:])), float(N.max(self.WavelengthData[:])))
	    self.Spectraplot1.range2d.y_range.set_bounds(N.min(self.IntensityData[:,:,self.intensityindex]) * self.SpectraMultiple, N.max(self.IntensityData[:,:,self.intensityindex]) * self.SpectraMultiple)
	    
	self.Spectraplot1.request_redraw()
	
    def _ImageLock_changed(self):
	if self.ImageLock == True:
	    xsize = 3
	    xi = self.InspectorPosition[0]
	    yi = self.InspectorPosition[1]
	    self.markerplotdatax = [xi-xsize, xi+xsize, xi, xi-xsize, xi+xsize]
	    self.markerplotdatay = [yi-xsize, yi+xsize, yi, yi+xsize, yi-xsize]
	elif self.ImageLock == False:
	    self.markerplotdatax = []
	    self.markerplotdatay = []
	    
	self.Mainplotdata.set_data("markerplotdatax", self.markerplotdatax)
	self.Mainplotdata.set_data("markerplotdatay", self.markerplotdatay)
	
    def _Markercolor_changed(self):
	self.Mainplot.MarkerPlot[0].color = self.Markercolor
	
    def _save_changed(self):	
    	if self.SaveFlag == True:
	    self.SaveFlag = False
	elif self.SaveFlag == False:
	    self.SaveFlag = True
	
    def _SaveFlag_changed(self):	
	DPI = 72
	print '--------------Save Initiated------------------'
	
	#Main plot save code
	size = (self.IntensityData[:,:,self.intensityindex].shape[0]*4, self.IntensityData[:,:,self.intensityindex].shape[1]*4)
	path = os.getenv('PWD')
	filenamelist = [path, '/', 'MainPlot_WaveLen', str(self.Wavelength).replace('.','_'), '.png']
	filename = ''.join(filenamelist)
	container = self.Main_img_plot
	temp = container.outer_bounds
	container.outer_bounds = list(size)
	container.do_layout(force=True)
	gc = PlotGraphicsContext(size, dpi=DPI)
	gc.render_component(container)
	gc.save(filename)
	container.outer_bounds = temp
	print "SAVED: ", filename
	
	#Spectra plot save code
	size = (1000,500)
	path = os.getenv('PWD')
	filenamelist = [path, '/', 'SpectraPlot_X', str(self.InspectorPosition[0]), '_Y', str(self.InspectorPosition[1]), '.png']
	filename = ''.join(filenamelist)
	container = self.Spectraplot1
	temp = container.outer_bounds
	container.outer_bounds = list(size)
	container.do_layout(force=True)
	gc = PlotGraphicsContext(size, dpi=DPI)
	gc.render_component(container)
	gc.save(filename)
	container.outer_bounds = temp
	print "SAVED: ", filename
	return
예제 #12
0
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)
예제 #13
0
class PeakFitWindow(HasTraits):
    pairs = List(DatasetPair)
    selected = Instance(DatasetPair)

    plot = Plot

    table_editor = TableEditor(auto_size=True,
                               selection_mode='row',
                               sortable=False,
                               configurable=False,
                               editable=False,
                               cell_bg_color='white',
                               label_bg_color=(232, 232, 232),
                               selection_bg_color=(232, 232, 232),
                               columns=[
                                   ObjectColumn(label='First position',
                                                name='first_name',
                                                cell_color='white',
                                                width=0.33),
                                   ObjectColumn(label='Second position',
                                                name='second_name',
                                                cell_color='white',
                                                width=0.33),
                                   ObjectColumn(label='Peak difference',
                                                name='peak_diff',
                                                cell_color='white',
                                                width=0.33),
                               ])

    traits_view = View(HGroup(
        Item('pairs', editor=table_editor, show_label=False),
        UItem('plot', editor=ComponentEditor(bgcolor='white')),
    ),
                       resizable=True,
                       width=0.75,
                       height=0.5,
                       kind='livemodal',
                       title='View peak fits')

    def __init__(self, *args, **kwargs):
        self.pairs = [
            DatasetPair(first=d1, second=d2)
            for d1, d2 in kwargs['dataset_pairs']
        ]
        self.pairs.sort(key=lambda pair: pair.first.name)
        self.range = kwargs.pop('range')
        super(PeakFitWindow, self).__init__(*args, **kwargs)
        self.table_editor.on_select = self._selection_changed
        self.selected = self.pairs[0] if self.pairs else None
        self.data = ArrayPlotData()
        self.plot = Plot(self.data)
        self.zoom_tool = ClickUndoZoomTool(self.plot,
                                           tool_mode="box",
                                           always_on=True,
                                           drag_button=settings.zoom_button,
                                           undo_button=settings.undo_button,
                                           zoom_to_mouse=True)
        self.plot.overlays.append(self.zoom_tool)
        for pair in self.pairs:
            self._plot_dataset(pair.first)
            self._plot_dataset(pair.second, offset=pair.peak_diff)
        self.plot.request_redraw()

    def _selection_changed(self, selected_objs):
        if self.selected:
            self.plot.plots[self.selected.first.name][0].visible = False
            self.plot.plots[self.selected.second.name][0].visible = False
        self.selected = selected_objs
        if self.selected is None:
            return
        self.plot.plots[self.selected.first.name][0].visible = True
        self.plot.plots[self.selected.second.name][0].visible = True
        self.plot.request_redraw()

    def _plot_dataset(self, dataset, offset=0.0):
        x, y = dataset.data[:, [0, 1]].T
        self.data.set_data(dataset.name + '_x', x + offset)
        self.data.set_data(dataset.name + '_y', y)
        plot = self.plot.plot((dataset.name + '_x', dataset.name + '_y'),
                              type='line',
                              color=dataset.metadata['ui'].color,
                              name=dataset.name,
                              visible=False)
        range = plot[0].index_mapper.range
        range.low, range.high = self.range
        pvr = plot[0].value_range
        y_in_range = y[(x > range.low) & (x < range.high)]
        pvr.low_setting, pvr.high_setting = (y_in_range.min(),
                                             y_in_range.max())
        pvr.refresh()
예제 #14
0
class PeakFitWindow(HasTraits):
    pairs = List(DatasetPair)
    selected = Instance(DatasetPair)

    plot = Plot

    table_editor = TableEditor(
        auto_size=True,
        selection_mode='row',
        sortable=False,
        configurable=False,
        editable=False,
        cell_bg_color='white',
        label_bg_color=(232,232,232),
        selection_bg_color=(232,232,232),
        columns=[
            ObjectColumn(label='First position', name='first_name', cell_color='white', width=0.33),
            ObjectColumn(label='Second position', name='second_name', cell_color='white', width=0.33),
            ObjectColumn(label='Peak difference', name='peak_diff', cell_color='white', width=0.33),
        ]
    )

    traits_view = View(
        HGroup(
            Item('pairs', editor=table_editor, show_label=False),
            UItem('plot', editor=ComponentEditor(bgcolor='white')),
        ),
        resizable=True, width=0.75, height=0.5, kind='livemodal',
        title='View peak fits'
    )

    def __init__(self, *args, **kwargs):
        self.pairs = [ DatasetPair(first=d1, second=d2) for d1, d2 in kwargs['dataset_pairs'] ]
        self.pairs.sort(key=lambda pair: pair.first.name)
        self.range = kwargs.pop('range')
        super(PeakFitWindow, self).__init__(*args, **kwargs)
        self.table_editor.on_select = self._selection_changed
        self.selected = self.pairs[0] if self.pairs else None
        self.data = ArrayPlotData()
        self.plot = Plot(self.data)
        self.zoom_tool = ClickUndoZoomTool(self.plot,
                        tool_mode="box", always_on=True,
                        drag_button=settings.zoom_button,
                        undo_button=settings.undo_button,
                        zoom_to_mouse=True)
        self.plot.overlays.append(self.zoom_tool)
        for pair in self.pairs:
            self._plot_dataset(pair.first)
            self._plot_dataset(pair.second, offset=pair.peak_diff)
        self.plot.request_redraw()

    def _selection_changed(self, selected_objs):
        if self.selected:
            self.plot.plots[self.selected.first.name][0].visible = False
            self.plot.plots[self.selected.second.name][0].visible = False
        self.selected = selected_objs
        if self.selected is None:
            return
        self.plot.plots[self.selected.first.name][0].visible = True
        self.plot.plots[self.selected.second.name][0].visible = True
        self.plot.request_redraw()

    def _plot_dataset(self, dataset, offset=0.0):
        x, y = dataset.data[:,[0,1]].T
        self.data.set_data(dataset.name + '_x', x + offset)
        self.data.set_data(dataset.name + '_y', y)
        plot = self.plot.plot((dataset.name + '_x', dataset.name + '_y'),
                              type='line',
                              color=dataset.metadata['ui'].color,
                              name=dataset.name,
                              visible=False)
        range = plot[0].index_mapper.range
        range.low, range.high = self.range
        pvr = plot[0].value_range
        y_in_range = y[(x>range.low) & (x<range.high)]
        pvr.low_setting, pvr.high_setting = (y_in_range.min(), y_in_range.max())
        pvr.refresh()
예제 #15
0
파일: tools.py 프로젝트: jeicher/nmrpy2
class DataPlotter(traits.HasTraits):
    plot = traits.Instance(
        Plot
    )  # the attribute 'plot' of class DataPlotter is a trait that has to be an instance of the chaco class Plot.
    plot_data = traits.Instance(ArrayPlotData)
    data_index = traits.List(traits.Int)
    data_selected = traits.List(traits.Int)

    y_offset = traits.Range(0.0, 20.0, value=0)
    x_offset = traits.Range(-10.0, 10.0, value=0)
    y_scale = traits.Range(1e-3, 2.0, value=1.0)
    x_range_up = traits.Float()
    x_range_dn = traits.Float()
    x_range_btn = traits.Button(label="Set range")

    reset_plot_btn = traits.Button(label="Reset plot")
    select_all_btn = traits.Button(label="All")
    select_none_btn = traits.Button(label="None")

    # basic processing
    lb = traits.Float(10.0)
    lb_btn = traits.Button(label="Apodisation")
    lb_plt_btn = traits.Button(label="Plot Apod.")
    zf_btn = traits.Button(label="Zero-fill")
    ft_btn = traits.Button(label="FT")

    # phasing
    ph_auto_btn = traits.Button(label="Auto: all")
    ph_auto_single_btn = traits.Button(label="Auto: selected")
    ph_mp = traits.Bool(True, label="Parallelise")
    ph_man_btn = traits.Button(label="Manual")
    ph_global = traits.Bool(label="apply globally")
    _peak_marker_overlays = {}
    _bl_marker_overlays = {}
    _bl_range_plots = {}

    # baseline correctoin
    bl_cor_btn = traits.Button(label="BL correct")
    bl_sel_btn = traits.Button(label="Select points")

    # peak-picking
    peak_pick_btn = traits.Button(label="Peak-picking")
    peak_pick_clear = traits.Button(label="Clear peaks")
    deconvolute_btn = traits.Button(label="Deconvolute")
    plot_decon_btn = traits.Button(label="Show Lineshapes")
    lorgau = traits.Range(0.0, 1.0, value=0, label="Lorentzian = 0, Gaussian = 1")
    deconvolute_mp = traits.Bool(True, label="Parallelise")

    plot_ints_btn = traits.Button(label="Plot integrals")
    save_fids_btn = traits.Button(label="Save FIDs")
    save_ints_btn = traits.Button(label="Integrals -> csv")

    _peaks_now = []
    _ranges_now = []
    _bl_ranges_now = []
    _bl_ranges = []
    _bl_indices = []

    _flags = {"manphasing": False, "bl_selecting": False, "picking": False, "lineshapes_vis": False}

    # progress bar
    # progress_val = traits.Int()
    loading_animation = traits.File("/home/jeicher/Apps/NMRPy/nmrpy/loading.gif")
    busy_animation = traits.Bool(False)

    # def _metadata_handler(self):
    # return #print self.metadata_source.metadata.get('selections')

    def _bl_handler(self):
        # set_trace()
        self._bl_ranges_now = list(self.bl_tool.ranges_now)
        if self.bl_tool.ranges_now:
            picked_ranges = [self.correct_padding(r) for r in self.bl_tool.ranges_now]
            if self._bl_ranges is not picked_ranges:
                self._bl_ranges = picked_ranges
                self.bl_marker(self._bl_ranges[-1][0], colour="blue")
                self.bl_marker(self._bl_ranges[-1][1], colour="blue")
                l_bl = len(self._bl_ranges) - 1
                bl_range_x = self._bl_ranges[l_bl]
                y = 0.2 * self.plot.range2d.y_range.high
                bl_range_y = [y, y]
                self.plot_data.set_data("bl_range_x_%i" % (l_bl), bl_range_x)
                self.plot_data.set_data("bl_range_y_%i" % (l_bl), bl_range_y)
                self._bl_range_plots["bl_range_x_%i" % (l_bl)] = self.plot.plot(
                    ("bl_range_x_%i" % (l_bl), "bl_range_y_%i" % (l_bl)),
                    type="line",
                    name="bl_range_%i" % (l_bl),
                    line_width=0.5,
                    color="blue",
                )[0]

    def _peak_handler(self):
        # set_trace()
        self._peaks_now = list(self.picking_tool.peaks_now)
        self._ranges_now = list(self.picking_tool.ranges_now)
        picked_peaks = self.index2ppm(np.array(self.picking_tool.peaks_now))
        if picked_peaks != self.fid.peaks:
            self.fid.peaks = picked_peaks
            if self.fid.peaks:
                peak_ppm = self.fid.peaks[-1]
                self.plot_marker(peak_ppm)
        if self.picking_tool.ranges_now:
            picked_ranges = [self.correct_padding(r) for r in self.picking_tool.ranges_now]
            if self.fid.ranges is not picked_ranges:
                self.fid.ranges = picked_ranges
                self.range_marker(self.fid.ranges[-1][0], colour="blue")
                self.range_marker(self.fid.ranges[-1][1], colour="blue")

    def index2ppm(self, index):
        return list(
            np.array(
                self.fid.params["sw_left"] - (index - self.plot.padding_left) / self.plot.width * self.fid.params["sw"],
                dtype="float16",
            )
        )

    def correct_padding(self, values):
        return list(
            np.array(
                np.array(values) + float(self.plot.padding_left) / self.plot.width * self.fid.params["sw"],
                dtype="float16",
            )
        )

    def __init__(self, fid):
        super(DataPlotter, self).__init__()
        self.fid = fid
        data = fid.data
        self.data_index = range(len(data))
        if self.fid._flags["ft"]:
            self.x = np.linspace(
                self.fid.params["sw_left"], fid.params["sw_left"] - fid.params["sw"], len(self.fid.data[0])
            )
            self.plot_data = ArrayPlotData(x=self.x, *np.real(data))
            plot = Plot(self.plot_data, default_origin="bottom right", padding=[5, 0, 0, 35])
        else:
            self.x = np.linspace(0, self.fid.params["at"], len(self.fid.data[0]))
            self.plot_data = ArrayPlotData(x=self.x, *np.real(data))
            plot = Plot(self.plot_data, default_origin="bottom left", padding=[5, 0, 0, 35])
        self.plot = plot
        self.plot_init()

    def plot_init(self, index=[0]):
        if self.fid._flags["ft"]:
            self.plot.x_axis.title = "ppm."
        else:
            self.plot.x_axis.title = "sec."
        self.zoomtool = BetterZoom(self.plot, zoom_to_mouse=False, x_min_zoom_factor=1, zoom_factor=1.5)
        self.pantool = PanTool(self.plot)
        self.phase_dragtool = PhaseDragTool(self.plot)
        self.plot.tools.append(self.zoomtool)
        self.plot.tools.append(self.pantool)
        self.plot.y_axis.visible = False
        for i in index:
            self.plot.plot(("x", "series%i" % (i + 1)), type="line", line_width=0.5, color="black")[0]
        self.plot.request_redraw()
        self.old_y_scale = self.y_scale
        self.index_array = np.arange(len(self.fid.data))
        self.y_offsets = self.index_array * self.y_offset
        self.x_offsets = self.index_array * self.x_offset
        self.data_selected = index
        self.x_range_up = round(self.x[0], 3)
        self.x_range_dn = round(self.x[-1], 3)
        # this is necessary for phasing:
        self.plot._ps = self.fid.ps
        self.plot._data_complex = self.fid.data

    def text_marker(self, text, colour="black"):
        xl, xh, y = self.plot.range2d.x_range.low, self.plot.range2d.x_range.high, self.plot.range2d.y_range.high
        x = xl + 0.1 * (xh - xl)
        y = 0.8 * y

        dl = DataLabel(
            self.plot.plots["plot0"][0],
            data_point=(x, y),
            label_position="top",
            label_text=text,
            show_label_coords=False,
            marker_visible=False,
            border_visible=True,
            arrow_visible=False,
        )
        self.plot.plots["plot0"][0].overlays.append(dl)
        self.plot.request_redraw()

    def plot_marker(self, ppm, colour="red"):
        dl = DataLabel(
            self.plot.plots["plot0"][0],
            data_point=(ppm, 0.0),
            arrow_color=colour,
            arrow_size=10,
            label_position="top",
            label_format="%(x).3f",
            padding_bottom=int(self.plot.height * 0.1),
            marker_visible=False,
            border_visible=False,
            arrow_visible=True,
        )
        self.plot.plots["plot0"][0].overlays.append(dl)
        self._peak_marker_overlays[ppm] = dl
        self.plot.request_redraw()

    def range_marker(self, ppm, colour="blue"):
        dl = DataLabel(
            self.plot.plots["plot0"][0],
            data_point=(ppm, 0.0),
            arrow_color=colour,
            arrow_size=10,
            label_position="top",
            label_format="%(x).3f",
            padding_bottom=int(self.plot.height * 0.25),
            marker_visible=False,
            border_visible=False,
            arrow_visible=True,
        )
        self.plot.plots["plot0"][0].overlays.append(dl)
        self._peak_marker_overlays[ppm] = dl
        self.plot.request_redraw()

    def bl_marker(self, ppm, colour="blue"):
        dl = DataLabel(
            self.plot.plots["plot0"][0],
            data_point=(ppm, 0.0),
            arrow_color=colour,
            arrow_size=10,
            label_position="top",
            label_format="%(x).3f",
            padding_bottom=int(self.plot.height * 0.25),
            marker_visible=False,
            border_visible=False,
            arrow_visible=True,
        )
        self.plot.plots["plot0"][0].overlays.append(dl)
        self._bl_marker_overlays[ppm] = dl
        self.plot.request_redraw()

    def _x_range_btn_fired(self):
        if self.x_range_up < self.x_range_dn:
            xr = self.x_range_up
            self.x_range_up = self.x_range_dn
            self.x_range_dn = xr
        self.set_x_range(up=self.x_range_up, dn=self.x_range_dn)
        self.plot.request_redraw()

    def set_x_range(self, up=x_range_up, dn=x_range_dn):
        if self.fid._flags["ft"]:
            self.plot.index_range.high = up
            self.plot.index_range.low = dn
        else:
            self.plot.index_range.high = dn
            self.plot.index_range.low = up
        pass

    def _y_scale_changed(self):
        self.set_y_scale(scale=self.y_scale)

    def set_y_scale(self, scale=y_scale):
        self.plot.value_range.high /= scale / self.old_y_scale
        self.plot.request_redraw()
        self.old_y_scale = scale

    def reset_plot(self):
        self.x_offset, self.y_offset = 0, 0
        self.y_scale = 1.0
        if self.fid._flags["ft"]:
            self.plot.index_range.low, self.plot.index_range.high = [self.x[-1], self.x[0]]
        else:
            self.plot.index_range.low, self.plot.index_range.high = [self.x[0], self.x[-1]]
        self.plot.value_range.low = self.plot.data.arrays["series%i" % (self.data_selected[0] + 1)].min()
        self.plot.value_range.high = self.plot.data.arrays["series%i" % (self.data_selected[0] + 1)].max()

    def _reset_plot_btn_fired(self):
        print "resetting plot..."
        self.reset_plot()

    def _select_all_btn_fired(self):
        self.data_selected = range(len(self.fid.data))

    def _select_none_btn_fired(self):
        self.data_selected = []

    def set_plot_offset(self, x=None, y=None):
        if x == None and y == None:
            pass

        self.old_x_offsets = self.x_offsets
        self.old_y_offsets = self.y_offsets
        self.x_offsets = self.index_array * x
        self.y_offsets = self.index_array * y
        for i in np.arange(len([pt for pt in self.plot.plots if "plot" in pt])):
            self.plot.plots["plot%i" % i][0].position = [self.x_offsets[i], self.y_offsets[i]]
        self.plot.request_redraw()

    def _y_offset_changed(self):
        self.set_plot_offset(x=self.x_offset, y=self.y_offset)

    def _x_offset_changed(self):
        self.set_plot_offset(x=self.x_offset, y=self.y_offset)

    # for some mysterious reason, selecting new data to plot doesn't retain the plot offsets even if you set them explicitly
    def _data_selected_changed(self):
        if self._flags["manphasing"]:
            self.end_man_phasing()
        if self._flags["picking"]:
            self.end_picking()

        self.plot.delplot(*self.plot.plots)
        self.plot.request_redraw()
        for i in self.data_selected:
            self.plot.plot(
                ("x", "series%i" % (i + 1)),
                type="line",
                line_width=0.5,
                color="black",
                position=[self.x_offsets[i], self.y_offsets[i]],
            )  # FIX: this isn't working
        # self.reset_plot() # this is due to the fact that the plot automatically resets anyway
        if self._flags["lineshapes_vis"]:
            self.clear_lineshapes()
            self.plot_deconv()

    # processing buttons

    # plot the current apodisation function based on lb, and do apodisation
    # =================================================
    def _lb_plt_btn_fired(self):
        if self.fid._flags["ft"]:
            return
        if "lb1" in self.plot.plots:
            self.plot.delplot("lb1")
            self.plot.request_redraw()
            return
        self.plot_lb()

    def plot_lb(self):
        if self.fid._flags["ft"]:
            return
        lb_data = self.fid.data[self.data_selected[0]]
        lb_plt = np.exp(-np.pi * np.arange(len(lb_data)) * (self.lb / self.fid.params["sw_hz"])) * lb_data[0]
        self.plot_data.set_data("lb1", np.real(lb_plt))
        self.plot.plot(("x", "lb1"), type="line", name="lb1", line_width=1, color="blue")[0]
        self.plot.request_redraw()

    def _lb_changed(self):
        if self.fid._flags["ft"]:
            return
        lb_data = self.fid.data[self.data_selected[0]]
        lb_plt = np.exp(-np.pi * np.arange(len(lb_data)) * (self.lb / self.fid.params["sw_hz"])) * lb_data[0]
        self.plot_data.set_data("lb1", np.real(lb_plt))

    def _lb_btn_fired(self):
        if self.fid._flags["ft"]:
            return
        self.fid.emhz(self.lb)
        self.update_plot_data_from_fid()

    def _zf_btn_fired(self):
        if self.fid._flags["ft"]:
            return
        if "lb1" in self.plot.plots:
            self.plot.delplot("lb1")
        self.fid.zf()
        self.update_plot_data_from_fid()

    def _ft_btn_fired(self):
        if "lb1" in self.plot.plots:
            self.plot.delplot("lb1")
        if self.fid._flags["ft"]:
            return
        self.fid.ft()
        self.update_plot_data_from_fid()
        self.plot = Plot(self.plot_data, default_origin="bottom right", padding=[5, 0, 0, 35])
        self.plot_init(index=self.data_selected)
        self.reset_plot()

    def _ph_auto_btn_fired(self):
        if not self.fid._flags["ft"]:
            return
        for i in self.fid.data[
            np.iscomplex(self.fid.data) == False
        ]:  # as np.iscomplex returns False for 0+0j, we need to check manually
            if type(i) != np.complex128:
                print "Cannot perform phase correction on non-imaginary data."
                return
        self.fid.phase_auto(mp=self.ph_mp, discard_imaginary=False)
        self.update_plot_data_from_fid()

    def _ph_auto_single_btn_fired(self):
        if not self.fid._flags["ft"]:
            return
        for i in self.fid.data[
            np.iscomplex(self.fid.data) == False
        ]:  # as np.iscomplex returns False for 0+0j, we need to check manually
            if type(i) != np.complex128:
                print "Cannot perform phase correction on non-imaginary data."
                return
        for i in self.data_selected:
            self.fid._phase_area_single(i)
        self.update_plot_data_from_fid()

    def _ph_man_btn_fired(self):
        if not self.fid._flags["ft"]:
            return
        for i in self.fid.data[
            np.iscomplex(self.fid.data) == False
        ]:  # as np.iscomplex returns False for 0+0j, we need to check manually
            if type(i) != np.complex128:
                print "Cannot perform phase correction on non-imaginary data."
                return
        if not self._flags["manphasing"]:
            self._flags["manphasing"] = True
            self.text_marker("Drag to phase:\n up/down - p0\n left/right - p1")
            self.change_plot_colour(colour="red")
            self.disable_plot_tools()
            self.plot._data_selected = self.data_selected
            self.plot._data_complex = self.fid.data[np.array(self.data_selected)]
            self.plot.tools.append(PhaseDragTool(self.plot))
        elif self._flags["manphasing"]:
            self.end_man_phasing()

    def end_man_phasing(self):
        self._flags["manphasing"] = False
        self.remove_all_overlays()
        self.change_plot_colour(colour="black")
        print "p0: %f, p1: %f" % (self.plot.tools[0].p0, self.plot.tools[0].p1)
        if self.ph_global:
            self.fid.data = self.fid.ps(self.fid.data, p0=self.plot.tools[0].p0, p1=self.plot.tools[0].p1)
            self.update_plot_data_from_fid()
        else:
            for i, j in zip(self.plot._data_selected, self.plot._data_complex):
                self.fid.data[i] = j
        self.disable_plot_tools()
        self.enable_plot_tools()

    def remove_extra_overlays(self):
        self.plot.overlays = [self.plot.overlays[0]]
        self.plot.plots["plot0"][0].overlays = []

    def remove_all_overlays(self):
        self.plot.overlays = []
        self.plot.plots["plot0"][0].overlays = []

    def disable_plot_tools(self):
        self.plot.tools = []

    def enable_plot_tools(self):
        self.plot.tools.append(self.zoomtool)
        self.plot.tools.append(self.pantool)

    def change_plot_colour(self, colour="black"):
        for plot in self.plot.plots:
            self.plot.plots[plot][0].color = colour

    def _bl_sel_btn_fired(self):
        if not self.fid._flags["ft"]:
            return
        if self._flags["bl_selecting"]:
            self.end_bl_select()
        else:
            self._flags["bl_selecting"] = True
            self.plot.plot(
                ("x", "series%i" % (self.data_selected[0] + 1)),
                name="bl_plot",
                type="scatter",
                alpha=1.0,
                line_width=0,
                selection_line_width=0,
                marker_size=2,
                selection_marker_size=2,
                selection_color="black",  # change this to make selected points visible
                color="black",
            )[0]

            self.text_marker("Select ranges for baseline correction:\n drag right - select range")
            self.disable_plot_tools()
            self.plot.tools.append(
                BlSelectTool(
                    self.plot.plots["plot0"][0], metadata_name="selections", append_key=KeySpec(None, "control")
                )
            )
            self.plot.overlays.append(
                RangeSelectionOverlay(
                    component=self.plot.plots["bl_plot"][0], metadata_name="selections", axis="index", fill_color="blue"
                )
            )
            self.plot.overlays.append(
                LineInspector(
                    component=self.plot, axis="index_x", inspect_mode="indexed", write_metadata=True, color="blue"
                )
            )

            if self._bl_marker_overlays:
                self.plot.plots["plot0"][0].overlays = self._bl_marker_overlays.values()
            # for i in self._bl_range_plots: #for some reason, after re-adding these plot objects, deleting them doesn't actually delete the visual component in self.plot_components, thus they're being redrawn entirely below
            # self.plot.add(self._bl_range_plots[i])
            for l_bl in range(len(self._bl_ranges)):
                self.plot.plot(
                    ("bl_range_x_%i" % (l_bl), "bl_range_y_%i" % (l_bl)),
                    type="line",
                    name="bl_range_%i" % (l_bl),
                    line_width=0.5,
                    color="blue",
                )[0]

            self.plot.request_redraw()
            self.bl_tool = self.plot.tools[0]
            self.bl_tool.on_trait_change(self._bl_handler, name=["ranges_now"])

    def end_bl_select(self):
        self._flags["bl_selecting"] = False
        self._bl_indices = []
        for i, j in self._bl_ranges:
            self._bl_indices.append((i < self.x) * (self.x < j))
        self.fid.bl_points = np.where(sum(self._bl_indices, 0) == 1)[0]
        # self.plot.delplot('bl_plot')
        for i in [j for j in self.plot.plots if "bl_" in j]:
            self.plot.delplot(i)
        self.plot.request_redraw()
        self.remove_extra_overlays()
        self.disable_plot_tools()
        self.enable_plot_tools()

    def _bl_cor_btn_fired(self):
        if not self.fid._flags["ft"]:
            return
        if self._flags["bl_selecting"]:
            self.end_bl_select()
        self.fid.bl_fit()
        self.remove_all_overlays()
        self.update_plot_data_from_fid()

    def _peak_pick_btn_fired(self):
        if not self.fid._flags["ft"]:
            return
        if self._flags["picking"]:
            self.end_picking()
            # print 'self.fid.peaks', self.fid.peaks, '\nself.picking_tool.peaks_now',self.picking_tool.peaks_now
            return
        else:
            self._flags["picking"] = True

        self.reset_plot()
        if self._peak_marker_overlays:
            self.plot.plots["plot0"][0].overlays = self._peak_marker_overlays.values()
        self.text_marker("Peak-picking:\n left click - select peak\n drag right - select range")
        self.disable_plot_tools()

        # set_trace()
        pst = PeakSelectTool(self.plot.plots["plot0"][0], left_button_selects=True)
        pst.peaks_now = self._peaks_now
        pst.ranges_now = self._ranges_now

        self.plot.overlays.append(
            PeakPicker(
                component=self.plot,
                axis="index_x",
                inspect_mode="indexed",
                metadata_name="peaks",
                write_metadata=True,
                color="blue",
            )
        )
        self.plot.tools.append(pst)
        # metadata_name='selections',
        # append_key=KeySpec(None, 'control')))
        self.plot.overlays.append(
            RangeSelectionOverlay(
                component=self.plot.plots["plot0"][0], metadata_name="selections", axis="index", fill_color="blue"
            )
        )

        # Set up the trait handler for range selection
        # self.metadata_source = self.plot.plots['plot0'][0].index#self.plot.tools[0]
        # self.metadata_source.on_trait_change(self._metadata_handler, "metadata_changed")

        # Set up the trait handler for peak/range selections
        self.picking_tool = self.plot.tools[0]
        self.picking_tool.on_trait_change(self._peak_handler, name=["peaks_now", "ranges_now"])
        # print 'self.fid.peaks', self.fid.peaks, '\nself.picking_tool.peaks_now',self.picking_tool.peaks_now

    def end_picking(self):
        # set_trace()
        self._flags["picking"] = False
        if self.fid.peaks and self.fid.ranges:
            self.clear_invalid_peaks_ranges()
        else:
            self.clear_all_peaks_ranges()

        self.remove_all_overlays()
        self.disable_plot_tools()
        self.enable_plot_tools()
        self.plot.request_redraw()

    def clear_invalid_peaks_ranges(self):
        # set_trace()
        peaks_outside_of_ranges = self.peaks_outside_of_ranges()
        ranges_without_peaks = self.ranges_without_peaks()
        # remove uncoupled peak markers and empty range markers
        for i in peaks_outside_of_ranges:
            self._peak_marker_overlays.pop(self.fid.peaks[i])
        for i in ranges_without_peaks:
            for rng in self.fid.ranges[i]:
                self._peak_marker_overlays.pop(rng)
        # remove uncoupled peaks and empty ranges
        self.fid.peaks = [self.fid.peaks[i] for i in range(len(self.fid.peaks)) if i not in peaks_outside_of_ranges]
        self._peaks_now = [self._peaks_now[i] for i in range(len(self._peaks_now)) if i not in peaks_outside_of_ranges]
        self.fid.ranges = [self.fid.ranges[i] for i in range(len(self.fid.ranges)) if i not in ranges_without_peaks]
        self._ranges_now = [self._ranges_now[i] for i in range(len(self._ranges_now)) if i not in ranges_without_peaks]

    def clear_all_peaks_ranges(self):
        self.fid.peaks = []
        self.fid.ranges = []
        self.picking_tool.peaks_now = []
        self.picking_tool.ranges_now = []
        self._peak_marker_overlays = {}
        self.plot.plots["plot0"][0].overlays = []
        self.plot.request_redraw()
        print "Selected peaks and ranges cleared."

    def peaks_ranges_matrix(self):
        return np.array([(self.fid.peaks >= i[0]) * (self.fid.peaks <= i[1]) for i in self.fid.ranges])

    def peaks_outside_of_ranges(self):
        index = self.peaks_ranges_matrix().sum(0)
        return np.arange(len(self.fid.peaks))[np.where(index == 0)]

    def ranges_without_peaks(self):
        index = self.peaks_ranges_matrix().sum(1)
        return np.arange(len(self.fid.ranges))[np.where(index == 0)]

    def _peak_pick_clear_fired(self):
        self.clear_all_peaks_ranges()

    def busy(self):
        if self.busy_animation:
            self.busy_animation = False
        else:
            self.busy_animation = True

    def _deconvolute_btn_fired(self):
        # set_trace()
        # self.busy()
        if self._flags["picking"]:
            self.end_picking()
        if self.fid.peaks == []:
            print "No peaks selected."
            return
        print "Imaginary components discarded."
        self.fid.real()
        self.fid.deconv(gl=self.fid._flags["gl"], mp=self.deconvolute_mp)
        # self.busy()
        self._plot_decon_btn_fired()

    def clear_lineshapes(self):
        for line in [i for i in self.plot.plots if "lineshape" in i]:
            self.plot.delplot(line)
        for line in [i for i in self.plot.plots if "residual" in i]:
            self.plot.delplot(line)
        self.plot.request_redraw()

    def _plot_decon_btn_fired(self):
        if self._flags["lineshapes_vis"]:
            self.clear_lineshapes()
            self._flags["lineshapes_vis"] = False
            return

        self._flags["lineshapes_vis"] = True
        self.plot_deconv()

    def plot_deconv(self):
        index = self.data_selected[0]
        sw_left = self.fid.params["sw_left"]
        data = self.fid.data[index][::-1]
        if len(self.fid.fits) == 0:
            return
        paramarray = self.fid.fits[index]

        def i2ppm(index_value):
            return np.mgrid[sw_left - self.fid.params["sw"] : sw_left : complex(len(data))][index_value]

        def peaknum(paramarray, peak):
            pkr = []
            for i in paramarray:
                for j in i:
                    pkr.append(np.array(j - peak).sum())
            return np.where(np.array(pkr) == 0.0)[0][0]

        x = np.arange(len(data))
        peakplots = []
        for irange in paramarray:
            for ipeak in irange:
                # if txt:
                #    text(i2ppm(int(ipeak[0])), 0.1+pk.max(), str(peaknum(paramarray,ipeak)), color='#336699')
                peakplots.append(f_pk(ipeak, x)[::-1])
        # plot sum of all lines
        self.plot_data.set_data("lineshapes_%i" % (index), sum(peakplots, 0))
        self.plot.plot(
            ("x", "lineshapes_%i" % (index)), type="line", name="lineshapes_%i" % (index), line_width=0.5, color="blue"
        )[0]
        # plot residual
        self.plot_data.set_data("residuals_%i" % (index), data[::-1] - sum(peakplots, 0))
        self.plot.plot(
            ("x", "residuals_%i" % (index)), type="line", name="residuals_%i" % (index), line_width=0.5, color="red"
        )[0]
        # plot all individual lines
        for peak in range(len(peakplots)):
            self.plot_data.set_data("lineshape_%i_%i" % (index, peak), peakplots[peak])
            self.plot.plot(
                ("x", "lineshape_%i_%i" % (index, peak)),
                type="line",
                name="lineshape_%i_%i" % (index, peak),
                line_width=0.5,
                color="green",
            )[0]
        self.plot.request_redraw()

    def _lorgau_changed(self):
        self.fid._flags["gl"] = self.lorgau

    def update_plot_data_from_fid(self, index=None):
        if self.fid._flags["ft"]:
            self.x = np.linspace(
                self.fid.params["sw_left"], self.fid.params["sw_left"] - self.fid.params["sw"], len(self.fid.data[0])
            )
        else:
            self.x = np.linspace(0, self.fid.params["at"], len(self.fid.data[0]))
        self.plot_data.set_data("x", self.x)
        if index == None:
            for i in self.index_array:
                self.plot_data.set_data("series%i" % (i + 1), np.real(self.fid.data[i]))
        else:
            self.plot_data.set_data("series%i" % (index + 1), np.real(self.fid.data[index]))
        self.plot.request_redraw()

    def _plot_ints_btn_fired(self):
        if len(self.fid.integrals) == 0:
            print "self.integrals does not exist"
            return
        self.fid.plot_integrals()

    def _save_fids_btn_fired(self):
        self.fid.savefid_dict()

    def _save_ints_btn_fired(self):
        self.fid.save_integrals_csv()

    def default_traits_view(self):
        # exit_action = Action(name='Exit',
        #                action='exit_action')

        traits_view = View(
            Group(
                Group(
                    Item(
                        "data_index",
                        editor=TabularEditor(
                            show_titles=False,
                            selected="data_selected",
                            editable=False,
                            multi_select=True,
                            adapter=MultiSelectAdapter(),
                        ),
                        width=0.02,
                        show_label=False,
                        has_focus=True,
                    ),
                    Item("plot", editor=ComponentEditor(), show_label=False),
                    padding=0,
                    show_border=False,
                    orientation="horizontal",
                ),
                Group(
                    Group(
                        Group(
                            Item("select_all_btn", show_label=False),
                            Item("select_none_btn", show_label=False),
                            Item("reset_plot_btn", show_label=False),
                            orientation="vertical",
                        ),
                        Group(
                            Item("y_offset"),
                            Item("x_offset"),
                            Item("y_scale", show_label=True),
                            Group(
                                Item("x_range_btn", show_label=False),
                                Item("x_range_up", show_label=False),
                                Item("x_range_dn", show_label=False),
                                orientation="horizontal",
                            ),
                            orientation="vertical",
                        ),
                        orientation="horizontal",
                        show_border=True,
                        label="Plotting",
                    ),
                    Group(
                        Group(
                            Group(
                                Item("lb", show_label=False, format_str="%.2f Hz"),
                                Item("lb_btn", show_label=False),
                                Item("lb_plt_btn", show_label=False),
                                Item("zf_btn", show_label=False),
                                Item("ft_btn", show_label=False),
                                orientation="horizontal",
                                show_border=True,
                                label="Basic",
                            ),
                            Group(
                                Item("bl_cor_btn", show_label=False),
                                Item("bl_sel_btn", show_label=False),
                                orientation="horizontal",
                                show_border=True,
                                label="Baseline correction",
                            ),
                            orientation="horizontal",
                        ),
                        # Group(
                        # Item('zf_btn', show_label=False),
                        # Item('ft_btn', show_label=False),
                        # orientation='horizontal'),
                        Group(
                            Group(
                                Item("ph_auto_btn", show_label=False),
                                Item("ph_auto_single_btn", show_label=False),
                                Item("ph_mp", show_label=True),
                                orientation="horizontal",
                                show_border=True,
                            ),
                            Group(
                                Item("ph_man_btn", show_label=False),
                                Item("ph_global", show_label=True),
                                orientation="horizontal",
                                show_border=True,
                            ),
                            orientation="horizontal",
                            show_border=True,
                            label="Phase correction",
                        ),
                    ),
                    Group(
                        Group(
                            Group(
                                Item("peak_pick_btn", show_label=False),
                                Item("peak_pick_clear", show_label=False),
                                Item("deconvolute_btn", show_label=False),
                                Item(
                                    "lorgau",
                                    show_label=False,
                                    editor=RangeEditor(low_label="Lorentz", high_label="Gauss"),
                                ),
                                Item("deconvolute_mp", show_label=True),
                                orientation="horizontal",
                                show_border=False,
                            ),
                            Group(
                                Item("plot_decon_btn", show_label=False),
                                Item("plot_ints_btn", show_label=False),
                                orientation="horizontal",
                                show_border=False,
                            ),
                            orientation="vertical",
                            show_border=True,
                            label="Peak-picking and deconvolution",
                        ),
                        Group(
                            Item("save_fids_btn", show_label=False),
                            Item("save_ints_btn", show_label=False),
                            show_border=True,
                            label="Save",
                            orientation="horizontal",
                        ),
                        orientation="vertical",
                    ),
                    #                                            Group(
                    #                                        #    Item( 'loading_animation',
                    #                                        #        editor     = AnimatedGIFEditor(playing=str('busy_animation')),#( frame = 'frame_animation' ),
                    #                                        #        show_label = False),
                    #                                        #    #Item('progress_val',
                    #                                        #    #    show_label=False,
                    #                                        #    #    editor=ProgressEditor(
                    #                                        #    #        min=0,
                    #                                        #    #        max=100,
                    #                                        #    #        ),
                    #                                        #    #    )
                    #                                                Item('plot_ints_btn', show_label=False),
                    #                                                show_border=True,
                    #                                                orientation='horizontal'),
                    show_border=True,
                    orientation="horizontal",
                ),
            ),
            width=1.0,
            height=1.0,
            resizable=True,
            handler=TC_Handler(),
            title="NMRPy",
            # menubar=MenuBar(
            #            Menu(
            #                exit_action,
            #                name='File')),
        )
        return traits_view
예제 #16
0
class MyPlot(HasTraits):
    """ Displays a plot with a few buttons to control which overlay
        to display
    """
    plot = Instance(Plot)
    status_overlay = Instance(StatusLayer)

    error_button = Button('Error')
    warn_button = Button('Warning')
    no_problem_button = Button('No problem')

    traits_view = View(
        HGroup(UItem('error_button'), UItem('warn_button'),
               UItem('no_problem_button')),
        UItem('plot', editor=ComponentEditor()),
        width=700,
        height=600,
        resizable=True,
    )

    def __init__(self, index, data_series, **kw):
        super(MyPlot, self).__init__(**kw)

        plot_data = ArrayPlotData(index=index)
        plot_data.set_data('data_series', data_series)
        self.plot = Plot(plot_data)
        self.plot.plot(('index', 'data_series'))

    def _error_button_fired(self, event):
        """ removes the old overlay and replaces it with
            an error overlay
        """
        self.clear_status()

        self.status_overlay = ErrorLayer(component=self.plot,
                                         align='ul',
                                         scale_factor=0.25)
        self.plot.overlays.append(self.status_overlay)

        self.plot.request_redraw()

    def _warn_button_fired(self, event):
        """ removes the old overlay and replaces it with
            an warning overlay
        """
        self.clear_status()

        self.status_overlay = WarningLayer(component=self.plot,
                                           align='ur',
                                           scale_factor=0.25)
        self.plot.overlays.append(self.status_overlay)

        self.plot.request_redraw()

    def _no_problem_button_fired(self, event):
        """ removes the old overlay
        """
        self.clear_status()
        self.plot.request_redraw()

    def clear_status(self):
        if self.status_overlay in self.plot.overlays:
            # fade_out will remove the overlay when its done
            self.status_overlay.fade_out()
예제 #17
0
class TraitedPlot( HasTraits ):

  # the Traits Plot Container
  myTP = Instance( Plot )
  myTCB = Instance( ColorBar )
  myTIC = Instance( HPlotContainer )

  # contains a list of default colormap names
  colormapNameTE = Enum(
      default_colormaps.color_map_name_dict.keys(),
      label = 'Color Map Name',
      desc = 'the color map name',
  )

  # the low saturation value for the colormap
  colormapLowTR = Range(
      value = -1000,
      low = -1000,
      high = 1000,
      label = 'Color Map Low',
      desc = 'the color map low saturation value',
  )

  colormapHighTR = Range(
      value = 1000,
      low = -1000,
      high = 1000,
      label = 'Color Map High',
      desc = 'the color map high saturation value',
  )

  reversedColormapTB = Bool(
      value = False,
      label = 'Reverse the Color Map',
      desc = 'the color map reversal state',
  )

  # set up the view for both the graphics and control
  traits_view = View(
    Item(
        name = 'myTIC',
        editor = ComponentEditor(size = windowSize),
        show_label = False,
    ),
    Item( name = "colormapNameTE" ),
    Item(
        name = "colormapLowTR",
        editor = RangeEditor(
            auto_set = False,
            enter_set = True,
            mode = 'slider',
            low = -1000,
            high = 1000,
        ),
    ),
    Item(
        name = "colormapHighTR",
        editor = RangeEditor(
            auto_set = False,
            enter_set = True,
            mode = 'slider',
            low = -1000,
            high = 1000,
        ),
    ),
    Item( name = "reversedColormapTB" ),
    resizable = True,
    title = windowTitle,
  )

  def _myTIC_default( self ):

    # create an interesting scalar field for the image plot
    # Eggholder function
    limitF = 500.0
    xA = linspace(-limitF, limitF, 600)
    yA = linspace(-limitF, limitF, 600)
    ( xMG,yMG ) = meshgrid( xA,yA )
    zMG = -(yMG + 47) * sin( sqrt(abs(yMG + xMG/2 + 47 )))
    zMG = zMG - xMG * sin( sqrt(abs(xMG - (yMG + 47))))

    # Create an ArrayPlotData object and give it this data
    myAPD = ArrayPlotData()
    myAPD.set_data( "Z", zMG )
    myAPD.set_data( "X",xA )
    myAPD.set_data( "Y",yA )

    # Create the plot
    self.myTP = Plot( myAPD )

    # contains a dict of default colormaps and their functions. We have to
    # pass the colormapper the data range of interest to set up the private
    # attributes
    default_colormaps.color_map_name_dict

    # the colormap method needs the range of the image data that we want to
    # plot. We first put the image data (zMG) into an ImageData object. We
    # then use DataRange1D on the ImageData instance to produce a DataRange1D
    # instance describing the ImageData data. Finally, we feed the DataRange1D
    # instance into the colormapper to produce a working colormapper.
    myID = ImageData( )
    myID.set_data( zMG )
    self.myDR1D = DataRange1D( myID )

    # pick an unmodified (i.e. unreversed, no ranges) colormap and build
    # the colormap functions
    myColorMapperFn = default_colormaps.color_map_name_dict[self.colormapNameTE]
    myColorMapper = myColorMapperFn( self.myDR1D )

    # add the image plot to this plot object
    # specify the colormap explicitly
    self.myTP.img_plot(
        "Z",
        xbounds = (xA[0],xA[-1]),
        ybounds = (yA[0],yA[-1]),
        colormap = myColorMapper,
    )

    # add the title and padding around the plot
    self.myTP.title = "Eggholder Function"
    self.myTP.padding = 50

    # grids, fonts, etc
    self.myTP.x_axis.title = "X"
    self.myTP.y_axis.title = "Y"

    # generate a ColorBar. pulls its colormapper from the myTP Plot object
    self.myTCB = ColorBar(
      plot = self.myTP,
      index_mapper = LinearMapper( range = self.myTP.color_mapper.range ),
      orientation = 'v',
      resizable = 'v',
      width = 40,
      padding = 30,
    )

    # set the padding of the ColorBar to match the padding of the plot
    self.myTCB.padding_top = self.myTP.padding_top
    self.myTCB.padding_bottom = self.myTP.padding_bottom

    # build up a single container for the colorbar and the image
    myHPC = HPlotContainer( use_backbuffer = True )
    myHPC.add( self.myTP )
    myHPC.add( self.myTCB )

    return( myHPC )

  def _modify_colormap(self):

    #myTP.color_mapper.range.low_setting = 0
    #myTP.color_mapper.range.high_setting = 1000

    # pick out the color map function
    myColorMapperFn = default_colormaps.color_map_name_dict[self.colormapNameTE]

    # reverse the colormap, if req'd
    if self.reversedColormapTB:
      myColorMapperFn = default_colormaps.reverse( myColorMapperFn )

    ## TODO adjust for too low, too high, end cases

    myColorMapperFn = default_colormaps.fix(
        myColorMapperFn,
        (self.colormapLowTR, self.colormapHighTR)
    )
    myColorMapper = myColorMapperFn( self.myDR1D )
    self.myTP.color_mapper = myColorMapper
    self.myTP.request_redraw()

  def _reversedColormapTB_changed( self,old,new ):
    S = '_reversedColormapTB_changed() - old: %s, new: %s' % (old,new)
    print( S )
    self._modify_colormap()

  def _colormapNameTE_changed( self,old,new ):
    S = '_colormapNameTE_changed() - old: %s, new: %s' % (old,new)
    print( S )
    self._modify_colormap()

  def _colormapLowTR_changed( self,old,new ):
    S = '_colormapLowTR_changed() - old: %s, new: %s' % (old,new)
    print( S )

    # check for boundary conditions
    if self.colormapLowTR >= self.colormapHighTR:
      self.colormapLowTR = old
      print( 'colormapLowTR restored to old value: %s' % old )
    self._modify_colormap()

  def _colormapHighTR_changed( self,old,new ):
    S = '_colormapHighTR_changed() - old: %s, new: %s' % (old,new)
    print( S )
    if self.colormapHighTR <= self.colormapLowTR:
      self.colormapHighTR = old
      print( 'colormapHighTR restored to old value: %s' % old )
    self._modify_colormap()
예제 #18
0
class plot_window (HasTraits):
    _plot_data = Instance(ArrayPlotData)
    _plot = Instance(Plot)
    _click_tool = Instance(clicker_tool)
    _img_plot = Instance(ImagePlot)
    _right_click_avail = 0
    name = Str
    view = View(
        Item(name='_plot', editor=ComponentEditor(), show_label=False),

    )

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

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

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

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

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

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

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

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

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

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

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

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

    def update_image(self, image, is_float):
        if is_float:
            self._plot_data.set_data('imagedata', image.astype(np.float))
        else:
            self._plot_data.set_data('imagedata', image.astype(np.byte))
        self._plot.request_redraw()
예제 #19
0
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)
예제 #20
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)
예제 #21
0
파일: dataview.py 프로젝트: aestrivex/cvu
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)
예제 #22
0
class SourcePlot(HasTraits):
    """Main class for the Source function plots.
    
    Uses inspector position from MainPlot to get position.
    
    Abstracting to alternate data types is not trivial.
	To expand to alternate type rewrite CalcSourcePlotVals, this method extracts all necessary data from the file and returns generic objects.
	
    Plot can be neglected simply by not entereding a filename inthe indata field in the FileLoadWindow upon startup.
    
    """
    

    PrimaryPlotC = Instance(HPlotContainer)
    windowwidth = 1000
    Wavelength = Float()
    ImageLock = Bool()
    SaveFlag = Bool()
    colormap_list = Enum('jet', 'gist_gray', 'gist_heat', 'Blues', 'hot')
    ColotList = ['green', 'red', 'yellow']
    TauOnelinecolor = Enum('red', 'green', 'yellow')
    Velocitylinecolor = Enum('green', 'red', 'white', 'yellow')
    VelocityZerolinecolor = Enum('yellow', 'red', 'white', 'green')
    Intensitylinecolor = Enum('white', 'red', 'yellow', 'green')
    wave_ref = float(FileLoadWindow.Wave_Ref)
    
    
    
    traits_view = View(VGroup(Group(Item('PrimaryPlotC', editor = ComponentEditor(), show_label = False, springy = True)),
			      HGroup(Item('colormap_list', style = 'simple', label = 'Colormap'), Item('TauOnelinecolor', label = 'Tau One Color', style = 'simple'), Item('Velocitylinecolor', label = 'Velocity Color', style = 'simple'), Item('VelocityZerolinecolor', label = 'Zero Velocity Color', style = 'simple'), Item('Intensitylinecolor', label = 'Intensity Color', style = 'simple'))),
			      width = windowwidth, height = windowwidth, resizable = True, title = "Source Function Plot")
    


    #Array used for passing information to speactra line plto and also Source Function Plots.  Will be synced
    InspectorPosition = Array()
    
    def __init__(self):
	super(SourcePlot, self).__init__()
	self.Wavelength = self.wave_ref
	self.RayFile = Rh15dout()
	self.RayFile.read_ray(FileLoadWindow.file_name_Ray)
	self.RayFile.read_indata(FileLoadWindow.file_name_Indata)
	#self.RayFile.read_ray('/sanhome/tiago/rhout/cb24bih/MgII/PRD/385_PRD_newatom/output_ray.ncdf')
	#self.RayFile.read_indata('/sanhome/tiago/rhout/cb24bih/MgII/PRD/385_PRD_newatom/output_indata.ncdf')
	WavelengthData = self.RayFile.ray.wavelength
	IntensityData = self.RayFile.ray.intensity
        

        
	self.create_SourcePlot()
	
    def CalcSourcePlotVals(self, sel, xi, yi, wave_ref = None, cscale=0.2, vmax=59,zrange=[-0.1,2],tle='',newfig=True, colour=False):
	# wave indices
	widx = sel.ray.wavelength_indices[:]
	# depth indices for temp, vz # this ONLY WORKS with non memmap arrays!!!!!!
	didx2 = sel.atmos.temperature[xi,yi] < 1.e30
	
	# protect against completely masked columns
	if not (float(N.sum(didx2)) > 0):
	    vz   = N.zeros(sel.atmos.temperature.shape[-1])
	    temp = vz.copy()
	    height = vz.copy()
	else:
	    vz = sel.atmos.velocity_z[xi,yi,didx2]
	    temp = sel.atmos.temperature[xi,yi,didx2]
	    height = sel.atmos.height[xi,yi,didx2]
	    #height = sel.atmos.height[490,26,didx2]
	
	if 'mask' in dir(sel.ray.intensity[xi,yi,0]):
	    if sel.ray.intensity[xi,yi,0].mask:
                return
		print('Intensity at (%i,%i) is masked! Making empty plot.' % (xi, yi))
		plot_form_diag_empty(height, vz, temp, vrange=[-vmax,vmax], cscale=cscale,zrange=zrange, tle=tle, newfig=newfig)
		return
	
	intensity = sel.ray.intensity[xi,yi,widx]
	wave = sel.ray.wavelength[widx]
	
	# have chi/source_function or full stuff?
	if hasattr(sel.ray, 'chi') and hasattr(sel.ray, 'source_function'):
	    # depth indices for Chi, S
	    didx1 = sel.ray.chi[xi,yi,:,0] > 0.
	    chi = sel.ray.chi[xi,yi,didx1,:]
	    S = sel.ray.source_function[xi,yi,didx1,:]
	elif hasattr(sel.ray, 'eta_line') and hasattr(sel.ray, 'chi_line'):
	    # depth indices for Chi, S
	    didx1 = sel.ray.chi_line[xi,yi,:,0] > 0.        
	    chi = sel.ray.chi_line[xi,yi,didx1,:]
	    S = sel.ray.eta_line[xi,yi,didx1,:]/sel.ray.chi_line[xi,yi,didx1,:]
	else:
	    raise ValueError('(EEE) form_diag_rr: structure has no suitable source function/chi.')
	
	
	if wave_ref is None:
	    wave_ref = N.mean(sel.ray.wavelength[widx])    
    
	#Break in old funcs
	
	vrange=[-vmax,vmax]
	sint = intensity
	# Calculate tau
	tau = tau_integ(chi, height)
	tau_one = get_tau_one(tau,height)
	
	# Convert to more convenient units
	height = height/1.e6 # Mm
	vz     = -vz/1e3     # km/s, opposite positive convention 
	
	vaxis = 299792.45 * (wave - wave_ref)/wave_ref
       
	if wave_ref > N.max(wave) or wave_ref < N.min(wave):
	    raise ValueError("Reference wavelength not contained in input wave!")
    
	wi = max(N.where(vaxis >= vrange[0])[0][0]  - 1, 0)
	wf = min(N.where(vaxis <= vrange[1])[0][-1] + 1, vaxis.shape[0]   - 1)
     
	zi = max(N.where(height <= zrange[1])[0][0]  - 1, 0)
	zf = min(N.where(height >= zrange[0])[0][-1] + 1, height.shape[0] - 1)
	
	# slice the arrays to improve the scaling
	tau     = tau[wi:wf+1,zi:zf+1]
	chi     = N.transpose(chi)[wi:wf+1,zi:zf+1]
	S       = N.transpose(S)[wi:wf+1,zi:zf+1]
	height  = height[zi:zf+1]
	vz      = vz[zi:zf+1]
	T       = temp[zi:zf+1]
	wave    = wave[wi:wf+1]
	bint    = int2bt(sint[wi:wf+1], wave)/1e3 # intensity in brightness temp [kK]
	vaxis   = vaxis[wi:wf+1]
	tau_one = tau_one[wi:wf+1]/1e6
	
	#find wavelength point closest to maximum in tau --NOPE. Now using v=0
	#ind   = N.argmax(tau_one)
	ind   = N.argmin(N.abs(vaxis))
	Sline = int2bt(S[ind],wave[ind]) # source function at ind, in brightness temp.
	
	#Flip arrays for plotting
	height = height[::-1]
	chiCT = chi[:, ::-1]
	tauCT = tau[:, ::-1]
	vz = vz[::-1]
	T = T[::-1]
	Sline = Sline[::-1]
	
    
	# colours:
	if colour:
	    # tau=1, vel, planck, S
	    ct = ['c-', 'r-', 'w:', 'y--' ]
	else:
	    ct = ['0.5', 'w-', 'w:', 'w--']
    
	color_source = Instance(ImageData)
	
	return {'height':height, 'chiCT':chiCT, 'tauCT':tauCT, 'tau':tau, 'chi':chi, 'vz':vz, 'T':T, 'Sline':Sline, 'vaxis':vaxis, 'tau_one':tau_one, 'bint':bint, 'wave':wave, 'vrange':vrange, 'zrange':zrange, 'S':S}
	
    def create_SourcePlot(self):

	plotvals = self.CalcSourcePlotVals(sel = self.RayFile, xi = 0, yi = 0, wave_ref = self.wave_ref, vmax = float(FileLoadWindow.VMax_Min), zrange=[float(FileLoadWindow.ZRangeMin), float(FileLoadWindow.ZRangeMax)])
        #plotvals = self.CalcSourcePlotVals(sel = self.RayFile, xi = 0, yi = 0, wave_ref = self.wave_ref,  zrange=[0.2,3.0])
	
	#unpacks values from CalcSourcePlotVals
	vaxis = plotvals['vaxis']
	height = plotvals['height']
	chiCT = plotvals['chiCT']
	tauCT = plotvals['tauCT']
	tau = plotvals['tau']
	chi = plotvals['chi']
	vz = plotvals['vz']
	T = plotvals['T']
	Sline = plotvals['Sline']
	tau_one = plotvals['tau_one']
	bint = plotvals['bint']
	wave = plotvals['wave']
	vrange = plotvals['vrange']
	zrange = plotvals['zrange']
	S = plotvals['S']

	
	velocityzero = 299792.45 * (self.Wavelength - self.wave_ref)/self.wave_ref
	
	
	vaxispoints = 100
	heightaxispoints = 400
        self.new_vaxis = N.linspace(vrange[0], vrange[1], vaxispoints)
        self.new_height = N.linspace(zrange[0], zrange[1], heightaxispoints)
	VelocityZeroXPoints = [velocityzero, velocityzero]
	VelocityZeroYPoints = [self.new_height[0], self.new_height[-1]]
	
	#----------------------Create Chi/Tau Plot-------------------------------
	new_chiCT = lineformInterpolate2D(vaxis, height, chiCT, self.new_vaxis , self.new_height)
        new_tauCT = lineformInterpolate2D(vaxis, height, tauCT, self.new_vaxis , self.new_height)


	self._image_indexCT = GridDataSource(xdata = self.new_vaxis, ydata = self.new_height[1:]) 
        index_mapperCT = GridMapper(range = DataRange2D(self._image_indexCT))
        self._image_valueCT = ImageData(data =  (new_chiCT[:,1:]/new_tauCT[:,1:]), value_depth = 1)
        color_mapperCT = jet(DataRange1D(self._image_valueCT))

	self.ChiTauPlotData = ArrayPlotData(imagedata = (new_chiCT[:,1:]/new_tauCT[:,1:]), index = vaxis, TauOne= tau_one, Velocity = vz, Height = height, VelocityZeroXPoints = VelocityZeroXPoints, VelocityZeroYPoints = VelocityZeroYPoints)
        self.ChiTauPlot = Plot(self.ChiTauPlotData)
        self.ChiTauPlot.img_plot1 = self.ChiTauPlot.img_plot("imagedata", colormap = color_mapperCT, xbounds = (self.new_vaxis[0], self.new_vaxis[-1]), ybounds = (self.new_height[0], self.new_height[-1]))[0]
	self.ChiTauPlot.overlays.append(ZoomTool(self.ChiTauPlot.img_plot1))
	self.ChiTauPlot.tools.append(PanTool(self.ChiTauPlot.img_plot1, drag_button="right"))

        self.ChiTauPlot.TauOnePlot = self.ChiTauPlot.plot(("index","TauOne"), type = "line", color = "red", resizeable = True)
        self.ChiTauPlot.VelocityPlot = self.ChiTauPlot.plot(("Velocity","Height"), type = "line", color = "green", resizeable = True)
	self.ChiTauPlot.VelocityZeroPlot = self.ChiTauPlot.plot(("VelocityZeroXPoints","VelocityZeroYPoints"), type = "line", color = "yellow", resizeable = True)

        self.ChiTauPlot.title = "Chi/Tau Plot"
	self.ChiTauPlot.x_axis.title = "Velocity (km/s)"
	self.ChiTauPlot.y_axis.title = "Height (Mm)"
        self.ChiTauPlot.range2d.x_range.set_bounds(self.new_vaxis[0], self.new_vaxis[-1])
        self.ChiTauPlot.range2d.y_range.set_bounds(self.new_height[0], self.new_height[-1])

        self.ChiTauPlotC = OverlayPlotContainer()
        self.ChiTauPlotC.add(self.ChiTauPlot)
	
	
	#------------------Create source function plot-------------------------
	sourceSF = S[:, ::-1]
        
        new_sourceSF = lineformInterpolate2D(vaxis, height, sourceSF, self.new_vaxis , self.new_height)

        self._image_indexSF = GridDataSource(xdata = self.new_vaxis, ydata = self.new_height)     
        index_mapperSF = GridMapper(range = DataRange2D(self._image_indexSF))

        self._image_valueSF = ImageData(data  = new_sourceSF, value_depth = 1)
        color_mapperSF = jet(DataRange1D(self._image_valueSF))

        self.SourceFuncPlotData = ArrayPlotData(imagedata = new_sourceSF, colormap = color_mapperSF, index = vaxis, TauOne = tau_one, Velocity = vz, Height = height, T = T/1e3, VelocityZeroXPoints = VelocityZeroXPoints, VelocityZeroYPoints = VelocityZeroYPoints)
        self.SourceFuncPlot = Plot(self.SourceFuncPlotData)
        self.SourceFuncPlot.img_plot1 = self.SourceFuncPlot.img_plot("imagedata", colormap = color_mapperSF, xbounds = (self.new_vaxis[0], self.new_vaxis[-1]), ybounds = (self.new_height[0], self.new_height[-1]))[0]
	self.SourceFuncPlot.overlays.append(ZoomTool(self.SourceFuncPlot.img_plot1))
        self.SourceFuncPlot.tools.append(PanTool(self.SourceFuncPlot.img_plot1, drag_button="right"))
	
        self.SourceFuncPlot.TauOnePlot = self.SourceFuncPlot.plot(("index","TauOne"), type = "line", color = "red")
        self.SourceFuncPlot.VelocityPlot = self.SourceFuncPlot.plot(("Velocity","Height"), type = "line", color = "green", resizeable = True)
	self.SourceFuncPlot.VelocityZeroPlot = self.SourceFuncPlot.plot(("VelocityZeroXPoints","VelocityZeroYPoints"), type = "line", color = "yellow", resizeable = True)    
    

        self.TemperaturePlotData = ArrayPlotData(T = T/1e3, Sline = Sline/1e3, Height = height)
        self.TemperaturePlot = Plot(self.TemperaturePlotData)
        self.TemperaturePlot.TPlot = self.TemperaturePlot.plot(("T","Height"), type = "line", color = "white", resizeable = True, line_style = 'dot', origin = 'bottom right')
        self.TemperaturePlot.Slinelot = self.TemperaturePlot.plot(("Sline","Height"), type = "line", color = "white", resizeable = True, line_style = 'dash', origin = 'bottom right')
        self.TemperaturePlot.x_grid.visible = False
        self.TemperaturePlot.y_grid.visible = False
        self.TemperaturePlot.x_axis.orientation = 'top'

        self.TemperaturePlot.y_axis.visible = False
        self.TemperaturePlot.range2d.x_range.set_bounds(0,30)
        self.TemperaturePlot.x_axis.title = "T (kK)"
        self.TemperaturePlot.default_origin = 'bottom right'
	self.TemperaturePlot.y_mapper = self.SourceFuncPlot.y_mapper
        self.SourceFuncPlotC = OverlayPlotContainer()
        self.SourceFuncPlotC.add(self.SourceFuncPlot)
        self.SourceFuncPlotC.add(self.TemperaturePlot)


        self.SourceFuncPlot.title = "Source Function Plot"
	self.SourceFuncPlot.x_axis.title = "Velocity (km/s)"
	self.SourceFuncPlot.y_axis.title = "Height (Mm)"
        self.SourceFuncPlot.range2d.x_range.set_bounds(self.new_vaxis[0], self.new_vaxis[-1])
        self.SourceFuncPlot.range2d.y_range.set_bounds(self.new_height[0], self.new_height[-1])
	
	
	#---------------------Create Tau * Exp(-tau) plot---------------------
	tauCalcTE = (tau*N.exp(-tau))
        tauCalcTE = tauCalcTE[:, ::-1]
    
        new_tauCalcTE = lineformInterpolate2D(vaxis, height, tauCalcTE, self.new_vaxis, self.new_height)
    
    
        self._image_indexTE = GridDataSource(xdata = self.new_vaxis, ydata = self.new_height)     
        index_mapperTE = GridMapper(range = DataRange2D(self._image_indexTE))
        self._image_valueTE = ImageData(data  = new_tauCalcTE, value_depth = 1)
        color_mapperTE = jet(DataRange1D(self._image_valueTE))
    
        self.TauExpPlotData = ArrayPlotData(imagedata = new_tauCalcTE, colormap = color_mapperTE, index = vaxis, TauOne = tau_one, Velocity = vz, Height = height, VelocityZeroXPoints = VelocityZeroXPoints, VelocityZeroYPoints = VelocityZeroYPoints)
        self.TauExpPlot = Plot(self.TauExpPlotData)
        self.TauExpPlot.img_plot1 = self.TauExpPlot.img_plot("imagedata", colormap = color_mapperTE, xbounds = (self.new_vaxis[0], self.new_vaxis[-1]), ybounds = (self.new_height[0], self.new_height[-1]))[0]
        self.TauExpPlot.overlays.append(ZoomTool(self.TauExpPlot.img_plot1))
	self.TauExpPlot.tools.append(PanTool(self.TauExpPlot.img_plot1, drag_button="right"))

	
        self.TauExpPlot.TauOnePlot = self.TauExpPlot.plot(("index","TauOne"), type = "line", color = "red", resizeable = True)
        self.TauExpPlot.VelocityPlot = self.TauExpPlot.plot(("Velocity","Height"), type = "line", color = "green", resizeable = True)
        self.TauExpPlot.VelocityZeroPlot = self.TauExpPlot.plot(("VelocityZeroXPoints","VelocityZeroYPoints"), type = "line", color = "yellow", resizeable = True)
	
        self.TauExpPlot.title = "Tau * Exp Plot"
	self.TauExpPlot.x_axis.title = "Velocity (km/s)"
	self.TauExpPlot.y_axis.title = "Height (Mm)"
        self.TauExpPlot.range2d.x_range.set_bounds(self.new_vaxis[0], self.new_vaxis[-1])
        self.TauExpPlot.range2d.y_range.set_bounds(self.new_height[0], self.new_height[-1])
    
        self.TauExpPlotC = OverlayPlotContainer()
        self.TauExpPlotC.add(self.TauExpPlot)

	#--------------------Create Contribution Function Plot------------------------
	new_tau_oneCF = lineformInterpolate1D(vaxis, tau_one, self.new_vaxis)
        new_vzCF = lineformInterpolate1D(height, vz, self.new_height)
        new_bint = lineformInterpolate1D(vaxis, bint, self.new_vaxis)
        
        ContributionFuncCF = (chi*N.exp(-tau)*S)[:,::-1]
        ContributionFuncCF /= N.max(ContributionFuncCF, axis=0)
        new_ContributionPlotCF = lineformInterpolate2D(vaxis, height, ContributionFuncCF, self.new_vaxis , self.new_height)
	
	
        self._image_indexCF = GridDataSource(xdata = self.new_vaxis, ydata = self.new_height)     
        index_mapperCF = GridMapper(range = DataRange2D(self._image_indexCF))
        self._image_valueCF = ImageData(data  = new_ContributionPlotCF, value_depth = 1)
        color_mapperCF = jet(DataRange1D(self._image_valueCF))
        
        self.ContributionFuncPlotData = ArrayPlotData(imagedata = new_ContributionPlotCF, colormap = color_mapperCF, index = vaxis, TauOne = tau_one, Velocity = vz, Height = height, VelocityZeroXPoints = VelocityZeroXPoints, VelocityZeroYPoints = VelocityZeroYPoints)
        self.ContributionFuncPlot = Plot(self.ContributionFuncPlotData)
        self.ContributionFuncPlot.img_plot1 = self.ContributionFuncPlot.img_plot("imagedata", colormap = color_mapperCF, xbounds = (self.new_vaxis[0], self.new_vaxis[-1]), ybounds = (self.new_height[0], self.new_height[-1]))[0]
	self.ContributionFuncPlot.overlays.append(ZoomTool(self.ContributionFuncPlot.img_plot1))
	self.ContributionFuncPlot.tools.append(PanTool(self.ContributionFuncPlot.img_plot1, drag_button="right"))

        self.ContributionFuncPlot.TauOnePlot = self.ContributionFuncPlot.plot(("index","TauOne"), type = "line", color = "red", resizeable = True)
        self.ContributionFuncPlot.VelocityPlot = self.ContributionFuncPlot.plot(("Velocity","Height"), type = "line", color = "green", resizeable = True)
        self.ContributionFuncPlot.VelocityZeroPlot = self.ContributionFuncPlot.plot(("VelocityZeroXPoints","VelocityZeroYPoints"), type = "line", color = "yellow", resizeable = True)
    
        self.IntensityPlotData = ArrayPlotData(index = self.new_vaxis, bint = new_bint)
        self.IntensityPlot = Plot(self.IntensityPlotData)
        self.IntensityPlot.intensity = self.IntensityPlot.plot(("index","bint"), color = 'white', line_width = 2.0)
        self.IntensityPlot.y_axis.orientation = 'right'
        self.IntensityPlot.y_axis.title = "I_v (kK)"
        self.IntensityPlot.default_origin = 'bottom right'
        self.IntensityPlot.x_grid.visible = False
        self.IntensityPlot.y_grid.visible = False
        self.IntensityPlot.x_axis.visible = False
        self.IntensityPlot.x_axis = self.ContributionFuncPlot.x_axis
        self.IntensityPlot.range2d.y_range.set_bounds(3,7)
        #right_axis = LabelAxis(IntensityPlot, orientation = 'right')
        #IntensityPlot.underlays.append(right_axis)
	
	
        
        self.ContributionFuncPlot.title = "Contribution Function Plot"
	self.ContributionFuncPlot.x_axis.title = "Velocity (km/s)"
	self.ContributionFuncPlot.y_axis.title = "Height (Mm)"
        self.ContributionFuncPlot.range2d.x_range.set_bounds(self.new_vaxis[0], self.new_vaxis[-1])
        self.ContributionFuncPlot.range2d.y_range.set_bounds(self.new_height[0], self.new_height[-1])
	
        self.ContributionFuncPlotC = OverlayPlotContainer()
        self.ContributionFuncPlotC.add(self.ContributionFuncPlot)
        self.ContributionFuncPlotC.add(self.IntensityPlot)
	
	
	#-------------------------------Final Container Construction-------------------------------
	self.TauExpPlot.range2d = self.ChiTauPlot.range2d
	self.ContributionFuncPlot.range2d = self.ChiTauPlot.range2d
	self.SourceFuncPlot.range2d = self.ChiTauPlot.range2d
        self.LeftPlots = VPlotContainer(self.TauExpPlotC, self.ChiTauPlotC, background = "lightgray", use_back_buffer = True)
        self.LeftPlots.spacing = 0
        self.RightPlots = VPlotContainer(self.ContributionFuncPlotC, self.SourceFuncPlotC, background = "lightgray", use_back_buffer = True)
        self.RightPlots.spacing = 0
	
        MainContainer = HPlotContainer(self.LeftPlots, self.RightPlots, background = "lightgray", use_back_buffer = True)
        MainContainer.spacing = 0
        self.PrimaryPlotC = MainContainer 
	
    def _InspectorPosition_changed(self):
	if self.ImageLock == True:
	    return
	
	if len(self.InspectorPosition) > 0:
            xi = self.InspectorPosition[0]
            yi = self.InspectorPosition[1]
        else:
            xi = 0
            yi = 0
	
	plotvals = self.CalcSourcePlotVals(sel = self.RayFile, xi=xi, yi=yi, wave_ref = self.wave_ref, vmax = float(FileLoadWindow.VMax_Min), zrange=[float(FileLoadWindow.ZRangeMin), float(FileLoadWindow.ZRangeMax)])
	#plotvals = self.CalcSourcePlotVals(sel = self.RayFile, xi = xi, yi = yi, wave_ref = self.wave_ref, vmax = 59, zrange=[0.2,3.0])

	#unpacks values from CalcSourcePlotVals
	vaxis = plotvals['vaxis']
	height = plotvals['height']
	chiCT = plotvals['chiCT']
	tauCT = plotvals['tauCT']
	tau = plotvals['tau']
	chi = plotvals['chi']
	vz = plotvals['vz']
	T = plotvals['T']
	Sline = plotvals['Sline']
	tau_one = plotvals['tau_one']
	bint = plotvals['bint']
	wave = plotvals['wave']
	vrange = plotvals['vrange']
	zrange = plotvals['zrange']
	S = plotvals['S']
	
	#ChiTau Plot updates
	new_chiCT = lineformInterpolate2D(vaxis, height, chiCT, self.new_vaxis, self.new_height)
        new_tauCT = lineformInterpolate2D(vaxis, height, tauCT, self.new_vaxis , self.new_height)
        self.ChiTauPlotData.set_data("imagedata",(new_chiCT[:,1:]/new_tauCT[:,1:]))
        self.ChiTauPlotData.set_data("index", vaxis)
        self.ChiTauPlotData.set_data("TauOne", tau_one)
        self.ChiTauPlotData.set_data("Velocity",vz)
        self.ChiTauPlotData.set_data("Height", height)
	
	#Source Plot Updates
	sourceSF = S
	sourceSF = S[:, ::-1]
	new_sourceSF = lineformInterpolate2D(vaxis, height, sourceSF, self.new_vaxis, self.new_height)
	self.SourceFuncPlotData.set_data("imagedata", new_sourceSF)
	self.SourceFuncPlotData.set_data("index",vaxis)
	self.SourceFuncPlotData.set_data("TauOne",tau_one)
	self.SourceFuncPlotData.set_data("Velocity",vz)
	self.SourceFuncPlotData.set_data("Height",height)
	self.TemperaturePlotData.set_data("T", T/1.0e3)
	self.TemperaturePlotData.set_data("Sline",Sline/1e3)
	self.TemperaturePlotData.set_data("Height",height)
	 
	#Tau Plot updates
	tauCalcTE = (tau*N.exp(-tau))
	tauCalcTE = tauCalcTE[:, ::-1]
	new_tauCalcTE = lineformInterpolate2D(vaxis, height, tauCalcTE, self.new_vaxis, self.new_height)     
	self.TauExpPlotData.set_data("imagedata", new_tauCalcTE)
	self.TauExpPlotData.set_data("index",vaxis)
	self.TauExpPlotData.set_data("TauOne",tau_one)
	self.TauExpPlotData.set_data("Velocity",vz)
	self.TauExpPlotData.set_data("Height",height)
	 
	#Source Function Plot Updates
	new_tau_oneCF = lineformInterpolate1D(vaxis, tau_one, self.new_vaxis)
	new_vzCF = lineformInterpolate1D(height, vz, self.new_height)
	new_bint = lineformInterpolate1D(vaxis, bint, self.new_vaxis)
	ContributionFuncCF = (chi*N.exp(-tau)*S)[:,::-1]
	ContributionFuncCF /= N.max(ContributionFuncCF, axis=0)
	new_ContributionPlotCF = lineformInterpolate2D(vaxis, height, ContributionFuncCF, self.new_vaxis, self.new_height)
	self.new_vaxis = N.linspace(vrange[0], vrange[1], 100)
	self.new_height = N.linspace(zrange[0], zrange[1], 400)
	new_tau_oneCF = lineformInterpolate1D(vaxis, tau_one, self.new_vaxis)
	new_vzCF = lineformInterpolate1D(height, vz, self.new_height)
	new_bint = lineformInterpolate1D(vaxis, bint, self.new_vaxis)
	self.ContributionFuncPlotData.set_data("imagedata", new_ContributionPlotCF)
	self.ContributionFuncPlotData.set_data("index",vaxis)
	self.ContributionFuncPlotData.set_data("TauOne",tau_one)
	self.ContributionFuncPlotData.set_data("Velocity",vz)
	self.ContributionFuncPlotData.set_data("Height",height)
	self.IntensityPlotData.set_data("index",self.new_vaxis)
	self.IntensityPlotData.set_data("bint",new_bint)
	
    def _Wavelength_changed(self):
	velocityzero = 299792.45 * (self.Wavelength - self.wave_ref)/self.wave_ref
	VelocityZeroXPoints = [velocityzero, velocityzero]
	try:
	    self.ChiTauPlotData.set_data("VelocityZeroXPoints", VelocityZeroXPoints)
	    self.SourceFuncPlotData.set_data("VelocityZeroXPoints", VelocityZeroXPoints)
	    self.TauExpPlotData.set_data("VelocityZeroXPoints", VelocityZeroXPoints)
	    self.ContributionFuncPlotData.set_data("VelocityZeroXPoints", VelocityZeroXPoints)
	except:
	    pass

    def _colormap_list_changed(self):
	plotlist = [self.ChiTauPlot.img_plot1, self.SourceFuncPlot.img_plot1, self.TauExpPlot.img_plot1, self.ContributionFuncPlot.img_plot1]

	for x in plotlist:
	    clr_range = x.color_mapper.range
	    color_mapper = eval(self.colormap_list)(clr_range)
	    x.color_mapper = color_mapper

	self.ChiTauPlot.request_redraw()
    
    def _TauOnelinecolor_changed(self):
	self.ChiTauPlot.TauOnePlot[0].color = self.TauOnelinecolor
	self.SourceFuncPlot.TauOnePlot[0].color = self.TauOnelinecolor
	self.TauExpPlot.TauOnePlot[0].color = self.TauOnelinecolor
	self.ContributionFuncPlot.TauOnePlot[0].color = self.TauOnelinecolor
	
    def _Velocitylinecolor_changed(self):
	self.ChiTauPlot.VelocityPlot[0].color = self.Velocitylinecolor
	self.SourceFuncPlot.VelocityPlot[0].color = self.Velocitylinecolor
	self.TauExpPlot.VelocityPlot[0].color = self.Velocitylinecolor
	self.ContributionFuncPlot.VelocityPlot[0].color = self.Velocitylinecolor
	
    def _VelocityZerolinecolor_changed(self):
	self.ChiTauPlot.VelocityZeroPlot[0].color = self.VelocityZerolinecolor
	self.SourceFuncPlot.VelocityZeroPlot[0].color = self.VelocityZerolinecolor
	self.TauExpPlot.VelocityZeroPlot[0].color = self.VelocityZerolinecolor
	self.ContributionFuncPlot.VelocityZeroPlot[0].color = self.VelocityZerolinecolor

    def _Intensitylinecolor_changed(self):
	self.IntensityPlot.intensity[0].color = self.Intensitylinecolor
	
    def _SaveFlag_changed(self):
	DPI = 72
	#Main plot save code
	size = (1000,1000)
	path = os.getenv('PWD')
	filenamelist = [path, '/', 'SourcePlots_X', str(self.InspectorPosition[0]), '_Y', str(self.InspectorPosition[1]), '.png']
	filename = ''.join(filenamelist)
	container = self.PrimaryPlotC
	temp = container.outer_bounds
	container.outer_bounds = list(size)
	container.do_layout(force=True)
	gc = PlotGraphicsContext(size, dpi=DPI)
	gc.render_component(container)
	gc.save(filename)
	container.outer_bounds = temp
	print "SAVED: ", filename
예제 #23
0
class PlotWindow(HasTraits):
    _plot_data = Instance(ArrayPlotData)
    _plot = Instance(Plot)
    _click_tool = Instance(ClickerTool)
    _img_plot = Instance(ImagePlot)
    _right_click_avail = 0
    name = Str
    view = View(Item(name='_plot', editor=ComponentEditor(),
                     show_label=False), )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self._plot.request_redraw()
예제 #24
0
파일: Plot.py 프로젝트: kr2/TouchIT-Log
class MainPlot(HasTraits):

    plot = Instance(Plot)

    traits_view = View(
        Item('plot', editor=ComponentEditor(), show_label=False),
        width=800, height=600, resizable=True,
        title="Plot")

    def __init__(self):
        # list of allready added data
        # self.data[name] = [timeData,yData]
        self.data = {}

        # next color index from map
        self.colNr = 0

        self.plotdata = ArrayPlotData()

        self.plot = Plot(self.plotdata)
        self.plot.legend.visible = True

        self.__existingData = []  ## legenLabels

        # time axis
        time_axis = PlotAxis(self.plot, orientation="bottom", tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
        #self.plot.overlays.append(time_axis)
        self.plot.x_axis = time_axis

        hgrid, vgrid = add_default_grids(self.plot)
        self.plot.x_grid = None
        vgrid.tick_generator = time_axis.tick_generator

        # drag tool only time dir
        self.plot.tools.append(PanTool(self.plot, constrain=False,
                                #    constrain_direction="x"
                                      )
                                )

        # zoom tool only y dir
        self.plot.overlays.append(
        	#ZoomTool(self.plot, drag_button="right", always_on=True, tool_mode="range", axis="value" )
        	ZoomTool(self.plot, tool_mode="box", always_on=False)
        	)

        # init plot
        self.plot.plot(
            (
                self.plotdata.set_data(name = None, new_data = [time.mktime(testTime[i].timetuple()) for i in xrange(len(testTime))], generate_name=True),
                self.plotdata.set_data(name = None, new_data = testData, generate_name=True)
            ),
            name = 'temp')
        self.plot.request_redraw()
        self.plot.delplot('temp')

        #self.showData(testTime,testData,'ga1')

    def addData(self, _time, y , dataKey, overwriteData = False):
        """
        if name already exists the existing is overwritten if overwriteData
        """
        if not dataKey in self.data or overwriteData:
            x = [time.mktime(_time[i].timetuple()) for i in xrange(len(_time))]
            self.data[dataKey] = [
                self.plotdata.set_data(name = None, new_data = x, generate_name=True),
                self.plotdata.set_data(name = None, new_data = y, generate_name=True)
            ]


    def showData(self, legendLabel, dataKey):
        if not dataKey in self.data:
            raise Exception('No entry for that dataKey plz first use addData')

        #if not legendLabel in self.__existingData:
        self.plot.plot((self.data[dataKey][0], self.data[dataKey][1]), name = legendLabel, color=self._getColor())
        #else:
        #    self.plot.plot.showplot(legendLabel)

        zoomrange = self._get_zoomRange()
        self.plot.range2d.set_bounds(zoomrange[0],zoomrange[1])


        self.plot.request_redraw()

    def _get_zoomRange(self):
        values = []
        indices = []
        for renderers in self.plot.plots.values():
            for renderer in renderers:
                indices.append(renderer.index.get_data())
                values.append(renderer.value.get_data())

        indMin = None
        indMax = None

        valMin = None
        valMax = None

        for indice in indices:
            _min = min(indice)
            _max = max(indice)

            if indMin:
                indMin = min(indMin,_min)
            else:
                indMin = _min

            if indMin:
                indMax = max(indMax,_max)
            else:
                indMin = _max

        for value in values:
            _min = min(value)
            _max = max(value)

            if valMin:
                valMin = min(valMin,_min)
            else:
                valMin = _min

            if valMax:
                valMax = max(valMax,_max)
            else:
                valMax = _max

        if indMin and indMax and valMin and valMax:
            return ((indMin,valMin),(indMax,valMax))
        else:
            return None






    def hideData(self, legendLabel):
    	self.plot.delplot(legendLabel)
        #self.plot.hideplot(legendLabel)
        zoomrange = self._get_zoomRange()
        if zoomrange:
            self.plot.range2d.set_bounds(zoomrange[0],zoomrange[1])

        self.plot.request_redraw()

    def _getColor(self):
    	temp = self.colNr

    	self.colNr += 1
    	if self.colNr >= len(COLOR_PALETTE):
    		self.colNr = 0

    	return tuple(COLOR_PALETTE[temp])
예제 #25
0
class CameraWindow(traits.api.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 = traits.api.Instance(ArrayPlotData)
    _plot = traits.api.Instance(Plot)
    _click_tool = traits.api.Instance(Clicker)
    rclicked = traits.api.Int(0)

    cam_color = ''

    name = traits.api.Str
    view = traitsui.api.View(traitsui.api.Item(name='_plot', editor=ComponentEditor(), show_label=False))

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

    def __init__(self, color):
        """
            Initialization of plot system
        """
        traits.api.HasTraits.__init__(self)
        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 ClickerTool 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=False):
        """ 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)
        """
        print('image shape = ', image.shape, 'is_float =', is_float)
        if image.ndim > 2:
            image = img_as_ubyte(rgb2gray(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 = traits.api.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
            marker1 - 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)
            :rtype:
        """
        self._plot_data.set_data(str_x, np.atleast_1d(x))
        self._plot_data.set_data(str_y, np.atleast_1d(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):
        """ Draws multiple lines at once on the screen x1,y1->x2,y2 in the current camera window
        parameters:
            x1c - array of x1 coordinates
            y1c - array of y1 coordinates
            x2c - array of x2 coordinates
            y2c - array of y2 coordinates
            color - color of the line
            linewidth - linewidth of the line
        example usage:
            drawquiver ([100,200],[100,100],[400,400],[300,200],'red',linewidth=2.0)
            draws 2 red lines with thickness = 2 :  100,100->400,300 and 200,100->400,200

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

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

    @staticmethod
    def remove_short_lines(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)
        # self._plot.request_redraw()

    def add_line(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_data.set_data(str_x, [x1, x2])
        self._plot_data.set_data(str_y, [y1, y2])
        self._plot.add(Plot((str_x, str_y), type="line", color=color1))
예제 #26
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
                    )