File size: 4,935 Bytes
48c283c
 
0f4785f
 
 
 
4dd63ab
 
0e2051f
 
 
4dd63ab
 
 
 
 
4111c89
4dd63ab
 
 
 
 
 
 
 
 
 
 
 
 
b27e6a4
4dd63ab
0d99249
 
 
 
4dd63ab
 
95b7274
4dd63ab
0d99249
 
b27e6a4
4dd63ab
b27e6a4
0d99249
 
 
b27e6a4
 
db2b096
b27e6a4
 
0f4785f
b27e6a4
 
4dd63ab
 
 
 
 
 
 
b27e6a4
0f4785f
b27e6a4
4dd63ab
b27e6a4
0f4785f
b27e6a4
 
 
 
 
 
 
 
 
 
 
48c283c
 
b27e6a4
 
 
48c283c
b27e6a4
 
 
0f4785f
 
 
 
4dd63ab
0e2051f
 
 
 
 
 
b93eca7
 
 
 
 
 
 
 
 
0e2051f
53461be
12f2cdc
 
 
 
 
 
4dd63ab
 
 
0d99249
 
4dd63ab
b93eca7
0d99249
b93eca7
0d99249
 
4dd63ab
 
0d99249
4dd63ab
b93eca7
 
0f4785f
 
331fa49
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#file_path = "cleaned_bmd_medication_data.xlsx"

import streamlit as st
import pandas as pd
import plotly.graph_objs as go

# Constants from linear regression
REGRESSION_CONSTANTS = {
    'Femoral Neck': {'mu': 0.916852, 'sigma': 0.120754},
    'Total Hip': {'mu': 0.955439, 'sigma': 0.125406},
    'Lumbar spine (L1-L4)': {'mu': 1.131649, 'sigma': 0.139618},
}

# Load medication data
@st.cache_data
def load_medication_data():
    file_path = "cleaned_bmd_medication_data.xlsx"
    return pd.read_excel(file_path)

# Calculate predicted BMD after medication
def calculate_bmd(bmd, percentage_increase):
    return bmd * (1 + percentage_increase)

# Convert BMD to T-score
def calculate_tscore(bmd, mu, sigma):
    return (bmd - mu) / sigma

# Generate prediction table for all drugs
def generate_predictions(medication_data, site, bmd, mu, sigma):
    site_data = medication_data[medication_data['Site'] == site]
    all_results = []
    
    if site_data.empty:
        st.warning(f"No data available for the selected site: {site}")
        return all_results  # Return empty results

    for _, row in site_data.iterrows():
        drug = row['Medication']
        predictions = {'Year': ['0'], 'Predicted BMD': [round(bmd, 3)], 'Predicted T-score': [round(calculate_tscore(bmd, mu, sigma), 1)]}
        
        st.write(f"Processing drug: {drug}")
        
        for year in row.index[1:-1]:  # Skip 'Medication' and 'Site' columns
            if not pd.isna(row[year]):
                percentage_increase = row[year]
                st.write(f"Year: {year}, Percentage Increase: {percentage_increase}")
                
                predicted_bmd = bmd * (1 + percentage_increase)
                predicted_tscore = calculate_tscore(predicted_bmd, mu, sigma)
                
                predictions['Year'].append(year.replace(" Year", ""))  # Simplify year label
                predictions['Predicted BMD'].append(round(predicted_bmd, 3))
                predictions['Predicted T-score'].append(round(predicted_tscore, 1))
        
        all_results.append({'Drug': drug, 'Predictions': predictions})
    return all_results

# Display results as table and plots
def display_results(predictions, site):
    st.subheader(f"Predictions for {site}")
    
    for result in predictions:
        drug = result['Drug']
        predictions = result['Predictions']
        
        # Display table
        st.write(f"### {drug}")
        st.dataframe(pd.DataFrame(predictions))
        
        # Plot BMD and T-score
        bmd_plot = go.Scatter(
            x=predictions['Year'], y=predictions['Predicted BMD'], mode='lines+markers',
            name='Predicted BMD', line=dict(color='blue')
        )
        tscore_plot = go.Scatter(
            x=predictions['Year'], y=predictions['Predicted T-score'], mode='lines+markers',
            name='Predicted T-score', line=dict(color='green')
        )
        
        # Combine plots in a single row
        col1, col2 = st.columns(2)
        with col1:
            st.plotly_chart(go.Figure(data=[bmd_plot], layout=go.Layout(
                title=f"{drug} - Predicted BMD", xaxis_title="Year", yaxis_title="BMD (g/cm²)"
            )))
        with col2:
            st.plotly_chart(go.Figure(data=[tscore_plot], layout=go.Layout(
                title=f"{drug} - Predicted T-score", xaxis_title="Year", yaxis_title="T-score"
            )))

# Streamlit UI
def main():
    st.title("BMD and T-score Prediction Tool")
    
    # DEXA Machine Selection
    dexa_machine = st.selectbox("DEXA Machine", ["LUNAR"])
    
    # Gender Selection
    gender = st.selectbox("Gender", ["Female"])
    
    # Location (Site) Selection with Mapping
    site_mapping = {
        'Lumbar spine (L1-L4)': 'LS',
        'Femoral Neck': 'FN',
        'Total Hip': 'TH'
    }
    site_options = list(site_mapping.keys())
    selected_site = st.selectbox("Select Region (Site)", site_options)
    site = site_mapping[selected_site]  # Map to the actual value in the dataset
    
    # Input patient data
    bmd_patient = st.number_input(
        "Initial BMD",
        min_value=0.000, max_value=2.000,
        value=0.800, step=0.001,
        format="%.3f"
    )
    
    # Load constants and medication data
    medication_data = load_medication_data()
    st.write("Loaded Medication Data:")
    st.write(medication_data.head())  # Display the loaded data for verification
    
    constants = REGRESSION_CONSTANTS.get(selected_site, {})
    if not constants:
        st.warning(f"No constants available for the selected site: {selected_site}")
        return

    # Generate and display predictions
    if st.button("Predict"):
        st.write("Prediction started...")
        predictions = generate_predictions(medication_data, site, bmd_patient, constants['mu'], constants['sigma'])
        display_results(predictions, selected_site)


if __name__ == "__main__":
    main()