File size: 15,531 Bytes
0446529
 
 
 
 
 
 
3edb394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0446529
3edb394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 10:29:52 2026

@author: Ashmi
"""

# -*- coding: utf-8 -*-
"""
Heterosis Prediction - Gradio App for HuggingFace Hub
"""

import gradio as gr
import pandas as pd
import numpy as np
import os
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
import tempfile

from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error, r2_score
from scipy.stats import pearsonr
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization, LeakyReLU
from tensorflow.keras import regularizers
from tensorflow.keras.optimizers import Adam
import tensorflow as tf

# ── Reproducibility ──────────────────────────────────────────────────────────
seed_value = 42
os.environ['PYTHONHASHSEED'] = str(seed_value)
os.environ['TF_DETERMINISTIC_OPS'] = '1'
random.seed(seed_value)
np.random.seed(seed_value)
tf.random.set_seed(seed_value)


# ── Core Model ────────────────────────────────────────────────────────────────
def build_model(input_dim, l1_reg=0.001, l2_reg=0.001, dropout_rate=0.2):
    model = Sequential()
    for units in [512, 512, 256, 128, 64, 32, 16, 8]:
        model.add(Dense(units, input_shape=(input_dim,) if units == 512 else [],
                        kernel_initializer='he_normal',
                        kernel_regularizer=regularizers.l1_l2(l1=l1_reg, l2=l2_reg)))
        model.add(BatchNormalization())
        model.add(Dropout(dropout_rate))
        model.add(LeakyReLU(alpha=0.1))
    model.add(Dense(1, activation="relu"))
    model.compile(loss='mse', optimizer=Adam(), metrics=['mae'])
    return model


def heterosis_predict(
    num_F1, num_P,
    train_pheno_file, train_geno_file, parent_geno_file,
    test_geno_file=None,
    l1_reg=0.001, l2_reg=0.001, dropout_rate=0.2,
    k_folds=5, epochs=100, batch_size=16,
    progress=gr.Progress(track_tqdm=True)
):
    logs = []

    def log(msg):
        logs.append(msg)
        return "\n".join(logs)

    # ── Load Data ──────────────────────────────────────────────────────────
    try:
        train_pheno = pd.read_csv(train_pheno_file.name)
        train_geno  = pd.read_csv(train_geno_file.name,  index_col=0)
        parent_geno_df = pd.read_csv(parent_geno_file.name, index_col=0)
    except Exception as e:
        return None, None, None, None, None, f"❌ File loading error: {e}"

    parent_index = parent_geno_df.index
    train_Y = np.array(pd.to_numeric(train_pheno.iloc[:, 1], errors="coerce"))
    train_X = train_geno.to_numpy(dtype=np.float32)
    parent_X_raw = parent_geno_df.to_numpy(dtype=np.float32)

    scaler = StandardScaler()
    train_X = scaler.fit_transform(train_X)
    parent_X = scaler.transform(parent_X_raw)

    # ── K-Fold CV ──────────────────────────────────────────────────────────
    kfold = KFold(n_splits=k_folds, shuffle=True, random_state=60)
    fold_metrics = []
    log(f"πŸ”„ Starting {k_folds}-Fold Cross-Validation  (epochs={epochs}, batch={batch_size})\n")

    for fold, (train_idx, val_idx) in enumerate(kfold.split(train_X)):
        progress((fold) / k_folds, desc=f"Fold {fold+1}/{k_folds}")
        log(f"  β–Ά Fold {fold+1}/{k_folds} ...")
        model = build_model(train_X.shape[1], l1_reg, l2_reg, dropout_rate)
        model.fit(train_X[train_idx], train_Y[train_idx],
                  validation_data=(train_X[val_idx], train_Y[val_idx]),
                  epochs=epochs, batch_size=batch_size, verbose=0)

        val_pred = model.predict(train_X[val_idx], verbose=0).flatten()
        mse  = mean_squared_error(train_Y[val_idx], val_pred)
        rmse = np.sqrt(mse)
        r2   = r2_score(train_Y[val_idx], val_pred)
        pearson_corr, _ = pearsonr(train_Y[val_idx], val_pred)
        fold_metrics.append((mse, rmse, r2, pearson_corr))
        log(f"    MSE={mse:.4f}  RMSE={rmse:.4f}  RΒ²={r2:.4f}  Pearson r={pearson_corr:.4f}")

    avg_mse     = np.mean([m[0] for m in fold_metrics])
    avg_rmse    = np.mean([m[1] for m in fold_metrics])
    avg_r2      = np.mean([m[2] for m in fold_metrics])
    avg_pearson = np.mean([m[3] for m in fold_metrics])
    log(f"\nβœ… Avg CV β†’ MSE={avg_mse:.4f}  RMSE={avg_rmse:.4f}  RΒ²={avg_r2:.4f}  Pearson r={avg_pearson:.4f}")

    # ── Final Model ────────────────────────────────────────────────────────
    progress(0.85, desc="Training final model …")
    log("\nπŸš€ Training final model on full dataset …")
    final_model = build_model(train_X.shape[1], l1_reg, l2_reg, dropout_rate)
    final_model.fit(train_X, train_Y, epochs=epochs, batch_size=batch_size, verbose=0)

    # ── Parent GEBVs ────────────────────────────────────────────────────────
    parent_GEBV_values = final_model.predict(parent_X, verbose=0).flatten()
    parent_GEBV_dict   = dict(zip(parent_index, parent_GEBV_values))

    # ── Hybrid Predictions ─────────────────────────────────────────────────
    hybrid_geno, F1_names, SCA_list = [], [], []
    Parent1_GEBV_list, Parent2_GEBV_list = [], []

    for i in range(len(parent_X) - 1):
        for j in range(i + 1, len(parent_X)):
            hybrid = (parent_X[i] + parent_X[j]) / 2
            hybrid_geno.append(hybrid)
            F1_names.append(f"{parent_index[i]} : {parent_index[j]}")
            P1 = parent_GEBV_dict[parent_index[i]]
            P2 = parent_GEBV_dict[parent_index[j]]
            Parent1_GEBV_list.append(P1)
            Parent2_GEBV_list.append(P2)
            SCA_list.append((P1 + P2) / 2)

    hybrid_geno = np.array(hybrid_geno)
    GEBV_pred   = final_model.predict(hybrid_geno, verbose=0).flatten()

    parent_mean  = np.mean(train_Y)
    better_parent = np.max(train_Y)
    MPH = ((GEBV_pred - parent_mean)   / parent_mean)   * 100
    BPH = ((GEBV_pred - better_parent) / better_parent) * 100

    hybrid_results = pd.DataFrame({
        "Hybrid":        F1_names,
        "GEBV":          GEBV_pred,
        "MPH":           MPH,
        "BPH":           BPH,
        "Parent1_GEBV":  Parent1_GEBV_list,
        "Parent2_GEBV":  Parent2_GEBV_list
    }).sort_values(by="GEBV", ascending=False)

    F1_out = hybrid_results.head(num_F1)

    parent_GEBV_df = (
        hybrid_results
        .assign(Parent1=[x.split(":")[0].strip() for x in hybrid_results["Hybrid"]],
                Parent2=[x.split(":")[1].strip() for x in hybrid_results["Hybrid"]])
        .melt(id_vars=["GEBV"], value_vars=["Parent1","Parent2"],
              var_name="Type", value_name="Parent")
        .groupby("Parent")
        .agg(GEBV=("GEBV","mean"))
        .reset_index()
        .sort_values(by="GEBV", ascending=False)
    )
    P_out = parent_GEBV_df.head(num_P)

    # ── Optional test predictions ──────────────────────────────────────────
    test_out = None
    if test_geno_file is not None:
        test_df  = pd.read_csv(test_geno_file.name, index_col=0)
        test_X   = scaler.transform(test_df.to_numpy(dtype=np.float32))
        test_GEBV = final_model.predict(test_X, verbose=0).flatten()
        test_out  = pd.DataFrame({"Test Genotype": test_df.index, "GEBV": test_GEBV})

    # ── Plot ───────────────────────────────────────────────────────────────
    progress(0.97, desc="Generating plots …")
    fig, axes = plt.subplots(1, 2, figsize=(14, 5))
    fig.patch.set_facecolor('#0f1117')

    # Panel 1 – Top F1 GEBV bar chart
    top_data = hybrid_results.head(min(20, len(hybrid_results)))
    colors   = plt.cm.viridis(np.linspace(0.3, 0.9, len(top_data)))
    axes[0].barh(range(len(top_data)), top_data["GEBV"].values, color=colors)
    axes[0].set_yticks(range(len(top_data)))
    axes[0].set_yticklabels(top_data["Hybrid"].values, fontsize=7, color='white')
    axes[0].set_xlabel("Predicted GEBV", color='white')
    axes[0].set_title("Top Hybrid Combinations", color='white', fontweight='bold')
    axes[0].set_facecolor('#1a1d2e')
    axes[0].tick_params(colors='white')
    for spine in axes[0].spines.values():
        spine.set_edgecolor('#444')

    # Panel 2 – GEBV distribution
    axes[1].hist(hybrid_results["GEBV"].values, bins=30,
                 color='#7c5cbf', edgecolor='#b388ff', alpha=0.85)
    axes[1].set_xlabel("Predicted GEBV", color='white')
    axes[1].set_ylabel("Count",          color='white')
    axes[1].set_title("GEBV Distribution Across All Hybrids", color='white', fontweight='bold')
    axes[1].set_facecolor('#1a1d2e')
    axes[1].tick_params(colors='white')
    for spine in axes[1].spines.values():
        spine.set_edgecolor('#444')

    cv_text = (f"CV Results  |  MSE: {avg_mse:.4f}  "
               f"RMSE: {avg_rmse:.4f}  RΒ²: {avg_r2:.4f}  Pearson r: {avg_pearson:.4f}")
    fig.suptitle(cv_text, color='#aab4ff', fontsize=9, y=1.01)
    plt.tight_layout()

    tmp_plot = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
    plt.savefig(tmp_plot.name, bbox_inches='tight',
                facecolor=fig.get_facecolor(), dpi=150)
    plt.close(fig)

    # ── Save CSVs to temp files ────────────────────────────────────────────
    def to_tmp_csv(df, name):
        path = os.path.join(tempfile.gettempdir(), name)
        df.to_csv(path, index=False)
        return path

    f1_csv     = to_tmp_csv(F1_out,          "Top_F1_Hybrids.csv")
    p_csv      = to_tmp_csv(P_out,           "Top_Parents.csv")
    all_csv    = to_tmp_csv(hybrid_results,  "All_Hybrid_Results.csv")
    test_csv   = to_tmp_csv(test_out, "Test_GEBV.csv") if test_out is not None else None

    log(f"\nβœ… Done!  {len(hybrid_results)} hybrid combinations evaluated.")
    log(f"   Top {num_F1} F1 hybrids and Top {num_P} parents identified.")

    return (
        F1_out.round(4),
        P_out.round(4),
        test_out.round(4) if test_out is not None else pd.DataFrame({"Info": ["No test file provided"]}),
        tmp_plot.name,
        [f for f in [f1_csv, p_csv, all_csv, test_csv] if f],
        "\n".join(logs)
    )


# ── Gradio UI ─────────────────────────────────────────────────────────────────
css = """
body, .gradio-container {
    background: #0b0d18 !important;
    font-family: 'Courier New', monospace;
}
h1 { 
    background: linear-gradient(90deg, #7c5cbf, #4fa3e0);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-size: 2rem;
    font-weight: 900;
    letter-spacing: -0.5px;
}
.gr-button-primary {
    background: linear-gradient(135deg, #7c5cbf, #4fa3e0) !important;
    border: none !important;
    font-weight: 700 !important;
    letter-spacing: 0.5px !important;
}
.gr-box, .gr-panel { background: #13162a !important; border: 1px solid #2a2d4a !important; }
label { color: #aab4ff !important; font-size: 0.82rem !important; }
.gr-input, .gr-dropdown { background: #1a1d2e !important; color: #e0e6ff !important; border-color: #3a3d5a !important; }
"""

with gr.Blocks(css=css, title="Heterosis Prediction") as demo:

    gr.Markdown("""
# 🌿 Heterosis Prediction
### Deep Learning–based GEBV Prediction & Hybrid Screening
Upload your genotype/phenotype files, configure hyperparameters, and discover top-performing F1 hybrids.
""")

    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### πŸ“‚ Input Files")
            train_pheno_file = gr.File(label="Training Phenotype CSV  (col 0 = ID, col 1 = trait value)")
            train_geno_file  = gr.File(label="Training Genotype CSV   (row index = sample ID)")
            parent_geno_file = gr.File(label="Parent Genotype CSV     (row index = parent ID)")
            test_geno_file   = gr.File(label="Test Genotype CSV       (optional)")

            gr.Markdown("### βš™οΈ Parameters")
            with gr.Row():
                num_F1   = gr.Slider(1, 50,  value=5,  step=1,  label="Top F1 hybrids to report")
                num_P    = gr.Slider(1, 30,  value=5,  step=1,  label="Top parents to report")
            with gr.Row():
                k_folds  = gr.Slider(2, 10,  value=5,  step=1,  label="K-Fold CV splits")
                epochs   = gr.Slider(10, 500, value=100, step=10, label="Epochs")
            with gr.Row():
                batch_size   = gr.Slider(8, 128, value=16, step=8,    label="Batch size")
                dropout_rate = gr.Slider(0.0, 0.5, value=0.2, step=0.05, label="Dropout rate")
            with gr.Row():
                l1_reg = gr.Number(value=0.001, label="L1 regularization")
                l2_reg = gr.Number(value=0.001, label="L2 regularization")

            run_btn = gr.Button("πŸš€  Run Prediction", variant="primary")

        with gr.Column(scale=2):
            gr.Markdown("### πŸ“Š Results")
            with gr.Tabs():
                with gr.Tab("Top F1 Hybrids"):
                    f1_table = gr.DataFrame(label="Top F1 Hybrid Combinations")
                with gr.Tab("Top Parents"):
                    p_table  = gr.DataFrame(label="Top Parent Lines by Mean GEBV")
                with gr.Tab("Test Predictions"):
                    test_table = gr.DataFrame(label="Test Genotype GEBV Predictions")
                with gr.Tab("Plots"):
                    plot_out = gr.Image(label="Hybrid Performance Visualisation", type="filepath")
                with gr.Tab("Download CSVs"):
                    csv_out  = gr.Files(label="Download result files")

            gr.Markdown("### πŸ“‹ Training Log")
            log_box = gr.Textbox(label="", lines=12, max_lines=20,
                                 placeholder="Logs will appear here after training …")

    gr.Markdown("""
---
**Model architecture:** 8-layer DNN (512β†’512β†’256β†’128β†’64β†’32β†’16β†’8) with BatchNorm, LeakyReLU, Dropout & L1/L2 regularisation.  
**Metrics:** MSE Β· RMSE Β· RΒ² Β· Pearson r evaluated via K-Fold CV.  
**Heterosis indices computed:** Mid-Parent Heterosis (MPH) Β· Better-Parent Heterosis (BPH).
""")

    run_btn.click(
        fn=heterosis_predict,
        inputs=[
            num_F1, num_P,
            train_pheno_file, train_geno_file, parent_geno_file, test_geno_file,
            l1_reg, l2_reg, dropout_rate,
            k_folds, epochs, batch_size
        ],
        outputs=[f1_table, p_table, test_table, plot_out, csv_out, log_box]
    )

if __name__ == "__main__":
    demo.launch()