Пример #1
0
    def check_enum_mappings_value_change(self, style):

        image_enum_editor_factory = ImageEnumEditor(
            values=['top left', 'top right'],
            format_func=lambda v: v.upper(),
            prefix='@icons:',
            suffix='_origin',
            path='dummy_path',
        )
        formatted_view = View(
            UItem(
                "value",
                editor=image_enum_editor_factory,
                style=style,
            ))

        with reraise_exceptions(), self.setup_ui(EnumModel(),
                                                 formatted_view) as editor:

            self.assertEqual(editor.names, ["TOP LEFT", "TOP RIGHT"])
            self.assertEqual(
                editor.mapping,
                {
                    "TOP LEFT": "top left",
                    "TOP RIGHT": "top right"
                },
            )
            self.assertEqual(
                editor.inverse_mapping,
                {
                    "top left": "TOP LEFT",
                    "top right": "TOP RIGHT"
                },
            )

            image_enum_editor_factory.values = ["top right", "top left"]

            self.assertEqual(editor.names, ["TOP RIGHT", "TOP LEFT"])
            self.assertEqual(
                editor.mapping,
                {
                    "TOP RIGHT": "top right",
                    "TOP LEFT": "top left"
                },
            )
            self.assertEqual(
                editor.inverse_mapping,
                {
                    "top right": "TOP RIGHT",
                    "top left": "TOP LEFT"
                },
            )
Пример #2
0
class ImageEnumEditorDemo(HasTraits):
    """ Defines the ImageEnumEditor demo class.
    """

    # Define a trait to view:
    image_from_list = Enum(
        *image_list,
        editor=ImageEnumEditor(
            values=image_list,
            prefix='@icons:',
            suffix='_origin',
            cols=4,
            klass=Dummy
        )
    )

    # Items are used to define the demo display, one Item per editor style:
    img_group = Group(
        Item('image_from_list', style='simple', label='Simple'),
        Item('_'),
        Item('image_from_list', style='text', label='Text'),
        Item('_'),
        Item('image_from_list', style='readonly', label='ReadOnly'),
        Item('_'),
        Item('image_from_list', style='custom', label='Custom')
    )

    # Demo view:
    traits_view = View(
        img_group,
        title='ImageEnumEditor',
        buttons=['OK'],
        resizable=True
    )
Пример #3
0
class ImageEnumEditorDemo(HasTraits):
    """ This class specifies the details of the ImageEnumEditor demo.
    """

    # To demonstrate any given Trait editor, an appropriate Trait is required.
    image_from_list = Trait(editor=ImageEnumEditor(values=image_list,
                                                   prefix='@icons:',
                                                   suffix='_origin',
                                                   cols=4,
                                                   klass=Dummy),
                            *image_list)

    # Items are used to define the demo display - one Item per
    # editor style
    img_group = Group(Item('image_from_list', style='simple', label='Simple'),
                      Item('_'),
                      Item('image_from_list', style='custom', label='Custom'),
                      Item('_'),
                      Item('image_from_list', style='text', label='Text'),
                      Item('_'),
                      Item('image_from_list',
                           style='readonly',
                           label='ReadOnly'))

    #Demo view
    view1 = View(img_group,
                 title='ImageEnumEditor',
                 buttons=['OK'])
Пример #4
0
    def test_custom_editor_more_cols(self):
        # Smoke test for setting up an editor with more than one column
        enum_edit = EnumModel()
        view = View(
            UItem(
                'value',
                editor=ImageEnumEditor(
                    values=[
                        'top left',
                        'top right',
                        'bottom left',
                        'bottom right',
                    ],
                    prefix='@icons:',
                    suffix='_origin',
                    path='dummy_path',
                    cols=4,
                ),
                style="custom",
            ),
            resizable=True,
        )

        with reraise_exceptions(), self.setup_gui(enum_edit, view):
            pass
Пример #5
0
    def test_readonly_editor_name(self):
        class PossibleEnumModel(HasTraits):
            value = value = Enum('top left', 'top right')
            possible_values = List(['top left', 'top right'])

        formatted_view = View(
            UItem(
                'value',
                editor=ImageEnumEditor(
                    name="object.possible_values",
                    format_func=lambda v: v.upper(),
                    prefix='@icons:',
                    suffix='_origin',
                    path='dummy_path',
                ),
                style="readonly",
            ))
        model = PossibleEnumModel()

        with reraise_exceptions(), self.setup_ui(model,
                                                 formatted_view) as editor:

            # Readonly editor doesn't set up full mapping, only check that
            # str_value is mapped as expected
            self.assertEqual(model.value, "top left")
            self.assertEqual(editor.str_value, "TOP LEFT")
Пример #6
0
class Person(HasTraits):

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    name = Str('David Morrill')
    age = Int(39)
    sex = Trait('Male', 'Female')
    coolness = Range(0.0, 10.0, 10.0)
    number = Trait(1, Range(1, 6), 'one', 'two', 'three', 'four', 'five',
                   'six')
    human = Bool(True)
    employer = Trait(Employer(company='Enthought, Inc.', boss='eric'))
    eye_color = RGBAColor
    set = List(
        editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=4))
    font = KivaFont
    street = Str
    city = Str
    state = Str
    zip = Int(78663)
    password = Str
    books = List(Str,
                 ['East of Eden', 'The Grapes of Wrath', 'Of Mice and Men'])
    call = Event(0, editor=ButtonEditor(label='Click to call'))
    info = Str(editor=FileEditor())
    location = Str(editor=DirectoryEditor())
    origin = Trait(editor=ImageEnumEditor(values=origin_values,
                                          suffix='_origin',
                                          cols=4,
                                          klass=Employer),
                   *origin_values)

    nm = Item('name', enabled_when='object.age >= 21')
    pw = Item('password', defined_when='object.zip == 78664')
    view = View(
        ((nm, 'age', 'coolness', '_', 'eye_color', 'eye_color@', 'eye_color*',
          'eye_color~', '_', 'font', 'font@', 'font*', 'font~', '_', 'set',
          'set@', 'set*', 'set~', '_', 'sex', 'sex@', 'sex*', 'sex~', '_',
          'human', 'human@', 'human*', 'human~', '_', 'number', 'number@',
          'number*', 'number~', '_', 'books', '_', 'books@', '_', 'books*',
          '_', 'books~', '_', 'info', 'location', 'origin', 'origin@', 'call',
          'employer', 'employer[]@', 'employer*', 'employer~', pw,
          '|<[Person:]'),
         (' ', 'street', 'city', 'state', 'zip', '|<[Address:]'),
         (nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm,
          '|<[Names:]'), '|'),
        title='Traits 2 User Interface Test',
        handler=PersonHandler(),
        buttons=['Apply', 'Revert', 'Undo', 'OK'],
        height=0.5)

    wizard = View(('|p1:', 'name', 'age', 'sex'),
                  ('|p2:', 'street', 'city', 'state', 'zip'),
                  ('|p3:', 'eye_color', 'origin', 'human'),
                  handler=WizardHandler())
Пример #7
0
    def check_enum_mappings_name_change(self, style):
        class PossibleEnumModel(HasTraits):
            value = value = Enum('top left', 'top right')
            possible_values = List(['top left', 'top right'])

        formatted_view = View(
            UItem(
                'value',
                editor=ImageEnumEditor(
                    name="object.possible_values",
                    format_func=lambda v: v.upper(),
                    prefix='@icons:',
                    suffix='_origin',
                    path='dummy_path',
                ),
                style=style,
            ))
        model = PossibleEnumModel()

        with reraise_exceptions(), self.setup_ui(model,
                                                 formatted_view) as editor:

            self.assertEqual(editor.names, ["TOP LEFT", "TOP RIGHT"])
            self.assertEqual(
                editor.mapping,
                {
                    "TOP LEFT": "top left",
                    "TOP RIGHT": "top right"
                },
            )
            self.assertEqual(
                editor.inverse_mapping,
                {
                    "top left": "TOP LEFT",
                    "top right": "TOP RIGHT"
                },
            )

            model.possible_values = ["top right", "top left"]

            self.assertEqual(editor.names, ["TOP RIGHT", "TOP LEFT"])
            self.assertEqual(
                editor.mapping,
                {
                    "TOP RIGHT": "top right",
                    "TOP LEFT": "top left"
                },
            )
            self.assertEqual(
                editor.inverse_mapping,
                {
                    "top right": "TOP RIGHT",
                    "top left": "TOP LEFT"
                },
            )
Пример #8
0
def get_view(style):
    return View(
        UItem(
            'value',
            editor=ImageEnumEditor(
                values=[
                    'top left', 'top right', 'bottom left', 'bottom right'
                ],
                prefix='@icons:',
                suffix='_origin',
                path='dummy_path',
            ),
            style=style,
        ),
        resizable=True,
    )
Пример #9
0
class Align(HasTraits):
    # The position of the view
    position = Array(shape=(3, ))

    brightness = Range(-2., 2., value=0.)
    contrast = Range(0., 3., value=1.)
    opacity = Range(0., 1., value=.1)
    colormap = Enum(*lut_manager.lut_mode_list())
    fliplut = Bool

    outlines_visible = Bool(default_value=True)
    outline_rep = Enum(outline_reps)
    outline_color = Color(
        default=options.config.get("mayavi_aligner", "outline_color"))
    line_width = Range(0.5,
                       10.,
                       value=float(
                           options.config.get("mayavi_aligner", "line_width")))
    point_size = Range(0.5,
                       10.,
                       value=float(
                           options.config.get("mayavi_aligner", "point_size")))

    epi_filter = Enum(None, "median", "gradient")
    filter_strength = Range(1, 20, value=3)

    scene_3d = Instance(MlabSceneModel, ())
    scene_x = Instance(MlabSceneModel, ())
    scene_y = Instance(MlabSceneModel, ())
    scene_z = Instance(MlabSceneModel, ())

    # The data source
    epi_src = Instance(Source)
    surf_src = Instance(Source)
    xfm = Instance(Filter)
    surf = Instance(Module)

    disable_render = Bool

    flip_fb = Bool
    flip_lr = Bool
    flip_ud = Bool

    save_callback = Instance(types.FunctionType)
    save_btn = Button(label="Save Transform")

    legend = Str(legend)

    #---------------------------------------------------------------------------
    # Object interface
    #---------------------------------------------------------------------------
    def __init__(self, pts, polys, epi, xfm=None, xfmtype='magnet', **traits):
        '''
        Parameters
        ----------
        xfm : array_like, optional
            The initial 4x4 rotation matrix into magnet space 
            (epi with slice affine)
        '''
        self.load_epi(epi, xfm, xfmtype)
        self.pts, self.polys = pts, polys
        self._undolist = []
        self._redo = None
        super(Align, self).__init__(**traits)

    def load_epi(self, epifilename, xfm=None, xfmtype="magnet"):
        """Loads the EPI image from the specified epifilename.
        """
        nii = nibabel.load(epifilename)
        self.epi_file = nii
        epi = nii.get_data().astype(float).squeeze()
        if epi.ndim > 3:
            epi = epi[:, :, :, 0]
        self.affine = nii.get_affine()
        base = nii.get_header().get_base_affine()
        self.base = base
        self.origin = base[:3, -1]
        self.spacing = np.diag(base)[:3]
        if xfm is None:
            self.startxfm = np.dot(base, np.linalg.inv(self.affine))
        elif xfmtype == "magnet":
            self.startxfm = np.dot(np.dot(base, np.linalg.inv(self.affine)),
                                   xfm)
        else:
            print("using xfmtype %s" % xfmtype)
            self.startxfm = xfm

        self.center = self.spacing * nii.get_shape()[:3] / 2 + self.origin

        self.padshape = 2**(np.ceil(np.log2(np.array(epi.shape))))

        epi = np.nan_to_num(epi)
        self.epi_orig = epi - epi.min()
        self.epi_orig /= self.epi_orig.max()
        self.epi_orig *= 2
        self.epi_orig -= 1
        self.epi = self.epi_orig.copy()

    #---------------------------------------------------------------------------
    # Default values
    #---------------------------------------------------------------------------
    def _position_default(self):
        return np.abs(self.origin) + (
            (np.array(self.epi.shape) + 1) % 2) * np.abs(self.spacing) / 2

    def _epi_src_default(self):
        sf = mlab.pipeline.scalar_field(self.epi,
                                        figure=self.scene_3d.mayavi_scene,
                                        name='EPI')
        sf.origin = self.origin
        sf.spacing = self.spacing
        return sf

    def _surf_src_default(self):
        return mlab.pipeline.triangular_mesh_source(
            self.pts[:, 0],
            self.pts[:, 1],
            self.pts[:, 2],
            self.polys,
            figure=self.scene_3d.mayavi_scene,
            name='Cortex')

    def _surf_default(self):
        smooth = mlab.pipeline.poly_data_normals(
            self.xfm, figure=self.scene_3d.mayavi_scene)
        smooth.filter.splitting = False
        surf = mlab.pipeline.surface(smooth, figure=self.scene_3d.mayavi_scene)
        surf.actor.mapper.scalar_visibility = 0
        return surf

    def _xfm_default(self):
        xfm = mlab.pipeline.transform_data(self.surf_src,
                                           figure=self.scene_3d.mayavi_scene)

        def savexfm(info, evt):
            self._undolist.append(xfm.transform.matrix.to_array())
            np.save("/tmp/last_xfm.npy", self.get_xfm())

        xfm.widget.add_observer("EndInteractionEvent", savexfm)
        xfm.widget.add_observer("EndInteractionEvent", self.update_slabs)
        xfm.transform.set_matrix(self.startxfm.ravel())
        xfm.widget.set_transform(xfm.transform)
        return xfm

    #---------------------------------------------------------------------------
    # Scene activation callbacks
    #---------------------------------------------------------------------------
    @on_trait_change('scene_3d.activated')
    def display_scene_3d(self):
        self.scene_3d.mlab.view(40, 50)
        self.scene_3d.scene.renderer.use_depth_peeling = True
        self.scene_3d.scene.background = (0, 0, 0)
        # Keep the view always pointing up
        self.scene_3d.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain(
        )
        self.scene_3d.scene_editor.aligner = self

        self.opacity = float(options.config.get("mayavi_aligner", "opacity"))
        self.xfm.widget.enabled = False
        self.colormap = options.config.get("mayavi_aligner", "colormap")

        self.disable_render = True
        for ax in [self.x_axis, self.y_axis, self.z_axis]:
            ax.update_position()
            ax.reset_view()
        self.disable_render = False

    @on_trait_change('scene_x.activated')
    def display_scene_x(self):
        self.x_axis = XAxis(parent=self)

    @on_trait_change('scene_y.activated')
    def display_scene_y(self):
        self.y_axis = YAxis(parent=self)

    @on_trait_change('scene_z.activated')
    def display_scene_z(self):
        self.z_axis = ZAxis(parent=self)

    #---------------------------------------------------------------------------
    # Traits callback
    #---------------------------------------------------------------------------

    def _save_btn_changed(self):
        if self.save_callback is not None:
            self.save_callback(self)

    def _disable_render_changed(self):
        self.scene_3d.scene.disable_render = self.disable_render

    def _position_changed(self):
        self.disable_render = True
        for ax in [self.x_axis, self.y_axis, self.z_axis]:
            ax.update_position()
        self.disable_render = False

    def _outlines_visible_changed(self):
        self.disable_render = True
        for ax in [self.x_axis, self.y_axis, self.z_axis]:
            ax.toggle_outline()
        self.disable_render = False

    @on_trait_change("colormap, fliplut")
    def update_colormap(self):
        for ax in [self.x_axis, self.y_axis, self.z_axis]:
            if ax.ipw_3d and ax.ipw:
                ax.ipw_3d.parent.scalar_lut_manager.set(
                    lut_mode=self.colormap, reverse_lut=self.fliplut)
                ax.ipw.parent.scalar_lut_manager.set(lut_mode=self.colormap,
                                                     reverse_lut=self.fliplut)

    def _opacity_changed(self):
        self.surf.actor.property.opacity = self.opacity

    @on_trait_change("brightness,contrast")
    def update_brightness(self):
        self.epi_src.scalar_data = (self.epi * self.contrast) + self.brightness

    @on_trait_change("flip_ud")
    def update_flipud(self):
        #self.epi_src.scalar_data = self.epi_src.scalar_data[:,:,::-1]
        flip = np.eye(4)
        flip[2, 2] = -1
        mat = self.xfm.transform.matrix.to_array()
        self.set_xfm(np.dot(mat, flip), "base")

    @on_trait_change("flip_lr")
    def update_fliplr(self):
        #self.epi_src.scalar_data = self.epi_src.scalar_data[::-1]
        flip = np.eye(4)
        flip[0, 0] = -1
        mat = self.xfm.transform.matrix.to_array()
        self.set_xfm(np.dot(mat, flip), "base")

    @on_trait_change("flip_fb")
    def update_flipfb(self):
        #self.epi_src.scalar_data = self.epi_src.scalar_data[:,::-1]
        flip = np.eye(4)
        flip[1, 1] = -1
        mat = self.xfm.transform.matrix.to_array()
        self.set_xfm(np.dot(mat, flip), "base")

    @on_trait_change("epi_filter, filter_strength")
    def update_epifilter(self):
        if self.epi_filter is None:
            self.epi = self.epi_orig.copy()
        elif self.epi_filter == "median":
            fstr = np.floor(self.filter_strength / 2) * 2 + 1
            self.epi = volume.detrend_median(self.epi_orig.T, fstr).T
        elif self.epi_filter == "gradient":
            self.epi = volume.detrend_gradient(self.epi_orig.T,
                                               self.filter_strength).T

        self.update_brightness()

    def update_slabs(self, *args, **kwargs):
        self.disable_render = True
        for ax in [self.x_axis, self.y_axis, self.z_axis]:
            ax.update_slab()
        self.disable_render = False

    def get_xfm(self, xfmtype="magnet"):
        if xfmtype in ["anat->epicoord", "coord"]:
            ibase = np.linalg.inv(self.base)
            xfm = self.xfm.transform.matrix.to_array()
            return np.dot(ibase, xfm)
        elif xfmtype in ["anat->epibase", "base"]:
            return self.xfm.transform.matrix.to_array()
        elif xfmtype in ['anat->magnet', "magnet"]:
            ibase = np.linalg.inv(self.base)
            xfm = self.xfm.transform.matrix.to_array()
            return np.dot(self.affine, np.dot(ibase, xfm))

    def set_xfm(self, matrix, xfmtype='magnet'):
        assert xfmtype in "magnet coord base".split(), "Unknown transform type"
        if xfmtype == "coord":
            matrix = np.dot(self.base, matrix)
        elif xfmtype == "magnet":
            iaff = np.linalg.inv(self.affine)
            matrix = np.dot(self.base, np.dot(iaff, matrix))

        self.xfm.transform.set_matrix(matrix.ravel())
        self.xfm.widget.set_transform(self.xfm.transform)
        self.xfm.update_pipeline()
        self.update_slabs()

    def undo(self):
        if len(self._undolist) > 0:
            self.xfm.transform.set_matrix(self._undolist[-1].ravel())
            self.xfm.widget.set_transform(self.xfm.transform)
            self.xfm.update_pipeline()
            self.update_slabs()
            self._redo = self._undolist.pop()

    #---------------------------------------------------------------------------
    # The layout of the dialog created
    #---------------------------------------------------------------------------
    view = View(HGroup(
        Group(
            Item('scene_y', editor=SceneEditor(scene_class=FlatScene)),
            Item('scene_z', editor=SceneEditor(scene_class=FlatScene)),
            show_labels=False,
        ),
        Group(
            Item('scene_x', editor=SceneEditor(scene_class=FlatScene)),
            Item('scene_3d', editor=SceneEditor(scene_class=ThreeDScene)),
            show_labels=False,
        ),
        Group(Group(
            Item("save_btn",
                 show_label=False,
                 visible_when="save_callback is not None"),
            "brightness",
            "contrast",
            "epi_filter",
            Item('filter_strength', visible_when="epi_filter is not None"),
            "_",
            "opacity",
            "_",
            Item('colormap',
                 editor=ImageEnumEditor(values=lut_manager.lut_mode_list(),
                                        cols=6,
                                        path=lut_manager.lut_image_dir)),
            "fliplut",
            "_",
            "flip_ud",
            "flip_lr",
            "flip_fb",
            "_",
            Item('outline_color', editor=ColorEditor()),
            'outline_rep',
            'line_width',
            'point_size',
            '_',
        ),
              Group(
                  Item('legend',
                       editor=TextEditor(),
                       style='readonly',
                       show_label=False,
                       emphasized=True,
                       dock='vertical'),
                  show_labels=False,
              ),
              orientation='vertical'),
    ),
                resizable=True,
                title='Aligner')
Пример #10
0
class TraitsTest(HasTraits):

    #-------------------------------------------------------------------------
    #  Trait definitions:
    #-------------------------------------------------------------------------

    enabled = Bool(True)
    integer_text = Int(1)
    enumeration = Trait('one', 'two', 'three', 'four', 'five', 'six', cols=3)
    float_range = Range(0.0, 10.0, 10.0)
    int_range = Range(1, 6)
    int_range2 = Range(1, 50)
    compound = Trait(1, Range(1, 6), 'one', 'two', 'three', 'four', 'five',
                     'six')
    boolean = Bool(True)
    instance = Trait(Instance())
    color = Color('cyan')
    font = Font()
    check_list = List(
        editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=4))
    list = List(Str,
                ['East of Eden', 'The Grapes of Wrath', 'Of Mice and Men'])
    button = Event(0, editor=ButtonEditor(label='Click'))
    file = File()
    directory = Directory()
    image_enum = Trait(editor=ImageEnumEditor(values=origin_values,
                                              suffix='_origin',
                                              cols=4,
                                              klass=Instance),
                       *origin_values)

    #-------------------------------------------------------------------------
    #  View definitions:
    #-------------------------------------------------------------------------

    view = View(
        ('|{Enum}', ('enabled', ),
         ('|<[Enumeration]', 'f1:enumeration[Simple]', '_',
          'f2:enumeration[Custom]@', '_', 'f3:enumeration[Text]*', '_',
          'f4:enumeration[Readonly]~'),
         ('|<[Check List]', 'f5:check_list[Simple]', '_',
          'f6:check_list[Custom]@', '_', 'f7:check_list[Text]*', '_',
          'f8:check_list[Readonly]~')),
        ('|{Range}',
         ('|<[Float Range]', 'f9:float_range[Simple]', '_',
          'f10:float_range[Custom]@', '_', 'f11:float_range[Text]*', '_',
          'f12:float_range[Readonly]~'),
         ('|<[Int Range]', 'f13:int_range[Simple]', '_',
          'f14:int_range[Custom]@', '_', 'f15:int_range[Text]*', '_',
          'f16:int_range[Readonly]~'),
         ('|<[Int Range 2]', 'f17:int_range2[Simple]', '_',
          'f18:int_range2[Custom]@', '_', 'f19:int_range2[Text]*', '_',
          'f20:int_range2[Readonly]~')),
        ('|{Misc}',
         ('|<[Integer Text]', 'f21:integer_text[Simple]', '_',
          'f22:integer_text[Custom]@', '_', 'f23:integer_text[Text]*', '_',
          'f24:integer_text[Readonly]~'),
         ('|<[Compound]', 'f25:compound[Simple]', '_', 'f26:compound[Custom]@',
          '_', 'f27:compound[Text]*', '_', 'f28:compound[Readonly]~'),
         ('|<[Boolean]', 'f29:boolean[Simple]', '_', 'f30:boolean[Custom]@',
          '_', 'f31:boolean[Text]*', '_', 'f32:boolean[Readonly]~')),
        ('|{Color/Font}',
         ('|<[Color]', 'f33:color[Simple]', '_', 'f34:color[Custom]@', '_',
          'f35:color[Text]*', '_', 'f36:color[Readonly]~'),
         ('|<[Font]', 'f37:font[Simple]', '_', 'f38:font[Custom]@', '_',
          'f39:font[Text]*', '_', 'f40:font[Readonly]~')),
        ('|{List}', ('|<[List]', 'f41:list[Simple]', '_', 'f42:list[Custom]@',
                     '_', 'f43:list[Text]*', '_', 'f44:list[Readonly]~')),
        (
            '|{Button}',
            ('|<[Button]', 'f45:button[Simple]', '_', 'f46:button[Custom]@'),
            #                                        'button[Text]*',
            #                                        'button[Readonly]~' ),
            ('|<[Image Enum]', 'f47:image_enum[Simple]', '_',
             'f48:image_enum[Custom]@', '_', 'f49:image_enum[Text]*', '_',
             'f50:image_enum[Readonly]~'),
            ('|<[Instance]', 'f51:instance[Simple]', '_',
             'f52:instance[Custom]@', '_', 'f53:instance[Text]*', '_',
             'f54:instance[Readonly]~'),
        ),
        ('|{File}', (
            '|<[File]',
            'f55:file[Simple]',
            '_',
            'f56:file[Custom]@',
            '_',
            'f57:file[Text]*',
            '_',
            'f58:file[Readonly]~',
        ), ('|<[Directory]', 'f59:directory[Simple]', '_',
            'f60:directory[Custom]@', '_', 'f61:directory[Text]*', '_',
            'f62:directory[Readonly]~')),
        buttons=['Apply', 'Revert', 'Undo', 'OK'],
        handler=TraitsTestHandler())
Пример #11
0
class TraitsTest(HasTraits):

    #-------------------------------------------------------------------------
    #  Trait definitions:
    #-------------------------------------------------------------------------

    integer_text = Int(1)
    enumeration = Enum('one', 'two', 'three', 'four', 'five', 'six', cols=3)
    float_range = Range(0.0, 10.0, 10.0)
    int_range = Range(1, 6)
    int_range2 = Range(1, 50)
    compound = Trait(1, Range(1, 6), 'one', 'two', 'three', 'four', 'five',
                     'six')
    boolean = Bool(True)
    instance = Trait(Instance())
    color = Color
    font = Font
    check_list = List(
        editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=4))
    list = List(Str,
                ['East of Eden', 'The Grapes of Wrath', 'Of Mice and Men'])
    button = Event(0, editor=ButtonEditor(label='Click'))
    file = File
    directory = Directory
    image_enum = Trait(editor=ImageEnumEditor(values=origin_values,
                                              suffix='_origin',
                                              cols=4,
                                              klass=Instance),
                       *origin_values)

    #-------------------------------------------------------------------------
    #  View definitions:
    #-------------------------------------------------------------------------

    view = View(
        ('|{Enum}', ('|<[Enumeration]', 'enumeration[Simple]', '_',
                     'enumeration[Custom]@', '_', 'enumeration[Text]*', '_',
                     'enumeration[Readonly]~'),
         ('|<[Check List]', 'check_list[Simple]', '_', 'check_list[Custom]@',
          '_', 'check_list[Text]*', '_', 'check_list[Readonly]~')),
        ('|{Range}', ('|<[Float Range]', 'float_range[Simple]', '_',
                      'float_range[Custom]@', '_', 'float_range[Text]*', '_',
                      'float_range[Readonly]~'),
         ('|<[Int Range]', 'int_range[Simple]', '_', 'int_range[Custom]@', '_',
          'int_range[Text]*', '_', 'int_range[Readonly]~'),
         ('|<[Int Range 2]', 'int_range2[Simple]', '_', 'int_range2[Custom]@',
          '_', 'int_range2[Text]*', '_', 'int_range2[Readonly]~')),
        ('|{Misc}', ('|<[Integer Text]', 'integer_text[Simple]', '_',
                     'integer_text[Custom]@', '_', 'integer_text[Text]*', '_',
                     'integer_text[Readonly]~'),
         ('|<[Compound]', 'compound[Simple]', '_', 'compound[Custom]@', '_',
          'compound[Text]*', '_', 'compound[Readonly]~'),
         ('|<[Boolean]', 'boolean[Simple]', '_', 'boolean[Custom]@', '_',
          'boolean[Text]*', '_', 'boolean[Readonly]~')),
        ('|{Color/Font}', ('|<[Color]', 'color[Simple]', '_', 'color[Custom]@',
                           '_', 'color[Text]*', '_', 'color[Readonly]~'),
         ('|<[Font]', 'font[Simple]', '_', 'font[Custom]@', '_', 'font[Text]*',
          '_', 'font[Readonly]~')),
        ('|{List}', ('|<[List]', 'list[Simple]', '_', 'list[Custom]@', '_',
                     'list[Text]*', '_', 'list[Readonly]~')),
        (
            '|{Button}',
            ('|<[Button]', 'button[Simple]', '_', 'button[Custom]@'),
            #                                        'button[Text]*',
            #                                        'button[Readonly]~' ),
            ('|<[Image Enum]', 'image_enum[Simple]', '_',
             'image_enum[Custom]@', '_', 'image_enum[Text]*', '_',
             'image_enum[Readonly]~'),
            ('|<[Instance]', 'instance[Simple]', '_', 'instance[Custom]@', '_',
             'instance[Text]*', '_', 'instance[Readonly]~'),
        ),
        ('|{File}', (
            '|<[File]',
            'file[Simple]',
            '_',
            'file[Custom]@',
            '_',
            'file[Text]*',
            '_',
            'file[Readonly]~',
        ), ('|<[Directory]', 'directory[Simple]', '_', 'directory[Custom]@',
            '_', 'directory[Text]*', '_', 'directory[Readonly]~')),
        buttons=['Apply', 'Revert', 'Undo', 'OK'])
Пример #12
0
]

# Cursor styles:
CURSOR_X = 1
CURSOR_Y = 2

cursor_styles = {
    "default": -1,
    "none": 0,
    "horizontal": CURSOR_Y,
    "vertical": CURSOR_X,
    "both": CURSOR_X | CURSOR_Y,
}

border_size_editor = ImageEnumEditor(
    values=[x for x in range(9)], suffix="_weight", cols=3, module=base
)


# -----------------------------------------------------------------------------
# LineStyle trait
# -----------------------------------------------------------------------------

# Privates used for specification of line style trait.
_line_style_trait_values = {
    "solid": None,
    "dot dash": array([3.0, 5.0, 9.0, 5.0]),
    "dash": array([6.0, 6.0]),
    "dot": array([2.0, 2.0]),
    "long dash": array([9.0, 5.0]),
}
Пример #13
0
from traitsui.api \
    import Item, Group, View, ImageEnumEditor, InstanceEditor, HGroup
from mayavi.core.lut_manager import lut_mode_list, \
            lut_image_dir


def _number_of_lut_cols():
    return 1 if ETSConfig.toolkit == 'qt4' else 6


# The view of the LUT Manager object.
view = View(
    Group(
        Item(name='lut_mode',
             editor=ImageEnumEditor(values=lut_mode_list(),
                                    cols=_number_of_lut_cols(),
                                    path=lut_image_dir)),
        Item(name='file_name', visible_when="lut_mode=='file'"),
        Item(name='number_of_colors'),
        Item(name='reverse_lut'),
        Item(name='lut',
             show_label=False,
             editor=InstanceEditor(label='Edit LUT properties',
                                   id='mayavi.core.lut_manager.edit_lut')),
        Item(name='scalar_bar_representation',
             show_label=False,
             visible_when='scalar_bar_representation is not None',
             editor=InstanceEditor(
                 label='Edit Legend representation',
                 id='mayavi.core.lut_manager.edit_represetation')),
        Item(name='create_lut', show_label=False),
Пример #14
0
class PGClient(HasTraits):
    waveform = Instance(Waveform)
    selected_wf = List(Waveform)
    k_i = Range(0,
                2**13 - 1,
                600,
                desc="integration gain of the PID controller")
    integrator_reset = Bool(False, desc="reset the integrator")
    hv_input = Bool(True, desc="specify if the input jumper is on hv or not")
    error_signal_delay_1 = Range(
        0,
        8192,
        500,
        desc="TTL rising edge delay for error signal calculation in ns")
    error_signal_delay_2 = Range(
        0,
        8192,
        500,
        desc="TTL falling edge delay for error signal calculation in ns")
    send_changes = Button(desc="send changes to RedPitaya")
    controller_reset = Button(desc="set all controller parameters to 0")
    ch1_mode = Enum(
        'cont_out',
        'int_out',
        'error',
        'waveform_out',
        desc="output of channel 1, use for setting parameters/debugging")
    automatic_offset = Bool(
        True,
        desc="if error signal offset is measured automatically or set manually"
    )
    offset = Range(-8192, 8192, 0, desc="error signal offset in ADC counts")
    integrator_output = Int(0)
    onlock = Bool(False)
    onlock_image = Enum(['lock'], editor=ImageEnumEditor(path=os.getcwd()))
    not_onlock_image = Enum(['nolock'],
                            editor=ImageEnumEditor(path=os.getcwd()))

    traits_view = View(VGroup(
        HGroup(
            Item("waveform",
                 editor=InstanceEditor(name='selected_wf', editable=True),
                 style='custom',
                 label='Waveform Settings'), Spring()), Item('_'),
        HGroup(
            VGroup(Spring(), Item(label='Controller Settings:'), Spring()),
            VGroup(
                HGroup("k_i", "integrator_reset", "hv_input",
                       Item("controller_reset"), Spring()),
                HGroup("error_signal_delay_1", "error_signal_delay_2",
                       Spring()),
                HGroup("automatic_offset",
                       Item("offset", visible_when='not automatic_offset'),
                       Spring()))), Item('_'),
        HGroup(
            "send_changes",
            Item("ch1_mode",
                 editor=EnumEditor(
                     values=['cont_out', 'int_out', 'error', 'waveform_out'])),
            Item("integrator_output", style='readonly')),
        HGroup(
            Item("onlock_image",
                 show_label=False,
                 style='readonly',
                 visible_when='onlock'),
            Item("not_onlock_image",
                 show_label=False,
                 style='readonly',
                 visible_when='not onlock'), Spring())),
                       resizable=True,
                       title="RedPitaya PulseGenerator 3000")

    def __init__(self,
                 initwaveform,
                 initselections,
                 address='http://130.183.94.184:8000'):
        # create server proxy
        self.client = xmlrpclib.ServerProxy(address)

        # get current PID parameters
        self.waveform = initwaveform
        self.selected_wf = initselections
        self.integrator_reset = self.client.pg_get_values()[0]
        self.waveform.amplitude = self.client.pg_get_values()[1]
        self.k_i = self.client.pg_get_values()[2]
        self.error_signal_delay_1 = self.client.pg_get_values()[3]
        self.error_signal_delay_2 = self.client.pg_get_values()[4]
        self.automatic_offset = self.client.pg_get_values()[5]
        self.offset = self.client.pg_get_values()[6]
        self.integrator_output = self.client.pg_get_values()[7]

        # start thread to update the integrator output
        self.status_thread = LockStatusThread()
        self.status_thread.master = self
        self.status_thread.wants_abort = False
        self.status_thread.start()

    def _send_changes_fired(self):
        wave = self.waveform.create_waveform()

        if self.ch1_mode == 'cont_out':
            ch1mode = 0
        if self.ch1_mode == 'int_out':
            ch1mode = 1
        if self.ch1_mode == 'error':
            ch1mode = 2
        if self.ch1_mode == 'waveform_out':
            ch1mode = 3

        # set given values
        self.client.pg_set_values(self.integrator_reset,
                                  self.waveform.amplitude, wave, self.k_i,
                                  self.error_signal_delay_1,
                                  self.error_signal_delay_2, self.hv_input,
                                  ch1mode, self.automatic_offset, self.offset)

        # get current PID parameters
        self.integrator_reset = self.client.pg_get_values()[0]
        self.waveform.amplitude = self.client.pg_get_values()[1]
        self.k_i = self.client.pg_get_values()[2]
        self.error_signal_delay_1 = self.client.pg_get_values()[3]
        self.error_signal_delay_2 = self.client.pg_get_values()[4]
        self.automatic_offset = self.client.pg_get_values()[5]
        self.offset = self.client.pg_get_values()[6]
        self.integrator_output = self.client.pg_get_values()[7]

    def _controller_reset_fired(self):
        # reset PID
        self.client.cont_reset()

        # get current PID parameters
        self.integrator_reset = self.client.pg_get_values()[0]
        self.waveform.amplitude = self.client.pg_get_values()[1]
        self.k_i = self.client.pg_get_values()[2]
        self.error_signal_delay_1 = self.client.pg_get_values()[3]
        self.error_signal_delay_2 = self.client.pg_get_values()[4]
        self.automatic_offset = self.client.pg_get_values()[5]
        self.offset = self.client.pg_get_values()[6]
        self.integrator_output = self.client.pg_get_values()[7]

    def update_status(self, address='http://130.183.94.184:8000'):
        # create own proxy for this function. Needed because it is called by thread, which can interfere with the requests of ..._fired
        self.client_status = xmlrpclib.ServerProxy(address)

        # get the input value
        self.integrator_output = self.client_status.pg_get_values()[7]

        # compare input and setpoint of PID
        if (abs(self.integrator_output) > 200) & (abs(self.integrator_output) <
                                                  8000):
            self.onlock = True
        else:
            self.onlock = False
Пример #15
0
class PIDClient(HasTraits):
    # define traits
    setpoint = Float(0, desc="setpoint of the PID in Volts")
    k_i = Range(0,
                2**13 - 1,
                600,
                desc="integration gain of the PID controller")
    k_p = Range(0,
                2**13 - 1,
                0,
                desc="proportional gain of the PID controller")
    k_d = Range(0,
                2**13 - 1,
                0,
                desc="differential gain of the PID controller")
    integrator_reset = Bool(False, desc="reset the integrator")
    hv_input = Bool(True, desc="specify if the input jumper is on hv or not")
    sah_delay_1 = Float(500, desc="rising edge sample and hold delay in ns")
    sah_delay_2 = Float(500, desc="falling edge sample and hold delay in ns")
    send_changes = Button()
    mean_value = Float(0, desc="mean value of redpitaya's input in Volts")
    pid_reset = Button()
    onlock_image = Enum(['lock'], editor=ImageEnumEditor(path=os.getcwd()))
    not_onlock_image = Enum(['nolock'],
                            editor=ImageEnumEditor(path=os.getcwd()))
    onlock = Bool(False)

    # create Traits view
    traits_view = View(VGroup(
        VGroup(HGroup("setpoint", Spring()), HGroup("k_p", "k_i", "k_d"),
               HGroup("integrator_reset", "hv_input"),
               HGroup("sah_delay_1", "sah_delay_2")),
        HGroup("send_changes", "pid_reset", Spring()),
        Item("mean_value", style="readonly"),
        VGroup(
            Item("onlock_image",
                 show_label=False,
                 style='readonly',
                 visible_when='onlock'),
            Item("not_onlock_image",
                 show_label=False,
                 style='readonly',
                 visible_when='not onlock'), Spring())),
                       resizable=True,
                       title="RedPitaya PID-Client 3000")

    def __init__(self, address='http://130.183.94.184:8000'):
        # create server proxy
        self.client = xmlrpclib.ServerProxy(address)

        # get current PID parameters
        self.integrator_reset = self.client.pid_get_values()[0]
        self.setpoint = self.client.pid_get_values()[1]
        self.k_p = self.client.pid_get_values()[2]
        self.k_i = self.client.pid_get_values()[3]
        self.k_d = self.client.pid_get_values()[4]
        self.sah_delay_1 = self.client.pid_get_values()[5]
        self.sah_delay_2 = self.client.pid_get_values()[6]

        # start thread to update the input value
        self.status_thread = LockStatusThread()
        self.status_thread.master = self
        self.status_thread.wants_abort = False
        self.status_thread.start()

    def _send_changes_fired(self):
        # set given values
        self.client.pid_set_values(self.integrator_reset, self.setpoint,
                                   self.k_p, self.k_i, self.k_d,
                                   self.sah_delay_1, self.sah_delay_2,
                                   self.hv_input)

        # get current PID parameters
        self.integrator_reset = self.client.pid_get_values()[0]
        self.setpoint = self.client.pid_get_values()[1]
        self.k_p = self.client.pid_get_values()[2]
        self.k_i = self.client.pid_get_values()[3]
        self.k_d = self.client.pid_get_values()[4]
        self.sah_delay_1 = self.client.pid_get_values()[5]
        self.sah_delay_2 = self.client.pid_get_values()[6]

    def _pid_reset_fired(self):
        # reset PID
        self.client.pid_reset()

        # get current PID parameters
        self.integrator_reset = self.client.pid_get_values()[0]
        self.setpoint = self.client.pid_get_values()[1]
        self.k_p = self.client.pid_get_values()[2]
        self.k_i = self.client.pid_get_values()[3]
        self.k_d = self.client.pid_get_values()[4]
        self.sah_delay_1 = self.client.pid_get_values()[5]
        self.sah_delay_2 = self.client.pid_get_values()[6]

    def update_status(self, address='http://130.183.94.184:8000'):
        # create own proxy for this function. Needed because it is called by thread, which can interfere with the requests of ..._fired
        self.client_status = xmlrpclib.ServerProxy(address)

        # get the input value
        self.mean_value = self.client_status.acquire_signal()

        # compare input and setpoint of PID
        if abs(self.mean_value - self.setpoint) > 0.1:
            self.onlock = False
        else:
            self.onlock = True
Пример #16
0
"""
# Authors: Prabhu Ramachandran <*****@*****.**>
#          Judah De Paula <*****@*****.**>
# Copyright (c) 2005-2008, Enthought, Inc.
# License: BSD Style.

from traitsui.api \
    import Item, Group, View, ImageEnumEditor, InstanceEditor, HGroup
from mayavi.core.lut_manager import lut_mode_list, \
            lut_image_dir


# The view of the LUT Manager object.
view = View(Group(Item(name='lut_mode',
                       editor=ImageEnumEditor(values=lut_mode_list(),
                                              cols=6,
                                              path=lut_image_dir)),
                  Item(name='file_name', visible_when="lut_mode=='file'"),
                  Item(name='number_of_colors'),
                  Item(name='reverse_lut'),
                  Item(name='lut',
                       show_label=False,
                       editor=InstanceEditor(label='Edit LUT properties',
                                             id='mayavi.core.lut_manager.edit_lut')),
                  Item(name='scalar_bar_representation',
                       show_label=False,
                       visible_when='scalar_bar_representation is not None',
                       editor=InstanceEditor(label='Edit Legend representation',
                                             id='mayavi.core.lut_manager.edit_represetation')),
                  Item(name='create_lut', show_label=False),