Exemplo n.º 1
0
    def render_fields(self):
        #construct traits for each parameter and place in the class dictionary
        params = self.model.get_params()
        class_dict = {}
        #construct default view
        elements = []
        elements.extend([Label("Parameter"), Label("Error"), Label("Fixed?")])
        for param in params:
            pname = param.name
            class_dict["entry_" + pname] = Float(
                param.value)  #get the initial value
            class_dict["err_" + pname] = Float(
                param.error)  #get the initial value
            class_dict["fixed_" + pname] = Bool(
                param.fixed)  #determine if fixed or not
            elements.append(
                Item("entry_" + pname,
                     format_str="%0.4g",
                     show_label=True,
                     label=pname))
            elements.append(
                Item("err_" + pname,
                     format_str="+/- %0.2g",
                     show_label=False,
                     style='readonly'))
            elements.append(Item("fixed_" + pname, show_label=False))

        kwargs = {'columns': 3}
        class_dict['traits_view'] = View(VGrid(*elements, **kwargs))
        self.fields_class = new.classobj('Fields', (HasTraits, ), class_dict)
        self.fields = self.fields_class()
Exemplo n.º 2
0
class HelpExamplePreferencesPage(PreferencesPage):
    """ Base class for preferences pages for help examples.
    """
    #### 'PreferencesPage' interface ##########################################

    # The page's category (e.g. 'General/Appearance'). The empty string means
    # that this is a top-level page.
    category = 'Examples'

    # The page's help identifier (optional). If a help ID *is* provided then
    # there will be a 'Help' button shown on the preference page.
    help_id = ''

    # The page name (this is what is shown in the preferences dialog.
    name = Str

    def _name_default(self):
        return self.label

    # The path to the preferences node that contains the preferences.
    preferences_path = Str

    #### Preferences ###########################################################

    # The UI label for the help demo, which appears in menus or dialogs.
    label = Str

    # The full path to the main file of the example.
    filename = File

    traits_view = View(
        Item('filename', show_label=True),
        Label(
            "Filename can be absolute, or relative to the Python directory."),
    )
Exemplo n.º 3
0
    def default_traits_view(self):
        if self.model is None:
            g = Group()
            g.content.append(Label('No Model Selected'))
        else:
            #g = Group(label=self.modelname,show_border=False,orientation='horizontal',layout='flow')
            g = Group(label=self.modelname,show_border=True,orientation='vertical')
            hg = HGroup(Item('fittype',label='Fit Technique',
                             editor=EnumEditor(name='fittypes')))
            g.content.append(hg)
            gp = HGroup(scrollable=True)
            for p in self.model.params:
                gi = Group(orientation='horizontal',label=p)
                self.add_trait(p,Float)
                setattr(self,p,getattr(self.model,p))
                self.on_trait_change(self._param_change_handler,p)
                gi.content.append(Item(p,show_label=False))

                ffp = 'fixfit_'+p
                self.add_trait(ffp,Bool)
                #default to fixed if the paramtere is a class-level fixed model
                setattr(self,ffp,p in self.model.__class__.fixedpars)
                self.on_trait_change(self._param_change_handler,ffp)
                gi.content.append(Item(ffp,label='Fix?'))

                gp.content.append(gi)
            g.content.append(gp)

        return View(g,buttons=['Apply','Revert','OK','Cancel'])
Exemplo n.º 4
0
class HelpDocPreferencesPage(PreferencesPage):
    """ Base class for preferences pages for help documents.
    """
    #### 'PreferencesPage' interface ##########################################

    # The page's category.
    category = 'Documents'

    # The page's help identifier (optional).
    help_id = ''

    # The page name (this is what is shown in the preferences dialog.
    name = Str

    def _name_default(self):
        return self.label

    # The path to the preferences node that contains the preferences.
    preferences_path = Str

    #### Preferences ###########################################################

    # The UI label for the help doc, which appears in menus or dialogs.
    label = Str

    # The full path to the document on disk.
    filename = File

    # The program to use to view the document. 'browser' means the platform
    # default web browser.
    viewer = Either('browser', File)

    traits_view = View(
        Group(
            Item('viewer', show_label=True),
            Label("Viewer can be 'browser' or a path to a program."),
            show_border=True,
        ),
        Item('filename', show_label=True),
        Label(
            "Filename can be absolute, or relative to the Python directory."),
    )
Exemplo n.º 5
0
class FooDemo(HasTraits):
    """ Defines a class to run the demo.
    """

    foo = Instance(DerivedFoo, ())
    configure = Button('Configure')

    view = View(
        Label("Try configuring several times, each time changing the items "
              "on the 'Parents?' tab."), '_',
        HGroup(spring, Item('configure', show_label=False)))

    def _configure_changed(self):
        self.foo.configure_traits()
Exemplo n.º 6
0
class DataSourceWizardView(DataSourceWizard):

    #----------------------------------------------------------------------
    # Private traits
    #----------------------------------------------------------------------

    _top_label = Str('Describe your data')

    _info_text = Str('Array size do not match')

    _array_label = Str('Available arrays')

    _data_type_text = Str("What does your data represents?" )

    _lines_text = Str("Connect the points with lines" )

    _scalar_data_text = Str("Array giving the value of the scalars")

    _optional_scalar_data_text = Str("Associate scalars with the data points")

    _connectivity_text = Str("Array giving the triangles")

    _vector_data_text = Str("Associate vector components")

    _position_text = Property(depends_on="position_type_")

    _position_text_dict = {'explicit':
                'Coordinnates of the data points:',
                           'orthogonal grid':
                'Position of the layers along each axis:',
            }

    def _get__position_text(self):
        return self._position_text_dict.get(self.position_type_, "")

    _shown_help_text = Str

    _data_sources_wrappers = Property(depends_on='data_sources')

    def _get__data_sources_wrappers(self):
         return [
            ArrayColumnWrapper(name=name, 
                shape=repr(self.data_sources[name].shape))
                    for name in self._data_sources_names
                ]
            

    # A traits pointing to the object, to play well with traitsUI
    _self = Instance(DataSourceWizard)

    _suitable_traits_view = Property(depends_on="data_type_")

    def _get__suitable_traits_view(self):
        return "_%s_data_view" % self.data_type_

    ui = Any(False)

    _preview_button = Button(label='Preview structure')

    def __preview_button_fired(self):
        if self.ui:
            self.build_data_source()
            self.preview()

    _ok_button = Button(label='OK')

    def __ok_button_fired(self):
        if self.ui:
            self.ui.dispose()
            self.build_data_source()


    _cancel_button = Button(label='Cancel')

    def __cancel_button_fired(self):
        if self.ui:
            self.ui.dispose()

    _is_ok = Bool

    _is_not_ok = Bool

    def _anytrait_changed(self):
        """ Validates if the OK button is enabled.
        """
        if self.ui:
            self._is_ok =  self.check_arrays()
            self._is_not_ok = not self._is_ok
    
    _preview_window = Instance(PreviewWindow, ())

    _info_image = Instance(ImageResource, 
                    ImageLibrary.image_resource('@std:alert16',))

    #----------------------------------------------------------------------
    # TraitsUI views
    #----------------------------------------------------------------------

    _coordinates_group = \
                        HGroup(
                           Item('position_x', label='x',
                               editor=EnumEditor(name='_data_sources_names',
                                        invalid='_is_not_ok')), 
                           Item('position_y', label='y',
                               editor=EnumEditor(name='_data_sources_names', 
                                        invalid='_is_not_ok')), 
                           Item('position_z', label='z',
                               editor=EnumEditor(name='_data_sources_names', 
                                        invalid='_is_not_ok')), 
                       )


    _position_group = \
                    Group(
                       Item('position_type'),
                       Group(
                           Item('_position_text', style='readonly',
                                    resizable=False,
                                    show_label=False),
                           _coordinates_group,
                           visible_when='not position_type_=="image data"',
                       ),
                       Group(
                           Item('grid_shape_source_',
                            label='Grid shape',
                            editor=EnumEditor(
                                name='_grid_shape_source_labels',
                                        invalid='_is_not_ok')), 
                           HGroup(
                            spring,
                            Item('grid_shape', style='custom', 
                                    editor=ArrayEditor(width=-60),
                                    show_label=False),
                           enabled_when='grid_shape_source==""',
                            ),
                           visible_when='position_type_=="image data"',
                       ),
                       label='Position of the data points',
                       show_border=True,
                       show_labels=False,
                   ),


    _connectivity_group = \
                   Group(
                       HGroup(
                         Item('_connectivity_text', style='readonly',
                                resizable=False),
                         spring,
                         Item('connectivity_triangles',
                                editor=EnumEditor(name='_data_sources_names'),
                                show_label=False,
                                ),
                         show_labels=False,
                       ),
                       label='Connectivity information',
                       show_border=True,
                       show_labels=False,
                       enabled_when='position_type_=="explicit"',
                   ),


    _scalar_data_group = \
                   Group(
                       Item('_scalar_data_text', style='readonly', 
                           resizable=False,
                           show_label=False),
                       HGroup(
                           spring,
                           Item('scalar_data', 
                               editor=EnumEditor(name='_data_sources_names',
                                        invalid='_is_not_ok')), 
                           show_labels=False,
                           ),
                       label='Scalar value',
                       show_border=True,
                       show_labels=False,
                   )


    _optional_scalar_data_group = \
                   Group(
                       HGroup(
                       'has_scalar_data',
                       Item('_optional_scalar_data_text',
                            resizable=False,
                            style='readonly'),
                       show_labels=False,
                       ),
                       Item('_scalar_data_text', style='readonly', 
                            resizable=False,
                            enabled_when='has_scalar_data',
                           show_label=False),
                       HGroup(
                           spring, 
                           Item('scalar_data', 
                               editor=EnumEditor(name='_data_sources_names',
                                        invalid='_is_not_ok'), 
                               enabled_when='has_scalar_data'),
                           show_labels=False,
                           ),
                       label='Scalar data',
                       show_border=True,
                       show_labels=False,
                   ),


    _vector_data_group = \
                   VGroup(
                       HGroup(
                           Item('vector_u', label='u',
                               editor=EnumEditor(name='_data_sources_names', 
                                        invalid='_is_not_ok')), 
                           Item('vector_v', label='v',
                               editor=EnumEditor(name='_data_sources_names', 
                                        invalid='_is_not_ok')), 
                           Item('vector_w', label='w',
                               editor=EnumEditor(name='_data_sources_names', 
                                        invalid='_is_not_ok')), 
                       ),
                       label='Vector data',
                       show_border=True,
                   ),


    _optional_vector_data_group = \
                   VGroup(
                        HGroup(
                            Item('has_vector_data', show_label=False),
                            Item('_vector_data_text', style='readonly', 
                                resizable=False,
                                show_label=False),
                        ),
                       HGroup(
                           Item('vector_u', label='u',
                               editor=EnumEditor(name='_data_sources_names', 
                                        invalid='_is_not_ok')), 
                           Item('vector_v', label='v',
                               editor=EnumEditor(name='_data_sources_names', 
                                        invalid='_is_not_ok')), 
                           Item('vector_w', label='w',
                               editor=EnumEditor(name='_data_sources_names', 
                                        invalid='_is_not_ok')), 
                           enabled_when='has_vector_data',
                       ),
                       label='Vector data',
                       show_border=True,
                   ),


    _array_view = \
                View(
                    Item('_array_label', editor=TitleEditor(),
                        show_label=False),
                    Group(    
                    Item('_data_sources_wrappers', 
                      editor=TabularEditor(
                          adapter = ArrayColumnAdapter(),
                      ), 
                    ),
                    show_border=True,
                    show_labels=False
                ))

    _questions_view = View(
                Item('_top_label', editor=TitleEditor(),
                        show_label=False),
                HGroup(
                    Item('_data_type_text', style='readonly',
                                resizable=False),
                    spring,
                    'data_type',
                    spring,
                    show_border=True,
                    show_labels=False,
                  ),
                HGroup(
                    Item('_self', style='custom', 
                        editor=InstanceEditor(
                                    view_name='_suitable_traits_view'),
                        ),
                    Group(
                        # FIXME: Giving up on context sensitive help
                        # because of lack of time.
                        #Group(
                        #    Item('_shown_help_text', editor=HTMLEditor(), 
                        #        width=300,
                        #        label='Help',
                        #        ),
                        #    show_labels=False,
                        #    label='Help',
                        #),
                        #Group(
                            Item('_preview_button', 
                                    enabled_when='_is_ok'),
                            Item('_preview_window', style='custom',
                                    label='Preview structure'),
                            show_labels=False,
                            #label='Preview structure',
                        #),
                        #layout='tabbed',
                        #dock='tab',
                    ),
                    show_labels=False,
                    show_border=True,
                ),
            )

    _point_data_view = \
                View(Group(
                   Group(_coordinates_group,
                        label='Position of the data points',
                        show_border=True,
                   ),
                   HGroup(
                       'lines',
                       Item('_lines_text', style='readonly',
                                        resizable=False), 
                       label='Lines',
                       show_labels=False,
                       show_border=True,
                   ),
                   _optional_scalar_data_group,
                   _optional_vector_data_group,
                   # XXX: hack to have more vertical space
                   Label('\n'),
                   Label('\n'),
                   Label('\n'),
                ))


    _surface_data_view = \
                View(Group(
                   _position_group,
                   _connectivity_group,
                   _optional_scalar_data_group,
                   _optional_vector_data_group,
                ))


    _vector_data_view = \
                View(Group(
                   _vector_data_group,
                   _position_group,
                   _optional_scalar_data_group,
                ))


    _volumetric_data_view = \
                View(Group(
                   _scalar_data_group,
                   _position_group,
                   _optional_vector_data_group,
                ))


    _wizard_view = View(
          Group(
            HGroup(
                Item('_self', style='custom', show_label=False,
                     editor=InstanceEditor(view='_array_view'),
                     width=0.17,
                     ),
                '_',
                Item('_self', style='custom', show_label=False,
                     editor=InstanceEditor(view='_questions_view'),
                     ),
                ),
            HGroup(
                Item('_info_image', editor=ImageEditor(),
                    visible_when="_is_not_ok"),
                Item('_info_text', style='readonly', resizable=False,
                    visible_when="_is_not_ok"),
                spring, 
                '_cancel_button', 
                Item('_ok_button', enabled_when='_is_ok'),
                show_labels=False,
            ),
          ),
        title='Import arrays',
        resizable=True,
        )


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

    def __init__(self, **traits):
        DataSourceFactory.__init__(self, **traits)
        self._self = self


    def view_wizard(self):
        """ Pops up the view of the wizard, and keeps the reference it to
            be able to close it.
        """
        # FIXME: Workaround for traits bug in enabled_when
        self.position_type_
        self.data_type_
        self._suitable_traits_view
        self.grid_shape_source
        self._is_ok
        self.ui = self.edit_traits(view='_wizard_view')


    def preview(self):
        """ Display a preview of the data structure in the preview
            window.
        """
        self._preview_window.clear()
        self._preview_window.add_source(self.data_source)
        data = lambda name: self.data_sources[name]
        g = Glyph()
        g.glyph.glyph_source.glyph_source = \
                    g.glyph.glyph_source.glyph_list[0]
        g.glyph.scale_mode = 'data_scaling_off'
        if not (self.has_vector_data or self.data_type_ == 'vector'):
            g.glyph.glyph_source.glyph_source.glyph_type = 'cross'
            g.actor.property.representation = 'points'
            g.actor.property.point_size = 3.
        self._preview_window.add_module(g)
        if not self.data_type_ in ('point', 'vector') or self.lines:
            s = Surface()
            s.actor.property.opacity = 0.3
            self._preview_window.add_module(s)
        if not self.data_type_ == 'point':
            self._preview_window.add_filter(ExtractEdges())
            s = Surface()
            s.actor.property.opacity = 0.2
            self._preview_window.add_module(s)
Exemplo n.º 7
0
class ScatterPlotNM(MutableTemplate):

    #-- Template Traits --------------------------------------------------------

    # The title of the plot:
    title = TStr('NxM Scatter Plots')

    # The type of marker to use.  This is a mapped trait using strings as the
    # keys:
    marker = marker_trait(template='copy', event='update')

    # The pixel size of the marker (doesn't include the thickness of the
    # outline):
    marker_size = TRange(1, 5, 1, event='update')

    # The thickness, in pixels, of the outline to draw around the marker.  If
    # this is 0, no outline will be drawn.
    line_width = TRange(0.0, 5.0, 1.0)

    # The fill color of the marker:
    color = TColor('red', event='update')

    # The color of the outline to draw around the marker
    outline_color = TColor('black', event='update')

    # The number of rows of plots:
    rows = TRange(1, 3, 1, event='grid')

    # The number of columns of plots:
    columns = TRange(1, 5, 1, event='grid')

    # The contained scatter plots:
    scatter_plots = TList(ScatterPlot)

    #-- Derived Traits ---------------------------------------------------------

    plot = TDerived

    #-- Traits UI Views --------------------------------------------------------

    # The scatter plot view:
    template_view = View(VGroup(
        Item('title',
             show_label=False,
             style='readonly',
             editor=ThemedTextEditor(theme=Theme('@GBB', alignment='center'))),
        Item('plot',
             show_label=False,
             resizable=True,
             editor=EnableEditor(),
             item_theme=Theme('@GF5', margins=0))),
                         resizable=True)

    # The scatter plot options view:
    options_view = View(
        VGroup(
            VGroup(Label('Scatter Plot Options',
                         item_theme=Theme('@GBB', alignment='center')),
                   show_labels=False),
            VGroup(Item('title', editor=TextEditor()),
                   Item('marker'),
                   Item('marker_size', editor=ThemedSliderEditor()),
                   Item('line_width',
                        label='Line Width',
                        editor=ThemedSliderEditor()),
                   Item('color', label='Fill Color'),
                   Item('outline_color', label='Outline Color'),
                   Item('rows', editor=ThemedSliderEditor()),
                   Item('columns', editor=ThemedSliderEditor()),
                   group_theme=Theme('@GF5', margins=(-5, -1)),
                   item_theme=Theme('@G0B', margins=0))))

    #-- ITemplate Interface Implementation -------------------------------------

    def activate_template(self):
        """ Converts all contained 'TDerived' objects to real objects using the
            template traits of the object. This method must be overridden in
            subclasses.
            
            Returns
            -------
            None
        """
        plots = []
        i = 0
        for r in range(self.rows):
            row = []
            for c in range(self.columns):
                plot = self.scatter_plots[i].plot
                if plot is None:
                    plot = PlotComponent()
                row.append(plot)
                i += 1
            plots.append(row)

        self.plot = GridPlotContainer(shape=(self.rows, self.columns))
        self.plot.component_grid = plots

    #-- Default Values ---------------------------------------------------------

    def _scatter_plots_default(self):
        """ Returns the default value for the scatter plots list.
        """
        plots = []
        for i in range(self.rows * self.columns):
            plots.append(ScatterPlot())

        self._update_plots(plots)

        return plots

    #-- Trait Event Handlers ---------------------------------------------------

    def _update_changed(self, name, old, new):
        """ Handles a plot option being changed. 
        """
        for sp in self.scatter_plots:
            setattr(sp, name, new)

        self.plot = Undefined

    def _grid_changed(self):
        """ Handles the grid size being changed.
        """
        n = self.rows * self.columns
        plots = self.scatter_plots
        if n < len(plots):
            self.scatter_plots = plots[:n]
        else:
            for j in range(len(plots), n):
                plots.append(ScatterPlot())

        self._update_plots(plots)

        self.template_mutated = True

    #-- Private Methods --------------------------------------------------------

    def _update_plots(self, plots):
        """ Update the data sources for all of the current plots.
        """
        index = None
        i = 0
        for r in range(self.rows):
            for c in range(self.columns):
                sp = plots[i]
                i += 1
                desc = sp.value.description
                col = desc.rfind('[')
                if col >= 0:
                    desc = desc[:col]
                sp.value.description = '%s[%d,%d]' % (desc, r, c)
                sp.value.optional = True

                if index is None:
                    index = sp.index
                    index.description = 'Shared Plot Index'
                    index.optional = True
                else:
                    sp.index = index
Exemplo n.º 8
0
    def __init__(self,xdata=None,ydata=None,weights=None,model=None,
                 include_models=None,exclude_models=None,fittype=None,**traits):
        """

        :param xdata: the first dimension of the data to be fit
        :type xdata: array-like
        :param ydata: the second dimension of the data to be fit
        :type ydata: array-like
        :param weights:
            The weights to apply to the data. Statistically interpreted as inverse
            errors (*not* inverse variance). May be any of the following forms:

            * None for equal weights
            * an array of points that must match `ydata`
            * a 2-sequence of arrays (xierr,yierr) such that xierr matches the
              `xdata` and yierr matches `ydata`
            * a function called as f(params) that returns an array of weights
              that match one of the above two conditions

        :param model: the initial model to use to fit this data
        :type model:
            None, string, or :class:`pymodelfit.core.FunctionModel1D`
            instance.
        :param include_models:
            With `exclude_models`, specifies which models should be available in
            the "new model" dialog (see `models.list_models` for syntax).
        :param exclude_models:
            With `include_models`, specifies which models should be available in
            the "new model" dialog (see `models.list_models` for syntax).
        :param fittype:
            The fitting technique for the initial fit (see
            :class:`pymodelfit.core.FunctionModel`).
        :type fittype: string

        kwargs are passed in as any additional traits to apply to the
        application.

        """

        self.modelpanel = View(Label('empty'),kind='subpanel',title='model editor')

        self.tmodel = TraitedModel(model)

        if model is not None and fittype is not None:
            self.tmodel.model.fittype = fittype

        if xdata is None or ydata is None:
            if not hasattr(self.tmodel.model,'data') or self.tmodel.model.data is None:
                raise ValueError('data not provided and no data in model')
            if xdata is None:
                xdata = self.tmodel.model.data[0]
            if ydata is None:
                ydata = self.tmodel.model.data[1]
            if weights is None:
                weights = self.tmodel.model.data[2]

        self.on_trait_change(self._paramsChanged,'tmodel.paramchange')

        self.modelselector = NewModelSelector(include_models,exclude_models)

        self.data = [xdata,ydata]


        if weights is None:
            self.weights = np.ones_like(xdata)
            self.weighttype = 'equal'
        else:
            self.weights = np.array(weights,copy=True)
            self.savews = True

        weights1d = self.weights
        while len(weights1d.shape)>1:
            weights1d = np.sum(weights1d**2,axis=0)

        pd = ArrayPlotData(xdata=self.data[0],ydata=self.data[1],weights=weights1d)
        self.plot = plot = Plot(pd,resizable='hv')

        self.scatter = plot.plot(('xdata','ydata','weights'),name='data',
                         color_mapper=_cmapblack if self.weights0rem else _cmap,
                         type='cmap_scatter', marker='circle')[0]

        self.errorplots = None

        if not isinstance(model,FunctionModel1D):
            self.fitmodel = True

        self.updatemodelplot = False #force plot update - generates xmod and ymod
        plot.plot(('xmod','ymod'),name='model',type='line',line_style='dash',color='black',line_width=2)
        del plot.x_mapper.range.sources[-1]  #remove the line plot from the x_mapper source so only the data is tied to the scaling

        self.on_trait_change(self._rangeChanged,'plot.index_mapper.range.updated')

        self.pantool = PanTool(plot,drag_button='left')
        plot.tools.append(self.pantool)
        self.zoomtool = ZoomTool(plot)
        self.zoomtool.prev_state_key = KeySpec('a')
        self.zoomtool.next_state_key = KeySpec('s')
        plot.overlays.append(self.zoomtool)

        self.scattertool = None
        self.scatter.overlays.append(ScatterInspectorOverlay(self.scatter,
                        hover_color = "black",
                        selection_color="black",
                        selection_outline_color="red",
                        selection_line_width=2))


        self.colorbar = colorbar = ColorBar(index_mapper=LinearMapper(range=plot.color_mapper.range),
                                            color_mapper=plot.color_mapper.range,
                                            plot=plot,
                                            orientation='v',
                                            resizable='v',
                                            width = 30,
                                            padding = 5)
        colorbar.padding_top = plot.padding_top
        colorbar.padding_bottom = plot.padding_bottom
        colorbar._axis.title = 'Weights'

        self.plotcontainer = container = HPlotContainer(use_backbuffer=True)
        container.add(plot)
        container.add(colorbar)

        super(FitGui,self).__init__(**traits)

        self.on_trait_change(self._scale_change,'plot.value_scale,plot.index_scale')

        if weights is not None and len(weights)==2:
            self.weightsChanged() #update error bars
Exemplo n.º 9
0
class ScatterPlot2(Template):

    #-- Template Traits --------------------------------------------------------

    # The title of the plot:
    title = TStr('Dual Scatter Plots')

    # The type of marker to use.  This is a mapped trait using strings as the
    # keys:
    marker = marker_trait(template='copy', event='update')

    # The pixel size of the marker (doesn't include the thickness of the
    # outline):
    marker_size = TRange(1, 5, 1, event='update')

    # The thickness, in pixels, of the outline to draw around the marker.  If
    # this is 0, no outline will be drawn.
    line_width = TRange(0.0, 5.0, 1.0)

    # The fill color of the marker:
    color = TColor('red', event='update')

    # The color of the outline to draw around the marker
    outline_color = TColor('black', event='update')

    # The amount of space between plots:
    spacing = TRange(0.0, 20.0, 0.0)

    # The contained scatter plots:
    scatter_plot_1 = TInstance(ScatterPlot, ())
    scatter_plot_2 = TInstance(ScatterPlot, ())

    #-- Derived Traits ---------------------------------------------------------

    plot = TDerived

    #-- Traits UI Views --------------------------------------------------------

    # The scatter plot view:
    template_view = View(VGroup(
        Item('title',
             show_label=False,
             style='readonly',
             editor=ThemedTextEditor(theme=Theme('@GBB', alignment='center'))),
        Item('plot',
             show_label=False,
             resizable=True,
             editor=EnableEditor(),
             item_theme=Theme('@GF5', margins=0))),
                         resizable=True)

    # The scatter plot options view:
    options_view = View(
        VGroup(
            VGroup(Label('Scatter Plot Options',
                         item_theme=Theme('@GBB', alignment='center')),
                   show_labels=False),
            VGroup(Item('title', editor=TextEditor()),
                   Item('marker'),
                   Item('marker_size', editor=ThemedSliderEditor()),
                   Item('line_width',
                        label='Line Width',
                        editor=ThemedSliderEditor()),
                   Item('spacing', editor=ThemedSliderEditor()),
                   Item('color', label='Fill Color'),
                   Item('outline_color', label='Outline Color'),
                   group_theme=Theme('@GF5', margins=(-5, -1)),
                   item_theme=Theme('@G0B', margins=0))))

    #-- ITemplate Interface Implementation -------------------------------------

    def activate_template(self):
        """ Converts all contained 'TDerived' objects to real objects using the
            template traits of the object. This method must be overridden in
            subclasses.
            
            Returns
            -------
            None
        """
        plots = [
            p for p in [self.scatter_plot_1.plot, self.scatter_plot_2.plot]
            if p is not None
        ]
        if len(plots) == 2:
            self.plot = HPlotContainer(spacing=self.spacing)
            self.plot.add(*plots)
        elif len(plots) == 1:
            self.plot = plots[0]

    #-- Default Values ---------------------------------------------------------

    def _scatter_plot_1_default(self):
        """ Returns the default value for the first scatter plot.
        """
        result = ScatterPlot()
        result.index.description = 'Shared Plot Index'
        result.value.description += ' 1'

        return result

    def _scatter_plot_2_default(self):
        """ Returns the default value for the second scatter plot.
        """
        result = ScatterPlot(index=self.scatter_plot_1.index)
        result.value.description += ' 2'
        result.value.optional = True

        return result

    #-- Trait Event Handlers ---------------------------------------------------

    def _update_changed(self, name, old, new):
        """ Handles a plot option being changed. 
        """
        setattr(self.scatter_plot_1, name, new)
        setattr(self.scatter_plot_2, name, new)
        self.plot = Undefined

    def _spacing_changed(self, spacing):
        """ Handles the spacing between plots being changed.
        """
        self.plot = Undefined
Exemplo n.º 10
0
class ScatterPlot(Template):

    #-- Template Traits --------------------------------------------------------

    # The plot index data source:
    index = TDataSource

    # The plot value data source:
    value = TDataSource

    # The title of the plot:
    title = TStr('Scatter Plot')

    # The type of marker to use.  This is a mapped trait using strings as the
    # keys:
    marker = marker_trait(template='copy', event='update')

    # The pixel size of the marker (doesn't include the thickness of the
    # outline):
    marker_size = TRange(1, 5, 1, event='update')

    # The thickness, in pixels, of the outline to draw around the marker.  If
    # this is 0, no outline will be drawn.
    line_width = TRange(0.0, 5.0, 1.0)

    # The fill color of the marker:
    color = TColor('red', event='update')

    # The color of the outline to draw around the marker
    outline_color = TColor('black', event='update')

    #-- Derived Traits ---------------------------------------------------------

    plot = TDerived  # Instance( ScatterPlot )

    #-- Traits UI Views --------------------------------------------------------

    # The scatter plot view:
    template_view = View(VGroup(
        Item('title',
             show_label=False,
             style='readonly',
             editor=ThemedTextEditor(theme=Theme('@GBB', alignment='center'))),
        Item('plot',
             show_label=False,
             resizable=True,
             editor=EnableEditor(),
             item_theme=Theme('@GF5', margins=0))),
                         resizable=True)

    # The scatter plot options view:
    options_view = View(
        VGroup(
            VGroup(Label('Scatter Plot Options',
                         item_theme=Theme('@GBB', alignment='center')),
                   show_labels=False),
            VGroup(Item('title', editor=TextEditor()),
                   Item('marker'),
                   Item('marker_size', editor=ThemedSliderEditor()),
                   Item('line_width',
                        label='Line Width',
                        editor=ThemedSliderEditor()),
                   Item('color', label='Fill Color'),
                   Item('outline_color', label='Outline Color'),
                   group_theme=Theme('@GF5', margins=(-5, -1)),
                   item_theme=Theme('@G0B', margins=0))))

    #-- Default Values ---------------------------------------------------------

    def _index_default(self):
        """ Returns the default value for the 'index' trait.
        """
        return TemplateDataSource(
            items=[ValueDataNameItem(name='index', flatten=True)],
            description='Scatter Plot Index')

    def _value_default(self):
        """ Returns the default value for the 'value' trait.
        """
        return TemplateDataSource(
            items=[ValueDataNameItem(name='value', flatten=True)],
            description='Scatter Plot Value')

    #-- ITemplate Interface Implementation -------------------------------------

    def activate_template(self):
        """ Converts all contained 'TDerived' objects to real objects using the
            template traits of the object. This method must be overridden in
            subclasses.
            
            Returns
            -------
            None
        """
        # If our data sources are still unbound, then just exit; someone must
        # have marked them as optional:
        if ((self.index.context_data is Undefined)
                or (self.value.context_data is Undefined)):
            return

        # Create a plot data object and give it this data:
        pd = ArrayPlotData()
        pd.set_data('index', self.index.context_data)
        pd.set_data('value', self.value.context_data)

        # Create the plot:
        self.plot = plot = Plot(pd)
        plot.plot(('index', 'value'),
                  type='scatter',
                  index_sort='ascending',
                  marker=self.marker,
                  color=self.color,
                  outline_color=self.outline_color,
                  marker_size=self.marker_size,
                  line_width=self.line_width,
                  bgcolor='white')
        plot.set(padding_left=50,
                 padding_right=0,
                 padding_top=0,
                 padding_bottom=20)

        # Attach some tools to the plot:
        plot.tools.append(PanTool(plot, constrain_key='shift'))
        zoom = SimpleZoom(component=plot, tool_mode='box', always_on=False)
        plot.overlays.append(zoom)

    #-- Trait Event Handlers ---------------------------------------------------

    def _update_changed(self):
        """ Handles a plot option being changed. 
        """
        self.plot = Undefined
Exemplo n.º 11
0
class DynamicRangeEditor(HasPrivateTraits):
    """ Defines an editor for dynamic ranges (i.e. ranges whose bounds can be
        changed at run time).
    """

    # The value with the dynamic range:
    value = Float

    # This determines the low end of the range:
    low = Range(0.0, 10.0, 0.0)

    # This determines the high end of the range:
    high = Range(20.0, 100.0, 20.0)

    # An integer value:
    int_value = Int

    # This determines the low end of the integer range:
    int_low = Range(0, 10, 0)

    # This determines the high end of the range:
    int_high = Range(20, 100, 20)

    # Traits view definitions:
    view = View(

        # Dynamic simple slider demo:
        Group(Item('value',
                   editor=RangeEditor(low_name='low',
                                      high_name='high',
                                      format='%.1f',
                                      label_width=28,
                                      mode='auto')),
              '_',
              Item('low'),
              Item('high'),
              '_',
              Label('Move the Low and High sliders to change the range of '
                    'Value.'),
              label='Simple Slider'),

        # Dynamic large range slider demo:
        Group(Item('value',
                   editor=RangeEditor(low_name='low',
                                      high_name='high',
                                      format='%.1f',
                                      label_width=28,
                                      mode='xslider')),
              '_',
              Item('low'),
              Item('high'),
              '_',
              Label('Move the Low and High sliders to change the range of '
                    'Value.'),
              label='Large Range Slider'),

        # Dynamic spinner demo:
        Group(Item('int_value',
                   editor=RangeEditor(low=0,
                                      high=20,
                                      low_name='int_low',
                                      high_name='int_high',
                                      format='%d',
                                      is_float=False,
                                      label_width=28,
                                      mode='spinner')),
              '_',
              Item('int_low'),
              Item('int_high'),
              '_',
              Label('Move the Low and High sliders to change the range of '
                    'Value.'),
              label='Spinner'),
        title='Dynamic Range Editor Demonstration',
        buttons=['OK'],
        resizable=True)
Exemplo n.º 12
0
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.

"""

contact_label = """
http://github.com/rwl/godot
"""

about_view = View(
    Group(Label(license_label), label="License"),
    Group(Label(contact_label), label="Contribute"),
    #    Group(Label(credits_label), label="Credits"),
    title="About",
    buttons=["OK"],
    icon=frame_icon)

# EOF -------------------------------------------------------------------------