# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'lab.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

import random
import sys
import math
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
import matplotlib.pyplot as plt

class Trials(object):
    def __init__(self,val, count):
        self.val = val
        self. count = count

    def print(self):
       print(self.val," ", self.count)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1000, 500)
        font = QtGui.QFont()
        font.setPointSize(10)
        MainWindow.setFont(font)
        MainWindow.setStyleSheet("background-color: rgb(255, 254, 202);")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(10, 30, 431, 21))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(460, 30, 81, 31))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.textEdit.setFont(font)
        self.textEdit.setObjectName("textEdit")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(440, 100, 121, 41))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(440, 150, 121, 41))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(600, 100, 121, 41))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setObjectName("pushButton")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(130, 130, 55, 16))
        self.label_3.setText("")
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(10, 70, 161, 16))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(10, 420, 300, 16))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_5.setFont(font)
        self.label_5.setObjectName("label_5")

        self.label_9 = QtWidgets.QLabel(self.centralwidget)
        self.label_9.setGeometry(QtCore.QRect(10, 450, 300, 16))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_9.setFont(font)
        self.label_9.setObjectName("label_9")

        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(600, 30, 431, 21))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")

        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setGeometry(QtCore.QRect(600, 70, 431, 21))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_7.setFont(font)
        self.label_7.setObjectName("label_7")

        self.label_8 = QtWidgets.QLabel(self.centralwidget)
        self.label_8.setGeometry(QtCore.QRect(510, 420, 400, 16))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_8.setFont(font)
        self.label_8.setObjectName("label_8")

        self.textEdit_3 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_3.setGeometry(QtCore.QRect(845, 30, 81, 31))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.textEdit_3.setFont(font)
        self.textEdit_3.setObjectName("textEdit_3")

        self.textEdit_4 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_4.setGeometry(QtCore.QRect(865, 70, 81, 31))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.textEdit_4.setFont(font)
        self.textEdit_4.setObjectName("textEdit_4")

        self.textEdit_2 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_2.setGeometry(QtCore.QRect(180, 60, 71, 31))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.textEdit_2.setFont(font)
        self.textEdit_2.setObjectName("textEdit_2")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(10, 200, 480, 200))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.tableWidget.setFont(font)
        self.tableWidget.setColumnCount(4)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
        self.tableWidget.setHorizontalHeaderLabels(["y_i", "n_i", "n_i / n", "P({η = y_i})"])

        self.tableWidget_2 = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget_2.setGeometry(QtCore.QRect(510, 200, 480, 95))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.tableWidget_2.setFont(font)
        self.tableWidget_2.setColumnCount(8)
        self.tableWidget_2.setRowCount(1)
        self.tableWidget_2.setObjectName("tableWidget_2")
        self.tableWidget_2.horizontalHeader().setCascadingSectionResizes(False)
        self.tableWidget_2.setHorizontalHeaderLabels(["E", "x_", "|E - x_|", "D", "S^2","|D - S^2|", "Me", "R"])
        MainWindow.setCentralWidget(self.centralwidget)

        self.tableWidget_3 = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget_3.setGeometry(QtCore.QRect(510, 305, 480, 95))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.tableWidget_3.setFont(font)
        self.tableWidget_3.setColumnCount(1)
        self.tableWidget_3.setRowCount(1)
        self.tableWidget_3.setObjectName("tableWidget_3")
        self.tableWidget_3.horizontalHeader().setCascadingSectionResizes(False)
        self.tableWidget_3.setHorizontalHeaderLabels(["q_j"])
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)


        self.pushButton.clicked.connect(self.creat_table_1)

        self.pushButton_2.clicked.connect(self.tab_clear)

        self.pushButton_3.clicked.connect(self.check_gipotiz)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Вариант 21. Изготовление исправной детали"))
        self.label.setText(_translate("MainWindow", "Введите значение вероятности p, что деталь исправна"))
        self.textEdit.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; font-weight:400; font-style:normal;\">\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:20pt;\"><br /></p></body></html>"))
        self.pushButton.setText(_translate("MainWindow", "Вычислить"))
        self.pushButton_2.setText(_translate("MainWindow", "Очистить"))
        self.pushButton_3.setText(_translate("MainWindow", "Гипотеза"))
        self.label_4.setText(_translate("MainWindow", "Кол - во испытаний"))
        self.label_5.setText(_translate("MainWindow", "max|ni / n - P({η = yi})| = "))
        self.label_6.setText(_translate("MainWindow", "Введите число интервалов k = "))
        self.label_7.setText(_translate("MainWindow", "Введите уровень значимости a = "))
        self.textEdit_2.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; font-weight:400; font-style:normal;\">\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:20pt;\"><br /></p></body></html>"))
        self.textEdit_3.setHtml(_translate("MainWindow",
                                           "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                                           "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                                           "p, li { white-space: pre-wrap; }\n"
                                           "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; font-weight:400; font-style:normal;\">\n"
                                           "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:20pt;\"><br /></p></body></html>"))
        self.textEdit_4.setHtml(_translate("MainWindow",
                                           "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                                           "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                                           "p, li { white-space: pre-wrap; }\n"
                                           "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; font-weight:400; font-style:normal;\">\n"
                                           "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:20pt;\"><br /></p></body></html>"))


    def tab_clear(self):
        self.tableWidget.clear()
        self.tableWidget_2.clear()
        self.tableWidget_3.clear()


    def creat_table_1(self):
        p = float(self.textEdit.toPlainText())
        n = int(self.textEdit_2.toPlainText())
        trial = n
        i = 1
        it = 0
        mas = [[0.0 for i in range(0, 3)] for j in range(0,n)]
        self.tableWidget.setRowCount(n)
        while it < n:
            u = random.uniform(0.0, 1.0)
            while u > p:
                i += 1
                u = random.uniform(0.0, 1.0)
            x = i
            i = 1
            mas [it][1] = 1
            if it > 0 and n > 1:
                flag = 0
                for k in range(0, it):
                    if x == mas[k][0]:
                        count =  mas[k][1]
                        flag = 1
                        count += 1
                        mas[k][1] = count
                        mas[it][1] = 0
                        ratio = mas[k][1] / trial
                        mas[k][2] = ratio
                        it = it - 1
                        n = n - 1
                if flag == 0:
                    mas[it][0] = x
                    ratio = mas[it][1] / trial
                    mas[it][2] = ratio
            else:
                mas[it][0] = x
                ratio =  mas[it][1] / trial
                mas[it][2] = ratio

            it += 1
        mas.sort()

        flag = 0
        mas_new = [[0.0 for i in range(0, 3)] for j in range(0,n)]
        for it in range(0,trial):
            if mas[it][0] == 0:
                flag += 1
                continue
            else:
                mas_new[it- flag][0] =mas[it][0]
                mas_new[it - flag][1] = mas[it][1]
                mas_new[it - flag][2] = mas[it][2]
        max_dif = 0
        for it in range(0,n):
            self.tableWidget.setItem(it, 0, QtWidgets.QTableWidgetItem(str(mas_new[it][0])))
            self.tableWidget.setItem(it, 1, QtWidgets.QTableWidgetItem(str(mas_new[it][1])))
            self.tableWidget.setItem(it, 2, QtWidgets.QTableWidgetItem(str(mas_new[it][2])))
            p_theor = p* (1 - p) **(mas_new[it][0] - 1)
            self.tableWidget.setItem(it, 3, QtWidgets.QTableWidgetItem(str(p_theor)))
            if max_dif < abs(mas[it][2] - p_theor):
                max_dif = abs(mas[it][2] - p_theor)

        f = open("C:/Users/Dasha/PycharmProjects/lab/size.txt", "w")
        f.write(str(n))
        f.close()
        self.label_5.setText("max|ni / n - P({η = yi})| = " + str(max_dif))
        # заполнение 2-ой таблички
        self.creat_table_2(p, n, trial, mas_new)
        # график
        m_new = [mas_new[it][0] for it in range(0, n)]
        m_count = [mas_new[it][1] for it in range(0, n)]
        max_d = 0
        x = [it for it in range(0, 30)]
        y = [F_ksi(it, trial, m_new, m_count) for it in range(0,30)]
        f = [F_theor(it, p) for it in range(0,30)]
        for i in range(0, 30):
            if max_d < abs(y[i] - f[i]):
                max_d = abs(y[i] - f[i])
        self.label_9.setText("D = " + str(max_d))
        plt.plot(x, y, marker = '*')
        plt.plot(x, f, marker = 'o', color = 'g')
        plt.show()


    def creat_table_2(self,p, n, trial, mas):
        # мат ожидание
        e = 1 / p
        self.tableWidget_2.setItem(0, 0, QtWidgets.QTableWidgetItem(str(e)))
        # дисперсия
        d = (1-p) / (p * p)
        self.tableWidget_2.setItem(0, 3, QtWidgets.QTableWidgetItem(str(d)))
        # размах
        r = mas[n - 1][0] - mas[0][0]
        self.tableWidget_2.setItem(0, 7, QtWidgets.QTableWidgetItem(str(r)))
        # выборочное среднее
        sum_v = 0
        for it in range(n):
            sum_v += mas[it][0] * mas[it][1]
        x_ = float(sum_v / trial)
        self.tableWidget_2.setItem(0, 1, QtWidgets.QTableWidgetItem(str(x_)))
        #
        self.tableWidget_2.setItem(0, 2, QtWidgets.QTableWidgetItem(str(abs(e - x_))))
        # выборочная дисперсия
        sum_v = 0
        for it in range(n):
            sum_v += ((mas[it][0] - x_) ** 2) * mas[it][1]
        s = float(sum_v / trial)
        self.tableWidget_2.setItem(0, 4, QtWidgets.QTableWidgetItem(str(s)))
        #
        self.tableWidget_2.setItem(0, 5, QtWidgets.QTableWidgetItem(str(abs(d - s))))
        # выборочная медиана
        me = 0
        if (trial % 2) == 1:
            num = int(trial / 2) + 1
            it = 0
            pos = 0
            flag = 1
            while flag and it < n:
                pos += mas[it][1]
                if num <= pos:
                    me = mas[it][0]
                    flag = 0
                it += 1
            self.tableWidget_2.setItem(0, 6, QtWidgets.QTableWidgetItem(str(me)))
        else:
            num = int(trial / 2)
            it = 0
            pos = 0
            flag = 1
            while flag and it < n:
                pos += mas[it][1]
                if num <= pos:
                    if num < pos:
                        me = mas[it][0]
                    else:
                        me = float((mas[it][0] + mas[it + 1][0]) / 2)
                    flag = 0
                it += 1
            self.tableWidget_2.setItem(0, 6, QtWidgets.QTableWidgetItem(str(me)))

    def check_gipotiz(self):
        p = float((self.textEdit.toPlainText()))
        n = int(self.textEdit_2.toPlainText())
        k = int(self.textEdit_3.toPlainText())
        a = float(self.textEdit_4.toPlainText())
        f = open("C:/Users/Dasha/PycharmProjects/lab/size.txt", "r")
        l =f.readline().split()
        size = int(l[0])
        mas_new = [[0.0 for i in range(0, 2)] for j in range(0, size)]
        for i in range(0, size):
            mas_new[i][0] = int(self.tableWidget.model().index(i, 0).data())
            mas_new[i][1] = int(self.tableWidget.model().index(i, 1).data())
        interval = [1 for i in range(0, k)]
        print("Введите значения границ интервалов, k = " + str(k))
        for i in range(1, k):
           interval[i] = int(input())
        #interval = [1, 3, 8, 12]
        n_inter = [0 for i in range(0, k)]
        for j in range(0,size):
            for i in range(1, k):
                if interval[i - 1]<= mas_new[j][0] < interval[i]:
                    n_inter[i - 1] += mas_new[j][1]
                if i == k - 1 and mas_new[j][0]>=interval[k-1]:
                    n_inter[k-1]+= mas_new[j][1]
        for i in range(0, k):
            print(n_inter[i])
        # вероятность q_j
        q_inter = [0 for i in range(0, k)]
        self.tableWidget_3.setColumnCount(k)
        j = 1
        for i in range(1, k):   # k - кол во интервалов
            while interval[i - 1] <= j < interval[i]:   # interval - хранит границы от 1 до заданного последнего z_k-1
                q_inter[i - 1] += p * (1 - p) ** (j - 1)
                j += 1
            self.tableWidget_3.setItem(0, i-1, QtWidgets.QTableWidgetItem(str(q_inter[i-1])))
            if i == k-1:   # если интервал последний, то вероятность равна 1 - сумма
                p_pred = 0
                for t in range(0, k - 1):
                    p_pred += q_inter[t]
                q_inter[i] = 1 - p_pred
                self.tableWidget_3.setItem(0, i, QtWidgets.QTableWidgetItem(str(q_inter[i])))
        # найдем r_0
        r_0 = 0
        for i in range(0,k):
            r_0 +=((n_inter[i] - n * q_inter[i])**2) / (n*q_inter[i])
        print("r_0 " + str(r_0))
        # критический интервал
        cr_int = critic_table(a, k)
        # F(r_0)
        f_r = Function(r_0,k - 1)
        # принятие гипотезы
        if r_0 <= cr_int:
            self.label_8.setText("Н_0 - принята, F(R_0) = " + str(f_r))
        else:
            self.label_8.setText("Н_0 - отвергнута, F(R_0) = " + str(f_r))

def critic_table( a, k):
    alpha = [0.995, 0.990, 0.975, 0.950, 0.900, 0.750, 0.500, 0.250, 0.100, 0.050, 0.025, 0.010, 0.005]
    critic = [[0.0 for i in range(0, 13)] for j in range(0,25)]
    f = open('C:/Users/Dasha/PycharmProjects/lab/Critic.txt', "r")
    for i in range(0, 25):
        l = f.readline().split()
        for j in range(0, 13):
            critic[i][j] = float(l[j])
    f.close()
    # поиск хи
    pos = 0
    for i in range(0, 13):
        if a == alpha[i]:
            pos = i
    return critic[k - 1][pos]

def density(x, r):
    if x <= 0:
        return 0
    else:
        return 2 ** (-r / 2) * (1 / math.gamma(r / 2)) * x ** (r / 2 - 1) * math.exp(-x / 2)

def integral(a, b, r):
    n = 1000
    t = (b - a) / n
    res = 0
    for i in range(n):
        res += (density(a + t * i, r) + density(a + t * (i + 1), r)) * t / 2
    return res


def Function(R_0, r):
    return 1 - integral(0, R_0, r)

def F_ksi(t, trial, mas, count):
    num = 0
    if mas[0]>= t:
        return 0
    elif mas[len(mas) -1] < t:
        return 1
    else :
        for i in range(0, len(mas)):
            if mas[i] < t:
                num += count[i]
        return num/trial

def F_theor(t,p):
    res = 0
    i = 1
    while i < t:
        res += p * (1 - p) ** (i - 1)
        i += 1
    return res

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
