Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import tkinter as tk
from tkinter import ttk
import numpy as np
import math
from scipy.stats import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
# ==================================================== ГЛОБАЛЬНЫЕ ПЕРЕМЕННЫЕ ==============================================================
discrete_distributions = [
"Биномиальное",
"Отрицательное биномиальное",
"Пуассона",
"Геометрическое"
]
continuous_distributions = [
"Нормальное",
"Экспоненциальное",
"Равномерное",
"Стьюдента",
"Хи-квадрат"
]
distribution_parameters = {
"Биномиальное": ["n", "p"],
"Отрицательное биномиальное": ["r", "p"],
"Пуассона": ["lambda"],
"Геометрическое": ["p"],
"Нормальное": ["mu", "sigma"],
"Экспоненциальное": ["lambda"],
"Равномерное": ["a", "b"],
"Стьюдента": ["df"],
"Хи-квадрат": ["df"]
}
canvas1 = None
canvas2 = None
result_canvas = None
param_entries1 = {}
param_entries2 = {}
# ==================================================== ФУНКЦИИ =========================================================
# ----------------------------------- Обновление для выбора распределений -------------------------------------------
def update_distribution_comboboxes(selected_type):
if selected_type == "discrete":
available_distributions = discrete_distributions
elif selected_type == "continuous":
available_distributions = continuous_distributions
else:
available_distributions = []
dist1_combobox['values'] = available_distributions
dist2_combobox['values'] = available_distributions
dist1_combobox.set("Выберите...")
dist2_combobox.set("Выберите...")
update_parameter_fields()
clear_plots()
# ----------------------------------- Обновление для параметров распределений -------------------------------------
def update_parameter_fields(event=None):
global param_entries1, param_entries2
dist1_name = dist1_combobox.get()
dist2_name = dist2_combobox.get()
param_entries1 = create_parameter_widgets(params1_frame, dist1_name)
param_entries2 = create_parameter_widgets(params2_frame, dist2_name)
clear_plots()
# ----------------------------------- Создание виджетов для параметров -------------------------------------------
def create_parameter_widgets(frame, dist_name):
for widget in frame.winfo_children():
widget.destroy()
parameters = distribution_parameters.get(dist_name)
if parameters:
ttk.Label(frame, text=f"Параметры для {dist_name}:").grid(row=0, column=0, columnspan=2, sticky="w", pady=5)
entry_widgets = {}
for i, param_name in enumerate(parameters):
ttk.Label(frame, text=f"{param_name}:").grid(row=i+1, column=0, sticky="w", padx=5, pady=2)
entry = ttk.Entry(frame)
entry.grid(row=i+1, column=1, sticky="ew", padx=5, pady=2)
entry_widgets[param_name] = entry
frame.columnconfigure(1, weight=1)
return entry_widgets
else:
ttk.Label(frame, text="Выберите распределение").grid(row=0, column=0, sticky="w")
return None
# ----------------------------------- Очистка графиков -------------------------------------------
def clear_plots():
global canvas1, canvas2, result_canvas
if canvas1:
canvas1.get_tk_widget().destroy()
canvas1 = None
if canvas2:
canvas2.get_tk_widget().destroy()
canvas2 = None
if result_canvas:
result_canvas.get_tk_widget().destroy()
result_canvas = None
dist1_description_label.config(text="Распределение 1: Не выбрано")
dist2_description_label.config(text="Распределение 2: Не выбрано")
# ----------------------------------- Постройка графиков -------------------------------------------
def plot_distributions():
clear_plots()
dist1_name = dist1_combobox.get()
dist2_name = dist2_combobox.get()
# print("got names")
if dist1_name == "Выберите..." or dist2_name == "Выберите...":
print("Пожалуйста, выберите оба распределения.")
# TODO: Добавить вывод ошибки в GUI
return
params1_values = {name: entry.get() for name, entry in param_entries1.items()}
params2_values = {name: entry.get() for name, entry in param_entries2.items()}
# TODO: Здесь нужно будет добавить валидацию введенных параметров!
# Пока просто выведем их в консоль
print(f"Распределение 1: {dist1_name}, Параметры: {params1_values}")
print(f"Распределение 2: {dist2_name}, Параметры: {params2_values}")
dist1_description_label.config(text=f"Распределение 1: {dist1_name} (Параметры: {params1_values})")
dist2_description_label.config(text=f"Распределение 2: {dist2_name} (Параметры: {params2_values})")
# print("got params")
# --- Создание и отображение графика для Распределения 1 ---
global canvas1
fig1, ax1 = plt.subplots(figsize=(6, 4))
values1, probabilities1 = get_graph(dist1_name, params1_values)
# print("start viz1")
if dist1_name in discrete_distributions:
ax1.bar(values1, probabilities1, width=0.7, color='blue', edgecolor='black')
elif dist1_name in continuous_distributions:
ax1.plot(values1, probabilities1, color='blue')
ax1.set_title(f"{dist1_name}")
ax1.set_xlabel("Значение")
ax1.set_ylabel(f"{'Вероятность' if dist2_name in discrete_distributions else 'Плотность'}")
# print("end viz1")
canvas1 = FigureCanvasTkAgg(fig1, master=plot1_frame)
canvas1.draw()
canvas1.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
# --- Создание и отображение графика для Распределения 2 ---
global canvas2
fig2, ax2 = plt.subplots(figsize=(6, 4))
values2, probabilities2 = get_graph(dist2_name, params2_values)
# print("start viz2")
if dist2_name in discrete_distributions:
ax2.bar(values2, probabilities2, width=0.7, color='red', edgecolor='black')
elif dist2_name in continuous_distributions:
ax2.plot(values2, probabilities2, color='red')
ax2.set_title(f"{dist2_name}")
ax2.set_xlabel("Значение")
ax2.set_ylabel(f"{'Вероятность' if dist2_name in discrete_distributions else 'Плотность'}")
# print("end viz2")
canvas2 = FigureCanvasTkAgg(fig2, master=plot2_frame)
canvas2.draw()
canvas2.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
plt.close(fig1)
plt.close(fig2)
main_notebook.select(results_frame)
# ----------------------------------- Создание объекта распределения ----------------------------------------------
def get_dist(dist_name, params_values):
if dist_name in discrete_distributions:
dist = None
x = None
limit = None
if dist_name == "Биномиальное":
n = int(params_values['n'])
p = float(params_values['p'])
dist = binom(n=n, p=p)
x = 0
limit = n
elif dist_name == "Отрицательное биномиальное":
r = int(params_values['r'])
p = float(params_values['p'])
dist = nbinom(n=r, p=p)
x = r
elif dist_name == "Пуассона":
lmd = float(params_values['lambda'])
dist = poisson(mu=lmd)
x = 0
elif dist_name == "Геометрическое":
p = float(params_values['p'])
dist = geom(p=p)
x = 1
else:
print("Пожалуйста, выберите распределение")
# TODO: сделать ошибку в GUI
return
return dist, x, limit
elif dist_name in continuous_distributions:
dist = None
x = None
limit = None
if dist_name == "Нормальное":
mu = float(params_values['mu'])
sigma = float(params_values['sigma'])
dist = norm(loc=mu, scale=sigma)
elif dist_name == "Экспоненциальное":
lmd = float(params_values['lambda'])
dist = expon(loc=0, scale=1/lmd)
x = 0
elif dist_name == "Равномерное":
a = float(params_values['a'])
b = float(params_values['b'])
dist = uniform(loc=a, scale=b-a)
x = a
limit = b
elif dist_name == "Стьюдента":
df = int(params_values['df'])
dist = t(df, loc=0, scale=1)
elif dist_name == "Хи-квадрат":
df = int(params_values['df'])
dist = chi2(df, loc=0, scale=1)
else:
print("Пожалуйста, выберите распределение")
# TODO: сделать ошибку в GUI
return
return dist, x, limit
else:
print("Пожалуйста, выберите распределение")
# TODO: сделать ошибку в GUI
return
# ----------------------------------- Получение данных для графика ----------------------------------------------
def get_graph(dist_name, params_values):
if dist_name in discrete_distributions:
epsilon = 5e-4
def build(dist_, x_, limit_=None):
mean = dist_.mean()
values_ = []
probabilities_ = []
while True and (limit_ is None or x_ <= limit_):
px_ = dist_.pmf(x_)
if px_ < epsilon:
if x_ < mean:
x_ += 1
continue
break
values_.append(x_)
probabilities_.append(px_)
x_ += 1
values_ = np.array(values_)
probabilities_ = np.array(probabilities_)
return values_, probabilities_
dist, x, limit = get_dist(dist_name, params_values)
values, probabilities = build(dist, x, limit)
elif dist_name in continuous_distributions:
coverage = 0.99
if dist_name == "Равномерное":
coverage = 0.9999
alpha_ = 1 - coverage
num_points = 1000
def build(dist_):
low_b = dist_.ppf(alpha_ / 2)
up_b = dist_.ppf(1 - alpha_ / 2)
values_ = np.linspace(low_b, up_b, num_points)
probabilities_ = np.array([dist_.pdf(k) for k in values_])
return values_, probabilities_
dist, _, _ = get_dist(dist_name, params_values)
values, probabilities = build(dist)
else:
print("Пожалуйста, выберите распределение")
# TODO: сделать ошибку в GUI
return
return values, probabilities
# ----------------------------------- Получение числа с графика ----------------------------------------------
def get_dist_rnd(dist_name, params_values, sample_size):
if dist_name in discrete_distributions:
dist, _, _ = get_dist(dist_name, params_values)
elif dist_name in continuous_distributions:
dist, _, _ = get_dist(dist_name, params_values)
else:
print("Пожалуйста, выберите распределение")
# TODO: сделать ошибку в GUI
return
return dist.rvs(size=sample_size)
# ----------------------------------- Построение гистограммы сум ----------------------------------------------
def create_sum_result_hist():
dist1_name = dist1_combobox.get()
dist2_name = dist2_combobox.get()
if dist1_name == "Выберите..." or dist2_name == "Выберите...":
print("Пожалуйста, выберите оба распределения.")
# TODO: Добавить вывод ошибки в GUI
return
params1_values = {name: entry.get() for name, entry in param_entries1.items()}
params2_values = {name: entry.get() for name, entry in param_entries2.items()}
try:
sample_size = int(sample_size_entry.get())
except ValueError:
print("Введите коректный размер выборки")
return
sample1 = get_dist_rnd(dist1_name, params1_values, sample_size)
sample2 = get_dist_rnd(dist2_name, params2_values, sample_size)
samples_sum = sample1 + sample2
max_el = max(np.quantile(sample1, 0.99), np.quantile(sample2, 0.99), np.quantile(samples_sum, 0.99))
min_el = min(np.quantile(sample1, 0.01), np.quantile(sample2, 0.01), np.quantile(samples_sum, 0.01))
bins_num = math.floor(max_el - min_el + 1)
bins = None
if dist1_name in continuous_distributions:
bins_num = max(bins_num, 20)
bins_num = math.ceil(2 * (sample_size * bins_num ** 0.5) ** (1/3))
bins = np.linspace(min_el, max_el, bins_num)
else:
bins = np.arange(min_el, max_el + 2).astype(float)
bins = bins - 0.5
global canvas1, canvas2, result_canvas
if result_canvas:
result_canvas.get_tk_widget().destroy()
result_canvas = None
fig, ax = plt.subplots(figsize=(7, 5))
ax.hist(samples_sum, bins=bins, density=True, rwidth=0.7, color="black", histtype='stepfilled')
ax.hist(sample1, bins=bins, density=True, rwidth=0.7, color="blue", histtype='step', linewidth=3, alpha=0.5)
ax.hist(sample2, bins=bins, density=True, rwidth=0.7, color="red", histtype='step', linewidth=3, alpha=0.5)
ax.set_title(f"Гистограмма распределения сумм")
ax.set_xlabel("Значение")
ax.set_ylabel(f"{'Вероятность' if dist2_name in discrete_distributions else 'Плотность'}")
# ax.grid(True)
result_canvas = FigureCanvasTkAgg(fig, master=hist_frame)
result_canvas.draw()
result_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
plt.close(fig)
# ==================================================== СОЗДАНИЕ ОКНА ==================================================
# ------------------------------------------ Создание вкладок -------------------------------------
root = tk.Tk()
root.title("Project-KD")
# root.geometry("800x700")
main_notebook = ttk.Notebook(root)
main_notebook.pack(pady=10, padx=10, fill="both", expand=True)
setup_frame = ttk.Frame(main_notebook, padding="10")
results_frame = ttk.Frame(main_notebook, padding="10")
main_notebook.add(setup_frame, text='Настройка')
main_notebook.add(results_frame, text='Результаты')
# ------------------------------------------ Фрейм для выбора типа -------------------------------------
type_selection_frame = ttk.LabelFrame(setup_frame, text="Выберите тип распределений", padding="10")
type_selection_frame.pack(pady=10, padx=10, fill="x")
selected_distribution_type = tk.StringVar()
selected_distribution_type.set("discrete")
discrete_radio = ttk.Radiobutton(
type_selection_frame,
text="Дискретные",
variable=selected_distribution_type,
value="discrete",
command=lambda: update_distribution_comboboxes(selected_distribution_type.get())
)
discrete_radio.pack(side="left", padx=10)
continuous_radio = ttk.Radiobutton(
type_selection_frame,
text="Непрерывные",
variable=selected_distribution_type,
value="continuous",
command=lambda: update_distribution_comboboxes(selected_distribution_type.get())
)
continuous_radio.pack(side="left", padx=10)
# ------------------------------------------ Фрейм для выбора распределений -------------------------------------
distribution_selection_frame = ttk.LabelFrame(setup_frame, text="Выберите два распределения", padding="10")
distribution_selection_frame.pack(pady=5, padx=10, fill="x")
ttk.Label(distribution_selection_frame, text="Распределение 1:").grid(row=0, column=0, sticky="w", padx=5, pady=5)
dist1_combobox = ttk.Combobox(distribution_selection_frame, state="readonly")
dist1_combobox.grid(row=0, column=1, sticky="ew", padx=5, pady=5)
ttk.Label(distribution_selection_frame, text="Распределение 2:").grid(row=1, column=0, sticky="w", padx=5, pady=5)
dist2_combobox = ttk.Combobox(distribution_selection_frame, state="readonly")
dist2_combobox.grid(row=1, column=1, sticky="ew", padx=5, pady=5)
distribution_selection_frame.columnconfigure(1, weight=1)
dist1_combobox.bind("<<ComboboxSelected>>", update_parameter_fields)
dist2_combobox.bind("<<ComboboxSelected>>", update_parameter_fields)
# ------------------------------------------ Фрейм для параметров -------------------------------------
params1_frame = ttk.LabelFrame(setup_frame, text="Параметры Распределения 1", padding="10")
params1_frame.pack(pady=5, padx=10, fill="x")
params2_frame = ttk.LabelFrame(setup_frame, text="Параметры Распределения 2", padding="10")
params2_frame.pack(pady=5, padx=10, fill="x")
# ------------------------------------------ Кнопка постройки графиков -------------------------------------
plots_button = ttk.Button(setup_frame, text="Построить графики", command=plot_distributions)
plots_button.pack(pady=10)
# ------------------------------------------ Фрейм для графиков -------------------------------------
plots_frame = ttk.LabelFrame(results_frame, text="Распределения", padding="10")
plots_frame.pack(pady=5, padx=10, fill="x")
plot1_frame = ttk.LabelFrame(plots_frame, text="График Распределения 1", padding="10")
plot1_frame.grid(row=1, column=0, sticky="nsew", padx=10, pady=5)
plot2_frame = ttk.LabelFrame(plots_frame, text="График Распределения 2", padding="10")
plot2_frame.grid(row=1, column=1, sticky="nsew", padx=10, pady=5)
plots_frame.columnconfigure(0, weight=1)
plots_frame.columnconfigure(1, weight=1)
plots_frame.rowconfigure(1, weight=1)
dist1_description_label = ttk.Label(plots_frame, text="Распределение 1: Не выбрано")
dist1_description_label.grid(row=0, column=0, sticky="nw", padx=10, pady=5)
dist2_description_label = ttk.Label(plots_frame, text="Распределение 2: Не выбрано")
dist2_description_label.grid(row=0, column=1, sticky="nw", padx=10, pady=5)
# --------------------------------- Фрейм для размера выборки и кнопки запуска симуляции -------------------------------
simulation_frame = ttk.LabelFrame(results_frame, text="Настройка симуляции", padding="10")
simulation_frame.pack(pady=5, padx=10, fill="x")
ttk.Label(simulation_frame, text=f"Размер выборки: ").grid(row=0, column=0, sticky="w", pady=5)
sample_size_entry = ttk.Entry(simulation_frame)
sample_size_entry.insert(0, "100000")
sample_size_entry.grid(row=0, column=1, sticky="e", padx=5, pady=2)
simulation_button = ttk.Button(simulation_frame, text="Начать симуляцию", command=create_sum_result_hist)
simulation_button.grid(row=0, column=2, sticky="e", padx=5, pady=2)
simulation_frame.columnconfigure(2, weight=1)
simulation_frame.rowconfigure(0, weight=1)
# --------------------------------- Фрейм для гистограммы сумм -------------------------------
hist_frame = ttk.LabelFrame(results_frame, text="Гистограмма сумм", padding="10")
hist_frame.pack(pady=5, padx=10, fill="x")
# ==================================================== ЗАПУСК =========================================================
update_distribution_comboboxes(selected_distribution_type.get())
update_parameter_fields()
root.mainloop()
are there any bugs?
Yes, there are potential bugs and areas for improvement in the code, focusing on:
Input Validation: The code currently retrieves parameter values from the param_entries dictionaries using .get() without proper validation. This can lead to errors if the user enters non-numeric values, leaves fields blank, or enters values outside the valid range for a specific distribution parameter. This is a major issue and needs to be addressed immediately.
Error Handling: The code includes print statements for error messages ("Пожалуйста, выберите распределение", "Введите коректный размер выборки"). These should be replaced with proper GUI feedback, such as message boxes or labels that display error messages directly in the application window. Using print is not user-friendly.
Discrete Distribution Limit Handling: The build function in get_graph and get_dist has a rudimentary limit handling for discrete distributions but might not be optimal for all cases. Consider edge cases or distributions with long tails.
Continuous Distribution Coverage: The default coverage value for building continuous distributions is 0.99. Adjusting this value dynamically or providing a control to the user may be required in some cases.
Distribution Parameter Conversion: All distribution parameters are retrieved as strings and implicitly converted to int or float within the get_dist function. This could cause a ValueError if a parameter is not a valid number. It's better to handle conversion and validation immediately after getting the value.
Plot Closure: The lines plt.close(fig1) and plt.close(fig2) prevent the figures from being displayed in a separate window. This is intended, but important to note. If you wanted separate figure windows, you'd remove these.
Global Variables: While using global variables can be convenient, excessive use makes the code harder to reason about and maintain. Consider encapsulating parts of the code into classes to manage state more effectively.
Numerical Stability: If sigma in normal distribution or lambda in exponential distribution is set too high, it can cause problems.
Here's the code with the most critical issues (input validation and GUI error handling) addressed. This will require the most changes:
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox # Import for error messages
import numpy as np
import math
from scipy.stats import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
# ==================================================== ГЛОБАЛЬНЫЕ ПЕРЕМЕННЫЕ ==============================================================
discrete_distributions = [
"Биномиальное",
"Отрицательное биномиальное",
"Пуассона",
"Геометрическое"
]
continuous_distributions = [
"Нормальное",
"Экспоненциальное",
"Равномерное",
"Стьюдента",
"Хи-квадрат"
]
distribution_parameters = {
"Биномиальное": ["n", "p"],
"Отрицательное биномиальное": ["r", "p"],
"Пуассона": ["lambda"],
"Геометрическое": ["p"],
"Нормальное": ["mu", "sigma"],
"Экспоненциальное": ["lambda"],
"Равномерное": ["a", "b"],
"Стьюдента": ["df"],
"Хи-квадрат": ["df"]
}
canvas1 = None
canvas2 = None
result_canvas = None
param_entries1 = {}
param_entries2 = {}
# ==================================================== ФУНКЦИИ =========================================================
# ----------------------------------- Обновление для выбора распределений -------------------------------------------
def update_distribution_comboboxes(selected_type):
if selected_type == "discrete":
available_distributions = discrete_distributions
elif selected_type == "continuous":
available_distributions = continuous_distributions
else:
available_distributions = []
dist1_combobox['values'] = available_distributions
dist2_combobox['values'] = available_distributions
dist1_combobox.set("Выберите...")
dist2_combobox.set("Выберите...")
update_parameter_fields()
clear_plots()
# ----------------------------------- Обновление для параметров распределений -------------------------------------
def update_parameter_fields(event=None):
global param_entries1, param_entries2
dist1_name = dist1_combobox.get()
dist2_name = dist2_combobox.get()
param_entries1 = create_parameter_widgets(params1_frame, dist1_name)
param_entries2 = create_parameter_widgets(params2_frame, dist2_name)
clear_plots()
# ----------------------------------- Создание виджетов для параметров -------------------------------------------
def create_parameter_widgets(frame, dist_name):
for widget in frame.winfo_children():
widget.destroy()
parameters = distribution_parameters.get(dist_name)
if parameters:
ttk.Label(frame, text=f"Параметры для {dist_name}:").grid(row=0, column=0, columnspan=2, sticky="w", pady=5)
entry_widgets = {}
for i, param_name in enumerate(parameters):
ttk.Label(frame, text=f"{param_name}:").grid(row=i+1, column=0, sticky="w", padx=5, pady=2)
entry = ttk.Entry(frame)
entry.grid(row=i+1, column=1, sticky="ew", padx=5, pady=2)
entry_widgets[param_name] = entry
frame.columnconfigure(1, weight=1)
return entry_widgets
else:
ttk.Label(frame, text="Выберите распределение").grid(row=0, column=0, sticky="w")
return None
# ----------------------------------- Очистка графиков -------------------------------------------
def clear_plots():
global canvas1, canvas2, result_canvas
if canvas1:
canvas1.get_tk_widget().destroy()
canvas1 = None
if canvas2:
canvas2.get_tk_widget().destroy()
canvas2 = None
if result_canvas:
result_canvas.get_tk_widget().destroy()
result_canvas = None
dist1_description_label.config(text="Распределение 1: Не выбрано")
dist2_description_label.config(text="Распределение 2: Не выбрано")
# ----------------------------------- Постройка графиков -------------------------------------------
def plot_distributions():
clear_plots()
dist1_name = dist1_combobox.get()
dist2_name = dist2_combobox.get()
if dist1_name == "Выберите..." or dist2_name == "Выберите...":
messagebox.showerror("Ошибка", "Пожалуйста, выберите оба распределения.")
return
params1_values = {}
try:
for name, entry in param_entries1.items():
value = entry.get()
if not value:
raise ValueError(f"Пожалуйста, введите значение для параметра {name} (Распределение 1).")
# Try converting to int if it's an integer parameter, otherwise float
if name in ("n", "r", "df"): #integer parameters
params1_values[name] = int(value)
else:
params1_values[name] = float(value)
except ValueError as e:
messagebox.showerror("Ошибка", str(e))
return
params2_values = {}
try:
for name, entry in param_entries2.items():
value = entry.get()
if not value:
raise ValueError(f"Пожалуйста, введите значение для параметра {name} (Распределение 2).")
if name in ("n", "r", "df"):
params2_values[name] = int(value)
else:
params2_values[name] = float(value)
except ValueError as e:
messagebox.showerror("Ошибка", str(e))
return
dist1_description_label.config(text=f"Распределение 1: {dist1_name} (Параметры: {params1_values})")
dist2_description_label.config(text=f"Распределение 2: {dist2_name} (Параметры: {params2_values})")
# --- Создание и отображение графика для Распределения 1 ---
global canvas1
fig1, ax1 = plt.subplots(figsize=(6, 4))
values1, probabilities1 = get_graph(dist1_name, params1_values)
if dist1_name in discrete_distributions:
ax1.bar(values1, probabilities1, width=0.7, color='blue', edgecolor='black')
elif dist1_name in continuous_distributions:
ax1.plot(values1, probabilities1, color='blue')
ax1.set_title(f"{dist1_name}")
ax1.set_xlabel("Значение")
ax1.set_ylabel(f"{'Вероятность' if dist1_name in discrete_distributions else 'Плотность'}") # corrected to dist1_name
canvas1 = FigureCanvasTkAgg(fig1, master=plot1_frame)
canvas1.draw()
canvas1.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
# --- Создание и отображение графика для Распределения 2 ---
global canvas2
fig2, ax2 = plt.subplots(figsize=(6, 4))
values2, probabilities2 = get_graph(dist2_name, params2_values)
if dist2_name in discrete_distributions:
ax2.bar(values2, probabilities2, width=0.7, color='red', edgecolor='black')
elif dist2_name in continuous_distributions:
ax2.plot(values2, probabilities2, color='red')
ax2.set_title(f"{dist2_name}")
ax2.set_xlabel("Значение")
ax2.set_ylabel(f"{'Вероятность' if dist2_name in discrete_distributions else 'Плотность'}")
canvas2 = FigureCanvasTkAgg(fig2, master=plot2_frame)
canvas2.draw()
canvas2.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
plt.close(fig1)
plt.close(fig2)
main_notebook.select(results_frame)
# ----------------------------------- Создание объекта распределения ----------------------------------------------
def get_dist(dist_name, params_values):
try:
if dist_name in discrete_distributions:
dist = None
x = None
limit = None
if dist_name == "Биномиальное":
n = int(params_values['n'])
p = float(params_values['p'])
dist = binom(n=n, p=p)
x = 0
limit = n
elif dist_name == "Отрицательное биномиальное":
r = int(params_values['r'])
p = float(params_values['p'])
dist = nbinom(n=r, p=p)
x = r
elif dist_name == "Пуассона":
lmd = float(params_values['lambda'])
dist = poisson(mu=lmd)
x = 0
elif dist_name == "Геометрическое":
p = float(params_values['p'])
dist = geom(p=p)
x = 1
else:
messagebox.showerror("Ошибка", "Пожалуйста, выберите распределение")
return None, None, None
return dist, x, limit
elif dist_name in continuous_distributions:
dist = None
x = None
limit = None
if dist_name == "Нормальное":
mu = float(params_values['mu'])
sigma = float(params_values['sigma'])
dist = norm(loc=mu, scale=sigma)
elif dist_name == "Экспоненциальное":
lmd = float(params_values['lambda'])
dist = expon(loc=0, scale=1/lmd)
x = 0
elif dist_name == "Равномерное":
a = float(params_values['a'])
b = float(params_values['b'])
dist = uniform(loc=a, scale=b-a)
x = a
limit = b
elif dist_name == "Стьюдента":
df = int(params_values['df'])
dist = t(df, loc=0, scale=1)
elif dist_name == "Хи-квадрат":
df = int(params_values['df'])
dist = chi2(df, loc=0, scale=1)
else:
messagebox.showerror("Ошибка", "Пожалуйста, выберите распределение")
return None, None, None
return dist, x, limit
else:
messagebox.showerror("Ошибка", "Пожалуйста, выберите распределение")
return None, None, None
except ValueError as e:
messagebox.showerror("Ошибка", f"Invalid parameter value: {e}") # Report specific parameter error
return None, None, None
# ----------------------------------- Получение данных для графика ----------------------------------------------
def get_graph(dist_name, params_values):
if dist_name in discrete_distributions:
epsilon = 5e-4
def build(dist_, x_, limit_=None):
mean = dist_.mean()
values_ = []
probabilities_ = []
while True and (limit_ is None or x_ <= limit_):
px_ = dist_.pmf(x_)
if px_ < epsilon:
if x_ < mean:
x_ += 1
continue
break
values_.append(x_)
probabilities_.append(px_)
x_ += 1
values_ = np.array(values_)
probabilities_ = np.array(probabilities_)
return values_, probabilities_
dist, x, limit = get_dist(dist_name, params_values)
if dist is None:
return [], []
values, probabilities = build(dist, x, limit)
elif dist_name in continuous_distributions:
coverage = 0.99
if dist_name == "Равномерное":
coverage = 0.9999
alpha_ = 1 - coverage
num_points = 1000
def build(dist_):
low_b = dist_.ppf(alpha_ / 2)
up_b = dist_.ppf(1 - alpha_ / 2)
values_ = np.linspace(low_b, up_b, num_points)
probabilities_ = np.array([dist_.pdf(k) for k in values_])
return values_, probabilities_
dist, _, _ = get_dist(dist_name, params_values)
if dist is None:
return [], []
values, probabilities = build(dist)
else:
messagebox.showerror("Ошибка", "Пожалуйста, выберите распределение")
return [], []
return values, probabilities
# ----------------------------------- Получение числа с графика ----------------------------------------------
def get_dist_rnd(dist_name, params_values, sample_size):
dist, _, _ = get_dist(dist_name, params_values)
if dist is None:
return None # Or raise an exception, depending on the desired behavior
return dist.rvs(size=sample_size)
# ----------------------------------- Построение гистограммы сум ----------------------------------------------
def create_sum_result_hist():
dist1_name = dist1_combobox.get()
dist2_name = dist2_combobox.get()
if dist1_name == "Выберите..." or dist2_name == "Выберите...":
messagebox.showerror("Ошибка", "Пожалуйста, выберите оба распределения.")
return
params1_values = {}
try:
for name, entry in param_entries1.items():
value = entry.get()
if not value:
raise ValueError(f"Пожалуйста, введите значение для параметра {name} (Распределение 1).")
# Try converting to int if it's an integer parameter, otherwise float
if name in ("n", "r", "df"): #integer parameters
params1_values[name] = int(value)
else:
params1_values[name] = float(value)
except ValueError as e:
messagebox.showerror("Ошибка", str(e))
return
params2_values = {}
try:
for name, entry in param_entries2.items():
value = entry.get()
if not value:
raise ValueError(f"Пожалуйста, введите значение для параметра {name} (Распределение 2).")
if name in ("n", "r", "df"):
params2_values[name] = int(value)
else:
params2_values[name] = float(value)
except ValueError as e:
messagebox.showerror("Ошибка", str(e))
return
try:
sample_size = int(sample_size_entry.get())
if sample_size <= 0:
raise ValueError("Размер выборки должен быть положительным.")
except ValueError as e:
messagebox.showerror("Ошибка", f"Введите корректный размер выборки: {e}")
return
sample1 = get_dist_rnd(dist1_name, params1_values, sample_size)
if sample1 is None:
return
sample2 = get_dist_rnd(dist2_name, params2_values, sample_size)
if sample2 is None:
return
samples_sum = sample1 + sample2
max_el = max(np.quantile(sample1, 0.99), np.quantile(sample2, 0.99), np.quantile(samples_sum, 0.99))
min_el = min(np.quantile(sample1, 0.01), np.quantile(sample2, 0.01), np.quantile(samples_sum, 0.01))
bins_num = math.floor(max_el - min_el + 1)
bins = None
if dist1_name in continuous_distributions:
bins_num = max(bins_num, 20)
bins_num = math.ceil(2 * (sample_size * bins_num ** 0.5) ** (1/3))
bins = np.linspace(min_el, max_el, bins_num)
else:
bins = np.arange(min_el, max_el + 2).astype(float)
bins = bins - 0.5
global canvas1, canvas2, result_canvas
if result_canvas:
result_canvas.get_tk_widget().destroy()
result_canvas = None
fig, ax = plt.subplots(figsize=(7, 5))
ax.hist(samples_sum, bins=bins, density=True, rwidth=0.7, color="black", histtype='stepfilled')
ax.hist(sample1, bins=bins, density=True, rwidth=0.7, color="blue", histtype='step', linewidth=3, alpha=0.5)
ax.hist(sample2, bins=bins, density=True, rwidth=0.7, color="red", histtype='step', linewidth=3, alpha=0.5)
ax.set_title(f"Гистограмма распределения сумм")
ax.set_xlabel("Значение")
ax.set_ylabel(f"{'Вероятность' if dist2_name in discrete_distributions else 'Плотность'}")
# ax.grid(True)
result_canvas = FigureCanvasTkAgg(fig, master=hist_frame)
result_canvas.draw()
result_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
plt.close(fig)
# ==================================================== СОЗДАНИЕ ОКНА ==================================================
# ------------------------------------------ Создание вкладок -------------------------------------
root = tk.Tk()
root.title("Project-KD")
# root.geometry("800x700")
main_notebook = ttk.Notebook(root)
main_notebook.pack(pady=10, padx=10, fill="both", expand=True)
setup_frame = ttk.Frame(main_notebook, padding="10")
results_frame = ttk.Frame(main_notebook, padding="10")
main_notebook.add(setup_frame, text='Настройка')
main_notebook.add(results_frame, text='Результаты')
# ------------------------------------------ Фрейм для выбора типа -------------------------------------
type_selection_frame = ttk.LabelFrame(setup_frame, text="Выберите тип распределений", padding="10")
type_selection_frame.pack(pady=10, padx=10, fill="x")
selected_distribution_type = tk.StringVar()
selected_distribution_type.set("discrete")
discrete_radio = ttk.Radiobutton(
type_selection_frame,
text="Дискретные",
variable=selected_distribution_type,
value="discrete",
command=lambda: update_distribution_comboboxes(selected_distribution_type.get())
)
discrete_radio.pack(side="left", padx=10)
continuous_radio = ttk.Radiobutton(
type_selection_frame,
text="Непрерывные",
variable=selected_distribution_type,
value="continuous",
command=lambda: update_distribution_comboboxes(selected_distribution_type.get())
)
continuous_radio.pack(side="left", padx=10)
# ------------------------------------------ Фрейм для выбора распределений -------------------------------------
distribution_selection_frame = ttk.LabelFrame(setup_frame, text="Выберите два распределения", padding="10")
distribution_selection_frame.pack(pady=5, padx=10, fill="x")
ttk.Label(distribution_selection_frame, text="Распределение 1:").grid(row=0, column=0, sticky="w", padx=5, pady=5)
dist1_combobox = ttk.Combobox(distribution_selection_frame, state="readonly")
dist1_combobox.grid(row=0, column=1, sticky="ew", padx=5, pady=5)
ttk.Label(distribution_selection_frame, text="Распределение 2:").grid(row=1, column=0, sticky="w", padx=5, pady=5)
dist2_combobox = ttk.Combobox(distribution_selection_frame, state="readonly")
dist2_combobox.grid(row=1, column=1, sticky="ew", padx=5, pady=5)
distribution_selection_frame.columnconfigure(1, weight=1)
dist1_combobox.bind("<<ComboboxSelected>>", update_parameter_fields)
dist2_combobox.bind("<<ComboboxSelected>>", update_parameter_fields)
# ------------------------------------------ Фрейм для параметров -------------------------------------
params1_frame = ttk.LabelFrame(setup_frame, text="Параметры Распределения 1", padding="10")
params1_frame.pack(pady=5, padx=10, fill="x")
params2_frame = ttk.LabelFrame(setup_frame, text="Параметры Распределения 2", padding="10")
params2_frame.pack(pady=5, padx=10, fill="x")
# ------------------------------------------ Кнопка постройки графиков -------------------------------------
plots_button = ttk.Button(setup_frame, text="Построить графики", command=plot_distributions)
plots_button.pack(pady=10)
# ------------------------------------------ Фрейм для графиков -------------------------------------
plots_frame = ttk.LabelFrame(results_frame, text="Распределения", padding="10")
plots_frame.pack(pady=5, padx=10, fill="x")
plot1_frame = ttk.LabelFrame(plots_frame, text="График Распределения 1", padding="10")
plot1_frame.grid(row=1, column=0, sticky="nsew", padx=10, pady=5)
plot2_frame = ttk.LabelFrame(plots_frame, text="График Распределения 2", padding="10")
plot2_frame.grid(row=1, column=1, sticky="nsew", padx=10, pady=5)
plots_frame.columnconfigure(0, weight=1)
plots_frame.columnconfigure(1, weight=1)
plots_frame.rowconfigure(1, weight=1)
dist1_description_label = ttk.Label(plots_frame, text="Распределение 1: Не выбрано")
dist1_description_label.grid(row=0, column=0, sticky="nw", padx=10, pady=5)
dist2_description_label = ttk.Label(plots_frame, text="Распределение 2: Не выбрано")
dist2_description_label.grid(row=0, column=1, sticky="nw", padx=10, pady=5)
# --------------------------------- Фрейм для размера выборки и кнопки запуска симуляции -------------------------------
simulation_frame = ttk.LabelFrame(results_frame, text="Настройка симуляции", padding="10")
simulation_frame.pack(pady=5, padx=10, fill="x")
ttk.Label(simulation_frame, text=f"Размер выборки: ").grid(row=0, column=0, sticky="w", pady=5)
sample_size_entry = ttk.Entry(simulation_frame)
sample_size_entry.insert(0, "100000")
sample_size_entry.grid(row=0, column=1, sticky="e", padx=5, pady=2)
simulation_button = ttk.Button(simulation_frame, text="Начать симуляцию", command=create_sum_result_hist)
simulation_button.grid(row=0, column=2, sticky="e", padx=5, pady=2)
simulation_frame.columnconfigure(2, weight=1)
simulation_frame.rowconfigure(0, weight=1)
# --------------------------------- Фрейм для гистограммы сумм -------------------------------
hist_frame = ttk.LabelFrame(results_frame, text="Гистограмма сумм", padding="10")
hist_frame.pack(pady=5, padx=10, fill="x")
# ==================================================== ЗАПУСК =========================================================
update_distribution_comboboxes(selected_distribution_type.get())
update_parameter_fields()
root.mainloop()
Key changes in the corrected code:
messagebox: Added from tkinter import messagebox to enable the use of error dialogs.try...except blocks.ValueError if found.int or float based on the parameter name. This is a heuristic approach. You might want a more robust system based on the selected distribution.print statements with messagebox.showerror() to display errors directly to the user.get_dist and get_graph: Modified get_dist and get_graph to return None (or [], []) on error and added checks in the calling functions.create_sum_result_hist.This revised code is significantly more robust due to the input validation and error handling. It will prevent the program from crashing when the user enters invalid data and provide helpful error messages. It is essential that you use this code as a starting point and continue to refine the validation logic based on the specific requirements of each distribution. For instance, you might need to check that probabilities are within the range [0, 1], standard deviations are positive, degrees of freedom are positive integers, etc.
Remember to test the error handling thoroughly to ensure the application behaves as expected in various scenarios. The remaining points regarding discrete distribution limits, continuous distribution coverage, global variables, and numerical stability should be addressed after this critical fix.