Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • h2-veziroglu/sdgp_feedingdashboard
1 result
Show changes
Commits on Source (3)
__pycache__/
*.pyc
venv/
.DS_Store
This diff is collapsed.
import tkinter as tk
import os
from app1 import Homepage
from feeding_dashboard import UploadPage
class MainApplication(tk.Tk):
def __init__(self):
super().__init__()
print("MainApplication initialized.")
self.title("Patient Referral System")
self.geometry("1200x800")
self.container = tk.Frame(self)
self.container.pack(fill="both", expand=True)
self.container.grid_rowconfigure(0, weight=1)
self.container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (Homepage, UploadPage):
page_name = F.__name__
print(f"Creating {page_name} frame.")
frame = F(parent=self.container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
print(f"{page_name} frame created and added to frames dictionary.") # Debug
print("Showing Homepage frame.")
self.show_frame("Homepage")
self.protocol("WM_DELETE_WINDOW", self.on_closing)
def show_frame(self, page_name):
print(f"Attempting to show {page_name} frame.") # Debug
frame = self.frames.get(page_name)
if frame:
print(f"Raising {page_name} frame.") # Debug
frame.tkraise()
if page_name == "Homepage":
print("Calling show_homepage on Homepage frame.") # Debug
frame.show_homepage()
else:
print(f"Frame {page_name} not found in frames dictionary.") # Debug
def on_closing(self):
"""Delete data.csv when the application is closed."""
if os.path.exists("data.csv"):
os.remove("data.csv")
self.destroy()
if __name__ == "__main__":
app = MainApplication()
app.mainloop()
import tkinter as tk
from tkinter import filedialog, ttk
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class Homepage(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent)
self.controller = controller
self.sidebar = tk.Frame(self, bg='#2c3e50', width=220, height=800)
self.sidebar.pack(side=tk.LEFT, fill=tk.Y)
self.home_btn = tk.Button(self.sidebar, text="Homepage", command=lambda: controller.show_frame("Homepage"), bg='#3498db', font=("Arial", 12))
self.home_btn.pack(pady=10, padx=10, fill=tk.X)
self.upload_btn = tk.Button(self.sidebar, text="Upload CSV", command=lambda: controller.show_frame("UploadPage"), bg='#27ae60', font=("Arial", 12))
self.upload_btn.pack(pady=10, padx=10, fill=tk.X)
self.main_frame = tk.Frame(self, bg='white', width=980, height=800)
self.main_frame.pack(fill="both", expand=True)
self.data = None
self.show_homepage()
def show_homepage(self):
for widget in self.main_frame.winfo_children():
widget.destroy()
tk.Label(self.main_frame, text="Patient Referral Dashboard", font=("Arial", 20), bg='white').pack(pady=10)
try:
self.data = pd.read_csv("data.csv")
self.generate_charts()
except (FileNotFoundError, pd.errors.EmptyDataError):
tk.Label(self.main_frame, text="No data available. Please upload data in the Upload Data page.",
font=("Arial", 14), bg='white').pack(pady=20)
def generate_charts(self):
"""Generate and display charts only if data is available."""
if self.data is None or self.data.empty:
return
total_patients = len(self.data)
referral_patients = self.data['referral'].sum()
non_referral_patients = total_patients - referral_patients
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
labels = ['Need Referral', 'Do Not Need Referral']
sizes = [referral_patients, non_referral_patients]
axes[0].pie(sizes, labels=labels, autopct='%1.1f%%', startangle=100, colors=['#66c2a5', '#fc8d62'])
axes[0].set_title("Patient Referral Distribution", fontsize=16)
average_data = self.data.drop(columns=['encounterId', 'referral']).mean()
axes[1].bar(average_data.index, average_data.values, color='#1f77b4', width=0.4)
axes[1].set_xticklabels(average_data.index, rotation=45, ha='right', fontsize=10)
axes[1].set_title("Average Patient Data", fontsize=14)
plt.tight_layout()
canvas = FigureCanvasTkAgg(fig, master=self.main_frame)
canvas.draw()
canvas.get_tk_widget().pack(pady=10)
def show_data(self):
"""Display the uploaded CSV data in a table format."""
for widget in self.main_frame.winfo_children():
widget.destroy()
if self.data is not None:
tree = ttk.Treeview(self.main_frame)
tree['columns'] = tuple(self.data.columns)
for col in self.data.columns:
tree.heading(col, text=col)
tree.column(col, width=100)
for index, row in self.data.iterrows():
tree.insert("", "end", values=tuple(row))
tree.pack(fill=tk.BOTH, expand=True)
else:
tk.Label(self.main_frame, text="No Data Available", font=("Arial", 14), bg='white').pack(pady=20)
def on_closing(self):
"""Delete data.csv when the dashboard is closed."""
if os.path.exists("data.csv"):
os.remove("data.csv")
self.root.destroy()
This diff is collapsed.
File added
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import pandas as pd
import numpy as np
import joblib
import subprocess
model = joblib.load("dietitian_model.pkl")
REQUIRED_COLUMNS = ["end_tidal_co2", "feed_vol", "feed_vol_adm", "fio2", "fio2_ratio",
"insp_time", "oxygen_flow_rate", "peep", "pip", "resp_rate", "sip",
"tidal_vol", "tidal_vol_actual", "tidal_vol_kg", "tidal_vol_spon", "bmi"]
class UploadPage(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent)
self.controller = controller
self.sidebar = tk.Frame(self, bg='#2c3e50', width=220, height=800)
self.sidebar.pack(side=tk.LEFT, fill=tk.Y)
self.home_btn = tk.Button(self.sidebar, text="Homepage", command=lambda: self.controller.show_frame("Homepage"), bg='#3498db', font=("Arial", 12))
self.home_btn.pack(pady=10, padx=10, fill=tk.X)
self.upload_btn = tk.Button(self.sidebar, text="Upload CSV", command=self.upload_csv, bg='#27ae60', font=("Arial", 12))
self.upload_btn.pack(pady=10, padx=10, fill=tk.X)
self.main_frame = tk.Frame(self)
self.main_frame.pack(fill="both", expand=True)
self.filter_frame = tk.Frame(self.main_frame)
self.filter_frame.pack(side="top", fill="x", padx=10, pady=5)
self.search_var = tk.StringVar()
self.search_entry = tk.Entry(self.filter_frame, textvariable=self.search_var, width=20)
self.search_entry.pack(side="left", padx=5)
self.search_entry.bind("<KeyRelease>", self.search_patient)
self.show_all_btn = tk.Button(self.filter_frame, text="Show All", command=self.show_all)
self.show_all_btn.pack(side="left", padx=5)
self.need_referral_btn = tk.Button(self.filter_frame, text="Need Referral", command=lambda: self.filter_by_status("Need Referral"))
self.need_referral_btn.pack(side="left", padx=5)
self.no_need_referral_btn = tk.Button(self.filter_frame, text="No Need Referral", command=lambda: self.filter_by_status("No Need Referral"))
self.no_need_referral_btn.pack(side="left", padx=5)
self.table_frame = tk.Frame(self.main_frame)
self.table_frame.pack(side="left", fill="both", expand=True, padx=10, pady=10)
self.tree = ttk.Treeview(self.table_frame, columns=("ID", "Referral"), show="headings")
self.tree.heading("ID", text="Patient ID")
self.tree.heading("Referral", text="Dietitian Referral")
self.tree.bind("<Double-1>", self.view_patient_details)
self.tree.pack(fill="both", expand=True)
self.details_frame = tk.Frame(self.main_frame, relief=tk.SUNKEN, borderwidth=2)
self.details_visible = False
tk.Button(self, text="Upload New CSV", command=self.upload_csv).pack(pady=5)
self.patients = []
def open_homepage(self):
self.controller.show_frame("Homepage")
def close_patient_details(self):
"""Hide patient details panel."""
if self.details_visible:
self.details_frame.pack_forget()
self.details_visible = False
def view_patient_details(self, event):
"""Always show details when a patient is clicked."""
selected_item = self.tree.selection()
if not selected_item:
return
patient_id = int(float(self.tree.item(selected_item, "values")[0]))
patient = next((p for p in self.patients if p["encounterId"] == patient_id), None)
if patient:
for widget in self.details_frame.winfo_children():
widget.destroy()
self.details_label = tk.Label(self.details_frame, text="Patient Details", font=("Arial", 14, "bold"))
self.details_label.pack(anchor="n", pady=5)
close_button = tk.Button(self.details_frame, text="", font=("Arial", 12, "bold"),
command=self.close_patient_details, relief=tk.FLAT,
bg="white", fg="gray", width=2, height=1)
close_button.pack(anchor="ne", padx=3, pady=3)
self.details_table = ttk.Treeview(self.details_frame, columns=("Attribute", "Value"), show="headings")
self.details_table.heading("Attribute", text="Attribute")
self.details_table.heading("Value", text="Value")
self.details_table.pack(fill="both", expand=True, padx=5, pady=5)
referral_status = "Need Referral" if patient['referral'] else "No Need Referral"
self.details_table.insert("", "end", values=("Patient ID", patient['encounterId']))
self.details_table.insert("", "end", values=("Referral Status", referral_status), tags=(referral_status,))
self.details_table.tag_configure("Need Referral", background="#FFDDDD")
self.details_table.tag_configure("No Need Referral", background="#DDEEFF")
for key in REQUIRED_COLUMNS:
self.details_table.insert("", "end", values=(key.replace('_', ' ').title(), patient[key]))
self.details_frame.pack(side="right", fill="both", expand=True, padx=10, pady=10)
self.details_visible = True
def search_patient(self, event=None):
"""Search by Patient ID dynamically."""
search_query = self.search_var.get().strip()
self.tree.delete(*self.tree.get_children())
for patient in self.patients:
if search_query.isdigit() and str(patient["encounterId"]).startswith(search_query):
referral_status = "Need Referral" if patient["referral"] else "No Need Referral"
self.tree.insert("", "end", values=(patient["encounterId"], referral_status), tags=(referral_status,))
def filter_by_status(self, status):
"""Filter patients by referral status."""
self.tree.delete(*self.tree.get_children())
for patient in self.patients:
referral_status = "Need Referral" if patient["referral"] else "No Need Referral"
if referral_status == status:
self.tree.insert("", "end", values=(patient["encounterId"], referral_status), tags=(referral_status,))
def show_all(self):
"""Show all patients."""
self.tree.delete(*self.tree.get_children())
for patient in self.patients:
referral_status = "Need Referral" if patient["referral"] else "No Need Referral"
self.tree.insert("", "end", values=(patient["encounterId"], referral_status), tags=(referral_status,))
def upload_csv(self):
"""Upload CSV and update table."""
file_path = filedialog.askopenfilename(filetypes=[("CSV Files", "*.csv")])
if not file_path:
return
df = pd.read_csv(file_path)
if "encounterId" in df.columns:
df["encounterId"] = df["encounterId"].astype(int)
trained_feature_names = list(model.feature_names_in_)
missing_cols = [col for col in trained_feature_names if col not in df.columns]
if missing_cols:
messagebox.showerror("Error", f"Missing columns: {', '.join(missing_cols)}")
return
df = df[["encounterId"] + trained_feature_names]
self.patients.clear()
self.tree.delete(*self.tree.get_children())
feature_values = df[trained_feature_names].to_numpy()
referral_predictions = model.predict(feature_values)
for i, row in df.iterrows():
referral_prediction = int(referral_predictions[i])
patient_entry = {"encounterId": int(row["encounterId"]), "referral": referral_prediction}
for key in trained_feature_names:
patient_entry[key] = row[key]
self.patients.append(patient_entry)
referral_status = "Need Referral" if referral_prediction else "No Need Referral"
self.tree.insert("", "end", values=(int(row["encounterId"]), referral_status), tags=(referral_status,))
self.tree.tag_configure("Need Referral", background="#FFDDDD")
self.tree.tag_configure("No Need Referral", background="#DDEEFF")
df["referral"] = referral_predictions
df.to_csv("data.csv", index=False)
messagebox.showinfo("Success", "CSV uploaded successfully!")
\ No newline at end of file
Source diff could not be displayed: it is too large. Options to address this: view the blob.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
file_path = "FeedingDashboardData.csv"
df = pd.read_csv(file_path)
REQUIRED_COLUMNS = [
"end_tidal_co2", "feed_vol", "feed_vol_adm", "fio2", "fio2_ratio",
"insp_time", "oxygen_flow_rate", "peep", "pip", "resp_rate", "sip",
"tidal_vol", "tidal_vol_actual", "tidal_vol_kg", "tidal_vol_spon", "bmi", "referral"
]
missing_columns = [col for col in REQUIRED_COLUMNS if col not in df.columns]
if missing_columns:
print(f"⚠️ Missing columns in the uploaded data: {missing_columns}")
raise ValueError("Uploaded data is missing required columns.")
imputer = SimpleImputer(strategy="median")
df[REQUIRED_COLUMNS[:-1]] = imputer.fit_transform(df[REQUIRED_COLUMNS[:-1]])
# feetuee scaling
scaler = MinMaxScaler()
df[REQUIRED_COLUMNS[:-1]] = scaler.fit_transform(df[REQUIRED_COLUMNS[:-1]])
train_data, ml_data = train_test_split(df, test_size=0.2, random_state=42) #Split DAta
train_data.to_csv("dashboard_data1.csv", index=False)
ml_data.to_csv("ml_data1.csv", index=False)
print("✅ Data successfully validated, prepared, and saved!")
import unittest
import numpy as np
import joblib
import os
class TestDietitianModel(unittest.TestCase):
def setUp(self):
# Load the model once for all tests
model_path = "dietitian_model.pkl"
self.assertTrue(os.path.exists(model_path), "Model file not found.")
self.model = joblib.load(model_path)
# Example input (16 features in the correct order)
self.valid_input = np.array([[
35, # end_tidal_co2
250, # feed_vol
245, # feed_vol_adm
0.4, # fio2
300, # fio2_ratio
1.2, # insp_time
5, # oxygen_flow_rate
6, # peep
18, # pip
22, # resp_rate
5, # sip
450, # tidal_vol
460, # tidal_vol_actual
7.5, # tidal_vol_kg
100, # tidal_vol_spon
23.5 # bmi
]])
def test_model_predict_shape(self):
# Ensure the output has correct shape
prediction = self.model.predict(self.valid_input)
self.assertEqual(prediction.shape, (1,), "Prediction should return a single value.")
def test_prediction_output_type(self):
# Ensure the prediction is a binary classification (0 or 1)
prediction = self.model.predict(self.valid_input)[0]
self.assertIn(prediction, [0, 1], "Prediction should be 0 or 1 (No Referral or Need Referral).")
def test_model_input_size(self):
# Ensure the model expects 16 features
expected_features = 16
self.assertEqual(self.valid_input.shape[1], expected_features, "Input should have 16 features.")
if __name__ == "__main__":
unittest.main()
import pandas as pd
import joblib
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score
df = pd.read_csv("ml_data1.csv")
features = [
"end_tidal_co2", "feed_vol", "feed_vol_adm", "fio2", "fio2_ratio",
"insp_time", "oxygen_flow_rate", "peep", "pip", "resp_rate", "sip",
"tidal_vol", "tidal_vol_actual", "tidal_vol_kg", "tidal_vol_spon", "bmi"
]
df = df.dropna()
X = df[features]
y = df["referral"]
X.columns = features
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.8, random_state=42)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
joblib.dump(model, "dietitian_model.pkl")
print("✅ Model trained and saved successfully using only 20% of the data!")
y_pred = model.predict(X_test)
print("📈 Accuracy:", accuracy_score(y_test, y_pred))
print("📊 Classification Report:\n", classification_report(y_test, y_pred))