정보통신기술(ICT)

머터리얼 디스커버리 알고리즘

해머슴 2024. 11. 27. 11:03
import tkinter as tk
from tkinter import messagebox, simpledialog
import random
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# 데이터 생성 및 필터링
def generate_sample_data(total_samples=300000, filtered_count=300):
    data = pd.DataFrame({
        'Element': [f"Element_{i}" for i in range(1, total_samples + 1)],
        'Symbol': [f"E{i}" for i in range(1, total_samples + 1)],
        'X': [random.uniform(0, 100) for _ in range(total_samples)],
        'Y': [random.uniform(0, 100) for _ in range(total_samples)]
    })
    filtered_data = data.sample(n=filtered_count, random_state=42).reset_index(drop=True)
    return filtered_data

# 원소 추가
def add_element_to_database():
    element = simpledialog.askstring("Add Element", "Enter the full name of the element:")
    symbol = simpledialog.askstring("Add Symbol", "Enter the symbol for the element:")
    x = random.uniform(0, 100)
    y = random.uniform(0, 100)

    if element and symbol:
        new_row = {'Element': element, 'Symbol': symbol, 'X': x, 'Y': y}
        global filtered_data
        filtered_data = pd.concat([filtered_data, pd.DataFrame([new_row])], ignore_index=True)
        messagebox.showinfo("Success", f"Element '{element}' with symbol '{symbol}' added to the database.")
    else:
        messagebox.showerror("Error", "Element or symbol cannot be empty!")

# 그래프 표시 함수
def display_graph(element):
    try:
        row = filtered_data[filtered_data['Element'] == element]
        if row.empty:
            symbol_row = filtered_data[filtered_data['Symbol'] == element]
            if symbol_row.empty:
                raise ValueError(f"Element '{element}' not found in filtered data.")
            row = symbol_row

        x, y = row['X'].values[0], row['Y'].values[0]

        # 그래프 초기화
        fig, ax = plt.subplots()
        ax.scatter(filtered_data['X'], filtered_data['Y'], label="Filtered Samples", alpha=0.5)
        ax.scatter(x, y, color='red', label=f"Selected: {element}")
        ax.set_xlabel("X Coordinate")
        ax.set_ylabel("Y Coordinate")
        ax.set_title("Filtered Element Visualization")
        ax.legend()

        # Tkinter 창에 그래프 표시
        canvas = FigureCanvasTkAgg(fig, master=root)
        canvas_widget = canvas.get_tk_widget()
        canvas_widget.pack()
        canvas.draw()

    except ValueError as e:
        messagebox.showerror("Error", str(e))
        if messagebox.askyesno("Add Element", "Would you like to add this element to the database?"):
            add_element_to_database()

# GUI 초기화
def create_gui():
    global root, entry, filtered_data

    # Tkinter 메인 윈도우
    root = tk.Tk()
    root.title("Material Discovery Algorithm")

    # 필터링된 데이터 생성
    filtered_data = generate_sample_data()

    # 입력 필드
    tk.Label(root, text="Enter Element Name or Symbol (e.g., 'Element_123' or 'E123')").pack(pady=10)
    entry = tk.Entry(root, width=30)
    entry.pack()

    # 버튼
    tk.Button(root, text="Display Graph", command=lambda: display_graph(entry.get())).pack(pady=10)
    tk.Button(root, text="Add New Element", command=add_element_to_database).pack(pady=10)

    # GUI 루프 실행
    root.mainloop()

# 프로그램 실행
if __name__ == "__main__":
    create_gui()