Пример #1
0
    def __init__(self):
        super(ConnectedRange, self).__init__()
        x = linspace(-14, 14, 100)
        y = sin(x) * x ** 3
        plotdata = ArrayPlotData(x=x, y=y)

        scatter = Plot(plotdata)
        scatter.plot(("x", "y"), type="scatter", color="blue")

        line = Plot(plotdata)
        #line = Plot(plotdata, orientation="v", default_origin="top left")
        line.plot(("x", "y"), type="line", color="red")

        self.container = HPlotContainer(scatter, line)

        scatter.tools.append(PanTool(scatter))
        scatter.tools.append(ZoomTool(scatter))

        line.tools.append(PanTool(line))
        line.tools.append(ZoomTool(line))

        #Axis link options, try them out
        #scatter.value_range = line.value_range  # Link y-axis only
        #scatter.index_range = line.index_range  # Link x-axis only
        scatter.range2d = line.range2d  # Link both axes
Пример #2
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
Пример #3
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()
    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)
Пример #5
0
    def add_tools(self, img_plot):
        zoom = ZoomTool(component=img_plot, tool_mode="box", always_on=False)
        pan = PanTool(component=img_plot, restrict_to_data=True)
        img_plot.tools.append(pan)

        img_plot.overlays.append(zoom)
Пример #6
0
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
Пример #7
0
 def __init__(self, plot):
     PanTool.__init__(self, plot)
     self.speed = 2
     self.drag_pointer = "cross"
Пример #8
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()
Пример #9
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
Пример #10
0
    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