Exemplo n.º 1
0
class BasicH5Configurator(AbstractConfigurator):
    """
    BasicH5Configurator reads the starting network from an HD5 file.

    It receives the path of the file from the simulation
    option 'h5_file', which has to be specified in the
    command line option description.
    """
    options = {'h5_file'}

    starting_graph = Instance(h5py.File, allow_none=False)

    node_type = Type
    node_options = Instance(set)

    def create_edges(self):
        pass

    def create_nodes(self):
        ifile = h5py.File(self.h5_file, 'r')
        indptr = ifile['indptr']
        max_node = indptr.len() - 1

        self.node_arguments = extract_sub_dictionary(self.full_parameters,
                                                     self.node_options)
        node_manager_id = node_manager.NodeManager.name

        answers = [
            self.send(node_manager_id,
                      'create_node',
                      cls=self.node_type,
                      parameters=self.node_arguments) for _ in xrange(max_node)
        ]
        SequenceAsyncResult(answers).get()
        self.node_identifiers = xrange(max_node)
Exemplo n.º 2
0
class DummyModelInfo(HasTraits):

    object = Instance(HasTraits)

    ui = Instance(DummyUI)

    def _ui_default(self):
        return DummyUI()
Exemplo n.º 3
0
class PyannoResult(HasStrictTraits):
    """Class for database entries
    """

    #: :class:`~pyanno.annotations.AnnotationsContainer` object
    anno_container = Instance(AnnotationsContainer)

    #: pyAnno model (subclass of :class:`~pyanno.abstract_model.AbstractModel`)
    model = Instance(AbstractModel)

    #: value of the model performance (usually the log likelihood)
    value = Float
Exemplo n.º 4
0
class NXGraphConfigurator(AbstractConfigurator):
    """
    Sets up a network reading the initial configuration from a graph
    in a file supported by the NetworkX library.
    """

    options = {'starting_graph'}
    """
    The NXGraphConfigurator agent reads the `starting_graph` property
    """

    starting_graph = Instance(nx.Graph, allow_none=False)

    node_type = Type
    node_options = Instance(set)

    def create_edges(self):
        """
        Creates the edges as specified in the network it read.
        """
        graph = self.starting_graph
        for u, v in graph.edges_iter():
            u1 = self.node_map[u]
            v1 = self.node_map[v]
            self.send(v1, 'accept_link', originating_node=u1)

    def create_nodes(self):
        """
        Requires the `NodeManager` to create the nodes as specified in the network it read.
        """
        self.node_arguments = extract_sub_dictionary(self.full_parameters,
                                                     self.node_options)
        node_manager_id = node_manager.NodeManager.name
        graph = self.starting_graph
        assert isinstance(graph, nx.Graph)

        self.node_map = {}
        # create all the nodes
        nit_1, nit_2 = itertools.tee(graph.nodes_iter())
        answers = [
            self.send(node_manager_id,
                      'create_node',
                      cls=self.node_type,
                      parameters=self.node_arguments) for _node in nit_1
        ]
        self.node_map = {
            node: identifier
            for node, identifier in itertools.izip(
                nit_2,
                SequenceAsyncResult(answers).get())
        }
        self.node_identifiers = self.node_map.viewvalues()
Exemplo n.º 5
0
class DummyParent(HasTraits):

    number = Int()

    number2 = Int()

    instance = Instance(Dummy, allow_none=True)

    instance2 = Instance(Dummy)

    income = Float()

    dummies = List(Dummy)
Exemplo n.º 6
0
class PAFTest(HasTraits):
    context = Instance(ParametricModelingContext)
    parameters = Instance(Parameters)
    update = Button
    r = Float(1.)
    a = Float(100.)

    view = View(
        Item("parameters", editor=PAFContextEditorFactory(context='context')),
        Item("update"), Item("a"), Item("r"))

    def _update_changed(self):
        self.parameters.a = self.a
        self.parameters.r = self.r
Exemplo n.º 7
0
        class Target(HasTraits):
            event = Event(Instance(SomeEvent))

            event_count = Int(0)

            def _event_fired(self):
                self.event_count += 1
Exemplo n.º 8
0
class DateEditor(EditorFactory):
    """ Editor factory for date/time editors.
    """

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

    # -- ReadonlyEditor traits ------------------------------------------------

    #: Message to show when Date is None.
    message = Str("Undefined")

    #: The string representation of the date to show.  Uses time.strftime
    #: format.
    strftime = Str("%B %d %Y (%a)")

    #: An optional view to display when a read-only text editor is clicked:
    view = AView

    # -- CustomEditor traits --------------------------------------------------

    #: Should users be able to pick future dates when using the CustomEditor?
    allow_future = Bool(True)

    #: How many months to show at a time.
    months = Int(3)

    #: True: Must be a List of Dates.  False: Must be a Date instance.
    multi_select = Bool(False)

    #: When a user multi-selects entries and some of those entries are already
    #: selected and some are not, what should be the behavior for the seletion?
    #:
    #: Options:
    #:
    #: - 'toggle': Toggle each day to the opposite of the current state.
    #: - 'on': Always turn them on.
    #: - 'off': Always turn them off.
    #: - 'max_change': Change all to same state, with most days changing.
    #:   For example 1 selected and 9 not, then they would all get selected.
    #: - 'min_change': Change all to same state, with min days changing.
    #:   For example 1 selected and 9 not, then they would all get unselected.
    on_mixed_select = Enum("toggle", "on", "off", "max_change", "min_change")

    #: How much space to put between the individual months.
    padding = Int(5)

    #: Does the user have to hold down Shift for the left-click multiselect?
    shift_to_select = Bool(False)

    #: Style used when a date is selected.
    selected_style = Instance(
        CellFormat,
        kw={
            "bold": True,
            "fgcolor": (255, 255, 255),
            "bgcolor": (0, 128, 0)
        },
    )
Exemplo n.º 9
0
class ListOfFloatsWithCSVEditor(ModelView):
    model = Instance(ListOfFloats)

    traits_view = View(
        Item(label="Close the window to append data"),
        Item("model.data", editor=CSVListEditor()),
        buttons=["OK"],
    )
Exemplo n.º 10
0
class PosteriorView(HasTraits):

    show_maximum = Bool(False)
    show_majority_vote = Bool(False)
    posterior_plot = Instance(PosteriorPlot)
    annotations = Array

    def traits_view(self):
        height = 760 if is_display_small() else 900
        traits_view = View(VGroup(VGroup(
            Item('show_maximum', label='Show MAP estimate (circle)'),
            Item('show_majority_vote', label='Show majority vote (triangle)'),
        ),
                                  VGroup(
                                      Item('posterior_plot',
                                           editor=InstanceEditor(),
                                           style='custom',
                                           show_label=False), ),
                                  padding=0),
                           height=height,
                           scrollable=True,
                           resizable=True)

        return traits_view

    def _show_maximum_changed(self):
        plot = self.posterior_plot
        if self.show_maximum:
            maximum = plot.posterior.argmax(1)
            plot.add_markings(maximum,
                              'MAP',
                              'circle',
                              0.,
                              0.,
                              marker_size=3,
                              line_width=2.,
                              marker_color='gray')
        else:
            plot.remove_markings('MAP')
        plot.plot_posterior.request_redraw()

    def _show_majority_vote_changed(self):
        plot = self.posterior_plot
        if self.show_majority_vote:
            majority = majority_vote(self.annotations)
            plot.add_markings(majority,
                              'majority',
                              'triangle',
                              0.,
                              0.,
                              marker_size=3,
                              line_width=1.,
                              marker_color='green')
        else:
            plot.remove_markings('majority')
        plot.plot_posterior.request_redraw()
Exemplo n.º 11
0
class PAFContextEditor(Editor):
    display = Instance(OCCViewer)
    initialized = Bool

    parameters = Instance(Parameters)
    context = Instance(ParametricModelingContext)

    def init(self, parent):
        self.control = OCCTraitViewer(self)
        self.sync_value(self.name, 'parameters', 'both')
        self.sync_value(self.factory.context, 'context', 'both')
        if self.factory.display:
            self.sync_value(self.factory.display, 'display', 'both')
        print(self.display)

    def _initialized_changed(self):
        r"""when display has been set on the first paint event"""
        self.context.set_display(self.control._display)
        print('Display initialiazed')
Exemplo n.º 12
0
class ExtendedListenerInList(HasTraits):
    # Used in regression test for enthought/traits#403.

    dummy = Instance(Dummy)

    changed = Bool(False)

    @on_trait_change(["dummy:x"])
    def set_changed(self):
        self.changed = True
Exemplo n.º 13
0
class FigureWnd(HasTraits):
    figure = Instance(Figure)

    def _figure_default(self):
        pass

    def update_figure(self):
        fig = Figure()
        self.create_plot(fig)
        self.figure = fig
Exemplo n.º 14
0
def Optional(trait: TraitType) -> Union:
    """
    Return Union of function argument and Instance(_Undefined)
    Args:
        trait (TraitType): optional trait

    Returns:
        union with undefined instance

    """
    return Union(trait, Instance(_Undefined))
Exemplo n.º 15
0
class CodeView(ModelView):
    model = Instance(CodeModel)
    show_line_numbers = Bool(True)
    style = Enum('simple', 'readonly')

    def default_traits_view(self):
        traits_view = View(
            Item('model.code',
                 editor=CodeEditor(show_line_numbers=self.show_line_numbers),
                 style=self.style))
        return traits_view
Exemplo n.º 16
0
class FoobotChat(Controller):
    model = Instance(Foobot, ())

    def traits_view(self):
        v = View(UItem('console',
                       style='custom',
                       editor=TextEditor(read_only=True)),
                 UItem('message',
                       editor=TextEditor(enter_set=True, auto_set=False)),
                 width=500,
                 height=400,
                 resizable=True)
        return v
Exemplo n.º 17
0
class DelegateMess(HasTraits):
    dummy1 = Instance(Dummy, args=())
    dummy2 = Instance(Dummy2)

    y = DelegatesTo("dummy2")

    handler_called = Bool(False)

    def _dummy2_default(self):
        # Create `self.dummy1`
        return Dummy2(dummy=self.dummy1)

    @on_trait_change("dummy1.x")
    def _on_dummy1_x(self):
        self.handler_called = True

    def _init_trait_listeners(self):
        """ Force the DelegatesTo listener to hook up first to exercise the
        worst case.
        """
        for name in ["y", "_on_dummy1_x"]:
            data = self.__class__.__listener_traits__[name]
            getattr(self, "_init_trait_%s_listener" % data[0])(name, *data)
Exemplo n.º 18
0
class NewModelDialog(HasTraits):
    """Create a dialog requesting the parameters to create a pyAnno model."""

    model_name = Str
    parameters_group = Instance(Group)

    def traits_view(self):
        traits_view = View(
            Include('parameters_group'),
            buttons=OKCancelButtons,
            title='Create new ' + self.model_name,
            #kind='modal'
        )
        return traits_view
Exemplo n.º 19
0
class ModelB_MultipleThetaView(HasTraits):
    """Tabular view for the parameters theta in Model B.

    Includes a spin box to select the parameters for each annotator.
    """

    @classmethod
    def show(cls, theta):
        """Create a window that with a ThetaView inside."""
        tv = cls(theta=theta)
        tv.edit_traits()

    # 3D tensor to be displayed
    theta = Array

    # 4D tensor of samples (may be None if no samples available)
    theta_samples = Any

    # title of the view window
    title = "Model B, parameters theta"

    # annotator number
    annotator_idx = Int(0)

    # tabular view of theta for annotator j
    theta_j_view = Instance(HasTraits)

    def traits_view(self):
        traits_view = View(
            VGroup(
                Item('annotator_idx',
                     label='Annotator index',
                     editor=RangeEditor(mode='spinner',
                                        low=0, high=self.theta.shape[0]-1,
                                        ),
                ),
                HGroup(
                    Item('theta_j_view',
                         style='custom',
                         show_label=False),
                ),
            ),
            width = 500,
            height = 400,
            resizable = True
        )
        return traits_view
Exemplo n.º 20
0
class AbstractWnd(HasTraits):
    figure = Instance(Figure)

    def _figure_default(self):
        pass

    alive = Bool()
    auto_update = Bool(False)
    enable_update = Bool()
    start = Button()

    def _start_fired(self):
        self.enable_update = True
        Thread(target=self._loop).start()

    stop = Button()

    def _stop_fired(self):
        self.enable_update = False

    def _loop(self):
        if self.auto_update:
            while self.auto_update and self.enable_update:
                self._update()
        else:
            self._update()

    def _update(self):
        self.alive = True

        def stop_condition(t, tstart):
            return not self.enable_update

        data = self.measure(self.conf, stop_condition)
        self.alive = False

        fig = Figure()
        self.plot(data, fig)
        self.figure = fig
Exemplo n.º 21
0
class AbstractRandomSelector(HasTraits):
    implements(IRandomSelector)

    graph_container = Instance(IGraph)
    _initialized_preferential_attachment = false

    def preferential_attachment(self):
        if not self._initialized_preferential_attachment:
            self.prepare_preferential_attachment()
            self._initialized_preferential_attachment = True
        return int(self.extract_preferential_attachment())

    def prepare_preferential_attachment(self):
        raise NotImplementedError()

    def random_edge(self):
        raise NotImplementedError()

    def random_node(self):
        raise NotImplementedError()

    def extract_preferential_attachment(self):
        raise NotImplementedError()
Exemplo n.º 22
0
class BandwidthHighlighter(HasTraits):
    container = Instance(HPlotContainer)
    plot = Instance(Component)

    colormap_name_1 = Str('gray')

    path = Str
    # add_band = Button('Add band')
    highlight_bands = List(Band)

    def update_path(self, new):
        self.path = new

    def delete_band(self):
        self.highlight_bands.pop(-1)

    def add_band(self):
        self.highlight_bands.append(Band())

    def _path_changed(self):
        self._load_image(self.path)

    @on_trait_change('highlight_bands:[center,threshold,color, use]')
    def _refresh_highlight_bands(self, obj, name, old, new):
        if self.path:
            plot = self.oplot
            im = Image.open(self.path)
            rgb_arr = array(im.convert('RGB'))
            #            im_arr=array(im)
            gray_im = array(im.convert('L'))
            for band in self.highlight_bands:
                if band.use:
                    low = band.center - band.threshold
                    high = band.center + band.threshold

                    mask = where((gray_im > low) & (gray_im < high))
                    #                    print band.color[:3]
                    rgb_arr[mask] = band.color.toTuple()[:3]

            imgplot = plot.plots['plot0'][0]
            tools = imgplot.tools
            overlays = imgplot.overlays

            plot.delplot('plot0')
            plot.data.set_data('img', rgb_arr)
            img_plot = plot.img_plot('img', colormap=color_map_name_dict[self.colormap_name_1])[0]

            for ti in tools + overlays:
                ti.component = img_plot

            img_plot.tools = tools
            img_plot.overlays = overlays

            plot.request_redraw()

    def _load_image(self, path):
        self.container = self._container_factory()
        im = Image.open(path)
        #        oim = array(im)
        im = im.convert('L')
        odim = ndim = array(im)

        pd = ArrayPlotData()
        pd.set_data('img', odim)
        plot = Plot(data=pd, padding=[30, 5, 5, 30], default_origin='top left')
        img_plot = plot.img_plot('img',
                                 colormap=color_map_name_dict[self.colormap_name_1]
        )[0]
        self.add_inspector(img_plot)

        self.add_tools(img_plot)

        self.oplot = plot

        self.container.add(self.oplot)
        #        self.container.add(self.plot)
        self.container.request_redraw()

    def add_inspector(self, img_plot):
        imgtool = ImageInspectorTool(img_plot)
        img_plot.tools.append(imgtool)
        overlay = ImageInspectorOverlay(component=img_plot, image_inspector=imgtool,
                                        bgcolor="white", border_visible=True)

        img_plot.overlays.append(overlay)

    def add_tools(self, img_plot):
        zoom = ZoomTool(component=img_plot, tool_mode="box", always_on=False)
        pan = PanTool(component=img_plot, restrict_to_data=True)
        img_plot.tools.append(pan)

        img_plot.overlays.append(zoom)

    def _highlight_bands_default(self):
        return [Band(color='red'), Band(color='green'), Band(color='blue')]

    def traits_view(self):
        ctrl_grp = VGroup(
            # HGroup(UItem('add_band')),
            UItem('highlight_bands', height=115,editor=ListEditor(mutable=False,
                                                       style='custom',
                                                       editor=InstanceEditor())))
        v = View(
            VSplit(
            ctrl_grp,
            UItem('container',
                  editor=ComponentEditor(height=700))))
        return v

    def _container_factory(self):
        pc = HPlotContainer(padding=[5, 5, 5, 20])
        return pc

    def _container_default(self):
        return self._container_factory()

#============= EOF =============================================
 def test_list_editor_list_instance(self):
     trait = List(Instance(HasTraits))
     editor = list_editor(trait, trait)
     self.assertIsInstance(editor, traitsui.api.TableEditor)
Exemplo n.º 24
0
        class Target(HasTraits):
            event = Event(Instance(SomeEvent))

            event_count = Int(0)
class MassSpecAnalysisExporter(Exporter):
    destination = Instance(MassSpecDestination, ())

    def __init__(self, *args, **kw):
        """
            destination: dict.
                dict, required keys are (username, password, host, name)
        """
        super(MassSpecAnalysisExporter, self).__init__(*args, **kw)
        importer = MassSpecDatabaseImporter()
        self.importer = importer

    @on_trait_change('destination:[username, password, host, name]')
    def set_destination(self, name, new):
        importer = self.importer
        db = importer.db
        # for k in ('username', 'password', 'host', 'name'):
        setattr(db, name, new)
        # db.connect()

    def start_export(self):
        self.importer.db.connect()
        return self.importer.db.connected

    def export(self):
        self.info('committing current session to database')
        self.importer.db.commit()
        self.info('commit successful')

    # self.extractor.db.close()

    def rollback(self):
        """
            Mass Spec schema doesn't allow rollback
        """
        pass

    #        self.info('rollback')
    #        self.extractor.db.rollback()
    #        self.extractor.db.reset()

    def _make_spec(self, ai):
        rs_name, rs_text = '', ''
        rid = ai.record_id
        exp = MassSpecExportSpec(
            runid=rid,
            runscript_name=rs_name,
            runscript_text=rs_text,
            mass_spectrometer=ai.mass_spectrometer.capitalize(),
            isotopes=ai.isotopes)

        exp.load_record(ai)
        return exp

    def add(self, analysis):

        spec = self._make_spec(analysis)

        db = self.importer.db

        # rid = spec.runid
        # convert rid
        # if rid == 'c':
        #     if spec.mass_spectrometer == 'Pychron Jan':
        #         rid = '4359'
        #     else:
        #         rid = '4358'
        rid = self.importer.get_identifier(spec)

        irrad = spec.irradiation
        level = spec.level

        prodid = self.importer.add_irradiation_production(
            spec.production_name, spec.production_ratios,
            spec.interference_corrections)

        self.importer.add_irradiation_chronology(irrad, spec.chron_dosages)

        self.importer.add_irradiation(irrad, level, prodid)
        self.importer.add_irradiation_position(spec.irradpos,
                                               '{}{}'.format(irrad, level),
                                               spec.irradiation_position,
                                               j=float(
                                                   nominal_value(spec.j or 0)),
                                               jerr=float(std_dev(spec.j
                                                                  or 0)))

        if db.get_analysis(rid, spec.aliquot, spec.step):
            self.debug('analysis {} already exists in database'.format(rid))
        else:
            spec.update_rundatetime = True
            self.importer.add_analysis(spec)
            return True
Exemplo n.º 26
0
class Consoleable(Loggable):
    use_message_colormapping = Bool
    console_display = Instance(
        'pychron.core.displays.display.DisplayController')
    # console_updated = Event
    console_bgcolor = LIGHT_YELLOW
    console_fontsize = Int(11)
    console_default_color = Color('black')

    def console_bind_preferences(self, prefid):
        from pychron.core.ui.preference_binding import color_bind_preference, bind_preference

        color_bind_preference(self, 'console_bgcolor',
                              '{}.bgcolor'.format(prefid))
        color_bind_preference(self, 'console_default_color',
                              '{}.textcolor'.format(prefid))
        bind_preference(self, 'console_fontsize', '{}.fontsize'.format(prefid))

    def console_set_preferences(self, preferences, prefid):
        from pychron.core.ui.preference_binding import set_preference, color_set_preference

        color_set_preference(preferences, self, 'console_bgcolor',
                             '{}.bg_color'.format(prefid))
        color_set_preference(preferences, self, 'console_default_color',
                             '{}.textcolor'.format(prefid))
        set_preference(preferences,
                       self,
                       'console_fontsize',
                       '{}.fontsize'.format(prefid),
                       cast=int)

    def warning(self, msg, log=True, color=None, *args, **kw):
        super(Consoleable, self).warning(msg, *args, **kw)

        if color is None:
            color = 'red'

        msg = msg.upper()
        if self.console_display:
            self.console_display.add_text(msg, color=color)

        # self.console_updated = '{}|{}'.format(color, msg)

    def heading(self, msg, decorate_chr='*', *args, **kw):
        d = decorate_chr * 7
        msg = '{} {} {}'.format(d, msg, d)
        self.info(msg)

    def info(self, msg, log=True, color=None, *args, **kw):
        if color is None:  # or not self.use_message_colormapping:
            color = self.console_default_color

        if self.console_display:
            t = datetime.now().strftime('%H:%M:%S')
            msg = '{} -- {}'.format(t, msg)

            self.console_display.add_text(msg, color=color)

        if log:
            super(Consoleable, self).info(msg, *args, **kw)

        # self.console_updated = '{}|{}'.format(color, msg)

    def info_marker(self, char='=', color=None):
        if color is None:
            color = self.console_default_color
        if self.console_display:
            self.console_display.add_marker(char, color=color)

    def info_heading(self, msg):
        self.info('')
        self.info_marker('=')
        self.info(msg)
        self.info_marker('=')
        self.info('')

    def _console_display_default(self):
        from pychron.core.displays.display import DisplayController
        return DisplayController(bgcolor=self.console_bgcolor,
                                 font_size=self.console_fontsize,
                                 default_color=self.console_default_color,
                                 max_blocks=100)
Exemplo n.º 27
0
class ClassWithInstance(HasTraits):

    instance = Instance(ClassWithNumber)
Exemplo n.º 28
0
class AnnotationsStatisticsView(HasTraits):

    statistics_name = Enum(ALL_STATS_NAMES)

    annotations = Array

    nclasses = Int

    info_button = Button("Info...")

    stats_view = Instance(HasTraits)

    def _info_button_fired(self):
        """Open dialog with description of statistics."""
        if self.statistics_name in GLOBAL_STATS:
            stat_func = GLOBAL_STATS[self.statistics_name]
        else:
            stat_func = PAIRWISE_STATS[self.statistics_name]
        message(message=stat_func.__doc__, title='Statistics info')

    @on_trait_change('statistics_name')
    def _update_stats_view(self):
        if self.statistics_name in GLOBAL_STATS:
            stat_func = GLOBAL_STATS[self.statistics_name]

            try:
                res = stat_func(self.annotations, nclasses=self.nclasses)
            except PyannoValueError as e:
                logger.info(e)
                res = np.nan

            self.stats_view = _SingleStatView(value=res,
                                              name=self.statistics_name)

        else:
            stat_func = PAIRWISE_STATS[self.statistics_name]

            try:
                res = measures.pairwise_matrix(stat_func,
                                               self.annotations,
                                               nclasses=self.nclasses)
            except PyannoValueError as e:
                logger.info(e)
                nannotators = self.annotations.shape[1]
                res = np.empty((nannotators, nannotators))
                res.fill(np.nan)

            self.stats_view = MatrixPlot(matrix=res,
                                         colormap_low=-1.0,
                                         colormap_high=1.0,
                                         title=self.statistics_name)

    def traits_view(self):
        self.statistics_name = "Cohen's Kappa"
        traits_view = View(VGroup(
            HGroup(Item("statistics_name", show_label=False),
                   Item("info_button", show_label=False)),
            Spring(),
            HGroup(
                Spring(),
                Item("stats_view",
                     style="custom",
                     show_label=False,
                     width=300,
                     resizable=False), Spring()),
        ),
                           width=400,
                           resizable=True)
        return traits_view
Exemplo n.º 29
0
class MatrixPlot(PyannoPlotContainer):

    # data to be displayed
    matrix = Array

    #### plot-related traits
    colormap_low = Float(None)
    colormap_high = Float(None)
    origin = Str('top left')

    matrix_plot_container = Instance(HPlotContainer)

    def _create_colormap(self):
        if self.colormap_low is None:
            self.colormap_low = self.matrix.min()

        if self.colormap_high is None:
            self.colormap_high = self.matrix.max()

        if self.colormap_low >= 0.0:
            colormap_factory = Reds
        else:
            colormap_factory = reverse(RdBu)

        colormap = colormap_factory(
            DataRange1D(low=self.colormap_low, high=self.colormap_high))

        return colormap

    def _matrix_plot_container_default(self):
        matrix = np.nan_to_num(self.matrix)
        width = matrix.shape[0]

        # create a plot data object and give it this data
        plot_data = ArrayPlotData()
        plot_data.set_data("values", matrix)

        # create the plot
        plot = Plot(plot_data, origin=self.origin)

        img_plot = plot.img_plot("values",
                                 interpolation='nearest',
                                 xbounds=(0, width),
                                 ybounds=(0, width),
                                 colormap=self._create_colormap())[0]

        #### fix axes
        self._remove_grid_and_axes(plot)

        axis = self._create_increment_one_axis(plot, 0.5, width, 'bottom')
        self._add_value_axis(plot, axis)

        axis = self._create_increment_one_axis(
            plot,
            0.5,
            width,
            'left',
            ticks=[str(i) for i in range(width - 1, -1, -1)])
        self._add_index_axis(plot, axis)

        #### tweak plot attributes
        self._set_title(plot)
        plot.aspect_ratio = 1.
        # padding [left, right, up, down]
        plot.padding = [0, 0, 25, 25]

        # create the colorbar, handing in the appropriate range and colormap
        colormap = img_plot.color_mapper
        colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                            color_mapper=colormap,
                            plot=img_plot,
                            orientation='v',
                            resizable='v',
                            width=20,
                            padding=[0, 20, 0, 0])
        colorbar.padding_top = plot.padding_top
        colorbar.padding_bottom = plot.padding_bottom

        # create a container to position the plot and the colorbar side-by-side
        container = HPlotContainer(use_backbuffer=True)
        container.add(plot)
        container.add(colorbar)
        container.bgcolor = 0xFFFFFF

        self.decorate_plot(container, self.matrix)
        return container

    resizable_plot_item = Item('matrix_plot_container',
                               editor=ComponentEditor(),
                               resizable=True,
                               show_label=False,
                               width=600,
                               height=400)

    traits_plot_item = Instance(Item)

    def _traits_plot_item_default(self):
        return Item('matrix_plot_container',
                    editor=ComponentEditor(),
                    resizable=False,
                    show_label=False,
                    height=-200,
                    width=-200)
Exemplo n.º 30
0
class EventSelectionDialog(HasTraits):
    source_class_label = String("Select Event Source Classes")
    severity_level_label = String("Select Event Severity Levels")

    search = String(regex="^[_a-zA-Z0-9\*\.\$\^\?\s]*$")
    shown_event_names_list = String(regex="[_a-zA-Z0-9\*\.\$\^\?\n]*")
    quit_button = Button('Quit')
    query_button = Button('Run Query...')
    period_start_date = DelegatesTo("query_object")
    period_end_date = DelegatesTo("query_object")

    selected_list_of_event_severity_levels = DelegatesTo("query_object")
    list_of_event_severity_levels = DelegatesTo("query_object")

    selected_list_of_source_classes = DelegatesTo("query_object")
    list_of_source_classes = DelegatesTo("query_object")

    query_object = Instance(EventSelectionQuery)

    spring = Spring

    help_text = (
        "Search engine like queries using alphanumeric characters and '_'and '.' \n"
        + "Space indicate OR-separated queries\n" +
        "? = match any character\n" + "* = any number of characters\n" +
        "^ = match beginning\n"
        "$ = match end")

    view = View(
        Group(
            VGroup(
                HGroup(Item("period_start_date", label="Period"),
                       Item("period_end_date", show_label=False),
                       Item("", resizable=True, width=1.0, show_label=False),
                       HGroup(Item('quit_button', show_label=False),
                              Item('query_button', show_label=False)),
                       springy=True),
                HGroup(
                    VGroup(
                        HGroup(
                            Item("severity_level_label",
                                 show_label=False,
                                 style="readonly")),
                        Item("selected_list_of_event_severity_levels",
                             editor=CheckListEditor(
                                 name="list_of_event_severity_levels"),
                             style="custom",
                             show_label=False)),
                    VGroup(
                        HGroup(
                            Item("source_class_label",
                                 show_label=False,
                                 style="readonly")),
                        Item("selected_list_of_source_classes",
                             editor=CheckListEditor(
                                 name="list_of_source_classes"),
                             style="custom",
                             show_label=False)),
                    # springy=True
                ),
                show_border=True),
            Item("_"),
            VGroup(Item("search",
                        editor=HistoryEditor(auto_set=True),
                        show_label=False,
                        width=1.0,
                        tooltip=help_text),
                   Item(
                       name='shown_event_names_list',
                       style='readonly',
                       resizable=True,
                       show_label=False,
                   ),
                   scrollable=True,
                   show_border=True),
            orientation='vertical',
        ),
        title='Select Events to Visualize',
        dock='horizontal',
        resizable=True,
        width=.5,
        height=.7)

    def __init__(self, query_object, **kwargs):
        '''
        Creates a dialog window for selecting date period, source classes and event severity levels/types.
        :param query_object:
        :return:
        '''
        assert isinstance(query_object, EventSelectionQuery)

        self.shown_event_names_list = "\n".join(
            list(query_object.list_of_event_names))
        self.query_object = query_object
        self.query_start_date = query_object.period_start_date
        self.query_end_date = query_object.period_end_date

        HasTraits.__init__(self, **kwargs)

    def _search_changed(self):
        '''
        Matches search query to the event names.
        :return:
        '''
        query_st = str(self.search).strip()

        if re.match("^[_a-zA-Z0-9\*\.\$\^\?\s]*$", query_st) is None:
            return

        query_st = query_st.replace(".", "\.")
        query_st = query_st.replace("*", ".*")
        query_st = query_st.replace("?", ".?")
        queries = query_st.split()

        print self.search, query_st, queries,

        if len(queries) == 0:
            queries = [""]

        result = [
            s for s in list(self.query_object.list_of_event_names)
            for q in queries if re.search((".*%s.*" % q), s) is not None
        ]

        self.query_object.selected_list_of_event_names = result
        self.shown_event_names_list = "\n".join(result)

        print len(self.shown_event_names_list)

    def _save_search(self):
        # A bug fix, stops the clearing of the search expression
        tmp = self.search
        self.search = " "
        self.search = tmp

        print len(self.query_object.selected_list_of_event_names)

    def _query_button_changed(self):
        self._save_search()
        self.query_object.execute_query()

    def _quit_button_changed(self):
        self._save_search()
        sys.exit(0)