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?
The code you provided is quite extensive and implements a GUI-based application for selecting, visualizing, and simulating probability distributions. While the code appears to be well-structured and functional at first glance, there are several potential issues and areas for improvement that could lead to bugs or unexpected behavior. Below, I will outline these issues:
There is no validation for user inputs in the parameter fields (e.g., n, p, lambda, etc.). Users can enter invalid values such as negative numbers, non-numeric strings, or out-of-range probabilities.
If invalid inputs are provided, functions like get_dist or get_graph will fail when attempting to create distributions or compute probabilities.
Add input validation to ensure:
n, r, df, etc., are positive integers.p) are between 0 and 1.lambda, mu, sigma, etc., are positive floats.For example:
def validate_parameters(params):
for param_name, value in params.items():
if not value.strip(): # Check for empty input
return f"Parameter {param_name} is empty."
try:
if param_name in ["n", "r", "df"]:
if int(value) <= 0:
return f"Parameter {param_name} must be a positive integer."
elif param_name in ["p"]:
p = float(value)
if not (0 <= p <= 1):
return f"Probability {param_name} must be between 0 and 1."
else:
if float(value) <= 0:
return f"Parameter {param_name} must be positive."
except ValueError:
return f"Invalid value for parameter {param_name}."
return None
Call this function before creating distributions or plotting graphs.
If the user does not select valid distributions from the comboboxes, the program may attempt to access undefined variables or call functions with invalid arguments.
For example, if dist1_name or dist2_name is "Выберите..." or an invalid distribution, the program will fail when trying to access parameters or plot graphs.
Add checks to ensure valid distributions are selected before proceeding with any operations:
if dist1_name == "Выберите..." or dist2_name == "Выберите...":
messagebox.showerror("Ошибка", "Пожалуйста, выберите оба распределения.")
return
Use tkinter.messagebox to display error messages in the GUI.
The code creates multiple matplotlib figures but does not always close them properly. For example, plt.close(fig) is called only after plotting individual distributions, but not in all cases where figures are created.
This can lead to memory leaks, especially if the user repeatedly generates plots.
Ensure every figure is closed after use:
plt.close(fig1)
plt.close(fig2)
Additionally, consider using a context manager for figure creation:
with plt.figure(figsize=(6, 4)) as fig:
ax = fig.add_subplot(111)
# Plotting code here
The code assumes that the distinction between continuous and discrete distributions is always clear. However, some distributions (e.g., uniform) can be treated as either continuous or discrete depending on the context.
If a distribution is misclassified, the plotting logic may fail or produce incorrect results.
Clearly document the classification of each distribution and ensure consistency throughout the code.
Values like epsilon = 5e-4 and coverage = 0.99 are hardcoded in the get_graph function. These values may not be appropriate for all distributions or use cases.
For certain distributions or parameter ranges, these hardcoded values may lead to incomplete or inaccurate graphs.
Allow users to adjust these values via GUI inputs or dynamically compute them based on distribution properties.
The code uses global variables like canvas1, canvas2, and result_canvas. This can make the code harder to debug and maintain.
If these variables are not properly reset or updated, it could lead to unexpected behavior, such as overlapping plots or crashes.
Minimize the use of global variables by encapsulating related functionality into classes or passing variables explicitly between functions.
The code does not handle edge cases, such as:
These edge cases can cause runtime errors or incorrect results.
Add robust error handling and logging for edge cases. For example:
try:
# Code that may raise an exception
except Exception as e:
messagebox.showerror("Ошибка", f"Произошла ошибка: {str(e)}")
The create_sum_result_hist function generates large samples (e.g., sample_size = 100000) and computes histograms. This can be computationally expensive and slow.
The GUI may become unresponsive during long computations.
Run heavy computations in a separate thread or process using libraries like threading or multiprocessing. Update the GUI only after the computation is complete.
While the code is well-structured, some parts lack detailed comments or documentation, making it harder for others (or even the original author) to understand and maintain.
Add inline comments and docstrings to explain the purpose and functionality of each function and major block of code.
The layout of the GUI relies heavily on pack and grid managers. If the window is resized or additional widgets are added, the layout may break.
Widgets may overlap or disappear, leading to a poor user experience.
Test the GUI with different window sizes and resolutions. Consider using a more flexible layout manager like place or a GUI framework like PyQt.
The code is functional and well-designed, but it requires additional safeguards and improvements to handle edge cases, validate inputs, and optimize performance. Addressing the issues outlined above will make the application more robust, user-friendly, and maintainable.