Rathapoom commited on
Commit
0f4785f
·
verified ·
1 Parent(s): 0f2ba47

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -0
app.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.graph_objs as go
4
+
5
+ # Step 1: Load the cleaned sheet "Clean TH avg rise BMD" and display it
6
+ def load_clean_bmd_data(file_path):
7
+ sheet_clean_th_avg_rise = 'Clean TH avg rise BMD'
8
+ df_clean_th_avg_rise = pd.read_excel(file_path, sheet_name=sheet_clean_th_avg_rise)
9
+
10
+ # Select relevant columns: Drug names and BMD percentage increases
11
+ df_cleaned = df_clean_th_avg_rise[['Unnamed: 0', '1st', '2nd', '3rd', '4th', '5th', '6th', '8th', '10th']]
12
+
13
+ # Rename the first column to 'Drug'
14
+ df_cleaned.columns = ['Drug', '1st', '2nd', '3rd', '4th', '5th', '6th', '8th', '10th']
15
+
16
+ # Remove any rows with missing drug names
17
+ df_cleaned = df_cleaned.dropna(subset=['Drug'])
18
+
19
+ return df_cleaned
20
+
21
+ # Step 2: Adjust constants based on patient's BMD and T-score
22
+ def adjust_constants(bmd_patient, tscore_patient, c_avg, c_sd):
23
+ # Adjust C_avg and C_sd based on patient's BMD and T-score
24
+ error = tscore_patient - (bmd_patient - c_avg) / c_sd
25
+ c_avg_new = c_avg + error * c_sd
26
+ c_sd_new = (bmd_patient - c_avg) / tscore_patient
27
+ return c_avg_new, c_sd_new
28
+
29
+ # Step 3: Calculate BMD increase after medication (corrected version)
30
+ def calculate_bmd_increase(baseline_bmd, percentage_increase):
31
+ return baseline_bmd * (1 + percentage_increase)
32
+
33
+ # Step 4: Create a table showing BMD prediction and T-score conversion for each year for each drug
34
+ def create_bmd_and_tscore_prediction_tables(df_bmd_data, selected_drugs, bmd_patient, c_avg_new, c_sd_new):
35
+ years = ['1st', '2nd', '3rd', '4th', '5th', '6th', '8th', '10th']
36
+ drug_tables = {}
37
+
38
+ # Loop through each selected drug and generate the prediction table
39
+ for drug in selected_drugs:
40
+ predictions = []
41
+ for year in years:
42
+ if not pd.isna(df_bmd_data.loc[df_bmd_data['Drug'] == drug, year].values[0]):
43
+ percent_increase = df_bmd_data.loc[df_bmd_data['Drug'] == drug, year].values[0]
44
+ bmd_new = calculate_bmd_increase(bmd_patient, percent_increase) # Use baseline BMD
45
+ tscore_new = calculate_tscore_from_bmd(bmd_new, c_avg_new, c_sd_new) # Calculate predicted T-score
46
+ predictions.append((year, bmd_new, tscore_new))
47
+
48
+ # Create DataFrame for each drug
49
+ drug_table = pd.DataFrame(predictions, columns=['Year', 'Predicted BMD', 'Predicted T-score'])
50
+ drug_tables[drug] = drug_table
51
+
52
+ return drug_tables
53
+
54
+ # Step 5: Plot BMD and T-score as separate graphs side by side for each drug
55
+ def display_prediction_tables_and_plots(prediction_tables, baseline_bmd, baseline_tscore):
56
+ # Loop through each drug's prediction table
57
+ for drug, table in prediction_tables.items():
58
+ st.write(f"### {drug} Results")
59
+
60
+ # Display the prediction table for the current drug
61
+ st.dataframe(table)
62
+
63
+ # Create and display separate plots for each drug
64
+ years = ['0'] + list(table['Year'])
65
+ bmd_values = [baseline_bmd] + list(table['Predicted BMD'])
66
+ tscore_values = [baseline_tscore] + list(table['Predicted T-score'])
67
+
68
+ # Create BMD plot
69
+ trace_bmd = go.Scatter(x=years, y=bmd_values, mode='lines+markers', name=f'{drug} (BMD)', line=dict(color='blue'))
70
+ fig_bmd = go.Figure(data=[trace_bmd], layout=go.Layout(title=f'{drug} - Predicted BMD over Time', xaxis=dict(title='Years'), yaxis=dict(title='BMD (g/cm²)')))
71
+
72
+ # Create T-score plot
73
+ trace_tscore = go.Scatter(x=years, y=tscore_values, mode='lines+markers', name=f'{drug} (T-score)', line=dict(color='green'))
74
+ fig_tscore = go.Figure(data=[trace_tscore], layout=go.Layout(title=f'{drug} - Predicted T-score over Time', xaxis=dict(title='Years'), yaxis=dict(title='T-score')))
75
+
76
+ # Display the plots
77
+ col1, col2 = st.columns(2)
78
+ with col1:
79
+ st.plotly_chart(fig_bmd)
80
+ with col2:
81
+ st.plotly_chart(fig_tscore)
82
+
83
+ # Step 6: Check if goal is achieved and show the predicted BMD and T-score for each year
84
+ goal_achieved = False
85
+ for i, row in table.iterrows():
86
+ if row['Predicted T-score'] >= -2.49:
87
+ st.success(f"Goal achieved for {drug} at year {row['Year']} with T-score = {row['Predicted T-score']:.2f}")
88
+ goal_achieved = True
89
+ break
90
+ if not goal_achieved:
91
+ st.warning(f"Goal not achieved for {drug}")
92
+
93
+ # Step 6: Calculate T-score from adjusted BMD
94
+ def calculate_tscore_from_bmd(bmd_patient, c_avg, c_sd):
95
+ return (bmd_patient - c_avg) / c_sd
96
+
97
+ # Main function to load data, run the application, and plot results with T-score labels
98
+ def main_with_separate_tables(file_path, bmd_patient, tscore_patient, C_avg_lunar, C_sd_lunar, selected_drugs):
99
+ # Step 1: Load and clean BMD data from the Excel sheet
100
+ df_bmd_data = load_clean_bmd_data(file_path)
101
+
102
+ # Step 2: Adjust constants based on the patient's data
103
+ c_avg_new, c_sd_new = adjust_constants(bmd_patient, tscore_patient, C_avg_lunar, C_sd_lunar)
104
+
105
+ # Step 4: Create separate prediction tables for each selected drug
106
+ prediction_tables = create_bmd_and_tscore_prediction_tables(df_bmd_data, selected_drugs, bmd_patient, c_avg_new, c_sd_new)
107
+
108
+ # Display baseline BMD and T-score
109
+ st.write(f"Baseline: BMD = {bmd_patient:.3f}, T-score = {tscore_patient:.2f}")
110
+
111
+ # Step 5: Display prediction tables and plots for each drug
112
+ display_prediction_tables_and_plots(prediction_tables, bmd_patient, tscore_patient)
113
+
114
+ # Streamlit UI
115
+ def main():
116
+ st.title("BMD and T-score Prediction Tool")
117
+
118
+ # Input patient data
119
+ bmd_patient = st.number_input("Initial BMD", min_value=0.0, max_value=2.0, value=0.635, step=0.001)
120
+ tscore_patient = st.number_input("Initial T-score", min_value=-5.0, max_value=2.0, value=-2.5, step=0.01)
121
+
122
+ # Drug options
123
+ drug_options = ['Teriparatide', 'Teriparatide + Denosumab', 'Denosumab', 'Denosumab + Teriparatide',
124
+ 'Romosozumab', 'Romosozumab + Denosumab', 'Romosozumab + Alendronate',
125
+ 'Romosozumab + Ibandronate', 'Romosozumab + Zoledronate', 'Alendronate',
126
+ 'Risedronate', 'Ibandronate oral', 'Ibandronate IV (3mg)', 'Zoledronate']
127
+
128
+ # Add option to select multiple drugs
129
+ selected_drugs = st.multiselect("Select drugs to compare", drug_options)
130
+
131
+ # Set C_avg and C_sd for Lunar device (example values)
132
+ C_avg_lunar = 0.95 # Example: Average BMD for Total Hip from Excel (Lunar)
133
+ C_sd_lunar = 0.12 # Example: SD for Total Hip (Lunar)
134
+
135
+ # Example file path
136
+ file_path = "BMD constant calculator.xlsx"
137
+
138
+ # ตรวจสอบว่ามีการเลือกยาแล้วหรือไม่
139
+ if len(selected_drugs) == 0:
140
+ st.warning("Please select at least one drug to compare.")
141
+ else:
142
+ # Run prediction and plot results
143
+ if st.button("Predict"):
144
+ main_with_separate_tables(file_path, bmd_patient, tscore_patient, C_avg_lunar, C_sd_lunar, selected_drugs)
145
+
146
+ if __name__ == "__main__":
147
+ main()