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?
Here are the issues I’ve spotted (and suggestions for how to fix them):
Y–axis label of the first plot is tied to dist2_name instead of dist1_name
In plot_distributions() you do:
ax1.set_ylabel(
f"{'Вероятность' if dist2_name in discrete_distributions else 'Плотность'}"
)
→ it should read dist1_name there, because you’re labeling the first distribution:
- ax1.set_ylabel(f"{'Вероятность' if dist2_name in discrete_distributions else 'Плотность'}")
+ ax1.set_ylabel(f"{'Вероятность' if dist1_name in discrete_distributions else 'Плотность'}")
Negative-binomial support start is wrong
You wrote in get_dist()
elif dist_name == "Отрицательное биномиальное":
r = int(params_values['r'])
p = float(params_values['p'])
dist = nbinom(n=r, p=p)
x = r
But SciPy’s nbinom(n, p) is the count of failures before n successes, so its support is x = 0, 1, 2, …. If you start your loop at x=r you’ll miss all the mass at smaller x.
→ Change it to
- x = r
+ x = 0
Histogram / Y-axis labeling in the “sum” plot also only looks at dist2_name
In create_sum_result_hist() you do
ax.set_ylabel(f"{'Вероятность' if dist2_name in discrete_distributions else 'Плотность'}")
It would be more correct to say
For example:
is_sum_discrete = (dist1_name in discrete_distributions
and dist2_name in discrete_distributions)
ax.set_ylabel("Вероятность" if is_sum_discrete else "Плотность")
No parameter validation
Right now if you type sigma = -1 for a normal you’ll get an exception buried inside SciPy. You should at least do a quick check right after reading the entries:
try:
mu = float(params1_values['mu'])
sigma = float(params1_values['sigma'])
assert sigma > 0
except:
tk.messagebox.showerror("Ошибка","σ должно быть > 0")
return
Repeat / adapt for each distribution’s parameters.
(Minor) You set your default combobox text to "Выберите..." even though that value isn’t in the .values list. In practice it works, but it’s a bit non-standard. An alternative is to prepend "Выберите..." to your values list itself:
dist1_combobox['values'] = ["Выберите..."] + available_distributions
dist1_combobox.set("Выберите...")
With those changes in place your GUI should:
• Correctly label each plot
• Cover the entire support of the negative-binomial
• Avoid user-input explosions by validating parameters up front
Let me know if you run into anything else! 😊