def get_context_menu(self, pos):
        """ Returns a context menu containing split/collapse actions

        pos : position (in global coordinates) where the context menu was 
        requested
        """
        menu = Menu()
        splitter = None

        splitter = None
        for tabwidget in self.tabwidgets():
            # obtain tabwidget's bounding rectangle in global coordinates
            global_rect = QtCore.QRect(tabwidget.mapToGlobal(QtCore.QPoint(0, 0)), tabwidget.size())
            if global_rect.contains(pos):
                splitter = tabwidget.parent()

        # no split/collapse context menu for positions outside any tabwidget
        # region
        if not splitter:
            return

        # add split actions (only show for non-empty tabwidgets)
        if not splitter.is_empty():
            actions = [
                Action(
                    id="split_hor",
                    name="Create new pane to the right",
                    on_perform=lambda: splitter.split(orientation=QtCore.Qt.Horizontal),
                ),
                Action(
                    id="split_ver",
                    name="Create new pane to the bottom",
                    on_perform=lambda: splitter.split(orientation=QtCore.Qt.Vertical),
                ),
            ]

            splitgroup = Group(*actions, id="split")
            menu.append(splitgroup)

        # add collapse action (only show for collapsible splitters)
        if splitter.is_collapsible():
            if splitter is splitter.parent().leftchild:
                if splitter.parent().orientation() is QtCore.Qt.Horizontal:
                    text = "Merge with right pane"
                else:
                    text = "Merge with bottom pane"
            else:
                if splitter.parent().orientation() is QtCore.Qt.Horizontal:
                    text = "Merge with left pane"
                else:
                    text = "Merge with top pane"
            actions = [Action(id="merge", name=text, on_perform=lambda: splitter.collapse())]

            collapsegroup = Group(*actions, id="collapse")
            menu.append(collapsegroup)

        # return QMenu object
        return menu
class AffectsAverageColumn(ObjectColumn):

    # Define the context menu for the column:
    menu = Menu(Action(name='Add', action='column.add(object)'),
                Action(name='Sub', action='column.sub(object)'))

    # Right-align numeric values (override):
    horizontal_alignment = 'center'

    # Column width (override):
    width = 0.09

    # Don't allow the data to be edited directly:
    editable = False

    # Action methods for the context menu items:

    def add(self, object):
        """ Increment the affected player statistic.
        """
        setattr(object, self.name, getattr(object, self.name) + 1)

    def sub(self, object):
        """ Decrement the affected player statistic.
        """
        setattr(object, self.name, getattr(object, self.name) - 1)
Example #3
0
 def get_menu(self, object, trait, row, column):
     column_name = self.column_map[column]
     if column_name not in ['name', 'average']:
         menu = Menu(
             Action(name='Add', action='editor.adapter.add(item, column)'),
             Action(name='Sub', action='editor.adapter.sub(item, column)'))
         return menu
     else:
         return super().get_menu(object, trait, row, column)
 def get_menu(self):
     # See TreeEditor on_context_menu code to understand the context the
     # actions are evaluated in.
     return Menu(
         Action(name="New Simulation From Experiment...",
                action="object.request_new_simulations_from_experiments"),
         #: FIXME - cant refer to datasource in the action statement?
         # Action(name="Create New Simulation...",
         #        action="object.request_new_simulation_from_datasource")
     )
Example #5
0
File: misc.py Project: r0k3/jigna
def Menu_from_QMenu(qmenu):
    """ Create a TraitsUI Menu from a native Qt QMenu.
    Submenus are currently not supported, separators are supported.
    """
    qactions = qmenu.actions()
    groups = []
    grp_actions = []
    for action in reversed(qactions):
        action = Action_from_QAction(action)
        if isinstance(action, Separator):
            if len(grp_actions) > 0:
                groups.append(Group(*reversed(grp_actions)))
                grp_actions = []
            else:
                continue
        else:
            grp_actions.append(action)
    if len(grp_actions) > 0:
        groups.append(Group(*reversed(grp_actions)))
    menu = Menu(*groups)
    # Keep a reference to the original menu to prevent actions from being
    # destroyed then the menu is deleted.
    menu._qmenu = qmenu
    return menu
    def get_context_menu(self, pos):
        """ Returns a context menu containing split/collapse actions

        pos : position (in global coordinates) where the context menu was
        requested
        """
        menu = Menu()
        splitter = None

        splitter = None
        for tabwidget in self.tabwidgets():
            # obtain tabwidget's bounding rectangle in global coordinates
            global_rect = QtCore.QRect(tabwidget.mapToGlobal(QtCore.QPoint(0, 0)),
                                        tabwidget.size())
            if global_rect.contains(pos):
                splitter = tabwidget.parent()

        # no split/collapse context menu for positions outside any tabwidget
        # region
        if not splitter:
            return

        # add split actions (only show for non-empty tabwidgets)
        if not splitter.is_empty():
            actions = [Action(id='split_hor', name='Create new pane to the right',
                       on_perform=lambda : splitter.split(orientation=
                        QtCore.Qt.Horizontal)),
                       Action(id='split_ver', name='Create new pane to the bottom',
                       on_perform=lambda : splitter.split(orientation=
                        QtCore.Qt.Vertical))]

            splitgroup = Group(*actions, id='split')
            menu.append(splitgroup)

        # add collapse action (only show for collapsible splitters)
        if splitter.is_collapsible():
            if splitter is splitter.parent().leftchild:
                if splitter.parent().orientation() is QtCore.Qt.Horizontal:
                    text = 'Merge with right pane'
                else:
                    text = 'Merge with bottom pane'
            else:
                if splitter.parent().orientation() is QtCore.Qt.Horizontal:
                    text = 'Merge with left pane'
                else:
                    text = 'Merge with top pane'
            actions = [Action(id='merge', name=text,
                        on_perform=lambda : splitter.collapse())]

            collapsegroup = Group(*actions, id='collapse')
            menu.append(collapsegroup)

        # return QMenu object
        return menu
Example #7
0
    def config_model_view(self):
        menubar_config = MenuBar(
            Menu(Action(name='New Model',
                        action='new_model',
                        tooltip='Create a new model from scratch'),
                 Action(
                     name='Copy Model',
                     action='copy_model',
                     tooltip='Create a new model by copying an existing one'),
                 name='Create Model'))

        view_config = View(Group(Item(name='model_list', style='custom'),
                                 show_border=True),
                           Item(label="Lots of stuff should go here"),
                           menubar=menubar_config,
                           buttons=NoButtons,
                           title='BiKiPy Modeler')

        return (view_config)
class DatasetNode(TreeNode):

    # List of object classes the node applies to
    node_for = [Dataset]

    # Automatically open the children underneath the node
    auto_open = False

    # Label of the node (this is an attribute of the class in 'node_for')
    label = 'title'

    # Menu
    menu = Menu(
        Action(name="Test...",
               action="handler.get_measurement(editor,object)"))

    #icon_path = Str('../images/')

    # View for the node
    view = View()
from force_wfmanager.ui.setup.process.data_source_view \
    import DataSourceView
from force_wfmanager.ui.setup.process.execution_layer_view \
    import ExecutionLayerView
from force_wfmanager.ui.setup.process.process_view import ProcessView
from force_wfmanager.ui.setup.system_state import SystemState
from force_wfmanager.ui.setup.workflow_view import WorkflowView

# VerifierError severity constants
_ERROR = "error"
_WARNING = "warning"
_INFO = "information"

# Create an empty view and menu for objects that have no data to display:
no_view = View()
no_menu = Menu()

# -------------------
# Actions!
# -------------------

# A string to be used as the enabled_when argument for the actions.
# For reference, in the enabled_when expression namespace, handler is
# the WorkflowTree instance, object is the modelview for the selected node

# MCO Actions
new_mco_action = Action(name='New MCO...', action='new_mco')
delete_mco_action = Action(name='Delete', action='delete_mco')

# Notification Listener Actions
new_notification_listener_action = Action(name='New Notification Listener...',
Example #10
0
class ActorViewer(HasTraits):

    # The scene model.
    scene = Instance(MlabSceneModel, ())

    ######################
    # Using 'scene_class=MayaviScene' adds a Mayavi icon to the toolbar,
    # to pop up a dialog editing the pipeline.
    view = View(
        Item(name='scene',
             editor=SceneEditor(scene_class=MayaviScene),
             show_label=False,
             resizable=True,
             height=600,
             width=1000),
        menubar=MenuBar(
            Menu(
                Action(name="Load Gifti",
                       action="opengifti"),  # see Controller for
                Action(name="Inflate Gii", action="inflategii"),
                Action(name="Template", action="DoTemplate"),
                Action(name="Load Overlay",
                       action="loadoverlay"),  # these callbacks
                Action(name="Load Network", action="loadnetwork"),
                Separator(),
                CloseAction,
                name="File"), ),
        title="ByBP: AAL90 Brain Plotter",
        resizable=True)

    def __init__(self, **traits):
        HasTraits.__init__(self, **traits)
        #self.DoTemplate()

    def DoTemplate(self):
        v, f = template()
        self.DoPlot(v, f)

    def DoPlot(self, v, f):

        clf()
        self.pts = self.scene.mlab.triangular_mesh(v[:, 0],
                                                   v[:, 1],
                                                   v[:, 2],
                                                   f,
                                                   color=(1, 1, 1),
                                                   opacity=0.3)
        self.scene.mlab.get_engine().scenes[0].scene.x_plus_view()
        self.scene.mlab.draw()
        self.scene.mlab.view(0., 0.)
        self.v = v
        self.f = f
        ActorViewer.v = v
        ActorViewer.f = f
        ActorViewer.plot = self
        return self

    def opengifti(self):
        G = GetGifti()
        G.configure_traits()

    def inflategii(self):
        iG = GetGiftiInflate()
        iG.configure_traits()

    def loadoverlay(self):

        o = LoadOverlay90()
        o.configure_traits()

    def alignoverlaydraw(self, o):
        #o = self.o

        y = alignoverlay(self.v, self.f, o)
        v = self.v  # get these from store in ActorViewer
        f = self.f
        ActorViewer.y = y
        a = 0.3

        #fig = mlab.figure(1, bgcolor=(0, 0, 0))
        #ActorViewer.plot.pts.mlab_source.set(x = v[:,0], y = v[:,1], z = v[:,2], triangles=f, scalars=y[:,0],opacity=a)
        ActorViewer.plot.pts = self.scene.mlab.triangular_mesh(v[:, 0],
                                                               v[:, 1],
                                                               v[:, 2],
                                                               f,
                                                               scalars=y[:, 0],
                                                               opacity=a)
        #pts = self.scene.mlab.triangular_mesh(v[:,0], v[:,1], v[:,2], f,scalars=y[:,0],opacity=a)
        ActorViewer.plot.scene.mlab.get_engine().scenes[0].scene.x_plus_view()
        ActorViewer.plot.scene.mlab.view(0., 0.)
        ActorViewer.plot.scene.mlab.colorbar(title="overlay")
        ActorViewer.plot.scene.mlab.draw()

    def loadnetwork(self):

        n = LoadNetwork90()
        n.configure_traits()

    def PlotNet(self):

        xx = self.xx
        yy = self.yy
        vv = self.vv

        jet = cm.get_cmap('jet')
        cNorm = cm.colors.Normalize(vmin=vv.min(), vmax=vv.max())
        scalarMap = cm.ScalarMappable(norm=cNorm, cmap=jet)

        for i in range(len(xx)):
            colorVal = scalarMap.to_rgba(vv[i])
            colorVal = colorVal[0:3]
            ActorViewer.plot.scene.mlab.plot3d([xx[i][0], yy[i][0]],
                                               [xx[i][1], yy[i][1]],
                                               [xx[i][2], yy[i][2]],
                                               color=colorVal,
                                               line_width=10,
                                               tube_radius=2)
            ActorViewer.plot.scene.mlab.points3d(xx[i][0],
                                                 xx[i][1],
                                                 xx[i][2],
                                                 color=(1, 0, 0),
                                                 scale_factor=5)
            ActorViewer.plot.scene.mlab.points3d(yy[i][0],
                                                 yy[i][1],
                                                 yy[i][2],
                                                 color=(1, 0, 0),
                                                 scale_factor=5)
        ActorViewer.plot.scene.mlab.colorbar(title="Network")
Example #11
0
class FluorescenceRecoveryAfterPhotobleaching(ManagedJob, GetSetItemsMixin):

    plot = Instance(OverlayPlotContainer)
    plot_data = Instance(ArrayPlotData)
    time1 = Array()
    intensity = Array()
    distance = Array()

    def __init__(self, confocal):
        super(FluorescenceRecoveryAfterPhotobleaching, self).__init__()

        self._plot_default()
        self.confocal = confocal

    def _plot_default(self):
        plot_data = ArrayPlotData(distance=np.array((0., 1.)),
                                  i1=np.array((0., 1.)),
                                  i2=np.array((0., 1.)),
                                  i3=np.array((0., 1.)),
                                  i4=np.array((0., 1.)),
                                  i5=np.array((0., 1.)))
        plot = Plot(plot_data,
                    width=50,
                    height=40,
                    padding=8,
                    padding_left=64,
                    padding_bottom=32)
        plot.plot(('distance', 'i1'), color='green')
        plot.index_axis.title = 'distance'
        plot.value_axis.title = 'intensity'
        self.plot_data = plot_data
        #self.plot = plot

        #line2=Plot(plot_data, width=50, height=40, padding=8, padding_left=64, padding_bottom=32)
        plot.plot(('distance', 'i2'), color='red')

        #line3=Plot(plot_data, width=50, height=40, padding=8, padding_left=64, padding_bottom=32)
        plot.plot(('distance', 'i3'), color='blue')

        #line4=Plot(plot_data, width=50, height=40, padding=8, padding_left=64, padding_bottom=32)
        plot.plot(('distance', 'i4'), color='magenta')

        #line5=Plot(plot_data, width=50, height=40, padding=8, padding_left=64, padding_bottom=32)
        plot.plot(('distance', 'i5'), color='cyan')

        # container=OverlayPlotContainer(plot, line2, line3, line4, line5)

        # return container
        return plot

    def _run(self):

        file_name = 'D:/data/protonNMR/FRAP/bare diamond/21.02.17/0.1 mg per ml 30 min incubation/3'

        print file_name

        os.path.exists(file_name)

        pg.Night()
        r = 101

        self.intensity = np.zeros((r))

        self.confocal.resolution = r
        self.confocal.seconds_per_point = 0.001

        self.confocal.x1 = 15
        self.confocal.x2 = 35
        self.confocal.y1 = 15
        self.confocal.y2 = 35

        self.distance = np.linspace(self.confocal.x1, self.confocal.x2,
                                    self.confocal.resolution)
        self.confocal.slider = -8.34

        # pre-bleached image-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        pg.Light()
        self.confocal.submit()
        time.sleep(15)
        c = time.strftime('%H:%M:%S')
        time1 = float(c[0:2]) + float(c[3:5]) / 60 + float(c[6:8]) / 3600
        self.time1 = np.append(self.time1, time1)
        m = self.confocal.image
        y, x = np.ogrid[-r / 2 + 1:r - r / 2, -r / 2 + 1:r - r / 2]
        intensity = np.zeros(r / 2 + 1)

        for R in range(1, r / 2 + 2):
            mask = (x * x + y * y <= R * R) & (x * x + y * y >=
                                               (R - 1) * (R - 1))
            array = np.zeros((r, r))
            array[mask] = 1
            intensity[R - 1] = (m * array).sum() / array.sum()

        k = intensity[::-1]
        self.intensity = np.vstack(
            (self.intensity, np.concatenate((k[:-1], intensity), axis=0)))
        pg.Night()

        time.sleep(3)
        #self.confocal.center_cursor()
        file_nv = file_name + '/pre-bleached'
        self.confocal.save_image(file_nv + '.png')
        self.confocal.save(file_nv + '.pyd')

        #bleaching-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        pg.Light
        self.confocal.slider = -5
        pg.Light()
        time.sleep(5)

        # tracking the recovery process--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        self.confocal.slider = -8.34

        for i in range(5):

            pg.Light()
            self.confocal.submit()
            time.sleep(15)
            pg.Night()
            c = time.strftime('%H:%M:%S')
            time1 = float(c[0:2]) + float(c[3:5]) / 60 + float(c[6:8]) / 3600
            self.time1 = np.append(self.time1, time1)
            m = self.confocal.image
            intensity = np.zeros(r / 2 + 1)

            for R in range(1, r / 2 + 2):
                mask = (x * x + y * y <= R * R) & (x * x + y * y >=
                                                   (R - 1) * (R - 1))
                array = np.zeros((r, r))
                array[mask] = 1
                intensity[R - 1] = (m * array).sum() / array.sum()

            k = intensity[::-1]
            self.intensity = np.vstack(
                (self.intensity, np.concatenate((k[:-1], intensity), axis=0)))

            time.sleep(15)

            file_nv = file_name + '/recovery' + str(i)
            self.confocal.save_image(file_nv + '.png')
            self.confocal.save(file_nv + '.pyd')

        self.plot_data.set_data('distance', self.distance)
        self.plot_data.set_data('i1', self.intensity[1])
        self.plot_data.set_data('i2', self.intensity[2])
        self.plot_data.set_data('i3', self.intensity[3])
        self.plot_data.set_data('i4', self.intensity[4])
        self.plot_data.set_data('i5', self.intensity[-1])

        print 'finish'

    def save_image(self, filename=None):
        self.save_figure(self.plot, filename)

    traits_view = View(VGroup(
        HGroup(Item('submit_button', show_label=False), ),
        HGroup(Item('plot', editor=ComponentEditor(), show_label=False))),
                       menubar=MenuBar(
                           Menu(Action(action='save_image',
                                       name='Save Image (.png)'),
                                Action(action='save',
                                       name='Save (.pyd or .pys)'),
                                Action(action='load', name='Load'),
                                Action(action='_on_close', name='Quit'),
                                name='File'), ),
                       title='FRAP',
                       width=500,
                       height=500,
                       buttons=[],
                       resizable=True,
                       x=0,
                       y=0,
                       handler=GetSetSaveImageHandler)

    get_set_items = ['time1', 'intensity', 'distance', '__doc__']
Example #12
0
                           toolip="Add column",
                           image=ImageResource("icons/Add.png"),
                           action="add_column",
                           enabled_when='is_processing == False')

remove_column_action = Action(name="Remove",
                              description='Remove column to table',
                              toolip="Remove column",
                              image=ImageResource("icons/Remove.png"),
                              action="remove_column",
                              enabled_when='is_processing == False')

file_menu = Menu('|',
                 create_schedule_action,
                 open_schedule_action,
                 save_schedule_action,
                 '|',
                 CloseAction,
                 name='&File')

edit_menu = Menu(add_column_action, remove_column_action, name='&Edit')


class SimpleSchedule(HasStrictTraits):
    """A simple scheduler. This object can be used for generation of experimental
    schedules in GUI.
    
    Examples
    --------
    
    >>> class AlvMeasurement(Parameters):
Example #13
0
class Confocal( ManagedJob, GetSetItemsMixin ):
    
    (Item('submit_gsd_button', show_label=False),
                                                   Item('remove_gsd_button', show_label=False),
                                                   Item('priority_gsd'),
                                                   Item('state_gsd', style='readonly'),
                                                   Item('history_back_gsd', show_label=False),
                                                   Item('history_forward_gsd', show_label=False),
    
    # scanner position
    x = Range(low=scanner.getXRange()[0], high=scanner.getXRange()[1], value=0.5*(scanner.getXRange()[0]+scanner.getXRange()[1]), desc='x [micron]', label='x [micron]', mode='slider')
    y = Range(low=scanner.getYRange()[0], high=scanner.getYRange()[1], value=0.5*(scanner.getYRange()[0]+scanner.getYRange()[1]), desc='y [micron]', label='y [micron]', mode='slider')
    z = Range(low=scanner.getZRange()[0], high=scanner.getZRange()[1], value=0.5*(scanner.getZRange()[0]+scanner.getZRange()[1]), desc='z [micron]', label='z [micron]', mode='slider')

    # imagging parameters
    x1 = Range(low=scanner.getXRange()[0], high=scanner.getXRange()[1], value=scanner.getXRange()[0], desc='x1 [micron]', label='x1', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f'))
    y1 = Range(low=scanner.getYRange()[0], high=scanner.getYRange()[1], value=scanner.getYRange()[0], desc='y1 [micron]', label='y1', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f'))
    z1 = Range(low=scanner.getZRange()[0], high=scanner.getZRange()[1], value=scanner.getZRange()[0], desc='z1 [micron]', label='z1', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f'))
    x2 = Range(low=scanner.getXRange()[0], high=scanner.getXRange()[1], value=scanner.getXRange()[1], desc='x2 [micron]', label='x2', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f'))
    y2 = Range(low=scanner.getYRange()[0], high=scanner.getYRange()[1], value=scanner.getYRange()[1], desc='y2 [micron]', label='y2', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f'))
    z2 = Range(low=scanner.getZRange()[0], high=scanner.getZRange()[1], value=scanner.getZRange()[1], desc='z2 [micron]', label='z2', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f'))
    resolution = Range(low=1, high=1000, value=100, desc='Number of point in long direction', label='resolution', auto_set=False, enter_set=True)
    seconds_per_point = Range(low=1e-3, high=10, value=0.005, desc='Seconds per point [s]', label='Seconds per point [s]', mode='text', auto_set=False, enter_set=True)
    bidirectional = Bool( True )
    return_speed = Range(low=1.0, high=100., value=10., desc='Multiplier for return speed of Scanner if mode is monodirectional', label='return speed', mode='text', auto_set=False, enter_set=True)
    constant_axis = Enum('z', 'x', 'y',
                         label='constant axis',
                         desc='axis that is not scanned when acquiring an image',
                         editor=EnumEditor(values={'x':'1:x','y':'2:y','z':'3:z',},cols=3),)

    # buttons
    history_back    = Button(label='Back')
    history_forward = Button(label='Forward')
    reset_range     = Button(label='reset range')
    reset_cursor    = Button(label='reset position')

    # plot parameters
    thresh_high = Trait( 'auto', Str('auto'), Float(10000.), desc='High Limit of image plot', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float))
    thresh_low = Trait( 'auto', Str('auto'), Float(0.), desc='Low Limit of image plot', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float))
    colormap = Enum('Spectral','gray')
    show_labels = Bool(False)

    # scan data
    X = Array()
    Y = Array()
    image = Array()

    # plots
    plot_data           = Instance( ArrayPlotData )
    scan_plot           = Instance( CMapImagePlot )
    cursor              = Instance( CursorTool2D )
    zoom                = Instance( AspectZoomTool )
    figure              = Instance( Plot )
    figure_container    = Instance( HPlotContainer, editor=ComponentEditor() )
    z_label_text    = Str('z:0.0')
    cursor_position = Property(depends_on=['x','y','z','constant_axis'])
    
    get_set_items=['constant_axis', 'X', 'Y', 'thresh_high', 'thresh_low', 'seconds_per_point',
                   'return_speed', 'bidirectional', 'history', 'image', 'z_label_text',
                   'resolution', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'z', 'z1', 'z2']

    def __init__(self):
        super(Confocal, self).__init__()
        self.X = numpy.linspace(scanner.getXRange()[0], scanner.getXRange()[-1], self.resolution+1)
        self.Y = numpy.linspace(scanner.getYRange()[0], scanner.getYRange()[-1], self.resolution+1)
        self.image = numpy.zeros((len(self.X), len(self.Y)))
        self._create_plot()
        self.figure.index_range.on_trait_change(self.update_axis_li, '_low_value', dispatch='ui')
        self.figure.index_range.on_trait_change(self.update_axis_hi, '_high_value', dispatch='ui')
        self.figure.value_range.on_trait_change(self.update_axis_lv, '_low_value', dispatch='ui')
        self.figure.value_range.on_trait_change(self.update_axis_hv, '_high_value', dispatch='ui')
        self.zoom.on_trait_change(self.check_zoom, 'box', dispatch='ui')
        self.on_trait_change(self.set_mesh_and_aspect_ratio, 'X,Y', dispatch='ui')
        self.on_trait_change(self.update_image_plot, 'image', dispatch='ui')
        self.sync_trait('cursor_position', self.cursor, 'current_position')
        self.sync_trait('thresh_high', self.scan_plot.value_range, 'high_setting')
        self.sync_trait('thresh_low', self.scan_plot.value_range, 'low_setting')
        self.on_trait_change(self.scan_plot.request_redraw, 'thresh_high', dispatch='ui')
        self.on_trait_change(self.scan_plot.request_redraw, 'thresh_low', dispatch='ui')
        self.history = History(length = 10)
        self.history.put( self.copy_items(['constant_axis', 'X', 'Y', 'image', 'z_label_text', 'resolution'] ) )
        self.labels = {}
        self.label_list = []

    # scanner position

    @on_trait_change('x,y,z')
    def _set_scanner_position(self):
        if self.state != 'run':
            scanner.setPosition(self.x, self.y, self.z)
    
    @cached_property
    def _get_cursor_position(self):
        if self.constant_axis == 'x':
            return self.z, self.y
        elif self.constant_axis == 'y':
            return self.x, self.z
        elif self.constant_axis == 'z':
            return self.x, self.y
    
    def _set_cursor_position(self, position):
        if self.constant_axis == 'x':
            self.z, self.y = position
        elif self.constant_axis == 'y':
            self.x, self.z = position
        elif self.constant_axis == 'z':
            self.x, self.y = position
    
    # image acquisition
    
    def _run(self):
        """Acquire a scan"""

        try:
            self.state='run'

            self.update_mesh()
            X = self.X
            Y = self.Y
            
            XP = X[::-1]
    
            self.image=numpy.zeros((len(Y),len(X)))
            
            """
            if not self.bidirectional:
                scanner.initImageScan(len(X), len(Y), self.seconds_per_point, return_speed=self.return_speed)
            else:
                scanner.initImageScan(len(X), len(Y), self.seconds_per_point, return_speed=None)
            """
            for i,y in enumerate(Y):
                if threading.current_thread().stop_request.isSet():
                    break
                if i%2 != 0 and self.bidirectional:
                    XL = XP
                else:
                    XL = X
                YL = y * numpy.ones(X.shape)
                
                if self.constant_axis == 'x':
                      const = self.x * numpy.ones(X.shape)
                      Line = numpy.vstack( (const, YL, XL) )
                elif self.constant_axis == 'y':
                      const = self.y * numpy.ones(X.shape)
                      Line = numpy.vstack( (XL, const, YL) )
                elif self.constant_axis == 'z':
                      const = self.z * numpy.ones(X.shape)
                      Line = numpy.vstack( (XL, YL, const) )
                
                if self.bidirectional:
                    c = scanner.scanLine(Line, self.seconds_per_point)
                else:
                    c = scanner.scanLine(Line, self.seconds_per_point, return_speed=self.return_speed)
                if i%2 != 0 and self.bidirectional:
                    self.image[i,:] = c[-1::-1]
                else:
                    self.image[i,:] = c[:]
                
                """
                scanner.doImageLine(Line)
                self.image = scanner.getImage()
                """
                self.trait_property_changed('image', self.image)
          
                if self.constant_axis == 'x':
                    self.z_label_text='x:%.2f'%self.x
                elif self.constant_axis == 'y':
                    self.z_label_text='y:%.2f'%self.y
                elif self.constant_axis == 'z':
                    self.z_label_text='z:%.2f'%self.z

            """
            # block at the end until the image is ready 
            if not threading.current_thread().stop_request.isSet(): 
                self.image = scanner.getImage(1)
                self._image_changed()
            """
                
            scanner.setPosition(self.x, self.y, self.z)

            #save scan data to history
            self.history.put( self.copy_items(['constant_axis', 'X', 'Y', 'image', 'z_label_text', 'resolution'] ) )

        finally:
            self.state = 'idle'

    # plotting
    
    def _create_plot(self):
        plot_data = ArrayPlotData(image=self.image)
        plot = Plot(plot_data, width=500, height=500, resizable='hv', aspect_ratio=1.0, padding=8, padding_left=32, padding_bottom=32)
        plot.img_plot('image',  colormap=Spectral, xbounds=(self.X[0],self.X[-1]), ybounds=(self.Y[0],self.Y[-1]), name='image')
        image = plot.plots['image'][0]
        image.x_mapper.domain_limits = (scanner.getXRange()[0],scanner.getXRange()[1])
        image.y_mapper.domain_limits = (scanner.getYRange()[0],scanner.getYRange()[1])
        zoom = AspectZoomTool(image, enable_wheel=False)
        cursor = CursorTool2D(image, drag_button='left', color='blue', marker_size=1.0, line_width=1.0 )
        image.overlays.append(cursor)
        image.overlays.append(zoom)
        colormap = image.color_mapper
        colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                            color_mapper=colormap,
                            plot=plot,
                            orientation='v',
                            resizable='v',
                            width=16,
                            height=320,
                            padding=8,
                            padding_left=32)
        container = HPlotContainer()
        container.add(plot)
        container.add(colorbar)
        z_label = PlotLabel(text='z=0.0', color='red', hjustify='left', vjustify='bottom', position=[10,10])
        container.overlays.append(z_label)

        self.plot_data = plot_data
        self.scan_plot = image
        self.cursor = cursor
        self.zoom = zoom
        self.figure = plot
        self.figure_container = container
        self.sync_trait('z_label_text', z_label, 'text')

    def set_mesh_and_aspect_ratio(self):
        self.scan_plot.index.set_data(self.X,self.Y)
        x1=self.X[0]
        x2=self.X[-1]
        y1=self.Y[0]
        y2=self.Y[-1]
        
        self.figure.aspect_ratio = (x2-x1) / float((y2-y1))
        self.figure.index_range.low = x1
        self.figure.index_range.high = x2
        self.figure.value_range.low = y1
        self.figure.value_range.high = y2

    def check_zoom(self, box):
        li,lv,hi,hv=box
        if self.constant_axis == 'x':
            if not li<self.z<hi:
                self.z = 0.5*(li+hi)
            if not lv<self.y<hv:
                self.y = 0.5*(lv+hv)
        elif self.constant_axis == 'y':
            if not li<self.x<hi:
                self.x = 0.5*(li+hi)
            if not lv<self.z<hv:
                self.z = 0.5*(lv+hv)
        elif self.constant_axis == 'z':
            if not li<self.x<hi:
                self.x = 0.5*(li+hi)
            if not lv<self.y<hv:
                self.y = 0.5*(lv+hv)
        
    def center_cursor(self):
        i = 0.5 * (self.figure.index_range.low + self.figure.index_range.high) 
        v = 0.5 * (self.figure.value_range.low + self.figure.value_range.high) 
        if self.constant_axis == 'x':
            self.z = i
            self.y = v
        elif self.constant_axis == 'y':
            self.x = i
            self.z = v
        elif self.constant_axis == 'z':
            self.x = i
            self.y = v
    
    def _constant_axis_changed(self):
        self.update_mesh()
        self.image = numpy.zeros((len(self.X), len(self.Y)))  
        self.update_axis()
        self.set_mesh_and_aspect_ratio()

    def update_image_plot(self):
        self.plot_data.set_data('image', self.image)
    
    def _colormap_changed(self, new):
        data = self.figure.datasources['image']
        func = getattr(chaco.api,new)
        self.figure.color_mapper=func(DataRange1D(data))
        self.figure.request_redraw()

    def _show_labels_changed(self, name, old, new):
        for item in self.scan_plot.overlays:
            if isinstance(item, DataLabel) and item.label_format in self.labels:
                item.visible = new
        self.scan_plot.request_redraw()
        
    def get_label_index(self, key):
        for index, item in enumerate(self.scan_plot.overlays):
            if isinstance(item, DataLabel) and item.label_format == key:
                 return index
        return None

    def set_label(self, key, coordinates, **kwargs):

        plot = self.scan_plot

        if self.constant_axis == 'x':
            point = (coordinates[2],coordinates[1])
        elif self.constant_axis == 'y':
            point = (coordinates[0],coordinates[2])
        elif self.constant_axis == 'z':
            point = (coordinates[0],coordinates[1])

        defaults = {'component':plot,
                    'data_point':point,
                    'label_format':key,
                    'label_position':'top right',
                    'bgcolor':'transparent',
                    'text_color':'black',
                    'border_visible':False,
                    'padding_bottom':8,
                    'marker':'cross',
                    'marker_color':'black',
                    'marker_line_color':'black',
                    'marker_line_width':1.5,
                    'marker_size':6,
                    'arrow_visible':False,
                    'clip_to_plot':False,
                    'visible':self.show_labels}

        defaults.update(kwargs)

        label = DataLabel(**defaults)

        index = self.get_label_index(key)
        if index is None:
            plot.overlays.append(label)
        else:
            plot.overlays[index] = label
        self.labels[key] = coordinates
        plot.request_redraw()

    def remove_label(self, key):
        plot = self.scan_plot
        index = self.get_label_index(key)
        plot.overlays.pop(index)
        plot.request_redraw()
        self.labels.pop(key)
        
    def remove_all_labels(self):
        plot = self.scan_plot
        new_overlays = []
        for item in plot.overlays:
            if not ( isinstance(item, DataLabel) and item.label_format in self.labels ) :
                 new_overlays.append(item)
        plot.overlays = new_overlays
        plot.request_redraw()
        self.labels.clear()
        
    @on_trait_change('constant_axis')
    def relocate_labels(self):
        for item in self.scan_plot.overlays:
            if isinstance(item, DataLabel) and item.label_format in self.labels:
                coordinates = self.labels[item.label_format]
                if self.constant_axis == 'x':
                    point = (coordinates[2],coordinates[1])
                elif self.constant_axis == 'y':
                    point = (coordinates[0],coordinates[2])
                elif self.constant_axis == 'z':
                    point = (coordinates[0],coordinates[1])
                item.data_point = point

    def update_axis_li(self):
        if self.constant_axis == 'x':
            self.z1 = self.figure.index_range.low
        elif self.constant_axis == 'y':
            self.x1 = self.figure.index_range.low
        elif self.constant_axis == 'z':
            self.x1 = self.figure.index_range.low 
    def update_axis_hi(self):
        if self.constant_axis == 'x':
            self.z2 = self.figure.index_range.high
        elif self.constant_axis == 'y':
            self.x2 = self.figure.index_range.high
        elif self.constant_axis == 'z':
            self.x2 = self.figure.index_range.high 
    def update_axis_lv(self):
        if self.constant_axis == 'x':
            self.y1 = self.figure.value_range.low
        elif self.constant_axis == 'y':
            self.z1 = self.figure.value_range.low
        elif self.constant_axis == 'z':
            self.y1 = self.figure.value_range.low 
    def update_axis_hv(self):
        if self.constant_axis == 'x':
            self.y2 = self.figure.value_range.high
        elif self.constant_axis == 'y':
            self.z2 = self.figure.value_range.high
        elif self.constant_axis == 'z':
            self.y2 = self.figure.value_range.high
    
    def update_axis(self):
        self.update_axis_li()
        self.update_axis_hi()
        self.update_axis_lv()
        self.update_axis_hv()

    def update_mesh(self):
        if self.constant_axis == 'x':
            x1=self.z1
            x2=self.z2
            y1=self.y1
            y2=self.y2
        elif self.constant_axis == 'y':
            x1=self.x1
            x2=self.x2
            y1=self.z1
            y2=self.z2
        elif self.constant_axis == 'z':
            x1=self.x1
            x2=self.x2
            y1=self.y1
            y2=self.y2

        if (x2-x1) >= (y2-y1):
            self.X = numpy.linspace(x1,x2,self.resolution)
            self.Y = numpy.linspace(y1,y2,int(self.resolution*(y2-y1)/(x2-x1)))
        else:
            self.Y = numpy.linspace(y1,y2,self.resolution)
            self.X = numpy.linspace(x1,x2,int(self.resolution*(x2-x1)/(y2-y1)))
        
    # GUI buttons

    def _history_back_fired(self):
        self.stop()
        self.set_items( self.history.back() )

    def _history_forward_fired(self):
        self.stop()
        self.set_items( self.history.forward() )

    def _reset_range_fired(self):
        self.x1 = scanner.getXRange()[0]
        self.x2 = scanner.getXRange()[1]
        self.y1 = scanner.getYRange()[0]
        self.y2 = scanner.getYRange()[1]
        self.z1 = scanner.getZRange()[0]
        self.z2 = scanner.getZRange()[1]

    def _reset_cursor_fired(self):
        self.center_cursor()

    # saving images

    def save_image(self, filename=None):
        self.save_figure(self.figure_container, filename)
        
    traits_view = View(VGroup(Hsplit(HGroup(HGroup(Item('submit_button', show_label=False),
                                                   Item('remove_button', show_label=False),
                                                   Item('priority'),
                                                   Item('state', style='readonly'),
                                                   Item('history_back', show_label=False),
                                                   Item('history_forward', show_label=False),
                                                   ),
                                            Item('figure_container', show_label=False, resizable=True,enabled_when='state != "run"'),
                                            HGroup(Item('thresh_low', width=-80),
                                                   Item('thresh_high', width=-80),
                                                   Item('colormap', width=-100),
                                                   Item('show_labels'),
                                                   ),
                                            ),
                                      HGroup(HGroup(Item('submit_gsd_button', show_label=False),
                                                   Item('remove_button', show_label=False),
                                                   Item('history_back_gsd', show_label=False),
                                                   Item('history_forward_gsd', show_label=False),
                                                   ),
                                            Item('figure_container_gsd', show_label=False, resizable=True,enabled_when='state != "run"'),
                                            HGroup(Item('thresh_low_gsd', width=-80),
                                                   Item('thresh_high_gsd', width=-80),
                                                   Item('colormap_gsd', width=-100),
                                                   Item('show_labels'),
                                                   ),
                                            ),
                                     ),
                              HGroup(Item('resolution', enabled_when='state != "run"', width=-60),
                                     Item('x1', width=-60),
                                     Item('x2', width=-60),
                                     Item('y1', width=-60),
                                     Item('y2', width=-60),
                                     Item('z1', width=-60),
                                     Item('z2', width=-60),
                                     Item('reset_range', show_label=False),
                                     ),
                              HGroup(Item('constant_axis', style='custom', show_label=False, enabled_when='state != "run"'),
                                     Item('bidirectional', enabled_when='state != "run"'),
                                     Item('seconds_per_point', width=-80),
                                     Item('return_speed', width=-80),
                                     Item('reset_cursor', show_label=False),
                                     ),
                              Item('x', enabled_when='state != "run" or (state == "run" and constant_axis == "x")'),
                              Item('y', enabled_when='state != "run" or (state == "run" and constant_axis == "y")'),
                              Item('z', enabled_when='state != "run" or (state == "run" and constant_axis == "z")'),
                       ),
                       menubar = MenuBar(Menu(Action(action='save_image', name='Save Image (.png)'),
                                              Action(action='save', name='Save (.pyd or .pys)'),
                                              Action(action='load', name='Load'),
                                              Action(action='_on_close', name='Quit'),
                                              name='File'),),
                       title='Confocal', width=880, height=800, buttons=[], resizable=True, x=0, y=0,
                       handler=GetSetSaveImageHandler)
    
    
Example #14
0
class Goodspot(ManagedJob, GetSetItemsMixin, GoodspotBasic):

    X = Array()
    Y = Array()
    Xfit = Array()
    Yfit = Array()
    image = Array()
    image_forfit = Array()
    image2 = Array()
    fitimage = Array()
    label_text = Str('')

    resolution = [[0.1], [0.1]]
    refpoint = [[0], [0]]

    # plots
    plot_data = Instance(ArrayPlotData)
    scan_plot = Instance(CMapImagePlot)
    figure = Instance(Plot)
    fitplot_data = Instance(ArrayPlotData)
    fitscan_plot = Instance(CMapImagePlot)
    fitfigure = Instance(Plot)

    figure_container = Instance(HPlotContainer, editor=ComponentEditor())
    confocal = Any(editor=InstanceEditor)

    ImportImage = Button(label='import image')
    Getfitimage = Button(label='get fitimage')
    ExportTag = Str('nv')
    ExportButton = Button('Export to auto_focus')
    Centroids = list()
    Centroids1 = list()
    IntWeighting = Bool(True)
    off_diagonal_account = Bool(True)
    labels = dict()
    scaler = [[1], [1]]

    def __init__(self, confocal, auto_focus, **kwargs):
        super(Goodspot, self).__init__(**kwargs)
        self.confocal = confocal
        self.auto_focus = auto_focus
        self.X = numpy.linspace(self.confocal.scanner.getXRange()[0],
                                self.confocal.scanner.getXRange()[-1],
                                self.confocal.resolution + 1)
        self.Y = numpy.linspace(self.confocal.scanner.getYRange()[0],
                                self.confocal.scanner.getYRange()[-1],
                                self.confocal.resolution + 1)
        self.image = numpy.zeros((len(self.X), len(self.Y)))
        dim = min(self.image.shape)
        self.fitimage = numpy.zeros((dim, dim))
        self.Xfit = self.X[0:dim]
        self.Yfit = self.Y[0:dim]
        self._create_plot()
        self.on_trait_change(self.update_image_plot, 'image', dispatch='ui')
        self.on_trait_change(self._on_label_text_change,
                             'label_text',
                             dispatch='ui')

        self.on_trait_change(self.redraw_image,
                             'confocal.thresh_high',
                             dispatch='ui')
        self.on_trait_change(self.redraw_image,
                             'confocal.thresh_low',
                             dispatch='ui')
        self.on_trait_change(self.redraw_image,
                             'confocal.thresh_high',
                             dispatch='ui')
        self.on_trait_change(self.redraw_image,
                             'confocal.thresh_low',
                             dispatch='ui')
        self.on_trait_change(self.set_mesh_and_aspect_ratio,
                             'X,Y,Xfit,Yfit',
                             dispatch='ui')

    def _ImportImage_fired(self):
        # the long road for extracting the zoom parameters ...
        Dim = numpy.shape(self.confocal.image)
        ImagePosX = [self.confocal.X[0], self.confocal.X[-1]]
        ImagePosY = [self.confocal.Y[0], self.confocal.Y[-1]]
        ImageRangeX = self.confocal.figure.index_range.get()
        ImageRangeX = [
            ImageRangeX['_low_setting'], ImageRangeX['_high_setting']
        ]
        ImageRangeY = self.confocal.figure.value_range.get()
        ImageRangeY = [
            ImageRangeY['_low_setting'], ImageRangeY['_high_setting']
        ]

        FullRangeX = self.confocal.scanner.getXRange()
        FullRangeY = self.confocal.scanner.getYRange()
        resolution = [(ImagePosY[1] - ImagePosY[0]) / Dim[0],
                      (ImagePosX[1] - ImagePosX[0]) / Dim[1]]

        RangeX = numpy.round(
            numpy.asarray([
                ImageRangeX[0] - ImagePosX[0], ImageRangeX[1] - ImagePosX[0]
            ]) / resolution[1])
        RangeY = numpy.round(
            numpy.asarray([
                ImageRangeY[0] - ImagePosY[0], ImageRangeY[1] - ImagePosY[0]
            ]) / resolution[0])

        self.scaler[0] = FullRangeX[1] / resolution[1]

        self.scaler[1] = FullRangeY[1] / resolution[0]
        self.resolution = resolution
        self.refpoint = [ImagePosY[0], ImagePosX[0]]

        # import only the part of the image of the zoom
        self.image = self.confocal.image[RangeY[0]:RangeY[1] + 1,
                                         RangeX[0]:RangeX[1] + 1]
        #self.image2=self.confocal.image
        self.update_mesh()
        self.redraw_image()

    def _Getfitimage_fired(self):
        offset = 20.0
        amplitude = 70.0
        y0 = numpy.mean(self.Yfit)
        x0 = numpy.mean(self.Xfit)
        sigma_y = 0.2
        sigma_x = 0.2
        theta = 0.0
        initial_guess = (amplitude, y0, x0, sigma_y, sigma_x, theta, offset)
        popt, pcov = optimize.curve_fit(self.twoD_Gaussian,
                                        (self.Yfit, self.Xfit),
                                        self.image_forfit.ravel(),
                                        initial_guess)
        fit_data = self.twoD_Gaussian((self.Yfit, self.Xfit), *popt)
        self.fitparemeter = popt
        #print(fit_data)
        self.fitimage = fit_data.reshape(len(self.Yfit), len(self.Xfit))
        self.fitplot_data.set_data('fitimage', self.fitimage)

        s = 'amp: %.1f Kcounts\n' % popt[0]
        s += 'sigmay: %.3f and sigmax: %.3f micrometer\n' % (popt[3], popt[4])
        s += 'theta: %.1f degree\n' % float(popt[5] * 180 / 3.1415)
        self.label_text = s

    def redraw_image(self):
        self.scan_plot.value_range.high_setting = self.confocal.thresh_high
        self.scan_plot.value_range.low_setting = self.confocal.thresh_low
        self.scan_plot.request_redraw()

    def _create_plot(self):
        plot_data = ArrayPlotData(image=self.image)
        plot = Plot(plot_data,
                    width=500,
                    height=500,
                    resizable='hv',
                    aspect_ratio=1.0,
                    padding=8,
                    padding_left=32,
                    padding_bottom=32)
        plot.img_plot('image',
                      colormap=jet,
                      xbounds=(self.X[0], self.X[-1]),
                      ybounds=(self.Y[0], self.Y[-1]),
                      name='image')
        image = plot.plots['image'][0]
        fitplot_data = ArrayPlotData(fitimage=self.fitimage)
        fitplot = Plot(fitplot_data,
                       width=500,
                       height=500,
                       resizable='hv',
                       aspect_ratio=1.0,
                       padding=8,
                       padding_left=32,
                       padding_bottom=32)
        fitplot.img_plot('fitimage',
                         colormap=jet,
                         xbounds=(self.Xfit[0], self.Xfit[-1]),
                         ybounds=(self.Yfit[0], self.Yfit[-1]),
                         name='fitimage')
        fitplot.overlays.insert(
            0,
            PlotLabel(text=self.label_text,
                      hjustify='right',
                      vjustify='bottom',
                      position=[880, 590]))
        fitimage = fitplot.plots['fitimage'][0]

        image.x_mapper.domain_limits = (self.confocal.scanner.getXRange()[0],
                                        self.confocal.scanner.getXRange()[1])
        image.y_mapper.domain_limits = (self.confocal.scanner.getYRange()[0],
                                        self.confocal.scanner.getYRange()[1])
        fitimage.x_mapper.domain_limits = (
            self.confocal.scanner.getXRange()[0],
            self.confocal.scanner.getXRange()[1])
        fitimage.y_mapper.domain_limits = (
            self.confocal.scanner.getYRange()[0],
            self.confocal.scanner.getYRange()[1])
        colormap = image.color_mapper
        colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                            color_mapper=colormap,
                            plot=plot,
                            orientation='v',
                            resizable='v',
                            width=16,
                            height=320,
                            padding=8,
                            padding_left=32)
        container = HPlotContainer()
        container.add(plot)
        container.add(colorbar)
        container.add(fitplot)

        container.tools.append(SaveTool(container))

        self.plot_data = plot_data
        self.scan_plot = image
        self.figure = plot
        self.fitplot_data = fitplot_data
        self.fitscan_plot = fitimage
        self.fitfigure = fitplot

        self.figure_container = container

    def _on_label_text_change(self):
        self.fitfigure.overlays[0].text = self.label_text

    def update_image_plot(self):
        self.plot_data.set_data('image', self.image)

    def update_mesh(self):

        Info = self.confocal.figure.index_range.get()

        x1 = Info['_low_setting']
        x2 = Info['_high_setting']

        Info = self.confocal.figure.value_range.get()
        y1 = Info['_low_setting']
        y2 = Info['_high_setting']
        Dim = numpy.shape(self.image)
        self.Y = numpy.linspace(y1, y2, Dim[0])
        self.X = numpy.linspace(x1, x2, Dim[1])
        if Dim[0] > Dim[1]:
            self.Yfit = self.Y[0:Dim[1]]
            self.Xfit = numpy.linspace(x1, x2, Dim[1])
            self.image_forfit = self.image[:, 0:Dim[1]]
        else:
            self.Xfit = self.X[0:Dim[0]]
            self.Yfit = numpy.linspace(y1, y2, Dim[0])
            self.image_forfit = self.image[0:Dim[0], :]

    def set_mesh_and_aspect_ratio(self):
        self.scan_plot.index.set_data(self.X, self.Y)
        self.fitscan_plot.index.set_data(self.Xfit, self.Yfit)

        x1 = self.X[0]
        x2 = self.X[-1]
        y1 = self.Y[0]
        y2 = self.Y[-1]
        x1fit = self.Xfit[0]
        x2fit = self.Xfit[-1]
        y1fit = self.Yfit[0]
        y2fit = self.Yfit[-1]

        self.figure.aspect_ratio = (x2 - x1) / float((y2 - y1))
        self.figure.index_range.low = x1
        self.figure.index_range.high = x2
        self.figure.value_range.low = y1
        self.figure.value_range.high = y2

        self.fitfigure.aspect_ratio = 1
        self.fitfigure.index_range.low = x1fit
        self.fitfigure.index_range.high = x2fit
        self.fitfigure.value_range.low = y1fit
        self.fitfigure.value_range.high = y2fit

    def save_image(self, filename=None):
        self.save_figure(self.figure_container, filename)

    IAN = View(Item('ImportImage', show_label=False, resizable=True))
    traits_view = View(VSplit(
        HGroup(Item('ImportImage', show_label=False, resizable=True),
               Item('Getfitimage', show_label=False, resizable=True)),
        Item('figure_container', show_label=False, resizable=True,
             height=600)),
                       menubar=MenuBar(
                           Menu(Action(action='save_image',
                                       name='Save Image (.png)'),
                                Action(action='saveMatrixPlot',
                                       name='SaveMatrixPlot (.png)'),
                                name='File')),
                       title='Goodspot',
                       width=1080,
                       height=800,
                       buttons=[],
                       resizable=True,
                       x=0,
                       y=0,
                       handler=GetSetSaveImageHandler)
Example #15
0
     children='employees',
     label='=Employees',
     view=no_view,
     add=[Employee],
 ),
 TreeNode(
     node_for=[Department],
     auto_open=True,
     children='employees',
     label='name',
     menu=Menu(
         NewAction,
         Separator(),
         DeleteAction,
         Separator(),
         RenameAction,
         Separator(),
         CopyAction,
         CutAction,
         PasteAction,
     ),
     view=View(Group('name', orientation='vertical', show_left=True)),
     add=[Employee],
 ),
 TreeNode(
     node_for=[Employee],
     auto_open=True,
     label='name',
     menu=Menu(
         NewAction,
         Separator(),
Example #16
0
class MainWindow(HasTraits):
    '''The main window for the Beams application.'''

    # Current folder for file dialog
    _current_folder = None

    camera = Instance(Camera)
    id_string = DelegatesTo('camera')
    resolution = DelegatesTo('camera')
    status = Str()
    screen = Instance(CameraImage, args=())
    cmap = DelegatesTo('screen')
    display_frame_rate = Range(1, 60, 15)
    transform_plugins = List(Instance(TransformPlugin))
    display_plugins = List(Instance(DisplayPlugin))
    acquisition_thread = Instance(AcquisitionThread)  # default: None
    processing_thread = Instance(ProcessingThread)  # default: None
    processing_queue = Instance(queue.Queue, kw={'maxsize': MAX_QUEUE_SIZE})
    cameras_dialog = Instance(CameraDialog, args=())

    # Actions
    about = Action(name='&About...',
                   tooltip='About Beams',
                   image=find_icon('about'),
                   action='action_about')
    save = Action(name='&Save Image',
                  accelerator='Ctrl+S',
                  tooltip='Save the current image to a file',
                  image=find_icon('save'),
                  action='action_save')
    quit = Action(name='&Quit',
                  accelerator='Ctrl+Q',
                  tooltip='Exit the application',
                  image=find_icon('quit'),
                  action='_on_close')
    choose_camera = Action(name='Choose &Camera...',
                           tooltip='Choose from a number of camera plugins',
                           action='action_choose_camera')
    take_video = Action(name='Take &Video',
                        style='toggle',
                        tooltip='Start viewing the video feed from the camera',
                        image=find_icon('camera-video'),
                        action='action_take_video')
    take_photo = Action(name='Take &Photo',
                        tooltip='Take one snapshot from the camera',
                        image=find_icon('camera-photo'),
                        action='action_take_photo',
                        enabled_when='self.take_video.checked == False')

    find_resolution = Button()
    view = View(
        VGroup(
            HSplit(
                Tabbed(
                    VGroup(Item('id_string', style='readonly', label='Camera'),
                           Item('resolution',
                                style='readonly',
                                format_str=u'%i \N{multiplication sign} %i'),
                           Group(Item('camera',
                                      show_label=False,
                                      style='custom'),
                                 label='Camera properties',
                                 show_border=True),
                           label='Camera'),
                    VGroup(Item('cmap',
                                label='Color scale',
                                editor=EnumEditor(
                                    values={
                                        None: '0:None (image default)',
                                        gray: '1:Grayscale',
                                        bone: '2:Bone',
                                        pink: '3:Copper',
                                        jet: '4:Rainbow (considered harmful)',
                                        isoluminant: '5:Isoluminant',
                                        awesome: '6:Low-intensity contrast'
                                    })),
                           Item('screen',
                                show_label=False,
                                editor=ColorMapEditor(width=256)),
                           Item('display_frame_rate'),
                           label='Video'),
                    # FIXME: mutable=False means the items can't be deleted,
                    # added, or rearranged, but we do actually want them to
                    # be rearranged.
                    VGroup(Item('transform_plugins',
                                show_label=False,
                                editor=ListEditor(style='custom',
                                                  mutable=False)),
                           label='Transform'),
                    VGroup(Item('display_plugins',
                                show_label=False,
                                editor=ListEditor(style='custom',
                                                  mutable=False)),
                           label='Math')),
                Item('screen',
                     show_label=False,
                     width=640,
                     height=480,
                     style='custom')),
            Item('status', style='readonly', show_label=False)),
        menubar=MenuBar(
            # vertical bar is undocumented but it seems to keep the menu
            # items in the order they were specified in
            Menu('|', save, '_', quit, name='&File'),
            Menu(name='&Edit'),
            Menu(name='&View'),
            Menu('|',
                 choose_camera,
                 '_',
                 take_photo,
                 take_video,
                 name='&Camera'),
            Menu(name='&Math'),
            Menu(about, name='&Help')),
        toolbar=ToolBar('|', save, '_', take_photo, take_video),
        title='Beams',
        resizable=True,
        handler=MainHandler)

    def _find_resolution_fired(self):
        return self.view.handler.action_find_resolution(None)

    def _display_frame_rate_changed(self, value):
        self.processing_thread.update_frequency = value

    def _transform_plugins_default(self):
        plugins = []
        for name in ['Rotator', 'BackgroundSubtract']:
            module = __import__(name, globals(), locals(), [name])
            plugins.append(getattr(module, name)())
        return plugins

    def _display_plugins_default(self):
        plugins = []
        for name in [
                'BeamProfiler', 'MinMaxDisplay', 'DeltaDetector', 'Centroid'
        ]:
            module = __import__(name, globals(), locals(), [name])
            plugins.append(getattr(module, name)(screen=self.screen))
        return plugins

    def __init__(self, **traits):
        super(MainWindow, self).__init__(**traits)

        # Build the camera selection dialog box
        self.cameras_dialog.on_trait_change(self.on_cameras_response, 'closed')
        self.on_cameras_response()

        self.processing_thread = ProcessingThread(self, self.processing_queue,
                                                  self.display_frame_rate)
        self.processing_thread.start()

    def on_cameras_response(self):
        plugin_obj = self.cameras_dialog.get_plugin_object()
        try:
            self.select_plugin(plugin_obj)
        except ImportError:
            # some module was not available, select the dummy
            error(
                None, 'Loading the {} camera plugin failed. '
                'Taking you back to the dummy plugin.'.format(
                    plugin_obj['name']))
            self.cameras_dialog.select_fallback()
            info = self.cameras_dialog.get_plugin_info()
            self.select_plugin(*info)

    # Select camera plugin
    def select_plugin(self, plugin_obj):
        # Set up image capturing
        self.camera = plugin_obj()
        try:
            self.camera.open()
        except CameraError:
            error(None,
                  'No camera was detected. Did you forget to plug it in?')
            sys.exit()
Example #17
0
class Zeeman(Job, GetSetItemsMixin):
    """Zeeman measurement."""

    start_button = Button(label='start', desc='Start the measurement.')
    stop_button = Button(label='stop', desc='Stop the measurement.')

    def _start_button_fired(self):
        """React to submit button. Submit the Job."""
        self.start()

    def _stop_button_fired(self):
        """React to remove button. Remove the Job."""
        self.stop()

    current = Array(dtype=float)
    basename = File()

    odmr = Instance(ODMR, factory=ODMR)

    frequency = Array()

    line_data = Instance(ArrayPlotData)
    line_plot = Instance(Plot, editor=ComponentEditor())

    traits_view = View(
        VGroup(
            HGroup(
                Item('start_button', show_label=False),
                Item('stop_button', show_label=False),
                Item('state', style='readonly'),
                Item('odmr', editor=InstanceEditor(), show_label=False),
            ),
            VGroup(
                Item('basename'),
                Item('current'),  # ToDo: migrate to a custom TabularEditor
            ),
            Item('line_plot', show_label=False, resizable=True),
        ),
        menubar=MenuBar(
            Menu(Action(action='save', name='Save (.pyd or .pys)'),
                 Action(action='load', name='Load (.pyd or .pys)'),
                 Action(action='save_line_plot', name='Save Plot (.png)'),
                 Action(action='_on_close', name='Quit'),
                 name='File'), ),
        title='Zeeman',
        buttons=[],
        resizable=True,
        handler=SaveLinePlotHandler)

    get_set_items = ['current', 'frequency', 'odmr', '__doc__']

    def __init__(self):
        super(Zeeman, self).__init__()
        self._create_line_plot()
        self.on_trait_change(self._update_plot, 'frequency', dispatch='ui')

    def _run(self):

        try:
            self.state = 'run'

            if self.basename == '':
                raise ValueError(
                    'Filename missing. Please specify a filename and try again.'
                )

            odmr = self.odmr
            if odmr.stop_time == np.inf:
                raise ValueError('ODMR stop time set to infinity.')
            delta_f = (odmr.frequency_end - odmr.frequency_begin)

            self.frequency = np.array(())

            for i, current_i in enumerate(self.current):

                Coil().set_output(1, current_i)
                odmr.perform_fit = False
                odmr.submit()
                while odmr.state != 'done':
                    threading.currentThread().stop_request.wait(1.0)
                    if threading.currentThread().stop_request.isSet():
                        odmr.remove()
                        break
                odmr.perform_fit = True
                basename = self.basename
                try:
                    appendix = basename[-4:]
                    if appendix in ['.pyd', '.pys', '.asc', '.txt']:
                        basename = basename[:-4]
                    else:
                        appendix = '.pys'
                except:
                    appendix = '.pys'
                filename = basename + '_' + str(current_i) + 'A' + appendix
                odmr.save(filename)

                f = odmr.fit_frequencies[0]
                self.frequency = np.append(self.frequency, f)

                odmr.frequency_begin = f - 0.5 * delta_f
                odmr.frequency_end = f + 0.5 * delta_f

            self.state = 'done'
        except:
            logging.getLogger().exception('Error in Zeeman.')
            self.state = 'error'

    def _create_line_plot(self):
        line_data = ArrayPlotData(
            current=np.array(()),
            frequency=np.array(()),
        )
        plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=36)
        plot.plot(('current', 'frequency'), color='blue', name='zeeman')
        plot.index_axis.title = 'current [mA]'
        plot.value_axis.title = 'frequency [MHz]'
        self.line_data = line_data
        self.line_plot = plot

    def _update_plot(self, new):
        n = len(new)
        self.line_data.set_data('current', self.current[:n])
        self.line_data.set_data('frequency', new * 1e-6)

    def save_line_plot(self, filename):
        self.save_figure(self.line_plot, filename)
Example #18
0
class SMRCWindow(HasTraits):
    """
    SMRCWindow is the Mainwindow of the application SmartRecord. The window 
    shows the time and the current phase of the experiment when it's running. 
    Furthermore the window interacts with the SMRCModel and 
    make it possible that the user can start and 
    cancel the experiment by clicking a icon.
    """

    model = Instance(SMRCModel)

    smrc_handler = SMRCHandler()

    current_phase = Str("Current Phase - Not Started")

    clock = Str(secs_to_time(0))

    record_mode = Bool(True)

    def __init__(self, model):
        self.logger = getLogger("application")
        self.logger.debug("Initializes SMRCWindow")
        self.record_mode = model.record_mode
        self.model = model
        self.model.experiment.window = self

    def start_clock(self):
        """Run the clock in the status bar."""
        self.logger.info("Start the time-thread [SMRCWindow]")
        self.clock = secs_to_time(0)
        RunThread(target=self._run_clock)

    def _run_clock(self):
        # Updates the status bar time once every second.
        self.clock_running = True
        self.start_time = time()
        while self.clock_running:
            self.td = time() - self.start_time
            self.clock = secs_to_time(self.td)
            sleep(1.0)

    #=========================================================================
    # Traitsview
    #=========================================================================

    # Switch to stop the running thread
    clock_running = Bool(False)

    view = View(UItem("model", style="custom"),
                menubar=MenuBar(Menu(*file_actions, name="File"),
                                Menu(*configure_actions, name="Configuration"),
                                Menu(*import_action, name="Import"),
                                Menu(help_docs, name="Help")),
                toolbar=ToolBar(*toolbar_actions,
                                show_tool_names=False,
                                image_size=(30, 30)),
                statusbar=[
                    StatusItem(name="current_phase", width=0.5),
                    StatusItem(name="clock", width=85)
                ],
                handler=smrc_handler,
                resizable=True,
                height=680,
                width=1300,
                title="SmartRecord",
                icon=ImageResource("../../icons/smrc_icon.png"))
        success = modelview.edit_traits(kind='livemodal')
        print("Logged in:", success)
        print("Username:"******"Password:", credentials.password)

        if success:
            ui_info.object.credentials = credentials


#: A view for the main app which displays an explanation and the username.
app_view = View(
    Item('information', style='readonly', show_label=False),
    HGroup(Item('object.credentials.username', style='readonly')),
    menubar=MenuBar(
        Menu(
            Action(name='Create Account', action='create_account'),
            name='File',
        )),
    buttons=[
        Action(name='Create Account', action='create_account'),
        'OK',
    ],
    width=480,
    height=320,
    resizable=True,
)

if __name__ == '__main__':
    app = MainApp()
    app.configure_traits(view=app_view, handler=MainAppHandler())
    def default_traits_view(self):
        """The layout of the View for the WorkflowTree"""

        tree_editor = TreeEditor(
            nodes=[
                # Root node "Workflow"
                TreeNodeWithStatus(node_for=[WorkflowView],
                                   auto_open=True,
                                   children='',
                                   name='Workflow',
                                   label='=Workflow',
                                   view=no_view,
                                   menu=no_menu,
                                   on_select=self.workflow_selected),
                # Node representing the Process"
                TreeNode(node_for=[WorkflowView],
                         auto_open=True,
                         children='process_view',
                         name='Process',
                         label='=Process',
                         view=no_view,
                         menu=no_menu,
                         on_select=self.workflow_selected),
                #: Node representing the Execution layers
                TreeNode(node_for=[ProcessView],
                         auto_open=True,
                         children='execution_layer_views',
                         label='=Execution Layers',
                         name='Execution Layers',
                         view=no_view,
                         menu=Menu(new_layer_action),
                         on_select=self.process_selected),
                TreeNodeWithStatus(node_for=[ExecutionLayerView],
                                   auto_open=True,
                                   children='data_source_views',
                                   label='label',
                                   name='DataSources',
                                   view=no_view,
                                   menu=Menu(delete_layer_action),
                                   on_select=self.execution_layer_selected),
                TreeNodeWithStatus(node_for=[DataSourceView],
                                   auto_open=True,
                                   children='',
                                   label='label',
                                   name='DataSources',
                                   menu=Menu(delete_data_source_action),
                                   on_select=self.data_source_selected),
                # Folder node "MCO" containing the MCO
                TreeNode(
                    node_for=[WorkflowView],
                    auto_open=True,
                    children='mco_view',
                    label='=MCO',
                    name='MCO',
                    view=no_view,
                    menu=no_menu,
                    on_select=self.mco_selected,
                ),
                # Node representing the MCO
                TreeNodeWithStatus(node_for=[MCOView],
                                   auto_open=True,
                                   children='mco_options',
                                   label='label',
                                   name='MCO',
                                   view=no_view,
                                   menu=Menu(delete_mco_action),
                                   on_select=self.mco_optimizer_selected),
                # Node representing the MCO Parameters
                TreeNodeWithStatus(node_for=[MCOParameterView],
                                   auto_open=True,
                                   children='',
                                   label='=Parameters',
                                   name='Parameters',
                                   view=no_view,
                                   menu=no_menu,
                                   on_select=self.mco_parameters_selected),
                # Node representing the MCO KPIs
                TreeNodeWithStatus(node_for=[KPISpecificationView],
                                   auto_open=True,
                                   children='',
                                   label='=KPIs',
                                   name='KPIs',
                                   view=no_view,
                                   menu=no_menu,
                                   on_select=self.mco_kpis_selected),
                TreeNode(node_for=[WorkflowView],
                         auto_open=True,
                         children='communicator_view',
                         name='Communicator',
                         label='=Communicator',
                         view=no_view,
                         menu=no_menu,
                         on_select=self.workflow_selected),
                TreeNode(node_for=[CommunicatorView],
                         auto_open=True,
                         children='notification_listener_views',
                         label='=Notification Listeners',
                         name='Notification Listeners',
                         view=no_view,
                         menu=no_menu,
                         on_select=self.communicator_selected),
                # Node representing the Notification Listener
                TreeNodeWithStatus(
                    node_for=[NotificationListenerView],
                    auto_open=True,
                    children='',
                    label='label',
                    name='Notification Listeners',
                    view=no_view,
                    menu=Menu(delete_notification_listener_action),
                    on_select=self.notification_listener_selected)
            ],
            orientation="horizontal",
            editable=False,
            selected="object.system_state.selected_view",
        )

        view = View(
            Group(
                VGroup(
                    UItem(name='workflow_view',
                          editor=tree_editor,
                          show_label=False), ),
                VGroup(UReadonly(
                    name='selected_error',
                    editor=TextEditor(),
                ),
                       label='Workflow Errors',
                       show_border=True),
            ),
            width=500,
            resizable=True,
            scrollable=True,
        )

        return view
Example #21
0
class ImageView(ModelView):
    """A model view of an image with actions.
    """

    #: The image model being viewed.
    model = Instance(ImageModel, (), allow_none=False)

    #: The image to display.
    image = Image()

    def rotate_left(self):
        """Rotate the image anticlockwise."""
        self.model.rotate("anticlockwise")

    def rotate_right(self):
        """Rotate the image clockwise."""
        self.model.rotate("clockwise")

    def flip_horizontal(self):
        """Flip the image horizontally."""
        self.model.flip("horizontal")

    def flip_vertical(self):
        """Flip the image vertically."""
        self.model.flip("vertical")

    def reload(self):
        """Reload the image from disk."""
        self.model.load_image()

    @observe('model.data')
    def _update_image(self, event):
        self.image = ArrayImage(data=self.model.data)

    def _image_default(self):
        return ArrayImage(data=self.model.data)

    view = View(
        HSplit(
            Item(
                'model.image_path',
                editor=FileEditor(
                    dialog_style='open',
                    filter=["*.png", "*.jpg", "*.jpeg"]
                ),
                style='custom',
            ),
            Item(
                'image',
                editor=ImageEditor(
                    scale=True,
                    preserve_aspect_ratio=True,
                    allow_upscaling=True,
                ),
                springy=True,
                resizable=True,
            ),
            show_labels=False,
            # NOTE: this id means the position of the sash will be saved
            id='viewer_split'
        ),
        resizable=True,
        toolbar=ToolBar(
            ActionGroup(
                Action(
                    name="Rotate Left",
                    tooltip="Rotate Left",
                    action='rotate_left',
                    image='rotate_left',
                ),
                Action(
                    name="Rotate Right",
                    tooltip="Rotate Right",
                    action='rotate_right',
                    image='rotate_right',
                ),
                Action(
                    name="Flip Horizontally",
                    tooltip="Flip Horizontally",
                    action='flip_horizontal',
                    image='flip_horizontal',
                ),
                Action(
                    name="Flip Vertically",
                    tooltip="Flip Vertically",
                    action='flip_vertical',
                    image='flip_vertical',
                ),
                name="Transpose Group",
                id="transpose_group",
            ),
            ActionGroup(
                Action(
                    name="Denoise",
                    tooltip="Denoise",
                    action='denoise',
                    image='denoise',
                ),
                name="Filter Group",
                id="filter_group",
            ),
            image_size=(24, 24),
            show_tool_names=False,
        ),
        menubar=MenuBar(
            Menu(
                Action(name="Revert Image", action="revert"),
                name="File",
                id="file_menu",
            ),
            Menu(
                ActionGroup(
                    Action(name="Rotate Left", action='rotate_left'),
                    Action(name="Rotate Right", action='rotate_right'),
                    Action(name="Flip Horizontally", action='flip_horizontal'),
                    Action(name="Flip Vertically", action='flip_vertical'),
                    name="Transpose Group",
                    id="transpose_group",
                ),
                ActionGroup(
                    Action(name="Denoise", action='denoise'),
                    name="Filter Group",
                    id="filter_group",
                ),
                name="Edit",
                id="edit_menu",
            ),
        ),
        # NOTE: this id means the size of the window will be saved
        id='image_preview',
    )
Example #22
0
    def populate(self, model):
        root = ModelTreeItem()

        model_item = ModelTreeItem(title='Model',
                                   icon=get_qt_icon('model.png'),
                                   controller=self.controller,
                                   ui=TopLevelModelView,
                                   ui_kwargs={'model': model})
        root.append_child(model_item)

        icon_provider = QFileIconProvider()
        folder_icon = icon_provider.icon(QFileIconProvider.Folder)

        controls_item = ModelTreeItem(title='Controls',
                                      icon=folder_icon,
                                      controller=self.controller)
        model_item.append_child(controls_item)

        for control in model.controls:
            item = ModelTreeItem.from_model_object(
                control,
                icon=get_qt_icon('control.png'),
                controller=self.controller,
                ui_kwargs={'obj': control},
                menu=Menu(RemoveAction))
            controls_item.append_child(item)

        metrics_item = ModelTreeItem(title='Metrics',
                                     icon=folder_icon,
                                     controller=self.controller)
        model_item.append_child(metrics_item)

        for metric in model.metrics:
            item = ModelTreeItem.from_model_object(
                metric,
                icon=get_qt_icon('metric.png'),
                controller=self.controller,
                ui_kwargs={'obj': metric},
                menu=Menu(RemoveAction))
            metrics_item.append_child(item)

        composite_item = ModelTreeItem(title='Composite Scores',
                                       icon=folder_icon,
                                       controller=self.controller)
        model_item.append_child(composite_item)

        for composite in model.composite_scores:
            item = ModelTreeItem.from_model_object(
                composite,
                icon=get_qt_icon('composite_score.png'),
                controller=self.controller,
                ui_kwargs={'obj': composite},
                menu=Menu(RemoveAction))
            composite_item.append_child(item)

        custom_item = ModelTreeItem(title='Custom Code',
                                    icon=get_qt_icon('code.png'),
                                    controller=self.controller,
                                    ui=UserCodeView,
                                    ui_kwargs={'model': model})
        model_item.append_child(custom_item)

        self._root_item = root
Example #23
0
class AutoFocus( ManagedJob, GetSetItemsMixin ):

    # overwrite default priority from ManagedJob (default 0)
    priority = 10

    confocal = Instance( Confocal )
    odmr = Instance( ODMR )
    #counter_trace = Instance ( CounterTrace )

    size_xy                 = Range(low=0.5, high=10., value=0.8,   desc='Size of XY Scan',                 label='Size XY [micron]',           mode='slider',  auto_set=False, enter_set=True)
    size_z                  = Range(low=0.5, high=10., value=1.5,    desc='Size of Z Scan',                  label='Size Z [micron]',            mode='slider',  auto_set=False, enter_set=True)
    step_xy                 = Range(low=0.01, high=10., value=0.04,  desc='Step of XY Scan',                 label='Step XY [micron]',           mode='slider',  auto_set=False, enter_set=True)
    step_z                  = Range(low=0.01, high=10., value=0.15,  desc='Step of Z Scan',                  label='Step Z [micron]',            mode='slider',  auto_set=False, enter_set=True)
    seconds_per_point_xy    = Range(low=1e-3, high=10, value=0.03,  desc='Seconds per point for XY Scan',   label='seconds per point XY [s]',   mode='text',    auto_set=False, enter_set=True)
    seconds_per_point_z     = Range(low=1e-3, high=10, value=0.05,   desc='Seconds per point for Z Scan',    label='seconds per point Z  [s]',    mode='text',    auto_set=False, enter_set=True)

    fit_method_xy = Enum('Maximum', 'Gaussian', desc='Fit Method for XY Scan',    label='XY Fit Method')
    fit_method_z  = Enum('Maximum', 'Gaussian', desc='Fit Method for Z Scan',     label='Z Fit Method')

    X = Array(value=np.array((0.,1.)) )
    Y = Array(value=np.array((0.,1.)) )
    Z = Array(value=np.array((-1.,1.)) )

    data_xy = Array( )
    data_z = Array( value=np.array((0,0)) )

    targets         = Instance( {}.__class__, factory={}.__class__ ) # Dict traits are no good for pickling, therefore we have to do it with an ordinary dictionary and take care about the notification manually 
    target_list     = Instance( list, factory=list, args=([None],) ) # list of targets that are selectable in current_target editor
    current_target  = Enum(values='target_list')
        
    drift               = Array( value=np.array(((0,0,0,),)) )
    drift_time          = Array( value=np.array((0,)) )
    current_drift       = Array( value=np.array((0,0,0)) )

    focus_interval    = Range(low=1, high=6000, value=10, desc='Time interval between automatic focus events', label='Interval [m]', auto_set=False, enter_set=True)
    periodic_focus    = Bool(False, label='Periodic focusing')
    periodic_freq_feedback  = Bool(False, label='Periodic freq feedback')
    threshold = Range(low=1, high=6000, value=1000, desc='ignore oil junks', label='threshold kcs/s', auto_set=False, enter_set=True)

    target_name = Str(label='name', desc='name to use when adding or removing targets')
    add_target_button       = Button(label='Add Target', desc='add target with given name')
    remove_current_target_button    = Button(label='Remove Current', desc='remove current target')
    next_target_button      = Button(label='Next Target', desc='switch to next available target')
    undo_button       = Button(label='undo', desc='undo the movement of the stage')
    
    previous_state = Instance( () )
    
    plot_data_image = Instance( ArrayPlotData )
    plot_data_line  = Instance( ArrayPlotData )
    plot_data_drift = Instance( ArrayPlotData )
    figure_image    = Instance( HPlotContainer, editor=ComponentEditor() )
    figure_line     = Instance( Plot, editor=ComponentEditor() )
    figure_drift    = Instance( Plot, editor=ComponentEditor() )
    image_plot      = Instance( CMapImagePlot )

    def __init__(self, confocal, odmr):
        super(AutoFocus, self).__init__()
        self.confocal = confocal
        self.odmr = odmr
        #self.counter_trace = counter_trace
        self.on_trait_change(self.update_plot_image, 'data_xy', dispatch='ui')
        self.on_trait_change(self.update_plot_line_value, 'data_z', dispatch='ui')
        self.on_trait_change(self.update_plot_line_index, 'Z', dispatch='ui')
        self.on_trait_change(self.update_plot_drift_value, 'drift', dispatch='ui')
        self.on_trait_change(self.update_plot_drift_index, 'drift_time', dispatch='ui')
        

    @on_trait_change('next_target_button')
    def next_target(self):
        """Convenience method to switch to the next available target."""
        keys = self.targets.keys()
        key = self.current_target
        if len(keys) == 0:
            logging.getLogger().info('No target available. Add a target and try again!')
        elif not key in keys:
            self.current_target = keys[0]
        else:
            self.current_target = keys[(keys.index(self.current_target)+1)%len(keys)]

    def _targets_changed(self, name, old, new):
        l = new.keys() + [None]      # rebuild target_list for Enum trait
        l.sort()
        self.target_list = l
        self._draw_targets()    # redraw target labels

    def _current_target_changed(self):
        self._draw_targets()    # redraw target labels

    def _draw_targets(self):
        c = self.confocal
        c.remove_all_labels()
        c.show_labels=True
        for key, coordinates in self.targets.iteritems():
            if key == self.current_target:
                c.set_label(key, coordinates, marker_color='red')
            else:
                c.set_label(key, coordinates)

    def _periodic_focus_changed(self, new):
        if not new and hasattr(self, 'cron_event'):
            CronDaemon().remove(self.cron_event)
        if new:
            self.cron_event = CronEvent(self.submit, min=range(0,60,self.focus_interval))
            CronDaemon().register(self.cron_event)

    def fit_xy(self):
        if self.fit_method_xy == 'Maximum':
            index = self.data_xy.argmax()
            xp = self.X[index%len(self.X)]
            yp = self.Y[index/len(self.X)]
            self.XYFitParameters = [xp, yp]
            self.xfit = xp
            self.yfit = yp
            return xp, yp
        else:
            print 'Not Implemented! Fix Me!'

    def fit_z(self):
        if self.fit_method_z == 'Maximum':
            zp = self.Z[self.data_z.argmax()]
            self.zfit = zp
            return zp
        else:
            print 'Not Implemented! Fix Me!'

    def add_target(self, key, coordinates=None):
        if coordinates is None:
            c = self.confocal
            coordinates = np.array((c.x,c.y,c.z))
        if self.targets == {}:
            self.forget_drift()
        if self.targets.has_key(key):
            if warning('A target with this name already exists.\nOverwriting will move all targets.\nDo you want to continue?'):
                self.current_drift = coordinates - self.targets[key]
                self.forget_drift()
            else:
                return
        else:
            coordinates = coordinates - self.current_drift
            self.targets[key] = coordinates
        self.trait_property_changed('targets', self.targets)    # trigger event such that Enum is updated and Labels are redrawn
        self.confocal.show_labels=True

    def remove_target(self, key):
        if not key in self.targets:
            logging.getLogger().info('Target cannot be removed. Target does not exist.')
            return
        self.targets.pop(key)        # remove target from dictionary
        self.trait_property_changed('targets', self.targets)    # trigger event such that Enum is updated and Labels are redrawn
        
    def remove_all_targets(self):
        self.targets = {}

    def forget_drift(self):
        targets = self.targets
        # reset coordinates of all targets according to current drift
        for key in targets:
            targets[key] += self.current_drift
        # trigger event such that target labels are redrawn
        self.trait_property_changed('targets', self.targets)
        # set current_drift to 0 and clear plot
        self.current_drift = np.array((0., 0., 0.))
        self.drift_time = np.array((time.time(),))
        self.drift = np.array(((0,0,0),))
        
    def _add_target_button_fired(self):
        self.add_target( self.target_name )
        
    def _remove_current_target_button_fired(self):
        self.remove_target( self.current_target )

    def _run(self):
        
        logging.getLogger().debug("trying run.")
        
        try:
            self.state='run'
            #ha.PulseGenerator().Light()
            
           
            if self.current_target is None:
                self.focus()
                if np.amax(self.data_xy)<10:
                    self._undo_button_fired()
                    pg.Light()
                    self.focus()
                # if self.periodic_freq_feedback: 
                    # self.odmr.submit()
                   
            else: # focus target
                coordinates = self.targets[self.current_target]
                confocal = self.confocal
                confocal.x, confocal.y, confocal.z = coordinates + self.current_drift
                current_coordinates = self.focus()
                self.current_drift = current_coordinates - coordinates  
                self.drift = np.append(self.drift, (self.current_drift,), axis=0)
                self.drift_time = np.append(self.drift_time, time.time())
                logging.getLogger().debug('Drift: %.2f, %.2f, %.2f'%tuple(self.current_drift))
                # if self.periodic_freq_feedback: 
                    # self.odmr.submit()
                    
        finally:
            self.state = 'idle'

    def focus(self):
            """
            Focuses around current position in x, y, and z-direction.
            """
            xp = self.confocal.x
            yp = self.confocal.y
            zp = self.confocal.z
            self.previous_state = ((xp,yp,zp), self.current_target)
            ##+scanner.getXRange()[1]
            safety = 0 #distance to keep from the ends of scan range
            xmin = np.clip(xp-0.5*self.size_xy, scanner.getXRange()[0]+safety, scanner.getXRange()[1]-safety)
            xmax = np.clip(xp+0.5*self.size_xy, scanner.getXRange()[0]+safety, scanner.getXRange()[1]-safety)
            ymin = np.clip(yp-0.5*self.size_xy, scanner.getYRange()[0]+safety, scanner.getYRange()[1]-safety)
            ymax = np.clip(yp+0.5*self.size_xy, scanner.getYRange()[0]+safety, scanner.getYRange()[1]-safety)
            
            X = np.arange(xmin, xmax, self.step_xy)
            Y = np.arange(ymin, ymax, self.step_xy)

            self.X = X
            self.Y = Y

            XP = X[::-1]

            self.data_xy=np.zeros((len(Y),len(X)))
            #self.image_plot.index.set_data(X, Y)  
                        
            for i,y in enumerate(Y):
                if threading.current_thread().stop_request.isSet():
                    self.confocal.x = xp
                    self.confocal.y = yp
                    self.confocal.z = zp
                    return xp, yp, zp                    
                if i%2 != 0:
                    XL = XP
                else:
                    XL = X
                YL = y * np.ones(X.shape)
                ZL = zp * np.ones(X.shape)
                Line = np.vstack( (XL, YL, ZL) )
                
                c = scanner.scanLine(Line, self.seconds_per_point_xy)/1e3
                if i%2 == 0:
                    self.data_xy[i,:] = c[:]
                else:
                    self.data_xy[i,:] = c[-1::-1]
                
                self.trait_property_changed('data_xy', self.data_xy)
                
            for i in range(self.data_xy.shape[0]):
                for j in range(self.data_xy.shape[1]):
                    if self.data_xy[i][j]>self.threshold:
                        self.data_xy[i][j]=0
            
            xp, yp = self.fit_xy()
                        
            self.confocal.x = xp
            self.confocal.y = yp

            Z = np.hstack( ( np.arange(zp, zp-0.5*self.size_z, -self.step_z),
                                np.arange(zp-0.5*self.size_z, zp+0.5*self.size_z, self.step_z),
                                np.arange(zp+0.5*self.size_z, zp, -self.step_z) ) )
            Z = np.clip(Z, scanner.getZRange()[0]+safety, scanner.getZRange()[1]-safety)

            X = xp * np.ones(Z.shape)
            Y = yp * np.ones(Z.shape)

            if not threading.current_thread().stop_request.isSet():
                Line = np.vstack( (X, Y, Z) )
                data_z = scanner.scanLine(Line, self.seconds_per_point_z)/1e3

                self.Z = Z
                self.data_z = data_z
                
            for i in range(self.data_z.shape[0]):
                if self.data_z[i]>self.threshold:
                        self.data_z[i]=0

                zp = self.fit_z()

            self.confocal.z = zp

            logging.getLogger().info('Focus: %.2f, %.2f, %.2f' %(xp, yp, zp))
            return xp, yp, zp

    def undo(self):
        if self.previous_state is not None:
            coordinates, target = self.previous_state
            self.confocal.x, self.confocal.y, self.confocal.z = coordinates
            if target is not None:
                self.drift_time = np.delete(self.drift_time, -1)
                self.current_drift = self.drift[-2]
                self.drift = np.delete(self.drift, -1, axis=0)
            self.previous_state = None
        else:
            logging.getLogger().info('Can undo only once.')

    def _undo_button_fired(self):
        self.remove()
        self.undo()
    
    def _plot_data_image_default(self):
        return ArrayPlotData(image=np.zeros((2,2)))
    def _plot_data_line_default(self):
        return ArrayPlotData(x=self.Z, y=self.data_z)
    def _plot_data_drift_default(self):
        return ArrayPlotData(t=self.drift_time, x=self.drift[:,0], y=self.drift[:,1], z=self.drift[:,2])

    def _figure_image_default(self):
        plot = Plot(self.plot_data_image, width=180, height=180, padding=3, padding_left=48, padding_bottom=32)
        plot.img_plot('image', colormap=jet, name='image')
        plot.aspect_ratio=1
        #plot.value_mapper.domain_limits = (scanner.getYRange()[0],scanner.getYRange()[1])
        #plot.index_mapper.domain_limits = (scanner.getXRange()[0],scanner.getXRange()[1])
        plot.value_mapper.domain_limits = (0,self.size_xy)
        plot.index_mapper.domain_limits = (0,self.size_xy)

        container = HPlotContainer()
        image = plot.plots['image'][0]
        colormap = image.color_mapper
        colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                            color_mapper=colormap,
                            plot=plot,
                            orientation='v',
                            resizable='v',
                            width=20,
                            height=200,
                            padding=8,
                            padding_left=20)
        container = HPlotContainer()
        container.add(plot)
        container.add(colorbar)
        return container
    def _figure_line_default(self):
        plot = Plot(self.plot_data_line, width=70, height=40, padding=8, padding_left=64, padding_bottom=32)
        plot.plot(('x','y'), color='blue')
        plot.index_axis.title = 'z [um]'
        plot.value_axis.title = 'Fluorescence [ k / s ]'
        return plot
    def _figure_drift_default(self):
        plot = Plot(self.plot_data_drift, width=70, height=40, padding=8, padding_left=64, padding_bottom=32)
        plot.plot(('t','x'), type='line', color='blue', name='x')
        plot.plot(('t','y'), type='line', color='red', name='y')
        plot.plot(('t','z'), type='line', color='green', name='z')
        bottom_axis = PlotAxis(plot,
                               orientation="bottom",
                               tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
        plot.index_axis=bottom_axis
        plot.index_axis.title = 'time'
        plot.value_axis.title = 'drift [um]'
        plot.legend.visible=True
        return plot        

    def _image_plot_default(self):
        return self.figure_image.components[0].plots['image'][0]

    def update_plot_image(self):
        self.plot_data_image.set_data('image', self.data_xy)
    def update_plot_line_value(self):
        self.plot_data_line.set_data('y', self.data_z)        
    def update_plot_line_index(self):
        self.plot_data_line.set_data('x', self.Z)
    def update_plot_drift_value(self):
        if len(self.drift) == 1:
            self.plot_data_drift.set_data('x', np.array(()))
            self.plot_data_drift.set_data('y', np.array(()))
            self.plot_data_drift.set_data('z', np.array(()))            
        else:
            self.plot_data_drift.set_data('x', self.drift[:,0])
            self.plot_data_drift.set_data('y', self.drift[:,1])
            self.plot_data_drift.set_data('z', self.drift[:,2])
    def update_plot_drift_index(self):
        if len(self.drift_time) == 0:
            self.plot_data_drift.set_data('t', np.array(()))
        else:
            self.plot_data_drift.set_data('t', self.drift_time - self.drift_time[0])

    traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
                                     Item('remove_button', show_label=False),
                                     Item('priority'),
                                     Item('state', style='readonly'),
                                     Item('undo_button', show_label=False),
                                     ),
                              Group(VGroup(HGroup(Item('target_name'),
                                                  Item('add_target_button', show_label=False),
                                                  ),
                                           HGroup(Item('current_target'),
                                                  Item('next_target_button', show_label=False),
                                                  Item('remove_current_target_button', show_label=False),
                                                  ),
                                           HGroup(Item('periodic_focus'),
                                                  Item('focus_interval', enabled_when='not periodic_focus'),
                                                  ),
                                           HGroup(Item('periodic_freq_feedback'),
                                                  Item('threshold')
                                                  ),       
                                           label='tracking',
                                           ),
                                    VGroup(Item('size_xy'),
                                           Item('step_xy'),
                                           Item('size_z'),
                                           Item('step_z'),
                                           HGroup(Item('seconds_per_point_xy'),
                                                  Item('seconds_per_point_z'),
                                                  ),
                                           label='Settings',
                                           springy=True,
                                           ),
                                    layout='tabbed'
                                    ),
                              VSplit(Item('figure_image', show_label=False, resizable=True)),
                              HGroup(Item('figure_line', show_label=False, resizable=True),
                                     Item('figure_drift', show_label=False, resizable=True),
                                    ),
                              ),
                       menubar = MenuBar(Menu(Action(action='save', name='Save (.pyd or .pys)'),
                                              Action(action='load', name='Load'),
                                              Action(action='_on_close', name='Quit'),
                                              name='File'),
                                         Menu(Action(action='remove_all_targets', name='Remove All'),
                                              Action(action='forget_drift', name='Forget Drift'),
                                              name='Target'),),
                       title='Auto Focus', width=500, height=700, buttons=[], resizable=True,
                       handler=AutoFocusHandler)

    get_set_items=['confocal','targets','current_target','current_drift','drift','drift_time','periodic_focus',
                   'size_xy', 'size_z', 'step_xy', 'step_z', 'seconds_per_point_xy', 'seconds_per_point_z',
                   'data_xy', 'data_z', 'X', 'Y', 'Z', 'focus_interval', 'threshold' ]
    get_set_order=['confocal','targets']
Example #24
0
    def dynamic_view(self):
        return View(
            Item('electrodes',
                editor=TableEditor( columns = 
                    [ObjectColumn(label='electrode',
                                  editor=TextEditor(),
                                  style='readonly',
                                  editable=False,
                                  name='strrepr'),

                     ObjectColumn(label='corner',
                                  editor=CheckListEditor(
                                    values=['','corner 1','corner 2',
                                        'corner 3']),
                                  style='simple',
                                  name='corner'),

                     ObjectColumn(label='geometry',
                                  editor=CSVListEditor(),
                                  #editor=TextEditor(),
                                  #style='readonly',
                                  #editable=False,
                                  name='geom_coords'),
                                  
                     ObjectColumn(label='channel name',
                                  editor=TextEditor(),
                                  name='name'),

                     ObjectColumn(label='ROIs',
                                  editor=ListStrEditor(),
                                  editable=False, 
                                  name='roi_list'),
                     ],
                    selected='cur_sel',
                    deletable=True,
                    #row_factory=electrode_factory,
                    row_factory=self.electrode_factory,
                    ),
                show_label=False, height=350, width=700),

            HGroup(
                VGroup( 
                    Label( 'Automatic labeling parameters' ),
                    Item( 'name_stem' ),
                    HGroup(
                        Item( 'naming_convention' ),
                        Item( 'grid_type' ),
                    ),
                ),
                #VGroup(
                #    Label( 'ROI identification parameters' ),
                #    Item('parcellation'),
                #    Item('error_radius'),
                #),
                #VGroup(
                #    Label('Image parameters' ),
                #    Item('img_dpi', label='dpi'),
                #    Item('img_size', label='size', editor=CSVListEditor()),
                #),
            ),

            resizable=True, kind='panel', title='modify electrodes',
            #buttons=[OKButton, swap_action, label_auto_action,
            #    interpolate_action, save_montage_action, find_rois_action]) 

            buttons = [self.label_auto_action, self.swap_action, OKButton],
            menubar = MenuBar(
                Menu( self.label_auto_action, self.add_blank_action,
                    self.interpolate_action, self.find_rois_action, 
                    self.find_all_rois_action,
                    self.manual_reposition_action,
                    name='Operations',
                ),
                Menu( self.save_montage_action, self.save_csv_action,
                    self.save_coronal_slice_action,
                    name='Save Output',
                ),
            )
        )
Example #25
0
                           style="custom"),
                      Item("aggregator", style="custom"),
                      show_labels=False),
               Item(
                   "scene3d",
                   editor=SceneEditor(scene_class=Scene),
                   height=500,
                   width=500),
               show_labels=False),
        Item("vslicer", style="custom"),
        show_labels=False),
 menubar=MenuBar(
     Menu(a_add_streamlines,
          a_change_datasource,
          Separator(),
          a_change_reference_volume,
          a_mni152_2mm_reference_volume,
          Separator(),
          a_load_ltpa,
          name="Data"),
     Menu(a_set_coords_from_nifti, name="Query"),
     Menu(a_query_region_pair,
          a_evaluate_aggregation,
          name="Aggregation"),
     Menu(a_edit_streamline_viz,
          a_ltpa_graphics,
          a_edit_scene3d,
          a_edit_volumes,
          a_take_screenshot,
          name="Graphics"),
     Menu(a_save_streamlines,
          a_save_csv,