OmidGHO's picture
Upload 2 files
d9d5092 verified
import pandas as pd
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.neighbors import NearestNeighbors
import gradio as gr
# --- 1. MODEL AND DATA LOADING ---
# Load the dataset from the CSV file
df = pd.read_csv('data.csv')
# Define the columns for features and parameters
FEATURE_COLS = ['Thickness', 'Age', 'Diameter', 'Sex', 'Valve_phenotype', 'Region']
PARAM_COLS = ['mu', 'k1', 'k2', 'k_op', 'k_ip1', 'k_ip2', 'alpha1', 'alpha2']
NUMERIC_FEATURES = ['Thickness', 'Age', 'Diameter']
CATEGORICAL_FEATURES = ['Sex', 'Valve_phenotype', 'Region']
# Separate features (X)
X = df[FEATURE_COLS]
# Create and fit the preprocessor
# This learns how to scale numbers and encode categories from your full dataset
preprocessor = ColumnTransformer(
transformers=[
('num', StandardScaler(), NUMERIC_FEATURES),
('cat', OneHotEncoder(handle_unknown='ignore'), CATEGORICAL_FEATURES)
])
preprocessor.fit(X)
# Transform the data using the fitted preprocessor
X_processed = preprocessor.transform(X)
# Define and train the k-Nearest Neighbors model
knn = NearestNeighbors(n_neighbors=1, metric='euclidean')
knn.fit(X_processed)
print("Model initialized successfully!")
# --- 2. THE PREDICTION FUNCTION ---
# This function will be called by the Gradio interface
def find_closest_patient(thickness, age, diameter, sex, valve, region):
"""
Takes new patient data from the UI, finds the closest match,
and returns the results as formatted strings.
"""
# Create a DataFrame from the user's input
new_patient_df = pd.DataFrame([{
'Thickness': thickness,
'Age': age,
'Diameter': diameter,
'Sex': sex,
'Valve_phenotype': valve,
'Region': region
}])[FEATURE_COLS]
# Preprocess the new data
new_patient_processed = preprocessor.transform(new_patient_df)
# Find the nearest neighbor's index
distances, indices = knn.kneighbors(new_patient_processed)
closest_index = indices[0][0]
# Get the info and parameters of the closest match
closest_patient_info = df.loc[closest_index, FEATURE_COLS].to_dict()
closest_patient_params = df.loc[closest_index, PARAM_COLS].to_dict()
# Format the output nicely for display
info_str = "\n".join([f"{key}: {value}" for key, value in closest_patient_info.items()])
params_str = "\n".join([f"{key}: {value}" for key, value in closest_patient_params.items()])
return info_str, params_str
# --- 3. THE GRADIO WEB INTERFACE ---
# We define the user interface here
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# Constitutive Parameter Estimator for ATAA")
gr.Markdown("Enter the clinical information for a patient to find the constitutive parameters from the most similar case in the dataset.")
with gr.Row():
with gr.Column():
gr.Markdown("### Patient Clinical Information")
thickness_input = gr.Slider(minimum=1.0, maximum=4.0, value=2.4, step=0.01, label="Thickness (mm)")
age_input = gr.Slider(minimum=20, maximum=90, value=40, step=1, label="Age (years)")
diameter_input = gr.Slider(minimum=40.0, maximum=65.0, value=53.0, step=0.1, label="Diameter (mm)")
sex_input = gr.Radio(["M", "F"], label="Sex", value="F")
# The choices list is dynamically created from your CSV file's unique values
valve_input = gr.Dropdown(choices=df['Valve_phenotype'].unique().tolist(), label="Valve Phenotype", value="BAV")
region_input = gr.Dropdown(choices=df['Region'].unique().tolist(), label="Aortic Region", value="Anterior")
submit_button = gr.Button("Find Parameters", variant="primary")
with gr.Column():
gr.Markdown("### Results")
gr.Markdown("#### Closest Match Found in Dataset:")
output_info = gr.Textbox(label="Clinical Info of Match", lines=6)
gr.Markdown("#### Constitutive Parameters:")
output_params = gr.Textbox(label="Parameters", lines=8)
# Define what happens when the button is clicked
submit_button.click(
fn=find_closest_patient,
inputs=[thickness_input, age_input, diameter_input, sex_input, valve_input, region_input],
outputs=[output_info, output_params]
)
gr.Markdown("---")
gr.Markdown("### References\nFor methodology, please refer to: [Your Paper Citation Here]")
# Launch the web application
demo.launch()