Пример #1
0
    def _resplotter_default(self):
        res = np.zeros((400, 400))
        self.pd = ArrayPlotData(res=res)
        p = Plot(self.pd)
        img = p.img_plot('res', name="my_plot")
        my_plot = p.plots["my_plot"][0]
        colormap = my_plot.color_mapper
        colorbar = ColorBar(
            index_mapper=dc.LinearMapper(range=colormap.range),
            color_mapper=colormap,
            orientation='v',
            plot=my_plot,
            resizable='v',
            width=30,
            padding=20)

        range_selection = RangeSelection(component=colorbar)
        colorbar.tools.append(range_selection)
        colorbar.overlays.append(RangeSelectionOverlay(component=colorbar,
            border_color="white",
            alpha=0.8,
            fill_color="lightgray"))
        range_selection.listeners.append(my_plot)
        con = HPlotContainer()
        con.add(p)
        con.add(colorbar)
        return con
Пример #2
0
	def _plot_default(self):
		self.data = self._data_default()

		plot = Plot(self.data)

		for ii, s_name in enumerate(self._samples):
			color = COLORS[ii % len(self._samples)]
			plot.plot(('bins',s_name), name=s_name,
					   type='filled_line',
					   edge_color=color,
					   face_color=color,
					   alpha=0.5,
					   bgcolor='white',
					   render_style='hold') # render_style determines whether interpolate

		plot.index = plot._get_or_create_datasource('bins') #set index name manually so range selection works
		plot.index_scale = 'log'
		plot.title = 'Fermi Plot'
		plot.padding = 50
		plot.legend.visible = True

		plot.tools.append(PanTool(plot))
		plot.active_tool = RangeSelection(plot)
		plot.overlays.append(RangeSelectionOverlay(component=plot))
		zoom = ZoomTool(component=plot, tool_mode='box', always_on=False)
		plot.overlays.append(zoom)

		return plot	
Пример #3
0
    def update_main_plot(self):
        """ Build main plot
        """
        self.ts_plot = ToolbarPlot(self.arr_plot_data)
        for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]):
            renderer = self.ts_plot.plot(("index", k), name = k, color = colors[i % len(colors)])[0]
        if self.index_is_dates:
            # Index was an array of datetime: overwrite the x axis
            self.ts_plot.x_axis = None
            x_axis = PlotAxis(self.ts_plot, orientation="bottom",
                              tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
            self.ts_plot.overlays.append(x_axis)
            self.ts_plot.x_grid.tick_generator = x_axis.tick_generator
            
        if self.data_file:
            self.ts_plot.title = ("Time series visualization from %s" 
                                  % (os.path.split(self.data_file)[1]))
        else:
            self.ts_plot.title = "Time series visualization"
        attach_tools(self.ts_plot)

        # Attach the range selection to the last renderer; any one will do
        self.ts_plot.tools.append(RangeSelection(renderer, left_button_selects = False,
            auto_handle_event = False))
        # Attach the corresponding overlay
        self._range_selection_overlay = RangeSelectionOverlay(renderer,
                                    metadata_name="selections")
        self.ts_plot.overlays.append(self._range_selection_overlay)
        # Grab a reference to the Time axis datasource and add a listener to its
        # selections metadata
        self.times_ds = renderer.index
        self.times_ds.on_trait_change(self._selections_changed)
    def control(self):
        """
		A drawable control with a color bar.
		"""

        color_map = self.plot_obj.color_mapper
        linear_mapper = LinearMapper(range=color_map.range)
        color_bar = ColorBar(index_mapper=linear_mapper,
                             color_mapper=color_map,
                             plot=self.plot_obj,
                             orientation='v',
                             resizable='v',
                             width=30)
        color_bar._axis.tick_label_formatter = self.sci_formatter
        color_bar.padding_top = self.padding_top
        color_bar.padding_bottom = self.padding_bottom
        color_bar.padding_left = 50  # Room for labels.
        color_bar.padding_right = 10

        range_selection = RangeSelection(component=color_bar)
        range_selection.listeners.append(self.plot_obj)
        color_bar.tools.append(range_selection)

        range_selection_overlay = RangeSelectionOverlay(component=color_bar)
        color_bar.overlays.append(range_selection_overlay)

        container = HPlotContainer(use_backbuffer=True)
        container.add(self)
        container.add(color_bar)

        return Window(self.parent, component=container).control
Пример #5
0
    def _update_rangeselect(self):
        ''' Overwrites range selection tool in current plot.'''

        #### Remove current overlay
        self.plot.overlays = [
            obj for obj in self.plot.overlays
            if not isinstance(obj, RangeSelectionOverlay)
        ]

        mycomp = self.plot.plots.itervalues().next()[
            0]  #Quick wayt to get first value in dictionary

        inds = range(len(self.df.index))
        idx = ArrayDataSource(inds)
        vals = ArrayDataSource(df.index.values)

        index_range = DataRange1D(idx)
        val_range = DataRange1D(vals)
        imap = LinearMapper(
            range=index_range)  #,stretch_data=self.index_mapper.stretch_data)
        vmap = LinearMapper(range=val_range)
        #   mycomp.index_range.refresh()

        mycomp.index_mapper = imap
        mycomp.value_mapper = vmap

        self.rangeselect = RangeSelection(mycomp, axis=self.selection_axis)
        self.plot.active_tool = self.rangeselect
        self.plot.overlays.append(RangeSelectionOverlay(component=mycomp))
        self.rangeselect.on_trait_change(self.on_selection_changed,
                                         "selection")
    def _create_price_plots(self, times, prices, mini_height=75):
        """ Creates the two plots of prices and returns them.  One of the
        plots can be zoomed and panned, and the other plot (smaller) always
        shows the full data.

        *dates* and *prices* are two data sources.
        """

        # Create the price plot
        price_plot = FilledLinePlot(
            index=times,
            value=prices,
            index_mapper=LinearMapper(range=DataRange1D(times)),
            value_mapper=LinearMapper(range=DataRange1D(prices)),
            edge_color="blue",
            face_color="paleturquoise",
            bgcolor="white",
            border_visible=True)

        # Add pan and zoom
        price_plot.tools.append(
            PanTool(
                price_plot, constrain=True, constrain_direction="x"))
        price_plot.overlays.append(
            ZoomTool(
                price_plot,
                drag_button="right",
                always_on=True,
                tool_mode="range",
                axis="index",
                max_zoom_out_factor=1.0, ))

        # Create the miniplot
        miniplot = LinePlot(
            index=times,
            value=prices,
            index_mapper=LinearMapper(range=DataRange1D(times)),
            value_mapper=LinearMapper(range=DataRange1D(prices)),
            color="black",
            border_visible=True,
            bgcolor="white",
            height=mini_height,
            resizable="h")

        # Add a range overlay to the miniplot that is hooked up to the range
        # of the main price_plot
        range_tool = RangeSelection(miniplot)
        miniplot.tools.append(range_tool)
        range_overlay = RangeSelectionOverlay(
            miniplot, metadata_name="selections")
        miniplot.overlays.append(range_overlay)
        range_tool.on_trait_change(self._range_selection_handler, "selection")

        # Attach a handler that sets the tool when the plot's index range changes
        self.range_tool = range_tool
        price_plot.index_range.on_trait_change(self._plot_range_handler,
                                               "updated")

        return price_plot, miniplot
Пример #7
0
    def _featureselmode_changed(self, old, new):
        pl = self.plot

        if new == 'No Selection':
            pl.tools[0].drag_button = 'left'
            self.maintool = (None, None)

        elif new == 'Click Select':
            pl.tools[0].drag_button = 'right'
            fctool = FeatureClickTool(plot=self.plot)
            self.maintool = (fctool, None)
            fctool.on_trait_change(self._add_feature_point, 'mouse_clicked')

        elif new == 'Range Select':
            pl.tools[0].drag_button = 'right'
            fplot = pl.plots['flux'][0]

            #TODO:clean up these hacky bugfix techniques if possible
            rstool = RangeSelectionBugfix(component=fplot,
                                          left_button_selects=True,
                                          enable_resize=False,
                                          mapper=self.plot.x_mapper)
            rstool.plot = fplot
            rstool.component = pl

            rsoverlay = RangeSelectionOverlay(component=fplot,
                                              mapper=self.plot.x_mapper)
            rsoverlay.plot = fplot
            rsoverlay.component = pl
            self.maintool = (rstool, rsoverlay)
            rstool.on_trait_change(self._add_feature_range,
                                   'selection_completed')

        elif new == 'Base Select':
            pl.tools[0].drag_button = 'right'
            slt = SingleLineTool(component=self.plot)
            slt.component = self.plot
            self.maintool = (slt, slt)
            slt.on_trait_change(self._add_feature_base, 'finished')
        elif new == 'Click Delete':
            pl.tools[0].drag_button = 'right'
            fctool = FeatureClickTool(plot=self.plot)
            self.maintool = (fctool, None)
            fctool.on_trait_change(self._del_feature_point, 'mouse_clicked')
        else:
            assert True, 'enum invalid!'
Пример #8
0
    def _featureselmode_changed(self,old,new):
        pl = self.plot

        if new == 'No Selection':
            pl.tools[0].drag_button = 'left'
            self.maintool = (None,None)

        elif new == 'Click Select':
            pl.tools[0].drag_button = 'right'
            fctool = FeatureClickTool(plot=self.plot)
            self.maintool = (fctool,None)
            fctool.on_trait_change(self._add_feature_point,'mouse_clicked')

        elif new == 'Range Select':
            pl.tools[0].drag_button = 'right'
            fplot = pl.plots['flux'][0]

            #TODO:clean up these hacky bugfix techniques if possible
            rstool = RangeSelectionBugfix(component=fplot,
                                          left_button_selects=True,
                                          enable_resize=False,
                                          mapper=self.plot.x_mapper)
            rstool.plot = fplot
            rstool.component = pl

            rsoverlay = RangeSelectionOverlay(component=fplot,
                                              mapper=self.plot.x_mapper)
            rsoverlay.plot = fplot
            rsoverlay.component = pl
            self.maintool = (rstool,rsoverlay)
            rstool.on_trait_change(self._add_feature_range,'selection_completed')

        elif new == 'Base Select':
            pl.tools[0].drag_button = 'right'
            slt = SingleLineTool(component=self.plot)
            slt.component = self.plot
            self.maintool = (slt,slt)
            slt.on_trait_change(self._add_feature_base,'finished')
        elif new == 'Click Delete':
            pl.tools[0].drag_button = 'right'
            fctool = FeatureClickTool(plot=self.plot)
            self.maintool = (fctool,None)
            fctool.on_trait_change(self._del_feature_point,'mouse_clicked')
        else:
            assert True,'enum invalid!'
Пример #9
0
    def plot_datasets(self, datasets, scale='linear', reset_view=True):
        if self.plots:
            self.plot.delplot(*self.plot.plots.keys())
            self.plots = {}
        active = filter(lambda d: d.metadata['ui'].active, datasets)
        hilite = filter(lambda d: d.metadata['ui'].markers, active)
        
        if len(active)==0:
            return None
            
        for dataset in active:
            ui = dataset.metadata['ui']
            data = dataset.data
            name = ui.name or dataset.name
            x, y = np.transpose(data[:, [0,1]])
            self.plot_data.set_data(name + '_x', x)
            self.plot_data.set_data(name + '_y', rescale(y, method=scale))
            color = ui.color
            if color is None:
                color = 'auto'
            plot = self.plot.plot((name + '_x', name + '_y'),
                                  name=name, type='line', color=color,
                                  line_width=ui.line_width)
            if color == 'auto':
                ui.color = tuple(
                    (np.array(plot[0].color_) * 255).astype('uint8').tolist())
            self.plots[name] = plot

        for dataset in hilite:
            ui = dataset.metadata['ui']
            data = dataset.data
            name = ui.name or dataset.name
            # Overlay a scatter plot on the original line plot to highlight
            # data points as circles.
            plot = self.plot.plot((name + '_x', name + '_y'),
                                  name=name + '_selection', type='scatter',
                                  color=ui.color, outline_color=ui.color,
                                  marker_size=ui.marker_size,
                                  line_width=ui.line_width)
            self.plots[name] = plot

        if len(datasets) > 0:
            self.plot0renderer = plot[0]
            self.range_selection_tool = RangeSelection(self.plot0renderer, left_button_selects=True)
            self.range_selection_overlay = RangeSelectionOverlay(component=self.plot0renderer)

        if reset_view:
            self.reset_view()
        # Since highlighted datasets are plotted twice, both plots show up in
        # the legend. This fixes that.
        self.plot.legend.plots = self.plots

        self.show_legend('Overlay')
        self._set_scale(scale)
Пример #10
0
 def _plot_default(self):
     plot_data = ArrayPlotData(
         x=np.linspace(0, 1, 10), y=np.linspace(0, 1, 10)
     )
     plot = Plot(plot_data)
     r, = plot.plot(("x", "y"))
     range_tool = RangeSelection(r)
     r.overlays.append(RangeSelectionOverlay(axis='index', component=r))
     r.tools.append(range_tool)
     self.range_tool = range_tool
     return plot
Пример #11
0
def create_colorbar(colormap):
    colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                        color_mapper=colormap,
                        orientation='v',
                        resizable='v',
                        width=30,
                        padding=20)
    colorbar.tools.append(RangeSelection(component=colorbar))
    colorbar.overlays.append(RangeSelectionOverlay(component=colorbar,
                                                   border_color="white",
                                                   alpha=0.8,
                                                   fill_color="lightgray"))
    return colorbar
Пример #12
0
    def setup(self, x, y, ans):
        p = self.new_plot()
        p.padding_left = 60
        p.y_axis.tick_label_formatter = tick_formatter
        p.y_axis.tick_generator = StaticTickGenerator()
        p.y_axis.title = 'Analysis Type'

        # p.y_grid.line_style='solid'
        # p.y_grid.line_color='green'
        # p.y_grid.line_weight = 1.5

        self.set_y_limits(min_=-1, max_=len(TICKS))

        p.index_range.tight_bounds = False
        p.x_axis.tick_generator = ScalesTickGenerator(
            scale=CalendarScaleSystem())
        p.x_grid.tick_generator = p.x_axis.tick_generator
        p.x_axis.title = 'Time'
        # p.y_axis.tick_label_rotate_angle = 45

        scatter, _ = self.new_series(x,
                                     y,
                                     type='scatter',
                                     marker_size=1.5,
                                     selection_marker='circle',
                                     selection_marker_size=2.5)

        broadcaster = BroadcasterTool()
        scatter.tools.append(broadcaster)

        point_inspector = AnalysisPointInspector(
            scatter,
            analyses=ans,
            value_format=get_analysis_type,
            additional_info=lambda x:
            ('Time={}'.format(x.rundate), 'Project={}'.format(x.project)))

        pinspector_overlay = PointInspectorOverlay(component=scatter,
                                                   tool=point_inspector)

        range_selector = RangeSelection(scatter, left_button_selects=True)
        broadcaster.tools.append(point_inspector)
        broadcaster.tools.append(range_selector)

        scatter.overlays.append(RangeSelectionOverlay(component=scatter))
        scatter.overlays.append(pinspector_overlay)

        self.scatter = scatter
Пример #13
0
    def _create_returns_plot(self):
        plot = Plot(self.plotdata)
        plot.legend.visible = True
        #FIXME: The legend move tool doesn't seem to quite work right now
        #plot.legend.tools.append(LegendTool(plot.legend))
        plot.x_axis = None
        x_axis = PlotAxis(
            plot,
            orientation="bottom",
            tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
        plot.overlays.append(x_axis)
        plot.x_grid.tick_generator = x_axis.tick_generator
        for i, name in enumerate(self.plotdata.list_data()):
            if name == "times":
                continue
            renderer = plot.plot(("times", name),
                                 type="line",
                                 name=name,
                                 color=tuple(COLOR_PALETTE[i]))[0]

        # Tricky: need to set auto_handle_event on the RangeSelection
        # so that it passes left-clicks to the PanTool
        # FIXME: The range selection is still getting the initial left down
        renderer.tools.append(
            RangeSelection(renderer,
                           left_button_selects=False,
                           auto_handle_event=False))
        plot.tools.append(
            PanTool(plot,
                    drag_button="left",
                    constrain=True,
                    constrain_direction="x",
                    restrict_to_data=True))
        plot.overlays.append(
            ZoomTool(plot,
                     tool_mode="range",
                     max_zoom_out=1.0,
                     x_min_zoom_factor=float(1e-3)))
        # Attach the range selection to the last renderer; any one will do
        self._range_selection_overlay = RangeSelectionOverlay(
            renderer, metadata_name="selections")
        renderer.overlays.append(self._range_selection_overlay)
        # Grab a reference to the Time axis datasource and add a listener to its
        # selections metadata
        self.times_ds = renderer.index
        self.times_ds.on_trait_change(self._selections_changed,
                                      'metadata_changed')
        self.returns_plot = plot
Пример #14
0
    def _time_plot_default(self):
        plot = Plot(self.data)
        line_plot = plot.plot(('t', 'y'))[0]

        line_plot.active_tool = RangeSelection(line_plot,
                                               left_button_selects=True)
        line_plot.overlays.append(RangeSelectionOverlay(component=line_plot))
        self.selection = line_plot.active_tool

        plot.padding = 20
        plot.padding_left = 50

        self.selection.on_trait_change(self.handle_selection_change,
                                       'selection')

        return plot
Пример #15
0
    def _create_returns_plot(self):
        plot = Plot(self.plotdata)
        plot.legend.visible = False
        plot.x_axis = None
        x_axis = PlotAxis(
            plot,
            orientation="bottom",
            tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
        plot.overlays.append(x_axis)
        plot.x_grid.tick_generator = x_axis.tick_generator
        for i, name in enumerate(self.plotdata.list_data()):
            if name == "times":
                continue
            renderer = plot.plot(("times", name),
                                 type="line",
                                 name=name,
                                 color="auto",
                                 line_width=2)[0]
        self.times_ds = renderer.index
        print('chaco: %s') % str(time.time() - tic)

        # Tricky: need to set auto_handle_event on the RangeSelection
        # so that it passes left-clicks to the PanTool
        # FIXME: The range selection is still getting the initial left down
        renderer.tools.append(
            RangeSelection(renderer,
                           left_button_selects=False,
                           auto_handle_event=False))
        plot.tools.append(
            PanTool(plot,
                    drag_button="left",
                    constrain=True,
                    constrain_direction="x"))
        plot.overlays.append(
            ZoomTool(plot, tool_mode="range", max_zoom_out=1.0))
        # Attach the range selection to the last renderer; any one will do
        self._range_selection_overlay = RangeSelectionOverlay(
            renderer, metadata_name="selections")
        renderer.overlays.append(self._range_selection_overlay)
        # Grab a reference to the Time axis datasource and add a listener to its
        # selections metadata
        self.times_ds = renderer.index
        self.times_ds.on_trait_change(self._selections_changed,
                                      'metadata_changed')

        self.returns_plot = plot
Пример #16
0
def _create_plot_component(use_downsampling=True):

    container = OverlayPlotContainer(padding=40,
                                     bgcolor="lightgray",
                                     use_backbuffer=True,
                                     border_visible=True,
                                     fill_padding=True)

    numpoints = 100000
    low = -5
    high = 15.0
    x = arange(low, high + 0.001, (high - low) / numpoints)

    # Plot some bessel functionsless ../en
    value_mapper = None
    index_mapper = None
    for i in range(10):
        y = jn(i, x)
        plot = create_line_plot((x, y),
                                color=tuple(COLOR_PALETTE[i]),
                                width=2.0)
        plot.use_downsampling = use_downsampling

        if value_mapper is None:
            index_mapper = plot.index_mapper
            value_mapper = plot.value_mapper
            add_default_grids(plot)
            add_default_axes(plot)
        else:
            plot.value_mapper = value_mapper
            value_mapper.range.add(plot.value)
            plot.index_mapper = index_mapper
            index_mapper.range.add(plot.index)
        if i % 2 == 1:
            plot.line_style = "dash"
        plot.bgcolor = "white"
        container.add(plot)

    selection_overlay = RangeSelectionOverlay(component=plot)
    plot.tools.append(RangeSelection(plot))
    zoom = ZoomTool(plot, tool_mode="box", always_on=False)
    plot.overlays.append(selection_overlay)
    plot.overlays.append(zoom)

    return container
Пример #17
0
    def generate_colorbar(self, desc):
        """ Generate the colorbar to display along side the plot.
        """
        super(CmapScatterPlotFactory, self).generate_colorbar(desc)

        colorbar = self.colorbar
        cmap_renderer = self._get_cmap_renderer()
        select_tool = "colorbar_selector" in self.plot_tools
        if select_tool:
            selection = ColormappedSelectionOverlay(cmap_renderer,
                                                    fade_alpha=0.35,
                                                    selection_type="mask")
            cmap_renderer.overlays.append(selection)

            colorbar.tools.append(RangeSelection(component=colorbar))
            overlay = RangeSelectionOverlay(component=colorbar,
                                            border_color="white",
                                            alpha=0.8,
                                            fill_color="lightgray")
            colorbar.overlays.append(overlay)
Пример #18
0
def _create_plot_component():

    numpoints = 100
    low = -5
    high = 15.001
    x = arange(low, high, (high - low) / numpoints)

    # Plot a bessel function
    y = jn(0, x)
    plot = create_line_plot((x, y),
                            color=(0, 0, 1, 1),
                            width=2.0,
                            index_sort="ascending")
    value_range = plot.value_mapper.range
    plot.active_tool = RangeSelection(plot, left_button_selects=True)
    plot.overlays.append(RangeSelectionOverlay(component=plot))
    plot.bgcolor = "white"
    plot.padding = 50
    add_default_grids(plot)
    add_default_axes(plot)

    return plot
Пример #19
0
    def _create_plot_component(self):

        # find longest date
        index_lengths = []
        for stock in self.stocks:
            if stock.stock_data_cache is not None:
                index_lengths.append(len(stock.stock_data_cache['date']))
            else:
                index_lengths.append(len(stock.stock_data['date']))

        index_lengths = np.array(index_lengths)
        lngest = index_lengths.argmax()
        shrtest = index_lengths.argmin()

        index = np.array([
            time.mktime(x.timetuple())
            for x in self.stocks[lngest].dates.tolist()
        ])

        sel_range_low = time.mktime(
            self.stocks[shrtest].dates.tolist()[0].timetuple())
        sel_range_high = time.mktime(
            self.stocks[shrtest].dates.tolist()[-1].timetuple())

        sel_range_low_idx = np.where(index == sel_range_low)[0].item()
        sel_range_high_idx = np.where(index == sel_range_high)[0].item()

        pd = ArrayPlotData()

        # Now plot the returns for each asset (cumulative sum of periodic rates of return)
        for i in range(len(self.stocks)):
            if self.stocks[i].stock_data_cache is None:
                stk = self.stocks[i].stock_data
            else:
                stk = self.stocks[i].stock_data_cache
            pd.set_data(
                "idx%s" % i,
                np.array([
                    time.mktime(x.timetuple()) for x in stk['date'].tolist()
                ]))
            pd.set_data("y%s" % i, metrics.rate_array(stk)['rate'].cumsum())

        plot = Plot(pd,
                    bgcolor="none",
                    padding=30,
                    border_visible=True,
                    overlay_border=True,
                    use_backbuffer=False)

        for i in range(len(self.stocks)):
            # hang on to a reference to the last one of these...
            plt = plot.plot(("idx%s" % i, "y%s" % i),
                            name=self.stocks[i].symbol,
                            color=self.colors[i])

        #value_range = plot.value_mapper.range
        #index_range = plot.index_mapper.range

        plt[0].active_tool = RangeSelection(plt[0], left_button_selects=True)
        plt[0].active_tool.selection = [
            index[sel_range_low_idx], index[sel_range_high_idx]
        ]
        plt[0].overlays.append(RangeSelectionOverlay(component=plt[0]))
        #plot.bgcolor = "white"
        plot.padding = 50
        add_default_grids(plot)

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(
            fill_ratio=0.4,
            default_numlabels=5,
            default_numticks=10,
        )
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = PlotAxis(plot,
                               orientation="bottom",
                               tick_generator=tick_gen,
                               label_color="white",
                               line_color="white")

        # Hack to remove default axis - TODO: how do I *replace* an axis?
        del (plot.underlays[-4])

        plot.overlays.append(bottom_axis)
        plot.legend.visible = True
        return plot
Пример #20
0
    def create_hplot(self, key=None, mini=False):
        if mini:
            hpc = HPlotContainer(bgcolor='darkgrey',
                                 height=MINI_HEIGHT,
                                 resizable='h',
                                 padding=0)
        else:
            hpc = HPlotContainer(bgcolor='lightgrey',
                                 padding=HPLOT_PADDING,
                                 resizable='hv')

        # make slice plot for showing intesity profile of main plot
        #************************************************************
        slice_plot = Plot(self.data,
                          width=SLICE_PLOT_WIDTH,
                          orientation="v",
                          resizable="v",
                          padding=MAIN_PADDING,
                          padding_left=MAIN_PADDING_LEFT,
                          bgcolor='beige',
                          origin='top left')

        slice_plot.x_axis.visible = False
        slice_key = key + '_slice'
        ydata_key = key + '_y'
        slice_plot.plot((ydata_key, slice_key), name=slice_key)

        # make main plot for editing depth lines
        #************************************************************
        main = Plot(
            self.data,
            border_visible=True,
            bgcolor='beige',
            origin='top left',
            padding=MAIN_PADDING,
            padding_left=MAIN_PADDING_LEFT,
        )
        if mini:
            main.padding = MINI_PADDING

        # add intensity img to plot and get reference for line inspector
        #************************************************************
        img_plot = main.img_plot(key,
                                 name=key,
                                 xbounds=self.model.xbounds[key],
                                 ybounds=self.model.ybounds[key],
                                 colormap=self._cmap)[0]

        # add line plots: use method since these may change
        #************************************************************
        self.update_line_plots(key, main, update=True)

        # set slice plot index range to follow main plot value range
        #************************************************************
        slice_plot.index_range = main.value_range

        # add vertical core lines to main plots and slices
        #************************************************************
        # save pos and distance in session dict for view info and control
        for core in self.model.core_samples:
            loc_index, loc, dist = self.model.core_info_dict[core.core_id]
            # add boundarys to slice plot
            ref_line = self.model.final_lake_depth
            self.plot_core_depths(slice_plot, core, ref_line, loc_index)
            # add positions to main plots
            self.plot_core(main, core, ref_line, loc_index, loc)

        # now add tools depending if it is a mini plot or not
        #************************************************************
        if mini:
            # add range selection tool only
            # first add a reference line to attach it to
            reference = self.make_reference_plot()
            main.add(reference)
            # attache range selector to this plot
            range_tool = RangeSelection(reference)
            reference.tools.append(range_tool)
            range_overlay = RangeSelectionOverlay(reference,
                                                  metadata_name="selections")
            reference.overlays.append(range_overlay)
            range_tool.on_trait_change(self._range_selection_handler,
                                       "selection")
            # add zoombox to mini plot
            main.plot(('zoombox_x', 'zoombox_y'),
                      type='polygon',
                      face_color=ZOOMBOX_COLOR,
                      alpha=ZOOMBOX_ALPHA)
            # add to hplot and dict
            hpc.add(main)
            self.hplot_dict['mini'] = hpc

        else:
            # add zoom tools
            main.tools.append(PanTool(main))
            zoom = ZoomTool(main, tool_mode='box', axis='both', alpha=0.5)
            main.tools.append(zoom)
            main.overlays.append(zoom)
            main.value_mapper.on_trait_change(self.zoom_all_value, 'updated')
            main.index_mapper.on_trait_change(self.zoom_all_index, 'updated')
            # add line inspector and attach to freeze tool
            #*********************************************
            line_inspector = LineInspector(component=img_plot,
                                           axis='index_x',
                                           inspect_mode="indexed",
                                           is_interactive=True,
                                           write_metadata=True,
                                           metadata_name='x_slice',
                                           is_listener=True,
                                           color="white")
            img_plot.overlays.append(line_inspector)
            self.inspector_freeze_tool.tool_set.add(line_inspector)

            # add listener for changes to metadata made by line inspector
            #************************************************************
            img_plot.on_trait_change(self.metadata_changed, 'index.metadata')

            # set slice plot index range to follow main plot value range
            #************************************************************
            slice_plot.index_range = main.value_range

            # add clickable legend ; must update legend when depth_dict updated
            #******************************************************************
            legend = Legend(component=main,
                            padding=0,
                            align="ur",
                            font='modern 8')
            legend_highlighter = LegendHighlighter(legend, drag_button="right")
            legend.tools.append(legend_highlighter)
            self.update_legend_plots(legend, main)
            legend.visible = False
            self.legend_dict[key] = [legend, legend_highlighter]
            main.overlays.append(legend)

            # add main and slice plot to hplot container and dict
            #****************************************************
            main.title = 'frequency = {} kHz'.format(key)
            main.title_font = TITLE_FONT
            hpc.add(main, slice_plot)
            self.hplot_dict[key] = hpc

        return hpc
Пример #21
0
def _create_plot_component():
    # Create a scalar field to colormap# Create a scalar field to colormap
    xbounds = (-2 * pi, 2 * pi, 600)
    ybounds = (-1.5 * pi, 1.5 * pi, 300)
    xs = linspace(*xbounds)
    ys = linspace(*ybounds)
    x, y = meshgrid(xs, ys)
    z = jn(2, x) * y * x

    # Create a plot data obect and give it this data
    pd = ArrayPlotData()
    pd.set_data("imagedata", z)

    # Create the plot
    plot = Plot(pd)
    plot.img_plot(
        "imagedata",
        name="my_plot",
        xbounds=xbounds[:2],
        ybounds=ybounds[:2],
        colormap=jet)

    # Tweak some of the plot properties
    plot.title = "Selectable Image Plot"
    plot.padding = 50

    # Right now, some of the tools are a little invasive, and we need the
    # actual CMapImage object to give to them
    my_plot = plot.plots["my_plot"][0]

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot))
    zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
    plot.overlays.append(zoom)

    # Create the colorbar, handing in the appropriate range and colormap
    colormap = my_plot.color_mapper
    colorbar = ColorBar(
        index_mapper=LinearMapper(range=colormap.range),
        color_mapper=colormap,
        plot=my_plot,
        orientation='v',
        resizable='v',
        width=30,
        padding=20)
    colorbar.padding_top = plot.padding_top
    colorbar.padding_bottom = plot.padding_bottom

    # create a range selection for the colorbar
    range_selection = RangeSelection(component=colorbar)
    colorbar.tools.append(range_selection)
    colorbar.overlays.append(
        RangeSelectionOverlay(
            component=colorbar,
            border_color="white",
            alpha=0.8,
            fill_color="lightgray"))

    # we also want to the range selection to inform the cmap plot of
    # the selection, so set that up as well
    range_selection.listeners.append(my_plot)

    # 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 = "lightgray"

    #my_plot.set_value_selection((-1.3, 6.9))

    return container
Пример #22
0
    def _create_plot_component(self):

        # we need the matrices!
        # start with the currently selected one
        #nr_nodes = self.matrix_data_ref[curr_edge].shape[0]

        # Create a plot data obect and give it this data
        self.pd = ArrayPlotData()
        self.pd.set_data("imagedata", self.matrix_data_ref[self.curr_edge])

        # Create the plot
        self.tplot = Plot(self.pd, default_origin="top left")
        self.tplot.x_axis.orientation = "top"
        self.tplot.img_plot(
            "imagedata",
            name="my_plot",
            #xbounds=(0,nr_nodes),
            #ybounds=(0,nr_nodes),
            colormap=jet)

        # Tweak some of the plot properties
        self.tplot.title = self.curr_edge
        self.tplot.padding = 50

        # Right now, some of the tools are a little invasive, and we need the
        # actual CMapImage object to give to them
        self.my_plot = self.tplot.plots["my_plot"][0]

        # Attach some tools to the plot
        self.tplot.tools.append(PanTool(self.tplot))
        zoom = ZoomTool(component=self.tplot, tool_mode="box", always_on=False)
        self.tplot.overlays.append(zoom)

        # my custom tool to get the connection information
        self.custtool = CustomTool(self.tplot)
        self.tplot.tools.append(self.custtool)

        # Create the colorbar, handing in the appropriate range and colormap
        colormap = self.my_plot.color_mapper
        self.colorbar = ColorBar(
            index_mapper=LinearMapper(range=colormap.range),
            color_mapper=colormap,
            plot=self.my_plot,
            orientation='v',
            resizable='v',
            width=30,
            padding=20)

        self.colorbar.padding_top = self.tplot.padding_top
        self.colorbar.padding_bottom = self.tplot.padding_bottom

        # TODO: the range selection gives a Segmentation Fault,
        # but why, the matrix_viewer.py example works just fine!
        # create a range selection for the colorbar
        self.range_selection = RangeSelection(component=self.colorbar)
        self.colorbar.tools.append(self.range_selection)
        self.colorbar.overlays.append(
            RangeSelectionOverlay(component=self.colorbar,
                                  border_color="white",
                                  alpha=0.8,
                                  fill_color="lightgray"))

        # we also want to the range selection to inform the cmap plot of
        # the selection, so set that up as well
        #self.range_selection.listeners.append(self.my_plot)

        # Create a container to position the plot and the colorbar side-by-side
        container = HPlotContainer(use_backbuffer=True)
        container.add(self.tplot)
        container.add(self.colorbar)
        container.bgcolor = "white"

        # my_plot.set_value_selection((-1.3, 6.9))

        return container
Пример #23
0
    def add_range_selector(self, plotid=0, series=0):
        #        plot = self.series[plotid][series]
        plot = self.plots[plotid].plots['plot{}'.format(series)][0]

        plot.active_tool = RangeSelection(plot, left_button_selects=True)
        plot.overlays.append(RangeSelectionOverlay(component=plot))
Пример #24
0
    def __init__(self, **kw):
        super(MLabChacoPlot, self).__init__(**kw)
        
        self.prices = get_data()
        x = self.prices['Date']
        pd = ArrayPlotData(index = x)
        pd.set_data("y", self.prices["Crude Supply"])

        # Create some line plots of some of the data
        plot = Plot(pd, bgcolor="none", padding=30, border_visible=True, 
                     overlay_border=True, use_backbuffer=False)
        #plot.legend.visible = True
        plot.plot(("index", "y"), name="Crude Price", color=(.3, .3, .8, .8))
        #plot.tools.append(PanTool(plot))

        plot.tools.append(PanTool(plot, constrain=True, drag_button="right",
                                  constrain_direction="x"))

        range_plt = plot.plots['Crude Price'][0]

        range_selection = RangeSelection(range_plt, left_button_selects=True)
        range_selection.on_trait_change(self.update_interval, 'selection')
        range_plt.tools.append(range_selection)
        range_plt.overlays.append(RangeSelectionOverlay(range_plt))


        zoom = ZoomTool(component=plot, tool_mode="range", always_on=False,
                        axis="index", max_zoom_out_factor=1.0,)
        plot.overlays.append(zoom)

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(fill_ratio=0.4,
                                        default_numlabels=5,
                                        default_numticks=10,)
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = ScalesPlotAxis(plot, orientation="bottom",
                                     tick_generator=tick_gen,
                                     label_color="white",
                                     line_color="white")

        # Hack to remove default axis - FIXME: how do I *replace* an axis?
        del(plot.underlays[-2])

        plot.overlays.append(bottom_axis)

        # Create the mlab test mesh and get references to various parts of the
        # VTK pipeline
        f = mlab.figure(size=(700,500))
        self.m = mlab.points3d(self.prices['Gasoline Supply'], self.prices['Jet Fuel Supply'], self.prices['Distillate Supply'], self.prices['Crude Supply'])
        
        # Add another glyph module to render the full set of points
        g2 = Glyph()
        g2.glyph.glyph_source.glyph_source.glyph_type = "circle"
        g2.glyph.glyph_source.glyph_source.filled = True
        g2.actor.property.opacity = 0.75
        self.m.module_manager.source.add_module(g2)
        
        # Set a bunch of properties on the scene to make things look right
        self.m.module_manager.scalar_lut_manager.lut_mode = 'PuBuGn'
        self.m.glyph.mask_points.random_mode = False
        self.m.glyph.mask_points.on_ratio = 1
        self.m.scene.isometric_view()
        self.m.scene.background = (.9, 0.95, 1.0)
        
        scene = mlab.gcf().scene
        render_window = scene.render_window
        renderer = scene.renderer
        rwi = scene.interactor

        plot.resizable = ""
        plot.bounds = [600,120]
        plot.padding = 25
        plot.bgcolor = "white"
        plot.outer_position = [30,30]
        plot.tools.append(MoveTool(component=plot,drag_button="right"))

        container = OverlayPlotContainer(bgcolor = "transparent",
                        fit_window = True)
        container.add(plot)

        # Create the Enable Window
        window = EnableVTKWindow(rwi, renderer, 
                component=container,
                istyle_class = tvtk.InteractorStyleTrackballCamera, 
                bgcolor = "transparent",
                event_passthrough = True,
                )

        mlab.show()
Пример #25
0
    def _create_plot_component(self):

        # Create a plot data object and give it this data
        self.pd = ArrayPlotData()
        self.pd.set_data("imagedata", self.data[self.data_name])

        # find dimensions
        xdim = self.data[self.data_name].shape[1]
        ydim = self.data[self.data_name].shape[0]

        # Create the plot
        self.tplot = Plot(self.pd, default_origin="top left")
        self.tplot.x_axis.orientation = "top"
        self.tplot.img_plot("imagedata",
                            name="my_plot",
                            xbounds=(0.5, xdim + 0.5),
                            ybounds=(0.5, ydim + 0.5),
                            colormap=jet)

        # Tweak some of the plot properties
        self.tplot.title = "Connection Matrix for %s" % self.data_name
        self.tplot.padding = 80

        # Right now, some of the tools are a little invasive, and we need the
        # actual CMapImage object to give to them
        self.my_plot = self.tplot.plots["my_plot"][0]

        # Attach some tools to the plot
        self.tplot.tools.append(PanTool(self.tplot))
        zoom = ZoomTool(component=self.tplot, tool_mode="box", always_on=False)
        self.tplot.overlays.append(zoom)

        # my custom tool to get the connection information
        self.custtool = CustomTool(self.tplot)
        self.tplot.tools.append(self.custtool)

        # Create the colorbar, handing in the appropriate range and colormap
        colormap = self.my_plot.color_mapper
        self.colorbar = ColorBar(
            index_mapper=LinearMapper(range=colormap.range),
            color_mapper=colormap,
            plot=self.my_plot,
            orientation='v',
            resizable='v',
            width=30,
            padding=20)

        self.colorbar.padding_top = self.tplot.padding_top
        self.colorbar.padding_bottom = self.tplot.padding_bottom

        # create a range selection for the colorbar
        self.range_selection = RangeSelection(component=self.colorbar)
        self.colorbar.tools.append(self.range_selection)
        self.colorbar.overlays.append(
            RangeSelectionOverlay(component=self.colorbar,
                                  border_color="white",
                                  alpha=0.8,
                                  fill_color="lightgray"))

        # we also want to the range selection to inform the cmap plot of
        # the selection, so set that up as well
        self.range_selection.listeners.append(self.my_plot)

        # Create a container to position the plot and the colorbar side-by-side
        container = HPlotContainer(use_backbuffer=True)
        container.add(self.tplot)
        container.add(self.colorbar)
        container.bgcolor = "white"

        return container
Пример #26
0
def create_timechart_container(project):
    """ create a vplotcontainer which connects all the inside plots to synchronize their index_range """

    # find index limits
    low = 1 << 64
    high = 0
    for i in range(len(project.c_states)):
        if len(project.c_states[i].start_ts):
            low = min(low, project.c_states[i].start_ts[0])
            high = max(high, project.c_states[i].end_ts[-1])
        if len(project.p_states[i].start_ts):
            low = min(low, project.p_states[i].start_ts[0])
            high = max(high, project.p_states[i].start_ts[-1])
    for tc in project.processes:
        if len(tc.start_ts):
            low = min(low, tc.start_ts[0])
            high = max(high, tc.end_ts[-1])
    project.process_stats(low, high)
    if low > high:
        low = 0
        high = 1
    # we have the same x_mapper/range for each plots
    index_range = DataRange1D(low=low, high=high)
    index_mapper = LinearMapper(range=index_range, domain_limit=(low, high))
    value_range = DataRange1D(low=0,
                              high=project.num_cpu * 2 + project.num_process)
    value_mapper = LinearMapper(range=value_range,
                                domain_limit=(0, project.num_cpu * 2 +
                                              project.num_process))
    index = ArrayDataSource(array((low, high)), sort_order="ascending")
    plot = tcPlot(index=index,
                  proj=project,
                  bgcolor="white",
                  padding=(0, 0, 0, 40),
                  use_backbuffer=True,
                  fill_padding=True,
                  value_mapper=value_mapper,
                  index_mapper=index_mapper,
                  line_color="black",
                  render_style='hold',
                  line_width=1)
    plot.lowest_i = low
    plot.highest_i = high
    project.on_trait_change(plot.invalidate, "plot_redraw")
    project.on_trait_change(plot.invalidate, "selected")
    max_process = 50
    if value_range.high > max_process:
        value_range.low = value_range.high - max_process
    # Attach some tools
    plot.tools.append(tools.myPanTool(plot, drag_button='left'))
    zoom = tools.myZoomTool(component=plot,
                            tool_mode="range",
                            always_on=True,
                            axis="index",
                            drag_button=None,
                            zoom_to_mouse=True,
                            x_max_zoom_factor=float("inf"),
                            x_min_zoom_factor=float("-inf"))
    plot.tools.append(zoom)

    plot.range_selection = tools.myRangeSelection(plot, resize_margin=3)
    plot.tools.append(plot.range_selection)
    plot.overlays.append(
        RangeSelectionOverlay(component=plot,
                              axis="index",
                              use_backbuffer=True))

    axe = PlotAxis(orientation='bottom',
                   title='time',
                   mapper=index_mapper,
                   component=plot)
    plot.underlays.append(axe)
    plot.options.connect(plot)
    plot.range_tools.connect(plot)
    return plot
Пример #27
0
    def __init__(self, **kwtraits):
        super(ResultExplorer, self).__init__(**kwtraits)
        # containers
        bgcolor = "sys_window"  #(212/255.,208/255.,200/255.) # Windows standard background
        self.plot_container = container = VPlotContainer(use_backbuffer=True,
                                                         padding=0,
                                                         fill_padding=False,
                                                         valign="center",
                                                         bgcolor=bgcolor)
        subcontainer = HPlotContainer(use_backbuffer=True,
                                      padding=0,
                                      fill_padding=False,
                                      halign="center",
                                      bgcolor=bgcolor)
        # freqs
        self.synth = FreqSelector(parent=self)
        # data source
        self.plot_data = pd = ArrayPlotData()
        self.set_result_data()
        self.set_pict()
        # map plot
        self.map_plot = Plot(pd, padding=40)
        self.map_plot.img_plot("image", name="image")
        imgp = self.map_plot.img_plot("map_data", name="map", colormap=jet)[0]
        self.imgp = imgp
        t1 = self.map_plot.plot(("xpoly", "ypoly"),
                                name="sector",
                                type="polygon")
        t1[0].face_color = (0, 0, 0, 0)  # set face color to transparent
        # map plot tools and overlays
        imgtool = ImageInspectorTool(imgp)
        imgp.tools.append(imgtool)
        overlay = ImageInspectorOverlay(component=imgp,
                                        image_inspector=imgtool,
                                        bgcolor="white",
                                        border_visible=True)
        self.map_plot.overlays.append(overlay)
        self.zoom = RectZoomSelect(self.map_plot,
                                   drag_button='right',
                                   always_on=True,
                                   tool_mode='box')
        self.map_plot.overlays.append(self.zoom)
        self.map_plot.tools.append(PanTool(self.map_plot))
        # colorbar
        colormap = imgp.color_mapper
        self.drange = colormap.range
        self.drange.low_setting = "track"
        self.colorbar = cb = ColorBar(
            index_mapper=LinearMapper(range=colormap.range),
            color_mapper=colormap,
            plot=self.map_plot,
            orientation='v',
            resizable='v',
            width=10,
            padding=20)
        # colorbar tools and overlays
        range_selection = RangeSelection(component=cb)
        cb.tools.append(range_selection)
        cb.overlays.append(
            RangeSelectionOverlay(component=cb,
                                  border_color="white",
                                  alpha=0.8,
                                  fill_color=bgcolor))
        range_selection.listeners.append(imgp)
        # spectrum plot
        self.spec_plot = Plot(pd, padding=25)
        px = self.spec_plot.plot(("freqs", "spectrum"),
                                 name="spectrum",
                                 index_scale="log")[0]
        self.yrange = self.spec_plot.value_range
        px.index_mapper = MyLogMapper(range=self.spec_plot.index_range)
        # spectrum plot tools
        self.cursor = CursorTool(
            px)  #, drag_button="left", color='blue', show_value_line=False)
        px.overlays.append(self.cursor)
        self.cursor.current_position = 0.3, 0.5
        px.index_mapper.map_screen(0.5)
        #        self.map_plot.tools.append(SaveTool(self.map_plot, filename='pic.png'))

        # layout
        self.set_map_details()
        self.reset_sector()
        subcontainer.add(self.map_plot)
        subcontainer.add(self.colorbar)
        #        subcontainer.tools.append(SaveTool(subcontainer, filename='pic.png'))
        container.add(self.spec_plot)
        container.add(subcontainer)
        container.tools.append(SaveTool(container, filename='pic.pdf'))
        self.last_valid_digest = self.Beamformer.ext_digest