示例#1
0
class IDockPane(ITaskPane):
    """ A pane that is useful but unessential for a task.

    Dock panes are arranged around the central pane in dock areas, and can, in
    general, be moved, resized, and hidden by the user.
    """

    # If enabled, the pane will have a button to close it, and a visibility
    # toggle button will be added to the View menu. Otherwise, the pane's
    # visibility will only be adjustable programmatically, though the 'visible'
    # attribute.
    closable = Bool(True)

    # The dock area in which the pane is currently present.
    dock_area = Enum("left", "right", "top", "bottom")

    # Whether the pane can be detached from the main window.
    floatable = Bool(True)

    # Whether the pane is currently detached from the main window.
    floating = Bool(False)

    # Whether the pane can be moved from one dock area to another.
    movable = Bool(True)

    # The size of the dock pane. Note that this value is read-only.
    size = Tuple()

    # Whether the pane is currently visible.
    visible = Bool(False)

    # ------------------------------------------------------------------------
    # 'IDockPane' interface.
    # ------------------------------------------------------------------------

    def create_contents(self, parent):
        """ Create and return the toolkit-specific contents of the dock pane.
        """

    def hide(self):
        """ Convenience method to hide the dock pane.
        """

    def show(self):
        """ Convenience method to show the dock pane.
class Buffer(Solution):
    """ A Solution with a name but not containing Product
    """

    # -------------------------------------------------------------------------
    # Buffer traits
    # -------------------------------------------------------------------------

    # -------------------------------------------------------------------------
    # ChromatographyData traits
    # -------------------------------------------------------------------------

    #: The type of data being represented by this class
    type_id = Constant(BUFFER_TYPE)

    #: The attributes that identify the data in this object uniquely in a
    #: collection of components
    _unique_keys = Tuple(('name',))
示例#3
0
class RunData(HasTraits):
    ''' General class for storing data in a specific fashion.  Inheriting classes will change import/outport schemes but
        retain the same basic data structures.  As long as data can be written into the correct file_data_info format, all 
        other methods drawing from it should work without alteration. '''	

    implements(IRun)
    source=Str('None')  #Class indicator really
    run_name=Str('Unnamed Run') #Name the run

    ### I CAN MAKE ALL OF THESE UPDATE WITH THE UPDATE_FILE_DATA_INFO METHOD OR MAKE THEM PROPERTIES.... SHOULD HAVE SAME DIFFERENCE ###

    file_data_info=Dict(Str, Tuple(Array(dtype=spec_dtype), Array) ) #Filename: (xy-Data), (Header)

    storage=Instance(RunStorage)

    spec_consistency = Enum(True, False, 'Unknown')

#	export=Button
#	def _export_fired(self): np.savetxt('test.txt', self.spectral_array, delimiter='\t', newline='\n' header='')

    def _spec_consistency_default(self): return 'Unknown' #How do this on declaration?

    def update_file_data_info(self): pass  #Method to set main data source in program

    def update_storage(self): 
        '''When file_data_info updated, new value passed to storage object which
           results in downstream creation of arrays, resetting of parameter etc... '''
        self.storage.file_data_info=self.file_data_info

    def spec_consistency_test(self):  
        first_wavelengths=self.get_wavelengths(self.sorted_file_array[0])
        for afile in self.sorted_file_array:
            if self.get_wavelengths(afile) != first_wavelengths:
                self.spec_consistency=False
                return
        self.spec_consistency=True
        return

    ### DEFINE EVENT LISTENERS ###
    def _file_data_info_changed(self): 
        if self.storage is None:
            self.storage=RunStorage(file_data_info=self.file_data_info)
        else:
            self.storage.file_data_info=self.file_data_info
class MoveTool(DragTool):
    """ Generic tool for moving a component's position relative to its container
    """

    drag_button = Enum("left", "right")

    # Should the moved component be raised to the top of its container's
    # list of components?  This is only recommended for overlaying containers
    # and canvases, but generally those are the only ones in which the
    # MoveTool will be useful.
    auto_raise = Bool(True)

    # The last cursor position we saw; used during drag to compute deltas
    _prev_pos = Tuple(0, 0)

    def is_draggable(self, x, y):
        if self.component:
            c = self.component
            return (c.x <= x <= c.x2) and (c.y <= y <= c.y2)
        else:
            return False

    def drag_start(self, event):
        if self.component:
            self._prev_pos = (event.x, event.y)
            self.component._layout_needed = True
            if self.auto_raise:
                # Push the component to the top of its container's list
                self.component.container.raise_component(self.component)
            event.window.set_mouse_owner(self, event.net_transform())
            event.handled = True
        return

    def dragging(self, event):
        if self.component:
            dx = event.x - self._prev_pos[0]
            dy = event.y - self._prev_pos[1]
            pos = self.component.position
            self.component.position = [pos[0] + dx, pos[1] + dy]
            self.component._layout_needed = True
            self.component.request_redraw()
            self._prev_pos = (event.x, event.y)
            event.handled = True
        return
class Image(HasTraits):
    """ An SEM image stored in a file. """

    filename = File(exists=True)
    sample_id = Str()
    operator = Str("N/A")
    date_acquired = Date()
    scan_size = Tuple(Float, Float)

    scan_width = Float
    scan_height = Float

    image = Array(shape=(None, None), dtype='uint8')

    pixel_area = Float()

    def traits_init(self):
        # useful secondary attributes
        self.scan_width, self.scan_height = self.scan_size

    # Trait observers

    @observe('filename')
    def read_image(self, event):
        pil_image = PILImage.open(self.filename).convert("L")
        self.image = np.array(pil_image)

    @observe('scan_width, scan_height, image')
    def update_pixel_area(self, event):
        if self.image.size > 0:
            self.pixel_area = (
                self.scan_height * self.scan_width / self.image.size
            )
        else:
            self.pixel_area = 0

    # Trait default methods

    def _date_acquired_default(self):
        return datetime.date.today()

    def _scan_size_default(self):
        return (1e-5, 1e-5)
示例#6
0
class Employee(Person):
    """ An employee is person with a boss and a phone number.

    """
    # The employee's boss
    boss = Instance(Employer)

    # The employee's phone number as a tuple of 3 ints
    phone = Tuple(Int, Int, Int)

    # This method is called automatically by traits to get the
    # default value for the phone number.
    def _phone_default(self):
        return (555, 555, 5555)

    # This method will be called automatically by traits when the
    # employee's phone number changes
    def _phone_changed(self, val):
        print 'received new phone number for %s: %s' % (self.first_name, val)
示例#7
0
class ToolBarSchema(Schema):
    """ A schema for a Pyface ToolBarManager.
    """

    #: Assign a default ID for tool bar schemas.
    id = "ToolBar"

    #: The tool bar's user visible name. Note that this name may not be used on
    #: all platforms.
    name = Str("Tool Bar")

    #: The size of tool images (width, height).
    image_size = Tuple((16, 16))

    #: The orientation of the toolbar.
    orientation = Enum("horizontal", "vertical")

    #: Should we display the horizontal divider?
    show_divider = Bool(True)

    #: Should we display the name of each tool bar tool under its image?
    show_tool_names = Bool(True)

    #: A factory for instantiating a pyface ToolBarManager
    tool_bar_manager_factory = Callable()

    def create(self, children):
        traits = dict(
            id=self.id,
            name=self.name,
            image_size=self.image_size,
            orientation=self.orientation,
            show_divider=self.show_divider,
            show_tool_names=self.show_tool_names,
        )
        return self.tool_bar_manager_factory(*children, **traits)

    # Trait initializers ---------------------------------------------------

    def _tool_bar_manager_factory_default(self):
        from pyface.action.tool_bar_manager import ToolBarManager
        return ToolBarManager
示例#8
0
class LinearScale(ScaleMixin):
    id = Constant("edu.mit.synbio.cytoflow.utility.linear_scale")
    name = "linear"

    experiment = Instance("cytoflow.Experiment")

    # none of these are actually used
    channel = Str
    condition = Str
    statistic = Tuple(Str, Str)

    mpl_params = Dict()

    def __call__(self, data):
        return data

    def inverse(self, data):
        return data

    def clip(self, data):
        return data

    def color_norm(self):
        if self.channel:
            vmin = self.experiment[self.channel].min()
            vmax = self.experiment[self.channel].max()
        elif self.condition:
            vmin = self.experiment[self.condition].min()
            vmax = self.experiment[self.condition].max()
        elif self.statistic:
            stat = self.experiment.statistics[self.statistic]
            try:
                vmin = min([min(x) for x in stat])
                vmax = max([max(x) for x in stat])
            except (TypeError, IndexError):
                vmin = stat.min()
                vmax = stat.max()
        else:
            raise CytoflowError("Must set one of 'channel', 'condition' "
                                "or 'statistic'.")

        return matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
示例#9
0
class Image(Resource):
    """ A resource object representing an image.

    Instances of this class are created by an `ImageProvider` when it
    handles a request for an image. Instances of this class should be
    treated as read-only once they are created.

    """
    #: The format of the image. By default, the consumer of the image
    #: will probe the header to automatically infer a type.
    format = Enum(
        'auto',  # Automatically determine the image format
        'png',  # Portable Network Graphics
        'jpg',  # Joint Photographic Experts Group
        'gif',  # Graphics Interchange Format
        'bmp',  # Windows Bitmap
        'xpm',  # X11 Pixmap
        'xbm',  # X11 Bitmap
        'pbm',  # Portable Bitmap
        'pgm',  # Portable Graymap
        'ppm',  # Portable Pixmap
        'tiff',  # Tagged Image File Format
        # 'array',    # A numpy array with an appropriate image dtype.
    )

    #: The (width, height) size of the image. An invalid size indicates
    #: that the size of the image should be automatically inferred.
    size = Tuple(Int(-1), Int(-1))

    # XXX this needs to be augmented to support arrays.
    #: The bytestring holding the data for the image.
    data = Str

    def snapshot(self):
        """ Get a snapshot dictionary for this image.

        """
        snap = super(Image, self).snapshot()
        snap['format'] = self.format
        snap['size'] = self.size
        snap['data'] = self.data
        return snap
示例#10
0
class DateRangeEditorDemo(HasTraits):
    """Demo class to show DateRangeEditor."""

    date_range = Tuple(Date, Date)

    traits_view = View(
        Group(
            Item(
                'date_range',
                editor=DateRangeEditor(),
                style='custom',
                label='Date range',
            ),
            label='Date range',
        ),
        resizable=True,
    )

    def _date_range_changed(self):
        print(self.date_range)
示例#11
0
class TupleEditorDemo(HasTraits):
    """ Defines the TupleEditor demo class.
    """

    # Define a trait to view:
    tuple = Tuple(Color, Range(1, 4), Str)

    # Display specification (one Item per editor style):
    tuple_group = Group(Item('tuple', style='simple', label='Simple'),
                        Item('_'), Item('tuple',
                                        style='custom',
                                        label='Custom'), Item('_'),
                        Item('tuple', style='text', label='Text'), Item('_'),
                        Item('tuple', style='readonly', label='ReadOnly'))

    # Demo view
    view = View(tuple_group,
                title='TupleEditor',
                buttons=['OK'],
                resizable=True)
示例#12
0
class PatternOverlay(AbstractInitializer):
    """ Overlay a pattern at a specified position. """

    #: The pattern to overlay.
    pattern = Array(dtype='uint8')

    #: The place to put the pattern.  If a value is -1 then place at center.
    position = Tuple((-1, -1))

    def initialize_states(self, states):
        position = [
            x if x != -1 else n // 2
            for x, n in zip(self.position, states.shape)
        ]
        slices = [
            slice(x - n // 2, x - n // 2 + n)
            for x, n in zip(position, self.pattern.shape)
        ]
        states[tuple(slices)] = self.pattern
        return states
示例#13
0
class Stats1DPlotParams(BasePlotParams):
    
    orientation = Enum(["vertical", "horizontal"])
    lim = Tuple(util.FloatOrNone(None), util.FloatOrNone(None)) 
    
    def default_traits_view(self):
        base_view = BasePlotParams.default_traits_view(self)
        
        return View(Item('orientation'),
                    Item('lim',
                         label = "Limits",
                         editor = TupleEditor(editors = [TextEditor(auto_set = False,
                                                                    evaluate = float,
                                                                    format_func = lambda x: "" if x == None else str(x)),
                                                         TextEditor(auto_set = False,
                                                                    evaluate = float,
                                                                    format_func = lambda x: "" if x == None else str(x))],
                                              labels = ["Min", "Max"],
                                              cols = 1)),
                    base_view.content)  
示例#14
0
class ModuleFactory(PipeFactory):
    """ Base class for all the modules factories"""
    color = Trait(
        None,
        None,
        Tuple(Range(0., 1.), Range(0., 1.), Range(0., 1.)),
        help="""the color of the vtk object. Overides the colormap,
                        if any, when specified. This is specified as a
                        triplet of float ranging from 0 to 1, eg (1, 1,
                        1) for white.""",
    )

    def _color_changed(self):
        if self.color:
            self._target.actor.property.color = self.color
            if hasattr(self._target.actor.mapper, "scalar_visibility"):
                self._target.actor.mapper.scalar_visibility = False
            if hasattr(self._target, "property"):
                self._target.property.color = self.color

    opacity = CFloat(1., desc="""The overall opacity of the vtk object.""")

    def _opacity_changed(self):
        try:
            self._target.actor.property.opacity = self.opacity
        except AttributeError:
            try:
                self._target.property.opacity = self.opacity
            except AttributeError:
                pass

    line_width = CFloat(2., desc=""" The width of the lines, if any used.""")

    def _line_width_changed(self):
        try:
            self._target.actor.property.line_width = self.line_width
        except (AttributeError, TraitError):
            try:
                self._target.property.line_width = self.line_width
            except (AttributeError, TraitError):
                pass
示例#15
0
class GraphNodeHoverTool(HoverTool):
    _last_xy = Tuple()

    def _is_in(self, x, y):
        return self.component.is_in(x, y)

    def normal_mouse_move(self, event):
        self._last_xy = (event.x, event.y)
        super(GraphNodeHoverTool, self).normal_mouse_move(event)

    def on_hover(self):
        """ This gets called when all the conditions of the hover action have
        been met, and the tool determines that the mouse is, in fact, hovering
        over a target region on the component.

        By default, this method call self.callback (if one is configured).
        """
        for component in self.component.components:
            if component.is_in(*self._last_xy):
                if self.callback is not None:
                    self.callback(component.label)
示例#16
0
class Image(HasTraits):
    """ An SEM image stored in a file. """

    filename = File(exists=True)

    sample_id = Str()

    date_acquired = Date()

    operator = Str("N/A")

    scan_size = Tuple(Float, Float)

    image = Array(shape=(None, None), dtype='uint8')

    def traits_init(self):
        # useful secondary attributes
        self.scan_width, self.scan_height = self.scan_size

    def _date_acquired_default(self):
        return datetime.datetime.today()
示例#17
0
class LinearScale(ScaleMixin):
    id = Constant("edu.mit.synbio.cytoflow.utility.linear_scale")
    name = "linear"
    
    experiment = Instance("cytoflow.Experiment")
    
    # none of these are actually used
    channel = Str
    condition = Str
    statistic = Tuple(Str, Str)

    mpl_params = Dict()

    def __call__(self, data):
        return data
    
    def inverse(self, data):
        return data
    
    def clip(self, data):
        return data
示例#18
0
class PyFibreGUI(TasksApplication):

    id = 'pyfibre.pyfibre_gui'

    name = 'PyFibre GUI'

    window_size = Tuple((1680, 1050))

    splash_screen = SplashScreen(image=ImageResource("images/splash"))

    # The default window-level layout for the application.
    default_layout = List(TaskWindowLayout)

    # Whether to restore the previous application-level layout
    # when the application is started.
    always_use_default_layout = Bool(True)

    n_proc = Int(1)

    def _default_layout_default(self):
        tasks = [factory.id for factory in self.task_factories]
        return [
            TaskWindowLayout(*tasks,
                             active_task='pyfibre.pyfibre_main_task',
                             size=self.window_size)
        ]

    def _load_state(self):
        super(PyFibreGUI, self)._load_state()
        if (self._state.window_layouts
                and self._state.window_layouts[0].get_active_task() is None):
            # This is a possible way a corrupted state file would manifest
            # Remove it and try again with a default state.
            state_file = os.path.join(self.state_location,
                                      'application_memento')
            if os.path.exists(state_file):
                os.unlink(state_file)
                logger.warning("The state file at {!r} was corrupted and has "
                               "been removed.".format(state_file))
            super(PyFibreGUI, self)._load_state()
示例#19
0
class Vis2DFW(Vis2D):

    Pw = Tuple()
    bc_right = Str
    bc_left = Str

    def _Pw_default(self):
        return ([0], [0], [0], [0])

    def update(self):
        sim = self.sim
        bc_right = sim.trait_get(self.bc_right)[self.bc_right]
        bc_left = sim.trait_get(self.bc_left)[self.bc_left]
        dofs_right = np.unique(bc_right.dofs)
        dofs_left = np.unique(bc_left.dofs)
        U_ti = sim.hist.U_t
        F_ti = sim.hist.F_t
        P = np.sum(F_ti[:, dofs_right], axis=1)
        P0 = np.sum(F_ti[:, dofs_left], axis=1)
        w = np.average(U_ti[:, dofs_right], axis=1)
        w0 = np.average(U_ti[:, dofs_left], axis=1)
        self.Pw = P, P0, w, w0
class BindingModel(BaseProductModel):
    """ Base class for all binding models.
    """
    #: The type of binding model (e.g. STERIC_MASS_ACTION) used for the
    #: chromatography simulation.
    model_type = Enum(values="all_model_types")

    all_model_types = List

    #: Kinetic rate expression or isotherm
    is_kinetic = Enum([0, 1])

    # ChromatographyData traits -----------------------------------------------

    #: The type of data being represented by this class
    type_id = Constant(BINDING_MODEL_TYPE)

    #: Attributes that identify an instance uniquely in a collection
    _unique_keys = Tuple(('target_product', 'name'))

    def _all_model_types_default(self):
        return BINDING_MODEL_TYPES
示例#21
0
文件: data.py 项目: alexlib/enable
class BenchResult(HasStrictTraits):
    """ The result of a benchmark run on a single backend
    """
    #: Short status field for checking the outcome of a benchmark
    # Default to "fail"!
    summary = Enum("fail", "skip", "success")

    #: A path to an output file with a format and size
    output = File()
    output_format = Property(Str(), observe="output")
    output_size = Tuple(Int(), Int())

    #: Timing results
    timing = Instance("BenchTiming")

    def _get_output_format(self):
        if self.output:
            return os.path.splitext(self.output)[-1]
        return ""

    def compare_to(self, other):
        return BenchComparison.from_pair(self, baseline=other)
class ToolPaletteManager(ActionManager):
    """ A tool bar manager realizes itself in a tool palette bar control. """

    #### 'ToolPaletteManager' interface #######################################

    # The size of tool images (width, height).
    image_size = Tuple((16, 16))

    # Should we display the name of each tool bar tool under its image?
    show_tool_names = Bool(True)

    #### Private interface ####################################################

    # Cache of tool images (scaled to the appropriate size).
    _image_cache = Instance(ImageCache)

    ###########################################################################
    # 'object' interface.
    ###########################################################################

    def __init__(self, *args, **traits):
        """ Creates a new tool bar manager. """

        # Base class contructor.
        super(ToolPaletteManager, self).__init__(*args, **traits)

        # An image cache to make sure that we only load each image used in the
        # tool bar exactly once.
        self._image_cache = ImageCache(self.image_size[0], self.image_size[1])

        return

    ###########################################################################
    # 'ToolPaletteManager' interface.
    ###########################################################################

    def create_tool_palette(self, parent, controller=None):
        """ Creates a tool bar. """
        return None
示例#23
0
class Stats1DPluginPlotParams(Stats1DPlotParams):

    variable_lim = Tuple(util.FloatOrNone(None), util.FloatOrNone(None))
    linestyle = Enum(LINE_STYLES)
    marker = Enum(SCATTERPLOT_MARKERS)
    markersize = util.PositiveCFloat(6, allow_zero=False)
    capsize = util.PositiveCFloat(0, allow_zero=True)
    alpha = util.PositiveCFloat(1.0)
    shade_error = Bool(False)
    shade_alpha = util.PositiveCFloat(0.2)

    def default_traits_view(self):
        base_view = Stats1DPlotParams.default_traits_view(self)

        return View(
            Item('variable_lim',
                 label="Variable\nLimits",
                 editor=TupleEditor(editors=[
                     TextEditor(auto_set=False,
                                evaluate=float,
                                format_func=lambda x: ""
                                if x == None else str(x)),
                     TextEditor(auto_set=False,
                                evaluate=float,
                                format_func=lambda x: ""
                                if x == None else str(x))
                 ],
                                    labels=["Min", "Max"],
                                    cols=1)), Item('linestyle'),
            Item('marker'),
            Item('markersize',
                 editor=TextEditor(auto_set=False),
                 format_func=lambda x: "" if x == None else str(x)),
            Item('capsize',
                 editor=TextEditor(auto_set=False),
                 format_func=lambda x: ""
                 if x == None else str(x)), Item('alpha'), Item('shade_error'),
            Item('shade_alpha'), base_view.content)
class TupleEditorDemo(HasTraits):
    """ This class specifies the details of the TupleEditor demo.
    """

    # To demonstrate any given Trait editor, an appropriate Trait is required.
    tuple = Tuple(Color, Range(1, 4), Str)

    # Display specification (one Item per editor style)
    tuple_group = Group(
        Item(
            'tuple', style='simple', label='Simple'),
        Item('_'),
        Item(
            'tuple', style='custom', label='Custom'),
        Item('_'),
        Item(
            'tuple', style='text', label='Text'),
        Item('_'),
        Item(
            'tuple', style='readonly', label='ReadOnly'))

    # Demo view
    view1 = View(tuple_group, title='TupleEditor', buttons=['OK'])
示例#25
0
class Component(ChromatographyData):
    """ Represents the properties associated with a component.
    """
    # -------------------------------------------------------------------------
    # Component traits
    # -------------------------------------------------------------------------

    #: The charge of the component (e.g. Sodium is -1)
    charge = Instance(UnitScalar)

    #: The negative logarithm of the acidity constant of the component
    pKa = Instance(UnitScalar)

    # -------------------------------------------------------------------------
    # ChromatographyData traits
    # -------------------------------------------------------------------------

    #: The type of data being represented by this class
    type_id = Constant(COMPONENT_TYPE)

    #: The attributes that identify the data in this object uniquely in a
    #: collection of components
    _unique_keys = Tuple(('name', ))
示例#26
0
class LatticeRecord(Vis2D):

    tstep = WeakRef

    Pw = Tuple()

    def _Pw_default(self):
        return ([0], [0])

    def setup(self):
        self.Pw = ([0], [0])

    def update(self):
        tstep = self.tstep
        c_dof = tstep.control_dofs
        U_ti = tstep.hist.U_t
        F_ti = tstep.hist.F_t
        P = np.sum(F_ti[:, c_dof], axis=-1)
        w = np.average(U_ti[:, c_dof], axis=-1)
        self.Pw = P, w

    def get_t(self):
        return self.tstep.hist.t
示例#27
0
class MVPointLabels(MVPBase):
    color = Tuple(1., 1., 1.)

    def __init__(self, **kw):

        e = get_engine()

        super(MVPointLabels, self).__init__(**kw)
        from mayavi.modules.api import Outline, Surface, Labels

        self.src = VTKDataSource(name=self.name, data=self.pd)
        e.add_source(self.src)

        self.labels = Labels(name='Node numbers',
                             object=self.src,
                             label_format='%g',
                             number_of_labels=100)
        self.labels.property.color = self.color
        e.add_module(self.labels)

    def redraw(self, label_mode='label_ids'):
        super(MVPointLabels, self).redraw()
        self.labels.mapper.label_mode = label_mode
示例#28
0
class CamStation(HasStrictTraits):
    '''Camera stations

    Specify the positions of the camera by defining the
    azimuth, elevation, distance and focal point
    and roll angle.
    '''

    prev_move = WeakRef

    azimuth = Float(0.0)
    elevation = Float(0.0)
    distance = Float(10.0)
    focal_point = Tuple(Float, Float, Float)

    time_stemp = Property

    def _get_time_stemp(self):
        if self.prev_move:
            return self.prev_move.ets
        else:
            return 0.0

    fpoint = Property

    roll = Float(0)

    def _get_fpoint(self):
        return np.array(list(self.focal_point), dtype='float_')

    view = View(Item('azimuth'),
                Item('elevation'),
                Item('distance'),
                Item('roll'),
                Item('focal_point'),
                Item('time_stemp', style='readonly'),
                buttons=['OK', 'Cancel'])
示例#29
0
class QuadWorkflowOp(WorkflowOperation, QuadOp):
    name = Str(apply=True)
    xchannel = Str(apply=True)
    ychannel = Str(apply=True)

    _xy = Tuple(util.FloatOrNone(None), util.FloatOrNone(None), apply=True)
    xthreshold = Property(util.FloatOrNone(None), observe='_xy')
    ythreshold = Property(util.FloatOrNone(None), observe='_xy')

    def _get_xthreshold(self):
        return self._xy[0]

    def _set_xthreshold(self, val):
        self._xy = (val, self._xy[1])

    def _get_ythreshold(self):
        return self._xy[1]

    def _set_ythreshold(self, val):
        self._xy = (self._xy[0], val)

    def default_view(self, **kwargs):
        return QuadSelectionView(op=self, **kwargs)

    def clear_estimate(self):
        # no-op
        return

    def get_notebook_code(self, idx):
        op = QuadOp()
        op.copy_traits(self, op.copyable_trait_names())

        return dedent("""
        op_{idx} = {repr}
                
        ex_{idx} = op_{idx}.apply(ex_{prev_idx})
        """.format(repr=repr(op), idx=idx, prev_idx=idx - 1))
示例#30
0
class ComponentEditor(BasicEditorFactory):
    """ TraitsUI editor factory for Enable components.
    """

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

    # The class used to create all editor styles (overrides BasicEditorFactory)
    klass = _ComponentEditor

    #: The background color for the window
    bgcolor = ColorTrait("sys_window")

    #: When available, use HiDPI for GraphicsContext rasterization.
    high_resolution = Bool(True)

    #: The default size of the Window wrapping this Enable component
    size = Tuple((400, 400))

    #: Convenience function for accessing the width
    width = Property

    #: Convenience function for accessing the width
    height = Property

    def _get_width(self):
        return self.size[0]

    def _set_width(self, width):
        self.size = (width, self.size[1])

    def _get_height(self):
        return self.size[1]

    def _set_height(self, height):
        self.size = (self.size[0], height)