Пример #1
0
def plotMovingLeastSquares(x_axis,
                           temperature,
                           rainfall,
                           interval_width=9,
                           degree=3):
    """Plot moving least squares (MLS) approximation."""
    temperature_axis, rainfall_axis = PlotGraph.initGraph(
        x_axis, temperature, rainfall,
        "Moving least squares (MLS) approximation (interval width: " +
        str(interval_width) + ", degree: " + str(degree) + ")")

    # constant to scale the x values if the
    # plot's x axis does not start at 0
    lowest_x_value = x_axis[0]

    x_values = []
    y_values_temperature = []
    y_values_rainfall = []

    # moves the chosen interval step by step over the whole array
    # while calculating the regression polynomial over each
    # intermediate interval and plotting the correponding function
    # value at the middle of the interval
    for i in range(interval_width, len(temperature) + 1):
        # calculates start and end index of the interval
        interval_start = i - interval_width
        interval_end = i

        # creates the specified interval of the x axis
        interval = np.arange(interval_start + lowest_x_value,
                             interval_end + lowest_x_value)

        # creates corresponding regression polynomial and
        # computes the function value of the middle x value
        coeff_temperature = createRegressionPolynomial(
            interval, temperature[interval_start:interval_end], degree)
        values_temperature = evaluatePolynomial(coeff_temperature, interval)
        coeff_rainfall = createRegressionPolynomial(
            interval, rainfall[interval_start:interval_end], degree)
        values_rainfall = evaluatePolynomial(coeff_rainfall, interval)

        # computes the x value in the middle of the interval
        x_value = ((interval_start + interval_end) // 2) + lowest_x_value
        interval_middle_index = math.floor(interval_width / 2)

        # inserts calculated values to the corresponding lists
        x_values.append(x_value)
        y_values_temperature.append(values_temperature[interval_middle_index])
        y_values_rainfall.append(values_rainfall[interval_middle_index])

    temperature_axis.plot(x_values,
                          y_values_temperature,
                          linewidth=2,
                          color="yellow")
    rainfall_axis.plot(x_values, y_values_rainfall, linewidth=2, color="green")
Пример #2
0
    def runButtonHandler(self):
        print('works')
        changed = False
        # collect values when we click
        txtFunc = self.txtFnc.get("1.0", 'end-1c')
        txtX = float(self.txtX.get("1.0", 'end-1c'))
        txtY = float(self.txtY.get("1.0", 'end-1c'))
        OrthXptA = float(self.OrthXptA.get("1.0", 'end-1c'))
        OrthXptB = float(self.OrthXptB.get("1.0", 'end-1c'))
        OrthYptA = float(self.OrthYptA.get("1.0", 'end-1c'))
        OrthYptB = float(self.OrthYptB.get("1.0", 'end-1c'))
        txtTau = float(self.txtTau.get("1.0", 'end-1c'))
        txtEps = Decimal(self.txtEps.get("1.0", 'end-1c'))
        txtBeta = float(self.txtBeta.get("1.0", 'end-1c'))
        txtAlpha = float(self.txtAlpha.get("1.0", 'end-1c'))

        # get labels so we can fill results
        minXlbl = self.minXlabel
        minYlbl = self.minYlabel
        iterlbl = self.IterLabel

        print(txtX, type(txtX))
        print(txtY, type(txtY))
        print(txtEps, type(txtEps))
        print(txtFunc, type(txtFunc))

        # Launch hooke
        it, endpt, points = hooke(2, [txtX, txtY], txtTau, txtEps, 1000,
                                  self.getValueFromUser)

        # Plot a graph
        figure = pg.PlotGraph(endpt, points, self.checkNumbers.get(),
                              self.checkLines.get(), self.checkSteps.get(),
                              self.checkStartEnd.get())

        # Save endpt - found minimum
        endpt_rounded = round(endpt, 2)
        #print('Iterations = ', it, ' end pt : ', endpt_rounded)

        # Set the results to labels in GUI
        minXlbl['text'] = (endpt_rounded[0])
        minYlbl['text'] = (endpt_rounded[1])
        iterlbl['text'] = it

        if (txtBeta != 1):
            it = it / txtBeta
            iterlbl['text'] = round(int(it))

        elif txtAlpha != 1:
            it = it / txtAlpha
            iterlbl['text'] = round(int(it))
        # Display plot in another window
        self.new_window(figure)
Пример #3
0
    def onButIntens(self):

        try:
            cp.plot_gr.close()
            try:
                del cp.plot_gr
            except:
                pass
        except:

            arr_x = rff.get_q_ave_for_stat_q_bins()
            if arr_x is None:
                logger.warning(
                    'Requested array q_ave_for_stat_q_bins is not available.'
                    '\nDrawing command is terminated.'
                    '\nCheck if the file is available.', __name__)
                return

            if self.but_intens_gr.hasFocus():

                arrsy = rff.get_intens_stat_q_bins_arr()
                if arrsy is None:
                    logger.warning(
                        'Requested array q_ave_for_stat_q_bins is not available.'
                        '\nDrawing command is terminated.'
                        '\nCheck if the file is available.', __name__)
                    return

                arr_n = rff.get_time_records_arr(
                )[:, 1]  # take the time of event component
                arrays = (arrsy, arr_x, arr_n)
                ofname = './fig_intensity_for_static_q_t-intervals.png'
                title = 'Intensity for static q bins in time intervals'

                #print 'arr_n :\n',     arr_n
                #print 'arr_n.shape :', arr_n.shape
                #print 'arr_x :\n',     arr_x
                #print 'arr_x.shape :', arr_x.shape
                #print 'arrsy :\n',     arrsy
                #print 'arrsy.shape :', arrsy.shape

            elif self.but_intens_gr1.hasFocus():

                arr_y = rff.get_intens_stat_q_bins()
                arrays = (arr_y, arr_x, None)
                ofname = './fig_intensity_for_static_q_ave.png'
                title = 'Intensity for static q bins averaged'

            labs = (r'$q_{static}$', r'$<I>(q)$')
            cp.plot_gr = PlotGraph(None, arrays, ofname, title, axlabs=labs)
            cp.plot_gr.move(self.parentWidget().parentWidget().pos().__add__(
                QtCore.QPoint(870, 20)))
            cp.plot_gr.show()
Пример #4
0
def plotConstant(x_axis, temperature, rainfall):
    """Plot given data with standard average."""
    temperature_axis, rainfall_axis = PlotGraph.initGraph(
        x_axis, temperature, rainfall, "Graph with constant average")

    # plots constant average for temperature
    avg_temperature = np.average(temperature)
    temperature_axis.axhline(avg_temperature, linewidth=2, color='yellow')

    # plots constant average for rainfall
    avg_rainfall = np.average(rainfall)
    rainfall_axis.axhline(avg_rainfall, linewidth=2, color='green')
Пример #5
0
def plotPolynomial(x_axis, temperature, rainfall, degree=3, maxErrorDegree=16):
    """Plot polynomial regression."""
    temperature_axis, rainfall_axis = PlotGraph.initGraph(
        x_axis, temperature, rainfall,
        "Polynomial regression (degree: " + str(degree) + ")")

    # creates corresponding regression polynomial and
    # computes all necessary function values
    coeff_temperature = createRegressionPolynomial(x_axis, temperature, degree)
    values_temperature = evaluatePolynomial(coeff_temperature, x_axis)
    coeff_rain = createRegressionPolynomial(x_axis, rainfall, degree)
    values_rain = evaluatePolynomial(coeff_rain, x_axis)

    # plots computed approximation
    temperature_axis.plot(x_axis,
                          values_temperature,
                          linewidth=2,
                          color="yellow")
    rainfall_axis.plot(x_axis, values_rain, linewidth=2, color="green")

    temperature_Regression_Error = []
    rainfall_Regression_Error = []
    # calculate Average Regression Error for degrees from 0 to 10
    for degree in range(maxErrorDegree):
        temperature_Regression_Error.append(
            RegressionAverageError(x_axis, temperature, degree))
        rainfall_Regression_Error.append(
            RegressionAverageError(x_axis, rainfall, degree))
    # plot Regression Errors
    temperature_Error_axis, rainfall_Error_axis = PlotGraph.initGraph(
        [], [], [], "RegressionError")
    temperature_Error_axis.set_xlabel("Degree of polynomial")
    temperature_Error_axis.plot(range(maxErrorDegree),
                                temperature_Regression_Error,
                                linewidth=2,
                                color="red")
    rainfall_Error_axis.plot(range(maxErrorDegree),
                             rainfall_Regression_Error,
                             linewidth=2,
                             color="blue")
Пример #6
0
def makeGraphTypeI():

    array_compare = []
    inputName = "T1Rpc-external"
    array_rpc = makeArrayFromFile(inputName)
    inputName = "T1Grpc-external"
    array_grpc = makeArrayFromFile(inputName)

    array_compare.append(array_rpc)
    array_compare.append(array_grpc)

    figure_name = "Compare_GRPCxRPYC_T1"
    text = "Análise Comparativa I : Sem Argumentos - Sem Retorno"

    plt.PlotGraph(array_compare, figure_name, text)
Пример #7
0
def plotPiecewise(x_axis, temperature, rainfall, intervals=20):
    """Divide data into intervals and plot the average over these intervals."""
    temperature_axis, rainfall_axis = PlotGraph.initGraph(
        x_axis, temperature, rainfall,
        "Graph with piecewise average approximation" + " (" + str(intervals) +
        " intervals)")

    # constant to scale the x values if the
    # plot's x axis does not start at 0
    lowest_x_value = x_axis[0]

    interval_size = math.ceil(len(temperature) / intervals)

    x_values = []
    y_values_temperature = []
    y_values_rainfall = []

    for i in range(intervals - 1):
        # calculates start and end index of the interval
        interval_start = i * interval_size
        interval_end = (i + 1) * interval_size
        # calculates average over the specified interval
        avg_temperature = np.average(temperature[interval_start:interval_end])
        avg_rainfall = np.average(rainfall[interval_start:interval_end])
        # uses the middle of the interval as x value
        x_value = ((interval_start + interval_end - 1) // 2) + lowest_x_value
        # inserts calculated values to the corresponding lists
        x_values.append(x_value)
        y_values_temperature.append(avg_temperature)
        y_values_rainfall.append(avg_rainfall)

    # calculates the last interval seperately
    # because its length may be different
    last_interval_start = (intervals - 1) * interval_size
    last_avg_temperature = np.average(temperature[last_interval_start:])
    last_avg_rainfall = np.average(rainfall[last_interval_start:])
    last_x_value = (
        (last_interval_start + len(temperature) - 1) // 2) + lowest_x_value
    x_values.append(last_x_value)
    y_values_temperature.append(last_avg_temperature)
    y_values_rainfall.append(last_avg_rainfall)

    # plots all values
    temperature_axis.plot(x_values,
                          y_values_temperature,
                          linewidth=2,
                          color="yellow")
    rainfall_axis.plot(x_values, y_values_rainfall, linewidth=2, color="green")
Пример #8
0
def plotQuadratic(x_axis, temperature, rainfall):
    """Plot quadratic regression."""
    temperature_axis, rainfall_axis = PlotGraph.initGraph(
        x_axis, temperature, rainfall, "Quadratic regression")
    coeff_temperature = quadraticRegression(x_axis, temperature)
    coeff_rain = quadraticRegression(x_axis, rainfall)
    # check correct result with Matrix-version
    # print(coeff_rain)
    # print(quadraticRegressionMatrix(x_axis, rainfall))
    values_temperature = quadraticFunction(coeff_temperature, x_axis)
    values_rain = quadraticFunction(coeff_rain, x_axis)
    temperature_axis.plot(x_axis,
                          values_temperature,
                          linewidth=2,
                          color="yellow")
    rainfall_axis.plot(x_axis, values_rain, linewidth=2, color="green")
Пример #9
0
def makeGraphTypeII(nGroups):

    array_mean_localhost = []
    array_mean_external = []
    array_std_localhost = []
    array_std_external = []

    inputName = "T2Rpc-external"
    array_rpc = makeArrayFromFile(inputName)
    inputName = "T2Grpc-external"
    array_grpc = makeArrayFromFile(inputName)

    array_mean_localhost.append(np.mean(array_rpc))
    array_mean_external.append(np.mean(array_grpc))

    array_std_localhost.append(np.std(array_rpc))
    array_std_external.append(np.std(array_grpc))

    i = 1

    while (i < nGroups):
        inputName = "T2.%iRpc-external" % i
        array_rpc = makeArrayFromFile(inputName)
        inputName = "T2.%iGrpc-external" % i
        array_grpc = makeArrayFromFile(inputName)

        array_mean_localhost.append(np.mean(array_rpc))
        array_mean_external.append(np.mean(array_grpc))

        array_std_localhost.append(np.std(array_rpc))
        array_std_external.append(np.std(array_grpc))
        i = i + 1

    list_values = [
        'String(4)', 'String(8)', 'String(16)', 'String(32)', 'String(64)',
        'String(128)'
    ]
    text = "Análise Comparativa II : Comparação de Strings de Diferentes Tamanhos"
    figure_name = "Compare_GRPCxRPYC_T2"
    plt.PlotGraphII(array_mean_localhost, array_mean_external,
                    array_std_localhost, array_std_external, nGroups,
                    list_values, text, figure_name)
Пример #10
0
    def __init__(self, mainWindow):

        self.colorList = []
        self.mainWindow = mainWindow

        menu = Menu(mainWindow)
        fileList = Menu(menu)

        dropDownList = menu.add_command(label="Open file dialog",
                                        command=self.openFileDialog)

        mainWin.config(menu=menu)

        self.graphFrame = Frame(mainWindow)
        self.graphFrame.pack(expand=0)
        self.TreeSelector = WidgetTreeViewTk.WidgetTreeViewTk(self)

        self.mainNote = ttk.Notebook(self.graphFrame, style="BW.TLabel")
        self.mainNote.pack(fill=BOTH, expand=1)

        # Create the several graph
        self.frame1 = ttk.Labelframe(self.mainNote,
                                     text='Power',
                                     width=100,
                                     height=100)

        self.frame2 = ttk.Labelframe(self.mainNote,
                                     text='Advanced Plot',
                                     width=100,
                                     height=100)
        self.mainNote.add(self.frame1, text="power")
        self.mainNote.add(self.frame2, text="Advanced Plot")
        self.frame2 = ttk.Frame(self.mainNote)
        self.mainNote.insert("end", self.frame2)

        self.graph = PlotGraph.PlotGraph(self.frame1)

        self.toggleFrame = Frame(self.graphFrame, width=25, height=10)
        self.toggleFrame.grid_propagate(0)
        self.toggleFrame.pack(fill=X, expand=1)

        self.graph.handleResize()
Пример #11
0
def plotLinear(x_axis, temperature, rainfall):
    """Plot linear regression."""
    temperature_axis, rainfall_axis = PlotGraph.initGraph(
        x_axis, temperature, rainfall, "Linear regression")

    coeff_temperature = linearRegression(x_axis, temperature)
    coeff_rain = linearRegression(x_axis, rainfall)

    boundary_points = np.array([x_axis[0], x_axis[len(x_axis) - 1]])

    values_temperature = linearFunction(coeff_temperature, boundary_points)
    values_rain = linearFunction(coeff_rain, boundary_points)

    temperature_axis.plot(boundary_points,
                          values_temperature,
                          linewidth=2,
                          color="yellow")
    rainfall_axis.plot(boundary_points,
                       values_rain,
                       linewidth=2,
                       color="green")
Пример #12
0
def plotRunning(x_axis, temperature, rainfall, interval_width=20):
    """Plot the running average on given data."""
    temperature_axis, rainfall_axis = PlotGraph.initGraph(
        x_axis, temperature, rainfall,
        "Graph with running average approximation" + " (width of interval: " +
        str(interval_width) + ")")

    # constant to scale the x values if the
    # plot's x axis does not start at 0
    lowest_x_value = x_axis[0]

    x_values = []
    y_values_temperature = []
    y_values_rainfall = []

    # moves the chosen interval step by step over the whole array
    # while calculating the average over each intermediate interval
    for i in range(interval_width, len(temperature) + 1):
        # calculates start and end index of the interval
        interval_start = i - interval_width
        interval_end = i
        # calculates average over the specified interval
        avg_temperature = np.average(temperature[interval_start:interval_end])
        avg_rainfall = np.average(rainfall[interval_start:interval_end])
        # uses the middle of the interval as x value
        x_value = ((interval_start + interval_end - 1) // 2) + lowest_x_value
        # inserts calculated values to the corresponding lists
        x_values.append(x_value)
        y_values_temperature.append(avg_temperature)
        y_values_rainfall.append(avg_rainfall)

    temperature_axis.plot(x_values,
                          y_values_temperature,
                          linewidth=2,
                          color="yellow")
    rainfall_axis.plot(x_values, y_values_rainfall, linewidth=2, color="green")
Пример #13
0
        # Prompt user whether they wish to continue
        txt2 = input(
            "\nThis program has fetched yearly and monthly spending for Liverpool City Council\n"
            "Do you wish to view this information in Bar and Line graphs?\n"
            "[1 = Yes, 2 = No]: \n")

        # Check user input and perform following action
        if txt2 == '1':

            # Tell user program is fetching new files
            print("Generating Graphs and Charts...")

            # MatPlotLib of spending for each department over a year line graph
            # Plot line graph
            PlotGraph.plotLineGraph(mergedDataframe, 'Yearly', yearToSearch)

            # MatPlotLib of spending per year in Bar chart
            PlotGraph.plotBarChart(yearSpendDF, 'Yearly', yearToSearch)

            # MatPlotLib of spending per year in Bar chart Logarithmic
            PlotGraph.plotBarChartLog(yearSpendDF, 'Yearly', yearToSearch)

            # For each month print the table with spending by department
            # Iterate over the month number until all records are done
            monthNum = 1
            for monthlyDf in dfSpendingPerMonth:

                # Check Month number is not greater than 12,
                # if it is then reset to 1 in case multiple years will be evaluated
                if monthNum > 12:
Пример #14
0
def plotLagrangePolynomial(x_axis, temperature, rainfall, control_points=5):
    """Use Lagrange interpolation to approximate the data."""
    temperature_axis, rainfall_axis = PlotGraph.initGraph(
        x_axis, temperature, rainfall,
        "Approximation using Lagrange polynomials")

    # gets x values of equally distributed points within the data
    x_chosen_points = np.linspace(x_axis[0],
                                  x_axis[-1],
                                  control_points,
                                  endpoint=False,
                                  dtype=np.int64)

    # constant to scale the x values if the
    # plot's x axis does not start at 0
    lowest_x_value = x_axis[0]

    # gets the corresponding y values
    y_chosen_points_temperature = []
    y_chosen_points_rainfall = []
    for x in x_chosen_points:
        y_chosen_points_temperature.append(temperature[int(x -
                                                           lowest_x_value)])
        y_chosen_points_rainfall.append(rainfall[int(x - lowest_x_value)])

    # plots all chosen points
    temperature_axis.plot(x_chosen_points,
                          y_chosen_points_temperature,
                          'o',
                          color="yellow")
    rainfall_axis.plot(x_chosen_points,
                       y_chosen_points_rainfall,
                       'o',
                       color="green")

    # makes sure that unimportant x values (i.e. values smaller than
    # the smallest x value of all chosen points or greater than the biggest)
    # are excluded regarding the plot of the Lagrange polynomial
    x_axis = np.arange(x_chosen_points[0], x_chosen_points[-1] + 1)

    x_values_temperature = []
    x_values_rainfall = []
    y_values_temperature = []
    y_values_rainfall = []

    # computes and evaluates the corresponding interpolation polynomial
    for x in x_axis:
        # interpolates the temperature data
        y_temperature = calcInterpolationPolynomial(
            x, x_chosen_points, y_chosen_points_temperature)
        x_values_temperature.append(x)
        y_values_temperature.append(y_temperature)

        # interpolates the rainfall data
        y_rainfall = calcInterpolationPolynomial(x, x_chosen_points,
                                                 y_chosen_points_rainfall)
        x_values_rainfall.append(x)
        y_values_rainfall.append(y_rainfall)

    # displays interpolated data
    temperature_axis.plot(x_values_temperature,
                          y_values_temperature,
                          linewidth=2,
                          color="yellow")
    rainfall_axis.plot(x_values_rainfall,
                       y_values_rainfall,
                       linewidth=2,
                       color="green")
Пример #15
0
        allHighSDs = []
        allLowSDs = []

        #for each exchange, calculate the lower and upper standard deviations for each exchange's minutely data
        for all in range(len(allStandard_dev)):
            highSD = []
            lowSD = []
            for x in range(len(allStandard_dev[all])):
                highSD.append(float(allAverages[all][x])+float(allStandard_dev[all][x]))
                lowSD.append(float(allAverages[all][x])-float(allStandard_dev[all][x]))
            allHighSDs.append(highSD)
            allLowSDs.append(lowSD)

        #call function in PlotGraph.py to graph the data.
        PlotGraph.plotStandardDeviation(allGraph_time, allAverages, allFinalSDs, allHighSDs, allLowSDs, allFinalAverages,
                                       minDate, maxDate, exchanges, "minutes")



    #SAME AS ABOVE, BUT GRAPHS HOURLY DATA
    if HOURLY == True:

        for ex in range(len(exchanges)):
            exchangeID = (trades_db.getExchangeID(exchanges[ex]))
            allHourlyData.append(analysis_db.getAllHoursFromExchangeRange(exchangeID, time1, time2))

        allAverages = []
        allStandard_dev = []
        allGraph_time = []
        allGraph_time_prices = []
        allGraph_time_seconds = []
Пример #16
0
    def __init__(self, *args, **kwds):
        # begin wxGlade: GenLoggerFrame.__init__
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((1044, 646))
        self.SetTitle("Generator Test")

        self.mainPanel = wx.Panel(self, wx.ID_ANY)
        self.mainPanel.SetMinSize((1024, 800))

        mainSizer = wx.FlexGridSizer(3, 1, 0, 0)

        self.configSizer = wx.FlexGridSizer(1, 9, 0, 8)
        mainSizer.Add(self.configSizer, 1, wx.ALL | wx.EXPAND, 5)

        self.portCombo = wx.ComboBox(self.mainPanel,
                                     wx.ID_ANY,
                                     choices=[],
                                     style=wx.CB_DROPDOWN)
        self.configSizer.Add(self.portCombo, 0, wx.EXPAND, 0)

        self.refreshButton = wx.Button(self.mainPanel, wx.ID_ANY,
                                       "Rescan Channels")
        self.configSizer.Add(self.refreshButton, 0, 0, 0)

        self.startButton = wx.Button(self.mainPanel, wx.ID_ANY, "Start")
        self.configSizer.Add(self.startButton, 0, 0, 0)

        self.stopButton = wx.Button(self.mainPanel, wx.ID_ANY, "Stop")
        self.configSizer.Add(self.stopButton, 0, 0, 0)

        self.startlogButton = wx.Button(self.mainPanel, wx.ID_ANY, "Start Log")
        self.configSizer.Add(self.startlogButton, 0, 0, 0)

        self.stoplogButton = wx.Button(self.mainPanel, wx.ID_ANY, "Stop Log")
        self.configSizer.Add(self.stoplogButton, 0, 0, 0)

        self.loggingStatus = wx.StaticText(self.mainPanel, wx.ID_ANY,
                                           "[Logging]")
        self.loggingStatus.Hide()
        self.configSizer.Add(self.loggingStatus, 0, wx.ALIGN_CENTER_VERTICAL,
                             0)

        self.playbackButton = wx.Button(self.mainPanel, wx.ID_ANY, "Playback")
        self.configSizer.Add(self.playbackButton, 0, 0, 0)

        self.gentestFrame = wx.Button(self.mainPanel, wx.ID_ANY, "Exit")
        self.configSizer.Add(self.gentestFrame, 0, 0, 0)

        plotSizer = wx.FlexGridSizer(2, 1, 0, 0)
        mainSizer.Add(plotSizer, 1, wx.ALL | wx.EXPAND, 0)

        self.frequencySizer = wx.FlexGridSizer(2, 1, 0, 0)
        plotSizer.Add(self.frequencySizer, 1, wx.ALL | wx.EXPAND, 0)

        titleFrequencySizer = wx.FlexGridSizer(1, 7, 0, 0)
        self.frequencySizer.Add(titleFrequencySizer, 1, wx.EXPAND, 0)

        self.enableFFTCheckbox1 = wx.CheckBox(self.mainPanel, wx.ID_ANY,
                                              "Phase 1")
        self.enableFFTCheckbox1.SetValue(1)
        titleFrequencySizer.Add(self.enableFFTCheckbox1, 0, 0, 0)

        self.enableFFTCheckbox2 = wx.CheckBox(self.mainPanel, wx.ID_ANY,
                                              "Phase 2")
        self.enableFFTCheckbox2.SetValue(1)
        titleFrequencySizer.Add(self.enableFFTCheckbox2, 0, 0, 0)

        label_1 = wx.StaticText(self.mainPanel, wx.ID_ANY, "Frequency FFT")
        titleFrequencySizer.Add(label_1, 0, wx.ALIGN_CENTER, 0)

        label_3 = wx.StaticText(self.mainPanel, wx.ID_ANY, "THD Phase1:")
        titleFrequencySizer.Add(label_3, 0, wx.ALIGN_CENTER_VERTICAL, 0)

        self.frequencyTHDtext1 = wx.TextCtrl(self.mainPanel, wx.ID_ANY, "")
        titleFrequencySizer.Add(self.frequencyTHDtext1, 0, 0, 0)

        label_4 = wx.StaticText(self.mainPanel, wx.ID_ANY, "THD Phase2:")
        titleFrequencySizer.Add(label_4, 0, wx.ALIGN_CENTER_VERTICAL, 0)

        self.frequencyTHDtext2 = wx.TextCtrl(self.mainPanel, wx.ID_ANY, "")
        titleFrequencySizer.Add(self.frequencyTHDtext2, 0, 0, 0)

        self.dummyFrequencyPanel = wx.Panel(self.mainPanel, wx.ID_ANY)
        self.frequencySizer.Add(self.dummyFrequencyPanel, 1, wx.EXPAND, 0)

        self.graphSizer = wx.FlexGridSizer(2, 1, 0, 0)
        plotSizer.Add(self.graphSizer, 1, wx.ALL | wx.EXPAND, 0)

        titleGraphSizer = wx.FlexGridSizer(1, 3, 0, 0)
        self.graphSizer.Add(titleGraphSizer, 1, wx.EXPAND, 0)

        self.enableGraphCheckbox1 = wx.CheckBox(self.mainPanel, wx.ID_ANY,
                                                "Phase 1")
        self.enableGraphCheckbox1.SetValue(1)
        titleGraphSizer.Add(self.enableGraphCheckbox1, 0, 0, 0)

        self.enableGraphCheckbox2 = wx.CheckBox(self.mainPanel, wx.ID_ANY,
                                                "Phase 2")
        self.enableGraphCheckbox2.SetValue(1)
        titleGraphSizer.Add(self.enableGraphCheckbox2, 0, 0, 0)

        label_2 = wx.StaticText(self.mainPanel, wx.ID_ANY, "Graph")
        titleGraphSizer.Add(label_2, 0, wx.ALIGN_CENTER, 0)

        self.dummyGraphPanel = wx.Panel(self.mainPanel, wx.ID_ANY)
        self.graphSizer.Add(self.dummyGraphPanel, 1, wx.EXPAND, 0)

        mainSizer.Add((20, 20), 0, 0, 0)

        titleGraphSizer.AddGrowableCol(2)

        self.graphSizer.AddGrowableRow(1)
        self.graphSizer.AddGrowableCol(0)

        titleFrequencySizer.AddGrowableCol(2)

        self.frequencySizer.AddGrowableRow(1)
        self.frequencySizer.AddGrowableCol(0)

        plotSizer.AddGrowableRow(0)
        plotSizer.AddGrowableRow(1)
        plotSizer.AddGrowableCol(0)

        self.configSizer.AddGrowableCol(0)

        mainSizer.AddGrowableRow(1)
        mainSizer.AddGrowableCol(0)
        self.mainPanel.SetSizer(mainSizer)

        self.Layout()

        self.Bind(wx.EVT_COMBOBOX, self.OnSelectLabjackCombo, self.portCombo)
        self.Bind(wx.EVT_BUTTON, self.OnRefreshPorts, self.refreshButton)
        self.Bind(wx.EVT_BUTTON, self.OnStartButton, self.startButton)
        self.Bind(wx.EVT_BUTTON, self.OnStopButton, self.stopButton)
        self.Bind(wx.EVT_BUTTON, self.OnStartLogButton, self.startlogButton)
        self.Bind(wx.EVT_BUTTON, self.OnStopLogButton, self.stoplogButton)
        self.Bind(wx.EVT_BUTTON, self.OnPlaybackButton, self.playbackButton)
        self.Bind(wx.EVT_BUTTON, self.OnExitButton, self.gentestFrame)
        self.Bind(wx.EVT_CHECKBOX, self.OnFFTCheckbox1,
                  self.enableFFTCheckbox1)
        self.Bind(wx.EVT_CHECKBOX, self.OnFFTCheckbox2,
                  self.enableFFTCheckbox2)
        self.Bind(wx.EVT_CHECKBOX, self.OnGraphCheckbox1,
                  self.enableGraphCheckbox1)
        self.Bind(wx.EVT_CHECKBOX, self.OnGraphCheckbox2,
                  self.enableGraphCheckbox2)
        self.Bind(wx.EVT_CLOSE, self.OnClose, self)
        # end wxGlade

        self.__labjack_port = None
        self.__labjack = None
        self.__plotitems = []
        self.__packet_thread_id = None
        self.__queue = Queue()
        self.__log_file = None
        self.__playback_file = None
        self.__playback_thread = None

        wx.CallLater(2000, self.OnRefreshPortsHelper)

        # Create FFT views
        phase_fft = PlotGraph(parent=self.mainPanel, name="Freq FFT", style=0)
        phase_fft.SetParams({
            "plottype":
            "fft",
            "points":
            self.__SCAN_RATE,
            "xmin":
            0,
            "xmax":
            self.__FREQ_LIMIT,
            "ymin":
            -20,
            "ymax":
            80,
            "yconvert":
            lambda y: 10 * math.log10(y) if y != 0 else 0,
            "zero":
            1,
            "results":
            "thd",  # Return THD from each fft SetValue
        })

        phase_fft.SetChannelColor("AIN0", wx.RED)
        phase_fft.SetChannelColor("AIN1", wx.BLUE)

        self.__plotitems.append(phase_fft)

        self.frequencySizer.Detach(self.dummyFrequencyPanel)
        self.frequencySizer.Add(phase_fft,
                                proportion=1,
                                border=0,
                                flag=wx.EXPAND)

        # Create freq plot
        freq_plot = PlotGraph(parent=self.mainPanel, name="Frequency", style=0)
        freq_plot.SetParams({
            "points":
            self.__FREQ_LIMIT,
            "xmin":
            0,
            "xmax":
            self.__FREQ_LIMIT,
            "ymin":
            -20,
            "ymax":
            20,
            "xlabelfun":
            lambda x: "%.2f" % (x / self.__SCAN_RATE),
        })

        freq_plot.SetChannelColor("AIN0", wx.RED)
        freq_plot.SetChannelColor("AIN1", wx.BLUE)

        self.__plotitems.append(freq_plot)

        self.graphSizer.Detach(self.dummyGraphPanel)
        self.graphSizer.Add(freq_plot, proportion=1, border=0, flag=wx.EXPAND)
Пример #17
0
    def __init__(self):
        super(Main, self).__init__()

        self.stationary = Cfg.params.stationary
        self.stationary_mode = Cfg.params.stationary_mode
        if self.stationary:
            self.ui = Stationary.Ui_MainWindow()
        else:
            self.ui = Transportable.Ui_MainWindow()
        self.ui.setupUi(self)

        if self.stationary and self.stationary_mode == Cfg.mode_enum.mode_1:
            self.ui.tabWidget.setTabEnabled(1, False)
            self.ui.tabWidget.setTabEnabled(3, False)

        if not self.stationary:
            group = QtGui.QButtonGroup(self)
            group.addButton(self.ui.bool_39, 1)
            group.addButton(self.ui.bool_40, 2)

            group_2 = QtGui.QButtonGroup(self)
            group_2.addButton(self.ui.bool_22, 1)
            group_2.addButton(self.ui.bool_23, 2)
            group_2.addButton(self.ui.bool_24, 3)

        self.commands_array = [False]*48
        self.ksu_array = [False]*8
        self.ksu_array[0] = True
        self.ksu_array[3] = True
        self.lsu_array = [False]*8
        self.lsu_2_array = [False]*8
        self.ks_array = [False]*8
        self.faults_array = [False]*8
        self.fc_state_array = [False]*8
        self.fc_2_state_array = [False]*8
        self.im_mask_array = [True]*16

        # self.ui.frame_lsu_2_role.setVisible(False)
        # self.ui.groupBox_lsu_2.setVisible(False)
        # self.ui.fc_2_state.setVisible(False)
        self.ui.frame_6.setVisible(False)
        if not self.stationary:
            self.ui.frame_14.setVisible(False)
            self.ui.frame_16.setVisible(False)
            self.ui.frame_20.setVisible(False)
        self.ui.reset.setVisible(False)
        self.ui.imitate.setVisible(False)

        self.lsu = LSU.LSU()
        if not Cfg.params.stationary or Cfg.params.stationary_mode == Cfg.mode_enum.mode_3:
            self.lsu.start()

        self.show()

        colors = [QtCore.Qt.black,
                  QtCore.Qt.red,
                  QtCore.Qt.blue,
                  QtCore.Qt.magenta,
                  QtCore.Qt.darkYellow,
                  QtCore.Qt.green,
                  QtCore.Qt.cyan,
                  QtCore.Qt.darkGray]

        names = [u"КР1",
                 u"КР2",
                 u"КТ1",
                 u"КТ2",
                 u"РТВ",
                 u"ЧВ ТГ",
                 u"ДП",
                 u"ЧВ ЭЦН"]

        y_names = [u'Положение клапанов, мм',
                   u'Положение РТВ, мм',
                   u'Частота вращения ТГ, об/мин',
                   u'Давление пара перед АТГУ, МПа',
                   u'Частота вращения ЭЦН, об/мин']

        y_scales_min = [0,
                        0,
                        0,
                        0,
                        0]

        y_scales_max = [30,
                        62,
                        10000,
                        3,
                        1000]

        formats = ['{:.3f}',
                   '{:.3f}',
                   '{:.3f}',
                   '{:.3f}',
                   '{:.3f}']

        axes = [0, 0, 0, 0, 1, 2, 3, 4]
        trends = []
        trends_lsu2 = []
        for color, name, axis in zip(colors, names, axes):
            trends.append({'color': color, 'name': name, 'axis': axis})
            trends_lsu2.append({'color': color, 'name': name, 'axis': axis})

        axes = []
        axes_lsu2 = []
        for name, y_scale_max, y_scale_min, y_format in zip(y_names, y_scales_max, y_scales_min, formats):
            axes.append({'scale': (y_scale_min, y_scale_max), 'name': name, 'format': y_format})
            axes_lsu2.append({'scale': (y_scale_min, y_scale_max), 'name': name, 'format': y_format})

        self.ui.graph.config(trends, axes, x_axis={'name': u'Время', 'format': '{:.2f}'}, trend_limit=2000)
        if self.stationary:
            self.ui.graph_lsu2.config(trends_lsu2, axes_lsu2, x_axis={'name': u'Время', 'format': '{:.2f}'}, trend_limit=2000)
            self.ui.pushButton_2.clicked.connect(self.stop_graph_2)

        self.ui.pushButton.clicked.connect(self.stop_graph)

        if self.stationary:
            for child in self.ui.valves_3.children() + self.ui.valves_4.children() + self.ui.valves_11.children() + self.ui.valves_12.children() + \
                    self.ui.valves_15.children() + self.ui.valves_16.children() + self.ui.valves_13.children() + self.ui.valves_14.children():
                if isinstance(child, QtGui.QCheckBox):
                    child.clicked.connect(self.imitate_params)
                elif isinstance(child, QtGui.QDoubleSpinBox):
                    child.valueChanged.connect(self.imitate_params)
            # self.ui.f1_im.clicked.connect(self.imitate_params)

        if not self.stationary:
            for b in self.ui.commands.children():
                if isinstance(b, QtGui.QPushButton):
                    if b.isCheckable():
                        b.clicked.connect(self.make_commands)
                    else:
                        b.pressed.connect(self.make_commands_true)
                        b.released.connect(self.make_commands_false)

        if not self.stationary:
            for b in self.ui.discrete_ksu.children():
                b.clicked.connect(self.make_ksu)

        for b in self.ui.discrete_lsu.children():
            b.clicked.connect(self.make_lsu)

        if self.stationary:
            for b in self.ui.discrete_lsu_2.children():
                b.clicked.connect(self.make_lsu_2)

        if not self.stationary:
            for b in self.ui.discrete_ks.children():
                b.clicked.connect(self.make_ks)

        for b in self.ui.discrete_faults.children():
            b.clicked.connect(self.make_faults)

        for b in self.ui.fc_state.children():
            b.clicked.connect(self.make_fc_state)

        if self.stationary:
            for b in self.ui.fc_2_state.children():
                b.clicked.connect(self.make_fc_2_state)

        if not self.stationary:
            for b in self.ui.im_mask.children():
                b.clicked.connect(self.make_im_mask)

        MP.mp()
        self.pu_struct = MP.pu_struct
        self.atgu_1 = MP.atgu_1
        self.atgu_2 = MP.atgu_2
        self.controls = MP.controls
        self.im_params = MP.im_params
        self.lsu_params = MP.lsu_params
        self.im_queue = MP.im_queue
        self.flag = MP.flag
        self.queue_plot = MP.queue_plot
        self.queue_adv = MP.queue_adv
        # self.adv_data = MP.

        self.ui.qr_in.valueChanged.connect(self.set_qr_in)
        self.ui.we_in.valueChanged.connect(self.set_we_in)
        self.ui.t_cool_in.valueChanged.connect(self.set_t_in)
        self.ui.t_hot_in.valueChanged.connect(self.set_t_in)

        if self.stationary:
            self.ui.qr_in_2.valueChanged.connect(self.set_qr_in)
            self.ui.we_in_2.valueChanged.connect(self.set_we_in)
            self.ui.t_cool_in_2.valueChanged.connect(self.set_t_in)
            self.ui.t_hot_in_2.valueChanged.connect(self.set_t_in)

        self.ui.freq_in.valueChanged.connect(self.set_freq_in)
        self.ui.mode.valueChanged.connect(self.set_mode)
        self.ui.dp_final.currentIndexChanged.connect(self.set_dp_final)
        self.ui.period.valueChanged.connect(self.set_period)
        self.ui.reset.clicked.connect(self.reset)
        self.ui.imitate.clicked.connect(lambda: self.imitate(self.ui.imitate.isChecked()))

        self.ui.qr_in.setValue(Cfg.params.power)
        self.ui.we_in.setValue(Cfg.params.electric_power)
        self.ui.t_cool_in.setValue(Cfg.params.cool_water_temperature)
        self.ui.t_hot_in.setValue(Cfg.params.hot_water_temperature)
        self.ui.p2_in.setValue(Cfg.params.atgu_pressure)
        self.ui.p8_in.setValue(Cfg.params.condenser_pressure)

        if not self.stationary:
            self.ui.kr1_2_set.valueChanged.connect(self.set_pp_2)
            self.ui.kr2_2_set.valueChanged.connect(self.set_pp_2)
            self.ui.kt1_2_set.valueChanged.connect(self.set_pp_2)
            self.ui.kt2_2_set.valueChanged.connect(self.set_pp_2)
            self.ui.rtv_2_set.valueChanged.connect(self.set_pp_2)

        self.model_process = Process(target=RK4_2.run,
                                     args=(self.queue_plot, self.flag, self.controls, self.im_params, self.atgu_1, self.atgu_2))
        self.model_process.start()

        self.plot_thread = QtCore.QThread()
        if self.stationary:
            self.plot = PlotGraph.Plot(self.ui.graph, self.ui.graph_lsu2)
        else:
            self.plot = PlotGraph.Plot(self.ui.graph)
        self.plot.moveToThread(self.plot_thread)
        self.plot_thread.started.connect(self.plot.run)
        self.plot.signal.connect(self.plot_add_points)
        self.plot_thread.start()

        if self.stationary:
            self.serial_process = Process(target=Serial.run,
                                          args=(self.atgu_1, self.atgu_2, self.lsu_params, self.flag))
            self.serial_process.start()
            self.adv_process = Process(target=Advantech.run,
                                       args=(self.flag, self.atgu_1, self.atgu_2, self.queue_adv, self.im_params))
            self.adv_process.start()
            self.udp_ksu_ts_process = Process(target=UDP_KSU_TS.run,
                                              args=[self.im_params, self.flag])
            self.udp_ksu_ts_process.start()
        else:
            self.udp_process = Process(target=UDP.run,
                                       args=(self.atgu_1, self.im_params, self.pu_struct, self.lsu_params, self.im_queue, self.flag))
            self.udp_process.start()

        self.t_ind = QtCore.QTimer()
        self.t_ind.timeout.connect(self.update_inds)
        self.t_ind.start(100)

        self.lsu_update = QtCore.QTimer()
        self.lsu_update.timeout.connect(self.update_lsu)
        self.lsu_update.start(10)