Spaces:
Sleeping

File size: 7,778 Bytes
81fbcf0
 
 
d40131a
81fbcf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f22c5f9
81fbcf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d40131a
81fbcf0
 
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import os
from pathlib import Path
os.environ.setdefault("FAMLIKE_DATA_PATH", str(Path(__file__).resolve().parent))
import streamlit as st
import pandas as pd
from main import PredictDrugLikeness
import plotly.express as px
import plotly.graph_objects as go
import re
svg_config = {
    'toImageButtonOptions': {
        'format': 'svg', # one of png, svg, jpeg, webp
        'filename': 'famlike_custom_plot',
        'height': 500,
        'width': 700,
        'scale': 1 
    }
}
def create_style_boxplot(df, columns, title, short_names_dict):

    fig = go.Figure()
    palette = px.colors.qualitative.Dark24
    unique_fams = list(short_names_dict.values())
    
    color_map = {fam: palette[i % len(palette)] for i, fam in enumerate(unique_fams)}
    bg_color = "rgba(245, 247, 250, 0.5)"

    for col in columns:
        raw_family = col
        
        # 1. Clean suffixes (e.g., "Oxidoreductase_DrugLikeness_Score" -> "Oxidoreductase")
        raw_family = re.sub(r'_druglikeness_score', '', raw_family, flags=re.IGNORECASE)
        raw_family = re.sub(r'_desirability', '', raw_family, flags=re.IGNORECASE)
        raw_family = re.sub(r'_gam_prob', '', raw_family, flags=re.IGNORECASE)
        
        # Remove prefix smoothly
        raw_family = re.sub(r'ensemble_prob_', '', raw_family, flags=re.IGNORECASE)
        display_name = short_names_dict.get(raw_family, raw_family)
        assigned_col = color_map.get(display_name, "#3A506B")
        fig.add_trace(
            go.Box(
                y=df[col],
                name=display_name,
                boxpoints="outliers",
                marker=dict(color=assigned_col, size=4),
                fillcolor = assigned_col,
                line= dict(color=assigned_col, width=1.5),
                showlegend=False

            )
        )

    fig.update_layout(
        title=dict(text=title, font=dict(size=18, family = "Helvetica Neue, sans-serif", color="#1C2541"), x=0),
        margin=dict(l=50, r=30, t=60, b=60), 
        height = 420,
        plot_bgcolor=bg_color,
        paper_bgcolor="rgba(0,0,0,0)",
        yaxis=dict(gridcolor='white', gridwidth=2, zeroline=False, tickfont=dict(color="#4A5568", size=12)),
        xaxis=dict(
            tickfont=dict(color="#4A5568", size=12, family="Helvetica Neue", weight="bold"),
            tickangle=-30)
    )
    return fig


st.set_page_config(page_title="FamLike Score", page_icon="🧪", layout="wide")
st.title("🧪 FamLike Score — Druglikeness Score")
st.caption("Target Family Specific Druglikeness Score using Desirability Functions (ADS), GAMs, and Tree Models")



@st.cache_resource(show_spinner="Loading models (one-time)...")
def get_warm_predictor(use_tree, use_gams, weighting_mode):
    dummy = pd.DataFrame({"SMILES": ["CCO"]})
    return PredictDrugLikeness(
        df=dummy,
        calc_desc=False,
        tree_models=use_tree,
        use_gams=use_gams,
        weighting_mode=weighting_mode,
    )

short_names = {
    "Kinase":         "Kinase",
    "Monoamine_GPCR": "Mono.GPCR",
    "Lipid_GPCR":     "Lipid GPCR",
    "Nuclear_Rec":    "Nuclear",
    "Nucleotid_GPCR": "Nucl.GPCR",
    "Peptide_GPCR":   "Pep.GPCR",
    "Protease":       "Protease",
    "Epigenetic_Reg": "Epigenetic Reg.",
    "Voltage_Ion":    "Volt.Ion",
    "Ligand_Ion":     "Lig.Ion",
    "Hydrolase_Viral":"Hydrolase (Viral)",
    'Oxidoreductase': "Oxidoreductase",
}

with st.sidebar:
    st.header("Settings")
    use_tree = st.checkbox("Tree models (RF + XGBoost)", value=True)
    use_gams = st.checkbox("GAM models", value=True)
    use_desirability = st.checkbox("Desirability functions (ADS)", value=True)
    visualize_FamLike = st.checkbox("Visualize FamLike Score distribution", value=True)
    visualize_Tree_Prob = st.checkbox("Visualize Tree model probabilities", value=True)
    visualize_GAM_Prob = st.checkbox("Visualize GAM model probabilities", value=True)
    visualize_ADS_Prob = st.checkbox("Visualize Desirability Scores", value=True)
    weighting = st.selectbox("Weighting mode", ["equal", "skill"])
    n_cores = st.slider("CPU cores (descriptor calc)", 1, 8, 2)


input_mode = st.radio("Input method", ["Single SMILES", "Upload CSV"])
df_in = None

if input_mode == "Single SMILES":
    smi = st.text_input("Enter SMILES", "CCO")
    if smi.strip():
        df_in = pd.DataFrame({"SMILES": [smi.strip()]})
else:
    uploaded = st.file_uploader("Upload CSV (must contain \"SMILES\" column)", type="csv")
    if uploaded:
        df_in = pd.read_csv(uploaded)
        st.write(f"Loaded {len(df_in)} rows")
        st.dataframe(df_in.head())


if st.button("Predict", type="primary") and df_in is not None:
    warm = get_warm_predictor(use_tree, use_gams, weighting)

    # Reuse loaded models, swap in user data
    warm.df = df_in.copy()
    warm.calc_desc = True
    warm.n_cores = n_cores

    with st.spinner("Calculating descriptors and running models..."):
        try:
            results = warm.predict()
            st.success(f"Done — {len(results)} molecules processed")

            # Show score columns prominently
            score_cols = [c for c in results.columns if "DrugLikeness_Score" in c]
            if score_cols:
                st.subheader("Final Druglikeness Scores (FamLike Scores)")
                display_cols = (
                    [c for c in results.columns if c.lower() in ("smiles", "canonical_smiles")]
                    + score_cols
                )
                st.dataframe(results[display_cols])

            with st.expander("Full results (all columns)"):
                st.dataframe(results)

            # 1. Composite Drug-likeness Scores Distribution
            if visualize_FamLike:
                score_cols = [c for c in results.columns if "DrugLikeness_Score" in c]
                if score_cols:
                    st.subheader("Distribution of Drug-likeness Scores")
                    fig = create_style_boxplot(results, score_cols, "Composite Drug-likeness Scores", short_names)
                    st.plotly_chart(fig,config=svg_config, width='stretch')

            # 2. Tree Model Probabilities
            if visualize_Tree_Prob and use_tree:
                tree_cols = [c for c in results.columns if "Ensemble_Prob" in c]
                if tree_cols:
                    st.subheader("Tree Model Probabilities")
                    fig = create_style_boxplot(results, tree_cols, "Tree Model Target Probabilities", short_names)
                    st.plotly_chart(fig,config=svg_config, width='stretch')

            # 3. GAM Model Probabilities
            if visualize_GAM_Prob and use_gams:
                gam_cols = [c for c in results.columns if "GAM_Prob" in c]
                if gam_cols:
                    st.subheader("GAM Model Probabilities")
                    fig = create_style_boxplot(results, gam_cols, "GAM Model Target Probabilities", short_names)
                    st.plotly_chart(fig,config=svg_config, width='stretch')

            # 4. Desirability Scores
            if visualize_ADS_Prob:
                ads_cols = [c for c in results.columns if "Desirability" in c]
                if ads_cols:
                    st.subheader("Desirability Scores")
                    fig = create_style_boxplot(results, ads_cols, "Desirability Scores (ADS)", short_names)
                    st.plotly_chart(fig,config=svg_config, width='stretch')
            st.download_button(
                "📥 Download results CSV",
                results.to_csv(index=False).encode(),
                "famlike_scores.csv",
                "text/csv",
            )
        except Exception as e:
            st.error(f"Prediction failed: {e}")



elif df_in is None:
    st.info("Provide a SMILES or upload a CSV to begin.")