Exemple #1
0
def _do_plot_boilerplate(kwargs, image=False):
    """ Used by various plotting functions.  Checks/handles hold state,
    returns a Plot object for the plotting function to use.
    """

    if "hold" in kwargs:
        hold(kwargs["hold"])
        del kwargs["hold"]

    # Check for an active window; if none, open one.
    if len(session.windows) == 0:
        if image:
            win = session.new_window(is_image=True)
            activate(win)
        else:
            figure()

    cont = session.active_window.get_container()

    if not cont:
        cont = Plot(session.data)
        session.active_window.set_container(cont)

    existing_tools = [type(t) for t in (cont.tools + cont.overlays)]
    if not PanTool in existing_tools:
        cont.tools.append(PanTool(cont))
    if not ZoomTool in existing_tools:
        cont.overlays.append(ZoomTool(cont, tool_mode="box", always_on=True, drag_button="right"))

    if not session.hold:
        cont.delplot(*list(cont.plots.keys()))

    return cont
Exemple #2
0
    def test_selection_mask(self):

        plot_data = ArrayPlotData()
        plot = Plot(plot_data)
        arr = np.array([-2, -1, 1, 2])
        plot_data.set_data("x", arr)
        plot_data.set_data("y", arr)
        splot = plot.plot(('x', 'y'), type='scatter')[0]
        tool = RectangularSelection(
            component=splot,
            selection_datasource=splot.index,
            metadata_name='selections',
        )
        splot.tools.append(tool)

        # Set the cursor start and stop positions to be such
        # that the middle two points of the four possible are selected.
        cursor_start = splot.map_screen([-1.5, -1.5])[0]
        cursor_stop = splot.map_screen([1.5, 1.5])[0]

        self.mouse_down(interactor=tool, x=cursor_start[0], y=cursor_start[1])

        self.mouse_move(interactor=tool, x=cursor_stop[0], y=cursor_stop[1])

        self.mouse_up(interactor=tool, x=cursor_stop[0], y=cursor_stop[1])

        expected_mask = [False, True, True, False]
        selection_mask = list(splot.index.metadata['selections'])
        self.assertEqual(expected_mask, selection_mask)
    def _view_expression_fired(self):
        context_adapter = PlotDataContextAdapter(context=self.expression_context)

        plot = Plot(context_adapter)
        plot.plot((self.index_expression, self.value_expression))
        self.plots.add(plot)
        self.plots.request_redraw()
        return
    def load(self):
        data = ArrayPlotData()
        p = Plot(data=data, padding=100)
        X = linspace(0, 2 * pi)
        data.set_data('x0', X)
        data.set_data('y0', cos(X))

        p.plot(('x0', 'y0'))
        self.container.add(p)
Exemple #5
0
    def load(self):
        data = ArrayPlotData()
        p = Plot(data=data, padding=100)
        X = linspace(0, 2 * pi)
        data.set_data('x0', X)
        data.set_data('y0', cos(X))

        p.plot(('x0', 'y0'))
        self.container.add(p)
    def _view_expression_fired(self):
        context_adapter = PlotDataContextAdapter(
            context=self.expression_context)

        plot = Plot(context_adapter)
        plot.plot((self.index_expression, self.value_expression))
        self.plots.add(plot)
        self.plots.request_redraw()
        return
    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
Exemple #8
0
    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
Exemple #9
0
    def cmap_plot(self, z):
        from chaco.array_plot_data import ArrayPlotData
        from chaco.plot import Plot
        from chaco.default_colormaps import color_map_name_dict

        pd = ArrayPlotData()
        pd.set_data("cmapdata", z)

        p = Plot(pd, padding=0)
        p.img_plot("cmapdata", xbounds=(-25, 25), ybounds=(-25, 25), colormap=color_map_name_dict["hot"])
        self.add(p)
        return pd
Exemple #10
0
    def setup_images(self, n, wh):
        self.container._components = []
        self.plotdata = plotdata = ArrayPlotData()
        for i in range(n):
            plot = Plot(plotdata, padding=0, default_origin="top left")

            name = 'imagedata{:03d}'.format(i)
            plotdata.set_data(name, ones(wh))

            plot.img_plot(name, colormap=hot)
            self.container.add(plot)

        self.container.request_redraw()
Exemple #11
0
    def setup_images(self, n, wh):
        self.container._components = []
        self.plotdata = plotdata = ArrayPlotData()
        for i in range(n):
            plot = Plot(plotdata, padding=0, default_origin="top left")

            name = 'imagedata{:03d}'.format(i)
            plotdata.set_data(name, ones(wh))

            plot.img_plot(name, colormap=hot)
            self.container.add(plot)

        self.container.request_redraw()
Exemple #12
0
def plotFFT(widget):
    """ Determine fft of signals in selected widget """
    print("plotFFT")

    model = ""
    for (modelNumber, modelName, variableName), data in widget.getData():
        # print "var:", var, "data: ", data
        minVal = (0, float("inf"))
        maxVal = (0, float("-inf"))
        # for time, value in data:

    # Get data from data array:
    time = numpy.array(list((x for x, _ in data)))  # data[0]
    values = numpy.array(list((x for _, x in data)))

    (Tmin, Tmax, N) = getFFTtimeRange(time)
    (timeInRange, valuesInRange) = getValuesInRange(time, values, Tmin, Tmax)

    # Compute fft: A=A(f)
    (f, A) = fft(timeInRange, valuesInRange, N)

    # Open new plot tab:
    import plotWidget
    window = widget.createNewWindow()
    container = plotWidget.plotContainer(window)
    plotWidget = plotWidget.PlotWidget(container)
    container.setPlotWidget(plotWidget)

    # Create the plot
    plotdata = ArrayPlotData(x=f,
                             y=A,
                             border_visible=True,
                             overlay_border=True)
    plot = Plot(plotdata, title="FFT")  # Plot(plotdata, title="FFT")
    barPlot = plot.plot(("x", "y"), type="bar", bar_width=0.1, color="blue")[0]
    # scatterPlot = plot.plot(("x", "y"), type="scatter", color="blue")[0]

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot))
    plot.overlays.append(ZoomTool(plot))

    # Activate Plot:
    plotWidget.setPlot(plot)
    container.setPlotWidget(plotWidget)

    layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom)
    layout.addWidget(container)
    window.setLayout(layout)
    window.show()
Exemple #13
0
    def cmap_plot(self, z):
        from chaco.array_plot_data import ArrayPlotData
        from chaco.plot import Plot
        from chaco.default_colormaps import color_map_name_dict

        pd = ArrayPlotData()
        pd.set_data('cmapdata', z)

        p = Plot(pd, padding=0)
        p.img_plot('cmapdata',
                   xbounds=(-25, 25),
                   ybounds=(-25, 25),
                   colormap=color_map_name_dict['hot'])
        self.add(p)
        return pd
Exemple #14
0
def plotFFT(widget):
    """ Determine fft of signals in selected widget """
    print("plotFFT")

    model = ""
    for (modelNumber, modelName, variableName), data in widget.getData():
        # print "var:", var, "data: ", data
        minVal = (0, float("inf"))
        maxVal = (0, float("-inf"))
        # for time, value in data:

    # Get data from data array:
    time = numpy.array(list((x for x, _ in data)))  # data[0]
    values = numpy.array(list((x for _ , x in data)))

    (Tmin, Tmax, N) = getFFTtimeRange(time)
    (timeInRange, valuesInRange) = getValuesInRange(time, values, Tmin, Tmax)

    # Compute fft: A=A(f)
    import Algorithms
    (f, A) = Algorithms.fft(timeInRange, valuesInRange, N)


    # Open new plot tab:
    import plotWidget
    window = widget.createNewWindow()
    container = plotWidget.plotContainer(window)
    plotWidget = plotWidget.PlotWidget(container)
    container.setPlotWidget(plotWidget)

    # Create the plot
    plotdata = ArrayPlotData(x=f, y=A, border_visible=True, overlay_border=True)
    plot = Plot(plotdata, title="FFT")  # Plot(plotdata, title="FFT")
    barPlot = plot.plot(("x", "y"), type="bar", bar_width=0.1, color="blue")[0]
    # scatterPlot = plot.plot(("x", "y"), type="scatter", color="blue")[0]

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot))
    plot.overlays.append(ZoomTool(plot))

    # Activate Plot:
    plotWidget.setPlot(plot)
    container.setPlotWidget(plotWidget)

    layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom)
    layout.addWidget(container)
    window.setLayout(layout)
    window.show()
Exemple #15
0
    def test_selection_no_warning(self):
        plot_data = ArrayPlotData()
        arr = np.arange(4)
        plot_data.set_data("x", arr)
        plot_data.set_data("y", arr)
        plot = Plot(plot_data)
        renderer = plot.plot(('x', 'y'))[0]
        tool = RangeSelection(renderer)
        with warnings.catch_warnings(record=True) as w:
            tool.selection = np.array([2.0, 3.0])
        self.assertEqual(w, [])

        # Accept tuples and lists and None
        tool.selection = (1.5, 3.5)
        tool.selection = [1.0, 2.0]
        tool.selection = None
Exemple #16
0
    def _theta_plot_default(self):

        theta = self.theta
        nclasses = theta.shape[0]

        # create a plot data object and give it this data
        plot_data = ArrayPlotData()

        plot_data.set_data('classes', list(range(nclasses)))

        # create the plot
        plot = Plot(plot_data)

        # --- plot theta samples
        if self.theta_samples is not None:
            self._plot_samples(plot, plot_data)

        # --- plot values of theta
        plots = self._plot_theta_values(plot, plot_data)

        # --- adjust plot appearance

        plot.aspect_ratio = 1.6 if is_display_small() else 1.7

        # adjust axis bounds
        y_high = theta.max()
        if self.theta_samples is not None:
            y_high = max(y_high, self.theta_samples.max())

        plot.range2d = DataRange2D(low=(-0.2, 0.0),
                                   high=(nclasses - 1 + 0.2, y_high * 1.1))

        # create new horizontal axis
        label_axis = self._create_increment_one_axis(plot, 0., nclasses,
                                                     'bottom')
        label_axis.title = 'True classes'
        self._add_index_axis(plot, label_axis)

        # label vertical axis
        plot.value_axis.title = 'Probability'

        # add legend
        legend = Legend(component=plot,
                        plots=plots,
                        align="ur",
                        border_padding=10)
        legend.tools.append(LegendTool(legend, drag_button="left"))
        legend.padding_right = -100
        plot.overlays.append(legend)

        container = VPlotContainer(width=plot.width + 100, halign='left')
        plot.padding_bottom = 50
        plot.padding_top = 10
        plot.padding_left = 0
        container.add(plot)
        container.bgcolor = 0xFFFFFF

        self.decorate_plot(container, theta)

        return container
 def __init__(self):
     super(SLM_UI, self).__init__()
     filename = os.path.join(os.path.dirname(__file__), 'slm3995_at1064_P8.lut')
     slm.lut(filename)
     
     self.focus = 0
     self.spherical = 0
     self.a = 1
     
     x = arange(512)
     self.x, self.y = meshgrid(x, x)
     self.r2 = (self.x - 256.)**2 + (self.y - 256.)**2
     self.r4 = self.r2**2
     self.plotdata = ArrayPlotData(x=self.x, y=self.y)
     self.calculate()
     plot = Plot(self.plotdata)
     plot.img_plot('series1', colormap=jet)
     self.plot = plot
Exemple #18
0
    def test_selecting_mouse_leave_clipping(self):
        # Regression test for #216.
        plot_data = ArrayPlotData()
        arr = np.arange(4.0)
        plot_data.set_data("x", arr)
        plot_data.set_data("y", arr)

        for origin in ('bottom left', 'top left', 'bottom right', 'top right'):
            for orientation in ('h', 'v'):
                for axis in ('index', 'value'):
                    plot = Plot(plot_data,
                                orientation=orientation,
                                origin='top right')

                    renderer = plot.plot(('x', 'y'))[0]
                    renderer.bounds = [10, 20]
                    tool = RangeSelection(
                        renderer,
                        left_button_selects=True,
                        axis=axis,
                    )
                    renderer.tools.append(tool)

                    low_x, low_y = plot.position
                    high_x = low_x + renderer.bounds[0] - 1
                    high_y = low_y + renderer.bounds[1] - 1

                    cx = 5
                    cy = 5

                    bounds = (
                        (low_x - 1, low_y),
                        (high_x + 1, low_y),
                        (low_x, low_y - 1),
                        (low_x, high_y + 1),
                    )
                    for x, y in bounds:
                        self.mouse_down(tool, x=cx, y=cy)
                        self.mouse_leave(tool, x=x, y=y)
                        selection = tool.selection
                        self.assertTrue(selection[0] <= selection[1])
                        self.mouse_up(tool, x=x, y=y)
    def test_selection_no_warning(self):
        plot_data = ArrayPlotData()
        arr = np.arange(4)
        plot_data.set_data("x", arr)
        plot_data.set_data("y", arr)
        plot = Plot(plot_data)
        renderer = plot.plot(('x', 'y'))[0]
        tool = RangeSelection(renderer)
        with warnings.catch_warnings(record=True) as w:
            # Ignore warnings coming from Traits
            warnings.filterwarnings("ignore",
                                    'elementwise == comparison failed')
            tool.selection = np.array([2.0, 3.0])

        self.assertEqual(w, [])

        # Accept tuples and lists and None
        tool.selection = (1.5, 3.5)
        tool.selection = [1.0, 2.0]
        tool.selection = None
    def _theta_plot_default(self):

        theta = self.theta
        nclasses = theta.shape[0]

        # create a plot data object and give it this data
        plot_data = ArrayPlotData()

        plot_data.set_data('classes', range(nclasses))

        # create the plot
        plot = Plot(plot_data)

        # --- plot theta samples
        if self.theta_samples is not None:
            self._plot_samples(plot, plot_data)

        # --- plot values of theta
        plots = self._plot_theta_values(plot, plot_data)

        # --- adjust plot appearance

        plot.aspect_ratio = 1.6 if is_display_small() else 1.7

        # adjust axis bounds
        y_high = theta.max()
        if self.theta_samples is not None:
            y_high = max(y_high, self.theta_samples.max())

        plot.range2d = DataRange2D(
            low  = (-0.2, 0.0),
            high = (nclasses-1+0.2, y_high*1.1)
        )

        # create new horizontal axis
        label_axis = self._create_increment_one_axis(
            plot, 0., nclasses, 'bottom')
        label_axis.title = 'True classes'
        self._add_index_axis(plot, label_axis)

        # label vertical axis
        plot.value_axis.title = 'Probability'

        # add legend
        legend = Legend(component=plot, plots=plots,
                        align="ur", border_padding=10)
        legend.tools.append(LegendTool(legend, drag_button="left"))
        legend.padding_right = -100
        plot.overlays.append(legend)

        container = VPlotContainer(width=plot.width + 100, halign='left')
        plot.padding_bottom = 50
        plot.padding_top = 10
        plot.padding_left = 0
        container.add(plot)
        container.bgcolor = 0xFFFFFF

        self.decorate_plot(container, theta)

        return container
    def test_selecting_mouse_leave_clipping(self):
        # Regression test for #216.
        plot_data = ArrayPlotData()
        arr = np.arange(4.0)
        plot_data.set_data("x", arr)
        plot_data.set_data("y", arr)

        for origin in ('bottom left', 'top left', 'bottom right', 'top right'):
            for orientation in ('h', 'v'):
                for axis in ('index', 'value'):
                    plot = Plot(
                        plot_data, orientation=orientation, origin='top right'
                    )

                    renderer = plot.plot(('x', 'y'))[0]
                    renderer.bounds = [10, 20]
                    tool = RangeSelection(
                        renderer, left_button_selects=True, axis=axis,
                    )
                    renderer.tools.append(tool)

                    low_x, low_y = plot.position
                    high_x = low_x + renderer.bounds[0] - 1
                    high_y = low_y + renderer.bounds[1] - 1

                    cx = 5
                    cy = 5

                    bounds = (
                        (low_x - 1, low_y),
                        (high_x + 1, low_y),
                        (low_x, low_y - 1),
                        (low_x, high_y + 1),
                    )
                    for x, y in bounds:
                        self.mouse_down(tool, x=cx, y=cy)
                        self.mouse_leave(tool, x=x, y=y)
                        selection = tool.selection
                        self.assertTrue(selection[0] <= selection[1])
                        self.mouse_up(tool, x=x, y=y)
    def test_selection_no_warning(self):
        plot_data = ArrayPlotData()
        arr = np.arange(4)
        plot_data.set_data("x", arr)
        plot_data.set_data("y", arr)
        plot = Plot(plot_data)
        renderer = plot.plot(('x', 'y'))[0]
        tool = RangeSelection(renderer)
        with warnings.catch_warnings(record=True) as w:
            # Ignore warnings coming from any package other than Chaco
            warnings.filterwarnings(
                "ignore",
                module="(?!chaco)",
            )
            tool.selection = np.array([2.0, 3.0])

        self.assertEqual(w, [])

        # Accept tuples and lists and None
        tool.selection = (1.5, 3.5)
        tool.selection = [1.0, 2.0]
        tool.selection = None
Exemple #23
0
    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 _default_plot(self):
        global Plot, PanTool, ZoomTool, LegendTool
        if Plot==None:
            from chaco.plot import Plot
        if PanTool==None or ZoomTool==None or LegendTool==None:
            from chaco.tools.api import PanTool, ZoomTool,  LegendTool #, LineInspector

        plot=Plot(self.pd, padding=50, fill_padding=True,
                        bgcolor="white", use_backbuffer=True,  unified_draw=True)#, use_downsampling=True)
        plot.tools.append(PanTool(plot, constrain_key="shift"))
        plot.overlays.append(ZoomTool(component=plot, tool_mode="box", always_on=False))
        plot.legend.tools.append(LegendTool(plot.legend, drag_button="right"))
        return plot
    def test_restrict_to_data_with_empty_source(self):
        # Regression test for #214.
        plot_data = ArrayPlotData()
        plot = Plot(plot_data)
        arr = np.arange(4.0)
        plot_data.set_data("x", arr)
        plot_data.set_data("y", arr)
        plot_data.set_data("z", np.array([], np.float64))
        plot.plot(('x', 'y'))
        plot.plot(('z', 'z'))
        tool = PanTool(plot, restrict_to_data=True)
        plot.tools.append(tool)

        x_range = plot.x_mapper.range
        y_range = plot.y_mapper.range

        x_bounds = (x_range.low, x_range.high)
        y_bounds = (y_range.low, y_range.high)
        self.mouse_down(tool, 0.0, 0.0)
        self.mouse_move(interactor=tool, x=1.0, y=1.0)
        self.mouse_up(interactor=tool, x=1.0, y=1.0)
        self.assertEqual((x_range.low, x_range.high), x_bounds)
        self.assertEqual((y_range.low, y_range.high), y_bounds)
    def test_restrict_to_data_with_empty_source(self):
        # Regression test for #214.
        plot_data = ArrayPlotData()
        plot = Plot(plot_data)
        arr = np.arange(4.0)
        plot_data.set_data("x", arr)
        plot_data.set_data("y", arr)
        plot_data.set_data("z", np.array([], np.float64))
        plot.plot(('x', 'y'))
        plot.plot(('z', 'z'))
        tool = PanTool(plot, restrict_to_data=True)
        plot.tools.append(tool)

        x_range = plot.x_mapper.range
        y_range = plot.y_mapper.range

        x_bounds = (x_range.low, x_range.high)
        y_bounds = (y_range.low, y_range.high)
        self.mouse_down(tool, 0.0, 0.0)
        self.mouse_move(interactor=tool, x=1.0, y=1.0)
        self.mouse_up(interactor=tool, x=1.0, y=1.0)
        self.assertEqual((x_range.low, x_range.high), x_bounds)
        self.assertEqual((y_range.low, y_range.high), y_bounds)
Exemple #27
0
    def normal_left_dclick(self, event):
        plot = Plot(self.data)
        for data, kw in self.command_queue:
            plot.plot(data, **kw)
            plot.title = self.title

        plot.title = self.title
        container = VPlotContainer(bgcolor=WindowColor)
        container.add(plot)
        plot.tools.append(PanTool(plot))
        plot.overlays.append(ZoomTool(plot))
        window = PlotWindow(plot=container)
        window.edit_traits(kind='live', parent=event.window.control)
def plotEigenvalues(model, gui):
    ''' This function calculates the linearization of model as well as additional information
        (eigenvalues, damping ...) if this was not done before.
        It opens a new plotting tab and displays this information
    '''
    if model is None:
        print("No model selected!")
        return

    # Check if already linearized, do so otherwise:
    try:
        data = model.pluginData["EigenvalueAnalysis"]
    except:
        print "Performing linearization"
        data = EigenvalueAnalysis()
        data._performLinearization(model)
        model.pluginData["EigenvalueAnalysis"] = data


    # Open new plotting tab:
    parent = QtGui.QApplication.activeWindow()
    widgetContainer = parent._newPlotContainer()
    widget = widgetContainer.activeWidget

    # Plot the data:
    x = numpy.real(data.eigenvalues[:])
    y = numpy.imag(data.eigenvalues[:])
    plotdata = ArrayPlotData(x=x, y=y, border_visible=True, overlay_border=True)
    plot = Plot(plotdata, title="Eigenvalues of %s" % data.modelName)
    scatter = plot.plot(("x", "y"), type="scatter", color="blue")[0]

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot))
    plot.overlays.append(ZoomTool(plot))

    # Add axis titles:
    x_axis = PlotAxis(orientation="bottom")
    x_axis.mapper = plot.index_mapper
    x_axis.title = "real part"
    plot.underlays.append(x_axis)
    y_axis = PlotAxis(orientation="left")
    y_axis.mapper = plot.value_mapper
    y_axis.title = "imag. part"
    plot.underlays.append(y_axis)

    # Attach the inspector and its overlay
    scatter.tools.append(ScatterInspector(scatter))
    overlay = myScatterInspectorOverlay(scatter,
                    hover_color="red",
                    hover_marker_size=6,
                    selection_marker_size=6,
                    selection_color="yellow",
                    selection_outline_color="purple",
                    selection_line_width=3,
                    stateNames=data.StateNames,
                    eigenVectors=data.eigenvectors,
                    frequencies=data.frequencies,
                    damping=data.damping,
                    observability=data.observability,
                    controllability=data.controllability)
    scatter.overlays.append(overlay)
    # Activate Plot:
    widget.setPlot(plot)
    widgetContainer.activeWidget = widget
    def create_plot(self):
        if hasattr(self.value, 'shadows'):
            color_gen = color_generator()
            shadowcolors = {}
            for shadow in self.value.shadows:
                shadowcolors[shadow] = color_gen.next()

        container_class = {
            'h': HPlotContainer,
            'v': VPlotContainer
        }[self.orientation]
        container = container_class(spacing=15,
                                    padding=15,
                                    bgcolor='transparent')
        container.fill_padding = True
        container.bgcolor = (236 / 255.0, 233 / 255.0, 216 / 255.0)

        if self.show_all:
            self.plot_items = self.value.keys()

        if len(self.plot_items) > 0:
            plot_configs = []
            for (plot_num, var_name) in enumerate(self.plot_items):
                if not (isinstance(self.value[var_name], ndarray) and \
                        len(self.value[var_name].shape) == 1):
                    continue
                plot_configs.append(
                    PlotConfig(x=var_name + '_index',
                               y=var_name,
                               type='Line',
                               number=plot_num))
            self.plot_configs = plot_configs

        if len(self.plot_configs) > 0:
            number_to_plots = {}
            for plot_config in self.plot_configs:
                plotlist = number_to_plots.get(plot_config.number, [])
                plotlist.append(plot_config)
                number_to_plots[plot_config.number] = plotlist

            keys = number_to_plots.keys()
            keys.sort()
            container_list = [number_to_plots[number] for number in keys]

            for plot_group in container_list:
                context_adapter = PlotDataContextAdapter(context=self.value)
                plot = Plot(context_adapter)
                plot.padding = 15
                plot.padding_left = 35
                plot.padding_bottom = 30
                plot.spacing = 15
                plot.border_visible = True
                for plot_item in plot_group:
                    if len(self.value[plot_item.y].shape) == 2:
                        color_range = DataRange1D(
                            low=min(self.value[plot_item.y]),
                            high=max(self.value[plot_item.y]))
                        plot.img_plot(plot_item.y,
                                      colormap=gray(color_range),
                                      name=plot_item.y)

                    else:
                        plot_type = {
                            'Line': 'line',
                            'Scatter': 'scatter'
                        }[plot_item.type]
                        plot.plot(
                            (plot_item.x, plot_item.y),
                            name=plot_item.x + " , " + plot_item.y,
                            color=(.7, .7, .7),
                            type=plot_type,
                        )
                        if plot.index_axis.title != '':
                            plot.index_axis.title = plot.index_axis.title + ', ' + plot_item.x
                        else:
                            plot.index_axis.title = plot_item.x

                        if plot.value_axis.title != '':
                            plot.value_axis.title = plot.value_axis.title + ', ' + plot_item.y
                        else:
                            plot.value_axis.title = plot_item.y

                        if self.view_shadows and hasattr(
                                self.value, 'shadows'):
                            self.generate_shadow_plots(plot, shadowcolors,
                                                       plot_item, plot_type)

                plot.tools.append(PanTool(plot))
                container.add(plot)

        self.plot = container
Exemple #30
0
    def initialize_plot(self):
        data = self.data_model

        container = self.plot_container
        self._series = []
        self._plots = {}
        index, rr = None, None
        for i, (a, title) in enumerate((
            ('water_head', 'Head'),
            ('adjusted_water_head', 'Adj. Head'),

                # ('temp', 'Temp.'),
                # ('water_level_elevation', 'Elev.')
        )):
            plot = Plot(
                data=ArrayPlotData(**{
                    'x': data.x,
                    a: getattr(data, a)
                }),
                padding=[70, 10, 10, 10],
                # resizable='h',
                # bounds=(1, 125)
            )

            if index is None:
                index = plot.index_mapper
                rr = plot.index_range
            else:
                plot.index_mapper = index
                plot.index_range = rr

            series = plot.plot(('x', a))[0]
            plot.plot(('x', a), marker_size=1.5, type='scatter')

            dt = DataTool(plot=series,
                          component=plot,
                          normalize_time=False,
                          use_date_str=True)
            dto = DataToolOverlay(component=series, tool=dt)
            series.tools.append(dt)
            series.overlays.append(dto)

            plot.y_axis.title = title
            if i != 0:
                plot.x_axis.visible = False
            else:

                zoom = ZoomTool(plot,
                                tool_mode="range",
                                axis='index',
                                color=(0, 1, 0, 0.5),
                                enable_wheel=False,
                                always_on=False)
                plot.overlays.append(zoom)

                tool = RangeSelection(series,
                                      left_button_selects=True,
                                      listeners=[self])
                self._tool = tool

                series.tools.append(tool)
                # series.active_tool = tool
                # plot.x_axis.title = 'Time'
                bottom_axis = PlotAxis(
                    plot,
                    orientation="bottom",  # mapper=xmapper,
                    tick_generator=ScalesTickGenerator(
                        scale=CalendarScaleSystem()))
                plot.x_axis = bottom_axis

                plot.padding_bottom = 50

            series.overlays.append(RangeSelectionOverlay(component=series))
            container.add(plot)
            self._series.append(series)
            self._plots[a] = plot

        container.invalidate_and_redraw()
    def _plot_container_default(self):
        data = self.posterior
        nannotations, nclasses = data.shape

        # create a plot data object
        plot_data = ArrayPlotData()
        plot_data.set_data("values", data)

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

        img_plot = plot.img_plot("values",
                                 interpolation='nearest',
                                 xbounds=(0, nclasses),
                                 ybounds=(0, nannotations),
                                 colormap=self._create_colormap())[0]
        ndisp = 55
        img_plot.y_mapper.range.high = ndisp
        img_plot.y_mapper.domain_limits=((0, nannotations))

        self._set_title(plot)
        plot.padding_top = 80

        # create x axis for labels
        label_axis = self._create_increment_one_axis(plot, 0.5, nclasses, 'top')
        label_axis.title = 'classes'
        self._add_index_axis(plot, label_axis)

        plot.y_axis.title = 'items'

        # tweak plot aspect
        goal_aspect_ratio = 2.0
        plot_width = (goal_aspect_ratio * self.plot_height
                      * nclasses / ndisp)
        self.plot_width = min(max(plot_width, 200), 400)
        plot.aspect_ratio = self.plot_width / self.plot_height

        # add colorbar
        colormap = img_plot.color_mapper
        colorbar = ColorBar(index_mapper = LinearMapper(range=colormap.range),
                            color_mapper = colormap,
                            plot = img_plot,
                            orientation = 'v',
                            resizable = '',
                            width = 15,
                            height = 250)
        colorbar.padding_top = plot.padding_top
        colorbar.padding_bottom = int(self.plot_height - colorbar.height -
                                      plot.padding_top)
        colorbar.padding_left = 0
        colorbar.padding_right = 30


        # 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 # light gray: 0xEEEEEE

        # add pan tools
        img_plot.tools.append(PanTool(img_plot, constrain=True,
                                      constrain_direction="y", speed=7.))

        self.decorate_plot(container, self.posterior)
        self.plot_posterior = plot
        return container
Exemple #32
0
    def _plot_container_default(self):
        data = self.posterior
        nannotations, nclasses = data.shape

        # create a plot data object
        plot_data = ArrayPlotData()
        plot_data.set_data("values", data)

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

        img_plot = plot.img_plot("values",
                                 interpolation='nearest',
                                 xbounds=(0, nclasses),
                                 ybounds=(0, nannotations),
                                 colormap=self._create_colormap())[0]
        ndisp = 55
        img_plot.y_mapper.range.high = ndisp
        img_plot.y_mapper.domain_limits = ((0, nannotations))

        self._set_title(plot)
        plot.padding_top = 80

        # create x axis for labels
        label_axis = self._create_increment_one_axis(plot, 0.5, nclasses,
                                                     'top')
        label_axis.title = 'classes'
        self._add_index_axis(plot, label_axis)

        plot.y_axis.title = 'items'

        # tweak plot aspect
        goal_aspect_ratio = 2.0
        plot_width = (goal_aspect_ratio * self.plot_height * nclasses / ndisp)
        self.plot_width = min(max(plot_width, 200), 400)
        plot.aspect_ratio = self.plot_width / self.plot_height

        # add colorbar
        colormap = img_plot.color_mapper
        colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
                            color_mapper=colormap,
                            plot=img_plot,
                            orientation='v',
                            resizable='',
                            width=15,
                            height=250)
        colorbar.padding_top = plot.padding_top
        colorbar.padding_bottom = int(self.plot_height - colorbar.height -
                                      plot.padding_top)
        colorbar.padding_left = 0
        colorbar.padding_right = 30

        # 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  # light gray: 0xEEEEEE

        # add pan tools
        img_plot.tools.append(
            PanTool(img_plot,
                    constrain=True,
                    constrain_direction="y",
                    speed=7.))

        self.decorate_plot(container, self.posterior)
        self.plot_posterior = plot
        return container
Exemple #33
0
    def load(self, path):
        parser = ElementTree(file=open(path, 'r'))
        circles = parser.find('circles')
        outline = parser.find('outline')

        bb = outline.find('bounding_box')
        bs = bb.find('width'), bb.find('height')
        w, h = map(lambda b: float(b.text), bs)

        use_label = parser.find('use_label')
        if use_label is not None:
            use_label = to_bool(use_label.text.strip())
        else:
            use_label = True

        data = ArrayPlotData()
        p = Plot(data=data, padding=100)
        p.x_grid.visible = False
        p.y_grid.visible = False
        p.x_axis.title = 'X cm'
        p.y_axis.title = 'Y cm'
        font = 'modern 22'
        p.x_axis.title_font = font
        p.x_axis.tick_label_font = font
        p.y_axis.title_font = font
        p.y_axis.tick_label_font = font
        #         p.x_axis_visible = False
        #         p.y_axis_visible = False
        p.index_range.low_setting = -w / 2
        p.index_range.high_setting = w / 2

        p.value_range.low_setting = -h / 2
        p.value_range.high_setting = h / 2

        thetas = linspace(0, 2 * pi)

        radius = circles.find('radius').text
        radius = float(radius)

        face_color = circles.find('face_color')
        if face_color is not None:
            face_color = face_color.text
        else:
            face_color = 'white'

        for i, pp in enumerate(circles.findall('point')):
            x, y, l = pp.find('x').text, pp.find('y').text, pp.find(
                'label').text

            #             print i, pp, x, y
            # load hole specific attrs
            r = pp.find('radius')
            if r is None:
                r = radius
            else:
                r = float(r.text)

            fc = pp.find('face_color')
            if fc is None:
                fc = face_color
            else:
                fc = fc.text

            x, y = map(float, (x, y))
            xs = x + r * sin(thetas)
            ys = y + r * cos(thetas)

            xn, yn = 'px{:03n}'.format(i), 'py{:03n}'.format(i)
            data.set_data(xn, xs)
            data.set_data(yn, ys)

            plot = p.plot(
                (xn, yn),
                face_color=fc,
                type='polygon',
            )[0]
            if use_label:
                label = myDataLabel(
                    component=plot,
                    data_point=(x, y),
                    label_text=l,
                    bgcolor='transparent',
                )
                plot.overlays.append(label)

        self.container.add(p)
Exemple #34
0
    def _theta_plot_default(self):
        """Create plot of theta parameters."""

        # We plot both the thetas and the samples from the posterior; if the
        # latter are not defined, the corresponding ArrayPlotData names
        # should be set to an empty list, so that they are not displayed
        theta = self.model.theta
        theta_len = theta.shape[0]

        # create the plot data
        if not self.theta_plot_data:
            self.theta_plot_data = ArrayPlotData()
            self._update_plot_data()

        # create the plot
        theta_plot = Plot(self.theta_plot_data)

        for idx in range(theta_len):
            # candle plot summarizing samples over the posterior
            theta_plot.candle_plot((_w_idx('index', idx),
                                    _w_idx('min', idx),
                                    _w_idx('barmin', idx),
                                    _w_idx('avg', idx),
                                    _w_idx('barmax', idx),
                                    _w_idx('max', idx)),
                                    color = get_annotator_color(idx),
                                    bar_line_color = "black",
                                    stem_color = "blue",
                                    center_color = "red",
                                    center_width = 2)

            # plot of raw samples
            theta_plot.plot((_w_idx('ysamples', idx),
                             _w_idx('xsamples', idx)),
                            type='scatter',
                            color='black',
                            marker='dot',
                            line_width=0.5,
                            marker_size=1)

            # plot current parameters
            theta_plot.plot((_w_idx('y', idx), _w_idx('x', idx)),
                            type='scatter',
                            color=get_annotator_color(idx),
                            marker='plus',
                            marker_size=8,
                            line_width=2)

        # adjust axis bounds
        theta_plot.range2d = self._compute_range2d()

        # remove horizontal grid and axis
        theta_plot.underlays = [theta_plot.x_grid, theta_plot.y_axis]

        # create new horizontal axis
        label_list = [str(i) for i in range(theta_len)]

        label_axis = LabelAxis(
            theta_plot,
            orientation = 'bottom',
            positions = range(1, theta_len+1),
            labels = label_list,
            label_rotation = 0
        )
        # use a FixedScale tick generator with a resolution of 1
        label_axis.tick_generator = ScalesTickGenerator(scale=FixedScale(1.))

        theta_plot.index_axis = label_axis
        theta_plot.underlays.append(label_axis)
        theta_plot.padding = 25
        theta_plot.padding_left = 40
        theta_plot.aspect_ratio = 1.0

        container = VPlotContainer()
        container.add(theta_plot)
        container.bgcolor = 0xFFFFFF

        self.decorate_plot(container, theta)
        self._set_title(theta_plot)

        return container
Exemple #35
0
    def load(self, path):
        parser = ElementTree(file=open(path, 'r'))
        circles = parser.find('circles')
        outline = parser.find('outline')

        bb = outline.find('bounding_box')
        bs = bb.find('width'), bb.find('height')
        w, h = [float(b.text) for b in bs]

        use_label = parser.find('use_label')
        if use_label is not None:
            use_label = to_bool(use_label.text.strip())
        else:
            use_label = True

        data = ArrayPlotData()
        p = Plot(data=data, padding=100)
        p.x_grid.visible = False
        p.y_grid.visible = False

        p.x_axis.visible = False
        p.y_axis.visible = False

        p.x_axis.title = 'X cm'
        p.y_axis.title = 'Y cm'

        # font = 'modern 22'
        # p.x_axis.title_font = font
        # p.x_axis.tick_label_font = font
        # p.y_axis.title_font = font
        # p.y_axis.tick_label_font = font
        #         p.x_axis_visible = False
        #         p.y_axis_visible = False
        p.index_range.low_setting = -w / 2
        p.index_range.high_setting = w / 2

        p.value_range.low_setting = -h / 2
        p.value_range.high_setting = h / 2

        thetas = linspace(0, 2 * pi)

        radius = circles.find('radius').text
        radius = float(radius)

        face_color = circles.find('face_color')
        if face_color is not None:
            face_color = face_color.text
        else:
            face_color = 'white'
        labels = []
        for i, pp in enumerate(circles.findall('point')):
            x, y, l = pp.find('x').text, pp.find('y').text, pp.find('label').text

            #             print i, pp, x, y
            # load hole specific attrs
            r = pp.find('radius')
            if r is None:
                r = radius
            else:
                r = float(r.text)

            fc = pp.find('face_color')
            if fc is None:
                fc = face_color
            else:
                fc = fc.text

            x, y = list(map(float, (x, y)))
            xs = x + r * sin(thetas)
            ys = y + r * cos(thetas)

            xn, yn = 'px{:03d}'.format(i), 'py{:03d}'.format(i)
            data.set_data(xn, xs)
            data.set_data(yn, ys)

            plot = p.plot((xn, yn),
                          face_color=fc,
                          type='polygon')[0]
            labels.append((x, y, l))
            # if use_label:
            #     label = myDataLabel(component=plot,
            #                         data_point=(x, y),
            #                         label_text=l,
            #                         bgcolor='transparent')
            #     plot.overlays.append(label)
        if use_label:
            p.overlays.append(LabelsOverlay(component=plot, labels=labels))

        self.container.add(p)
        self.container.invalidate_and_redraw()
 def __init__(self, *args, **kw):
     super(RegisteredImage, self).__init__(*args, **kw)
     self.plot = plot = Plot(self.pd, default_origin="top left")
     plot.x_axis.orientation = "top"
     plot.x_axis.visible = False
     plot.y_axis.visible = False
Exemple #37
0
    def _theta_plot_default(self):
        theta = self.theta
        nannotators = theta.shape[0]
        samples = self.theta_samples

        # plot data object
        plot_data = ArrayPlotData()

        # create the plot
        plot = Plot(plot_data)

        # --- plot theta as vertical dashed lines
        # add vertical lines extremes
        plot_data.set_data('line_extr', [0., 1.])

        for k in range(nannotators):
            name = self._theta_name(k)
            plot_data.set_data(name, [theta[k], theta[k]])

        plots = {}
        for k in range(nannotators):
            name = self._theta_name(k)
            line_plot = plot.plot(
                (name, 'line_extr'),
                line_width = 2.,
                color = get_annotator_color(k),
                line_style = 'dash',
                name = name
            )
            plots[name] = line_plot

        # --- plot samples as distributions
        if samples is not None:
            bins = np.linspace(0., 1., 100)
            max_hist = 0.
            for k in range(nannotators):
                name = self._theta_name(k) + '_distr_'
                hist, x = np.histogram(samples[:,k], bins=bins)
                hist = hist / float(hist.sum())
                max_hist = max(max_hist, hist.max())

                # make "bars" out of histogram values
                y = np.concatenate(([0], np.repeat(hist, 2), [0]))
                plot_data.set_data(name+'x', np.repeat(x, 2))
                plot_data.set_data(name+'y', y)

            for k in range(nannotators):
                name = self._theta_name(k) + '_distr_'
                plot.plot((name+'x', name+'y'),
                          line_width = 2.,
                          color = get_annotator_color(k)
                          )

        # --- adjust plot appearance

        plot.aspect_ratio = 1.6 if is_display_small() else 1.7
        plot.padding = [20,0,10,40]

        # adjust axis bounds
        x_low, x_high = theta.min(), theta.max()
        y_low, y_high = 0., 1.
        if samples is not None:
            x_high = max(x_high, samples.max())
            x_low = min(x_low, samples.min())
            y_high = max_hist

        plot.range2d = DataRange2D(
            low  = (max(x_low-0.05, 0.), y_low),
            high = (min(x_high*1.1, 1.), min(y_high*1.1, 1.))
        )

        # label axes
        plot.value_axis.title = 'Probability'
        plot.index_axis.title = 'Theta'

        # add legend
        legend = Legend(component=plot, plots=plots,
                        align="ul", padding=5)
        legend.tools.append(LegendTool(legend, drag_button="left"))
        plot.overlays.append(legend)

        container = VPlotContainer()
        container.add(plot)
        container.bgcolor = 0xFFFFFF

        self.decorate_plot(container, theta)
        self._set_title(plot)

        return container
def plotEigenvalues(model, gui):
    ''' This function calculates the linearization of model as well as additional information
        (eigenvalues, damping ...) if this was not done before.
        It opens a new plotting tab and displays this information
    '''
    if model is None:
        print("No model selected!")
        return

    # Check if already linearized, do so otherwise:
    try:
        data = model.pluginData["EigenvalueAnalysis"]
    except:
        print "Performing linearization"
        data = EigenvalueAnalysis()
        data._performLinearization(model)
        model.pluginData["EigenvalueAnalysis"] = data

    # Open new plotting tab:
    parent = QtGui.QApplication.activeWindow()
    widgetContainer = parent._newPlotContainer()
    widget = widgetContainer.activeWidget

    # Plot the data:
    x = numpy.real(data.eigenvalues[:])
    y = numpy.imag(data.eigenvalues[:])
    plotdata = ArrayPlotData(x=x,
                             y=y,
                             border_visible=True,
                             overlay_border=True)
    plot = Plot(plotdata, title="Eigenvalues of %s" % data.modelName)
    scatter = plot.plot(("x", "y"), type="scatter", color="blue")[0]

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot))
    plot.overlays.append(ZoomTool(plot))

    # Add axis titles:
    x_axis = PlotAxis(orientation="bottom")
    x_axis.mapper = plot.index_mapper
    x_axis.title = "real part"
    plot.underlays.append(x_axis)
    y_axis = PlotAxis(orientation="left")
    y_axis.mapper = plot.value_mapper
    y_axis.title = "imag. part"
    plot.underlays.append(y_axis)

    # Attach the inspector and its overlay
    scatter.tools.append(ScatterInspector(scatter))
    overlay = myScatterInspectorOverlay(scatter,
                                        hover_color="red",
                                        hover_marker_size=6,
                                        selection_marker_size=6,
                                        selection_color="yellow",
                                        selection_outline_color="purple",
                                        selection_line_width=3,
                                        stateNames=data.StateNames,
                                        eigenVectors=data.eigenvectors,
                                        frequencies=data.frequencies,
                                        damping=data.damping,
                                        observability=data.observability,
                                        controllability=data.controllability)
    scatter.overlays.append(overlay)
    # Activate Plot:
    widget.setPlot(plot)
    widgetContainer.activeWidget = widget
Exemple #39
0
def plotFFTPlusTHD(widget):
    """ Determine fft of signals in selected widget and
        calculate Total harmonic disturbance"""
    print("plotFFT and Total Harmonic Disturbance")

    model = ""
    for (modelNumber, modelName, variableName), data in widget.getData():
        # print "var:", var, "data: ", data
        minVal = (0, float("inf"))
        maxVal = (0, float("-inf"))
        # for time, value in data:

    # Get data from data array:
    time = numpy.array(list((x for x, _ in data)))  # data[0]
    values = numpy.array(list((x for _, x in data)))
    unit = ""

    (Tmin, Tmax, N) = getFFTtimeRange(time)
    (timeInRange, valuesInRange) = getValuesInRange(time, values, Tmin, Tmax)

    # Compute fft: A=A(f)
    (f, A) = fft(timeInRange, valuesInRange, N)

    #******* START THD CALCULATION    *************
    # Estimate fundamental frequency:
    maxindex = A.argmax()
    estimation = f[maxindex]

    def getExFreq(estimation):
        return estimation
        """
        Inquire im measured fundamental frequency is correct:
        """
        '''
        import guidata
        guidata.qapplication()
        import guidata.dataset.dataitems as di
        import guidata.dataset.datatypes as dt


        class Processing(dt.DataSet):
            """ Fundamental Frequency """
            correctedFreq    = di.FloatItem("fundamental frequency [Hz]", default=estimation)
        param = Processing()
        okPressed = param.edit()
        if okPressed:
            return param.correctedFreq
        else:  # Cancel button pressed
            return estimation
        '''

    # Ask for a better fundamental frequency
    exFreq = max(0, min(f.max(), getExFreq(estimation)))

    # Check if we have at least one harmonic:
    if exFreq > 0.5 * f.max():
        print "THD calculation not possible, extend frequency window to at least 2*fundamental frequency"
        THD = 999
    else:
        # Get 5% window around fundamental frequency and calculate power:
        mask = (f > exFreq * 0.975) & (f < exFreq * 1.025)
        print "Calculating fundamental energy from points: frequency=%s, Amplitude=%s" % (
            f[mask], A[mask])
        P1 = numpy.vdot(A[mask], A[mask])  # squared amplitude
        PH = 0
        # Sum up the Power of all harmonic frequencies in spectrum:
        noHarmonics = numpy.int(numpy.floor(f.max() / exFreq))
        for i in range(noHarmonics - 1):
            mask = (f > (i + 2) * exFreq * 0.975) & (f <
                                                     (i + 2) * exFreq * 1.025)
            PH = PH + (numpy.vdot(A[mask], A[mask]))  # squared amplitude
        THD = PH / P1 * 100

    #******* END THD CALCULATION    *************

    # Open new plot tab:
    import plotWidget
    window = widget.createNewWindow()
    container = plotWidget.plotContainer(window)
    plotWidget = plotWidget.PlotWidget(container)
    container.setPlotWidget(plotWidget)

    # Plot data
    plotdata = ArrayPlotData(x=f,
                             y=A,
                             border_visible=True,
                             overlay_border=True)
    plot = Plot(plotdata, title="FFT")  # Plot(plotdata, title="FFT")
    barPlot = plot.plot(("x", "y"), type="bar", bar_width=0.3, color="blue")[0]

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot))
    plot.overlays.append(ZoomTool(plot))

    # Activate Plot:
    plotWidget.setPlot(plot)
    if THD != 999:
        thdLabel = DataLabel(
            component=plotWidget.plot,
            data_point=(f[A.argmax()], A.max()),
            label_position="bottom right",
            padding_bottom=20,
            marker_color="transparent",
            marker_size=8,
            marker="circle",
            arrow_visible=False,
            label_format=str(
                'THD = %.4g percent based on %d harmonics of the %.4g Hz frequency'
                % (THD, noHarmonics, exFreq)))
        plotWidget.plot.overlays.append(thdLabel)
    container.setPlotWidget(plotWidget)

    layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom)
    layout.addWidget(container)
    window.setLayout(layout)
    window.show()
Exemple #40
0
    def _theta_plot_default(self):
        """Create plot of theta parameters."""

        # We plot both the thetas and the samples from the posterior; if the
        # latter are not defined, the corresponding ArrayPlotData names
        # should be set to an empty list, so that they are not displayed
        theta = self.model.theta
        theta_len = theta.shape[0]

        # create the plot data
        if not self.theta_plot_data:
            self.theta_plot_data = ArrayPlotData()
            self._update_plot_data()

        # create the plot
        theta_plot = Plot(self.theta_plot_data)

        for idx in range(theta_len):
            # candle plot summarizing samples over the posterior
            theta_plot.candle_plot((_w_idx('index', idx),
                                    _w_idx('min', idx),
                                    _w_idx('barmin', idx),
                                    _w_idx('avg', idx),
                                    _w_idx('barmax', idx),
                                    _w_idx('max', idx)),
                                    color = get_annotator_color(idx),
                                    bar_line_color = "black",
                                    stem_color = "blue",
                                    center_color = "red",
                                    center_width = 2)

            # plot of raw samples
            theta_plot.plot((_w_idx('ysamples', idx),
                             _w_idx('xsamples', idx)),
                            type='scatter',
                            color='black',
                            marker='dot',
                            line_width=0.5,
                            marker_size=1)

            # plot current parameters
            theta_plot.plot((_w_idx('y', idx), _w_idx('x', idx)),
                            type='scatter',
                            color=get_annotator_color(idx),
                            marker='plus',
                            marker_size=8,
                            line_width=2)

        # adjust axis bounds
        theta_plot.range2d = self._compute_range2d()

        # remove horizontal grid and axis
        theta_plot.underlays = [theta_plot.x_grid, theta_plot.y_axis]

        # create new horizontal axis
        label_list = [str(i) for i in range(theta_len)]

        label_axis = LabelAxis(
            theta_plot,
            orientation = 'bottom',
            positions = list(range(1, theta_len+1)),
            labels = label_list,
            label_rotation = 0
        )
        # use a FixedScale tick generator with a resolution of 1
        label_axis.tick_generator = ScalesTickGenerator(scale=FixedScale(1.))

        theta_plot.index_axis = label_axis
        theta_plot.underlays.append(label_axis)
        theta_plot.padding = 25
        theta_plot.padding_left = 40
        theta_plot.aspect_ratio = 1.0

        container = VPlotContainer()
        container.add(theta_plot)
        container.bgcolor = 0xFFFFFF

        self.decorate_plot(container, theta)
        self._set_title(theta_plot)

        return container
Exemple #41
0
    def _theta_plot_default(self):
        theta = self.theta
        nannotators = theta.shape[0]
        samples = self.theta_samples

        # plot data object
        plot_data = ArrayPlotData()

        # create the plot
        plot = Plot(plot_data)

        # --- plot theta as vertical dashed lines
        # add vertical lines extremes
        plot_data.set_data('line_extr', [0., 1.])

        for k in range(nannotators):
            name = self._theta_name(k)
            plot_data.set_data(name, [theta[k], theta[k]])

        plots = {}
        for k in range(nannotators):
            name = self._theta_name(k)
            line_plot = plot.plot(
                (name, 'line_extr'),
                line_width = 2.,
                color = get_annotator_color(k),
                line_style = 'dash',
                name = name
            )
            plots[name] = line_plot

        # --- plot samples as distributions
        if samples is not None:
            bins = np.linspace(0., 1., 100)
            max_hist = 0.
            for k in range(nannotators):
                name = self._theta_name(k) + '_distr_'
                hist, x = np.histogram(samples[:,k], bins=bins)
                hist = hist / float(hist.sum())
                max_hist = max(max_hist, hist.max())

                # make "bars" out of histogram values
                y = np.concatenate(([0], np.repeat(hist, 2), [0]))
                plot_data.set_data(name+'x', np.repeat(x, 2))
                plot_data.set_data(name+'y', y)

            for k in range(nannotators):
                name = self._theta_name(k) + '_distr_'
                plot.plot((name+'x', name+'y'),
                          line_width = 2.,
                          color = get_annotator_color(k)
                          )

        # --- adjust plot appearance

        plot.aspect_ratio = 1.6 if is_display_small() else 1.7
        plot.padding = [20,0,10,40]

        # adjust axis bounds
        x_low, x_high = theta.min(), theta.max()
        y_low, y_high = 0., 1.
        if samples is not None:
            x_high = max(x_high, samples.max())
            x_low = min(x_low, samples.min())
            y_high = max_hist

        plot.range2d = DataRange2D(
            low  = (max(x_low-0.05, 0.), y_low),
            high = (min(x_high*1.1, 1.), min(y_high*1.1, 1.))
        )

        # label axes
        plot.value_axis.title = 'Probability'
        plot.index_axis.title = 'Theta'

        # add legend
        legend = Legend(component=plot, plots=plots,
                        align="ul", padding=5)
        legend.tools.append(LegendTool(legend, drag_button="left"))
        plot.overlays.append(legend)

        container = VPlotContainer()
        container.add(plot)
        container.bgcolor = 0xFFFFFF

        self.decorate_plot(container, theta)
        self._set_title(plot)

        return container
    def load(self, path):
        parser = ElementTree(file=open(path, 'r'))
        circles = parser.find('circles')
        outline = parser.find('outline')

        bb = outline.find('bounding_box')
        bs = bb.find('width'), bb.find('height')
        w, h = map(lambda b:float(b.text), bs)


        data = ArrayPlotData()
        p = Plot(data=data)
        p.x_grid.visible = False
        p.y_grid.visible = False

        p.index_range.low_setting = -w / 2
        p.index_range.high_setting = w / 2

        p.value_range.low_setting = -h / 2
        p.value_range.high_setting = h / 2

        thetas = linspace(0, 2 * pi)

        radius = circles.find('radius').text
        radius = float(radius)

        face_color = circles.find('face_color')
        if face_color is not None:
            face_color = face_color.text
        else:
            face_color = 'white'

        for i, pp in enumerate(circles.findall('point')):
            x, y, l = pp.find('x').text, pp.find('y').text, pp.find('label').text

            # load hole specific attrs
            r = pp.find('radius')
            if r is None:
                r = radius
            else:
                r = float(r.text)

            fc = pp.find('face_color')
            if fc is None:
                fc = face_color
            else:
                fc = fc.text

            x, y = map(float, (x, y))
            xs = x + r * sin(thetas)
            ys = y + r * cos(thetas)

            xn, yn = 'px{:03n}'.format(i), 'py{:03n}'.format(i)
            data.set_data(xn, xs)
            data.set_data(yn, ys)

            plot = p.plot((xn, yn),
                   face_color=fc,
                   type='polygon',
                   )[0]

            label = myDataLabel(component=plot,
                              data_point=(x, y),
                              label_text=l,
                              bgcolor=fc
                              )
            plot.overlays.append(label)

        self.container.add(p)
    def create_plot(self):
        if hasattr(self.value, 'shadows'):
            color_gen = color_generator()
            shadowcolors = {}
            for shadow in self.value.shadows:
                shadowcolors[shadow] = color_gen.next()

        container_class = {'h' : HPlotContainer, 'v' : VPlotContainer}[self.orientation]
        container = container_class(spacing=15, padding=15, bgcolor = 'transparent')
        container.fill_padding = True
        container.bgcolor=(236/255.0, 233/255.0, 216/255.0)

        if self.show_all:
            self.plot_items = self.value.keys()

        if len(self.plot_items)>0:
            plot_configs = []
            for (plot_num, var_name) in enumerate(self.plot_items):
                if not (isinstance(self.value[var_name], ndarray) and \
                        len(self.value[var_name].shape) == 1):
                    continue
                plot_configs.append(PlotConfig(x=var_name + '_index',
                                               y=var_name,
                                               type='Line',
                                               number=plot_num))
            self.plot_configs = plot_configs


        if len(self.plot_configs)>0:
            number_to_plots = {}
            for plot_config in self.plot_configs:
                plotlist = number_to_plots.get(plot_config.number, [])
                plotlist.append(plot_config)
                number_to_plots[plot_config.number] = plotlist

            keys = number_to_plots.keys()
            keys.sort()
            container_list = [number_to_plots[number] for number in keys]

            for plot_group in container_list:
                context_adapter = PlotDataContextAdapter(context=self.value)
                plot = Plot(context_adapter)
                plot.padding = 15
                plot.padding_left=35
                plot.padding_bottom = 30
                plot.spacing=15
                plot.border_visible = True
                for plot_item in plot_group:
                    if len(self.value[plot_item.y].shape) == 2:
                        color_range = DataRange1D(low=min(self.value[plot_item.y]),
                                                  high=max(self.value[plot_item.y]))
                        plot.img_plot(plot_item.y, colormap=gray(color_range),
                                      name=plot_item.y)

                    else:
                        plot_type = {'Line':'line', 'Scatter':'scatter'}[plot_item.type]
                        plot.plot((plot_item.x, plot_item.y),
                                  name=plot_item.x + " , " + plot_item.y,
                                  color=(.7, .7, .7),
                                  type=plot_type,)
                        if plot.index_axis.title != '':
                            plot.index_axis.title = plot.index_axis.title + ', ' + plot_item.x
                        else:
                            plot.index_axis.title = plot_item.x

                        if plot.value_axis.title != '':
                            plot.value_axis.title = plot.value_axis.title + ', ' + plot_item.y
                        else:
                            plot.value_axis.title = plot_item.y


                        if self.view_shadows and hasattr(self.value, 'shadows'):
                            self.generate_shadow_plots(plot, shadowcolors, plot_item, plot_type)



                plot.tools.append(PanTool(plot))
                container.add(plot)

        self.plot = container
def plotFFTPlusTHD(widget):
    """ Determine fft of signals in selected widget and
        calculate Total harmonic disturbance"""
    print("plotFFT and Total Harmonic Disturbance")

    model = ""
    for (modelNumber, modelName, variableName), data in widget.getData():
        # print "var:", var, "data: ", data
        minVal = (0, float("inf"))
        maxVal = (0, float("-inf"))
        # for time, value in data:

    # Get data from data array:
    time = numpy.array(list((x for x, _ in data)))  # data[0]
    values = numpy.array(list((x for _ , x in data)))
    unit = ""

    (Tmin, Tmax, N) = getFFTtimeRange(time)
    (timeInRange, valuesInRange) = getValuesInRange(time, values, Tmin, Tmax)

    # Compute fft: A=A(f)
    (f, A) = fft(timeInRange, valuesInRange, N)





    #******* START THD CALCULATION    *************
    # Estimate fundamental frequency:
    maxindex = A.argmax()
    estimation = f[maxindex]

    def getExFreq(estimation):
        return estimation
        """
        Inquire im measured fundamental frequency is correct:
        """

        '''
        import guidata
        guidata.qapplication()
        import guidata.dataset.dataitems as di
        import guidata.dataset.datatypes as dt


        class Processing(dt.DataSet):
            """ Fundamental Frequency """
            correctedFreq    = di.FloatItem("fundamental frequency [Hz]", default=estimation)
        param = Processing()
        okPressed = param.edit()
        if okPressed:
            return param.correctedFreq
        else:  # Cancel button pressed
            return estimation
        '''
    # Ask for a better fundamental frequency
    exFreq = max(0, min(f.max(), getExFreq(estimation)))

    # Check if we have at least one harmonic:
    if exFreq > 0.5 * f.max():
        print "THD calculation not possible, extend frequency window to at least 2*fundamental frequency"
        THD = 999
    else:
        # Get 5% window around fundamental frequency and calculate power:
        mask = (f > exFreq * 0.975) & (f < exFreq * 1.025)
        print "Calculating fundamental energy from points: frequency=%s, Amplitude=%s" % (f[mask], A[mask])
        P1 = numpy.vdot(A[mask], A[mask])  # squared amplitude
        PH = 0
        # Sum up the Power of all harmonic frequencies in spectrum:
        noHarmonics = numpy.int(numpy.floor(f.max() / exFreq))
        for i in range(noHarmonics - 1):
            mask = (f > (i + 2) * exFreq * 0.975) & (f < (i + 2) * exFreq * 1.025)
            PH = PH + (numpy.vdot(A[mask], A[mask]))  # squared amplitude
        THD = PH / P1 * 100

    #******* END THD CALCULATION    *************

    # Open new plot tab:
    import plotWidget
    window = widget.createNewWindow()
    container = plotWidget.plotContainer(window)
    plotWidget = plotWidget.PlotWidget(container)
    container.setPlotWidget(plotWidget)

    # Plot data
    plotdata = ArrayPlotData(x=f, y=A, border_visible=True, overlay_border=True)
    plot = Plot(plotdata, title="FFT")  # Plot(plotdata, title="FFT")
    barPlot = plot.plot(("x", "y"), type="bar", bar_width=0.3, color="blue")[0]

    # Attach some tools to the plot
    plot.tools.append(PanTool(plot))
    plot.overlays.append(ZoomTool(plot))

    # Activate Plot:
    plotWidget.setPlot(plot)
    if THD != 999:
        thdLabel = DataLabel(component=plotWidget.plot, data_point=(f[A.argmax()], A.max()),
                           label_position="bottom right", padding_bottom=20,
                           marker_color="transparent",
                           marker_size=8,
                           marker="circle",
                           arrow_visible=False,
                           label_format=str('THD = %.4g percent based on %d harmonics of the %.4g Hz frequency' % (THD, noHarmonics, exFreq)))
        plotWidget.plot.overlays.append(thdLabel)
    container.setPlotWidget(plotWidget)

    layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom)
    layout.addWidget(container)
    window.setLayout(layout)
    window.show()
Exemple #45
0
 def _index_scale_changed(self, old, new):
     Plot._index_scale_changed(self, old, new)
     # Now adjust the ScaleSystems.
     self.x_ticks.scale = self._make_scale(self.index_scale)
Exemple #46
0
 def _value_scale_changed(self, old, new):
     Plot._value_scale_changed(self, old, new)
     # Now adjust the ScaleSystems.
     self.y_ticks.scale = self._make_scale(self.value_scale)