softwareDevelopment commited on
Commit
3edb394
Β·
verified Β·
1 Parent(s): 92bbf41

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +332 -0
app.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Heterosis Prediction - Gradio App for HuggingFace Hub
4
+ """
5
+
6
+ import gradio as gr
7
+ import pandas as pd
8
+ import numpy as np
9
+ import os
10
+ import random
11
+ import matplotlib
12
+ matplotlib.use('Agg')
13
+ import matplotlib.pyplot as plt
14
+ import seaborn as sns
15
+ import tempfile
16
+
17
+ from sklearn.model_selection import KFold
18
+ from sklearn.preprocessing import StandardScaler
19
+ from sklearn.metrics import mean_squared_error, r2_score
20
+ from scipy.stats import pearsonr
21
+ from tensorflow.keras.models import Sequential
22
+ from tensorflow.keras.layers import Dense, Dropout, BatchNormalization, LeakyReLU
23
+ from tensorflow.keras import regularizers
24
+ from tensorflow.keras.optimizers import Adam
25
+ import tensorflow as tf
26
+
27
+ # ── Reproducibility ──────────────────────────────────────────────────────────
28
+ seed_value = 42
29
+ os.environ['PYTHONHASHSEED'] = str(seed_value)
30
+ os.environ['TF_DETERMINISTIC_OPS'] = '1'
31
+ random.seed(seed_value)
32
+ np.random.seed(seed_value)
33
+ tf.random.set_seed(seed_value)
34
+
35
+
36
+ # ── Core Model ────────────────────────────────────────────────────────────────
37
+ def build_model(input_dim, l1_reg=0.001, l2_reg=0.001, dropout_rate=0.2):
38
+ model = Sequential()
39
+ for units in [512, 512, 256, 128, 64, 32, 16, 8]:
40
+ model.add(Dense(units, input_shape=(input_dim,) if units == 512 else [],
41
+ kernel_initializer='he_normal',
42
+ kernel_regularizer=regularizers.l1_l2(l1=l1_reg, l2=l2_reg)))
43
+ model.add(BatchNormalization())
44
+ model.add(Dropout(dropout_rate))
45
+ model.add(LeakyReLU(alpha=0.1))
46
+ model.add(Dense(1, activation="relu"))
47
+ model.compile(loss='mse', optimizer=Adam(), metrics=['mae'])
48
+ return model
49
+
50
+
51
+ def heterosis_predict(
52
+ num_F1, num_P,
53
+ train_pheno_file, train_geno_file, parent_geno_file,
54
+ test_geno_file=None,
55
+ l1_reg=0.001, l2_reg=0.001, dropout_rate=0.2,
56
+ k_folds=5, epochs=100, batch_size=16,
57
+ progress=gr.Progress(track_tqdm=True)
58
+ ):
59
+ logs = []
60
+
61
+ def log(msg):
62
+ logs.append(msg)
63
+ return "\n".join(logs)
64
+
65
+ # ── Load Data ──────────────────────────────────────────────────────────
66
+ try:
67
+ train_pheno = pd.read_csv(train_pheno_file.name)
68
+ train_geno = pd.read_csv(train_geno_file.name, index_col=0)
69
+ parent_geno_df = pd.read_csv(parent_geno_file.name, index_col=0)
70
+ except Exception as e:
71
+ return None, None, None, None, None, f"❌ File loading error: {e}"
72
+
73
+ parent_index = parent_geno_df.index
74
+ train_Y = np.array(pd.to_numeric(train_pheno.iloc[:, 1], errors="coerce"))
75
+ train_X = train_geno.to_numpy(dtype=np.float32)
76
+ parent_X_raw = parent_geno_df.to_numpy(dtype=np.float32)
77
+
78
+ scaler = StandardScaler()
79
+ train_X = scaler.fit_transform(train_X)
80
+ parent_X = scaler.transform(parent_X_raw)
81
+
82
+ # ── K-Fold CV ──────────────────────────────────────────────────────────
83
+ kfold = KFold(n_splits=k_folds, shuffle=True, random_state=60)
84
+ fold_metrics = []
85
+ log(f"πŸ”„ Starting {k_folds}-Fold Cross-Validation (epochs={epochs}, batch={batch_size})\n")
86
+
87
+ for fold, (train_idx, val_idx) in enumerate(kfold.split(train_X)):
88
+ progress((fold) / k_folds, desc=f"Fold {fold+1}/{k_folds}")
89
+ log(f" β–Ά Fold {fold+1}/{k_folds} ...")
90
+ model = build_model(train_X.shape[1], l1_reg, l2_reg, dropout_rate)
91
+ model.fit(train_X[train_idx], train_Y[train_idx],
92
+ validation_data=(train_X[val_idx], train_Y[val_idx]),
93
+ epochs=epochs, batch_size=batch_size, verbose=0)
94
+
95
+ val_pred = model.predict(train_X[val_idx], verbose=0).flatten()
96
+ mse = mean_squared_error(train_Y[val_idx], val_pred)
97
+ rmse = np.sqrt(mse)
98
+ r2 = r2_score(train_Y[val_idx], val_pred)
99
+ pearson_corr, _ = pearsonr(train_Y[val_idx], val_pred)
100
+ fold_metrics.append((mse, rmse, r2, pearson_corr))
101
+ log(f" MSE={mse:.4f} RMSE={rmse:.4f} RΒ²={r2:.4f} Pearson r={pearson_corr:.4f}")
102
+
103
+ avg_mse = np.mean([m[0] for m in fold_metrics])
104
+ avg_rmse = np.mean([m[1] for m in fold_metrics])
105
+ avg_r2 = np.mean([m[2] for m in fold_metrics])
106
+ avg_pearson = np.mean([m[3] for m in fold_metrics])
107
+ log(f"\nβœ… Avg CV β†’ MSE={avg_mse:.4f} RMSE={avg_rmse:.4f} RΒ²={avg_r2:.4f} Pearson r={avg_pearson:.4f}")
108
+
109
+ # ── Final Model ────────────────────────────────────────────────────────
110
+ progress(0.85, desc="Training final model …")
111
+ log("\nπŸš€ Training final model on full dataset …")
112
+ final_model = build_model(train_X.shape[1], l1_reg, l2_reg, dropout_rate)
113
+ final_model.fit(train_X, train_Y, epochs=epochs, batch_size=batch_size, verbose=0)
114
+
115
+ # ── Parent GEBVs ────────────────────────────────────────────────────────
116
+ parent_GEBV_values = final_model.predict(parent_X, verbose=0).flatten()
117
+ parent_GEBV_dict = dict(zip(parent_index, parent_GEBV_values))
118
+
119
+ # ── Hybrid Predictions ─────────────────────────────────────────────────
120
+ hybrid_geno, F1_names, SCA_list = [], [], []
121
+ Parent1_GEBV_list, Parent2_GEBV_list = [], []
122
+
123
+ for i in range(len(parent_X) - 1):
124
+ for j in range(i + 1, len(parent_X)):
125
+ hybrid = (parent_X[i] + parent_X[j]) / 2
126
+ hybrid_geno.append(hybrid)
127
+ F1_names.append(f"{parent_index[i]} : {parent_index[j]}")
128
+ P1 = parent_GEBV_dict[parent_index[i]]
129
+ P2 = parent_GEBV_dict[parent_index[j]]
130
+ Parent1_GEBV_list.append(P1)
131
+ Parent2_GEBV_list.append(P2)
132
+ SCA_list.append((P1 + P2) / 2)
133
+
134
+ hybrid_geno = np.array(hybrid_geno)
135
+ GEBV_pred = final_model.predict(hybrid_geno, verbose=0).flatten()
136
+
137
+ parent_mean = np.mean(train_Y)
138
+ better_parent = np.max(train_Y)
139
+ MPH = ((GEBV_pred - parent_mean) / parent_mean) * 100
140
+ BPH = ((GEBV_pred - better_parent) / better_parent) * 100
141
+
142
+ hybrid_results = pd.DataFrame({
143
+ "Hybrid": F1_names,
144
+ "GEBV": GEBV_pred,
145
+ "MPH": MPH,
146
+ "BPH": BPH,
147
+ "Parent1_GEBV": Parent1_GEBV_list,
148
+ "Parent2_GEBV": Parent2_GEBV_list
149
+ }).sort_values(by="GEBV", ascending=False)
150
+
151
+ F1_out = hybrid_results.head(num_F1)
152
+
153
+ parent_GEBV_df = (
154
+ hybrid_results
155
+ .assign(Parent1=[x.split(":")[0].strip() for x in hybrid_results["Hybrid"]],
156
+ Parent2=[x.split(":")[1].strip() for x in hybrid_results["Hybrid"]])
157
+ .melt(id_vars=["GEBV"], value_vars=["Parent1","Parent2"],
158
+ var_name="Type", value_name="Parent")
159
+ .groupby("Parent")
160
+ .agg(GEBV=("GEBV","mean"))
161
+ .reset_index()
162
+ .sort_values(by="GEBV", ascending=False)
163
+ )
164
+ P_out = parent_GEBV_df.head(num_P)
165
+
166
+ # ── Optional test predictions ──────────────────────────────────────────
167
+ test_out = None
168
+ if test_geno_file is not None:
169
+ test_df = pd.read_csv(test_geno_file.name, index_col=0)
170
+ test_X = scaler.transform(test_df.to_numpy(dtype=np.float32))
171
+ test_GEBV = final_model.predict(test_X, verbose=0).flatten()
172
+ test_out = pd.DataFrame({"Test Genotype": test_df.index, "GEBV": test_GEBV})
173
+
174
+ # ── Plot ───────────────────────────────────────────────────────────────
175
+ progress(0.97, desc="Generating plots …")
176
+ fig, axes = plt.subplots(1, 2, figsize=(14, 5))
177
+ fig.patch.set_facecolor('#0f1117')
178
+
179
+ # Panel 1 – Top F1 GEBV bar chart
180
+ top_data = hybrid_results.head(min(20, len(hybrid_results)))
181
+ colors = plt.cm.viridis(np.linspace(0.3, 0.9, len(top_data)))
182
+ axes[0].barh(range(len(top_data)), top_data["GEBV"].values, color=colors)
183
+ axes[0].set_yticks(range(len(top_data)))
184
+ axes[0].set_yticklabels(top_data["Hybrid"].values, fontsize=7, color='white')
185
+ axes[0].set_xlabel("Predicted GEBV", color='white')
186
+ axes[0].set_title("Top Hybrid Combinations", color='white', fontweight='bold')
187
+ axes[0].set_facecolor('#1a1d2e')
188
+ axes[0].tick_params(colors='white')
189
+ for spine in axes[0].spines.values():
190
+ spine.set_edgecolor('#444')
191
+
192
+ # Panel 2 – GEBV distribution
193
+ axes[1].hist(hybrid_results["GEBV"].values, bins=30,
194
+ color='#7c5cbf', edgecolor='#b388ff', alpha=0.85)
195
+ axes[1].set_xlabel("Predicted GEBV", color='white')
196
+ axes[1].set_ylabel("Count", color='white')
197
+ axes[1].set_title("GEBV Distribution Across All Hybrids", color='white', fontweight='bold')
198
+ axes[1].set_facecolor('#1a1d2e')
199
+ axes[1].tick_params(colors='white')
200
+ for spine in axes[1].spines.values():
201
+ spine.set_edgecolor('#444')
202
+
203
+ cv_text = (f"CV Results | MSE: {avg_mse:.4f} "
204
+ f"RMSE: {avg_rmse:.4f} RΒ²: {avg_r2:.4f} Pearson r: {avg_pearson:.4f}")
205
+ fig.suptitle(cv_text, color='#aab4ff', fontsize=9, y=1.01)
206
+ plt.tight_layout()
207
+
208
+ tmp_plot = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
209
+ plt.savefig(tmp_plot.name, bbox_inches='tight',
210
+ facecolor=fig.get_facecolor(), dpi=150)
211
+ plt.close(fig)
212
+
213
+ # ── Save CSVs to temp files ────────────────────────────────────────────
214
+ def to_tmp_csv(df, name):
215
+ path = os.path.join(tempfile.gettempdir(), name)
216
+ df.to_csv(path, index=False)
217
+ return path
218
+
219
+ f1_csv = to_tmp_csv(F1_out, "Top_F1_Hybrids.csv")
220
+ p_csv = to_tmp_csv(P_out, "Top_Parents.csv")
221
+ all_csv = to_tmp_csv(hybrid_results, "All_Hybrid_Results.csv")
222
+ test_csv = to_tmp_csv(test_out, "Test_GEBV.csv") if test_out is not None else None
223
+
224
+ log(f"\nβœ… Done! {len(hybrid_results)} hybrid combinations evaluated.")
225
+ log(f" Top {num_F1} F1 hybrids and Top {num_P} parents identified.")
226
+
227
+ return (
228
+ F1_out.round(4),
229
+ P_out.round(4),
230
+ test_out.round(4) if test_out is not None else pd.DataFrame({"Info": ["No test file provided"]}),
231
+ tmp_plot.name,
232
+ [f for f in [f1_csv, p_csv, all_csv, test_csv] if f],
233
+ "\n".join(logs)
234
+ )
235
+
236
+
237
+ # ── Gradio UI ─────────────────────────────────────────────────────────────────
238
+ css = """
239
+ body, .gradio-container {
240
+ background: #0b0d18 !important;
241
+ font-family: 'Courier New', monospace;
242
+ }
243
+ h1 {
244
+ background: linear-gradient(90deg, #7c5cbf, #4fa3e0);
245
+ -webkit-background-clip: text;
246
+ -webkit-text-fill-color: transparent;
247
+ font-size: 2rem;
248
+ font-weight: 900;
249
+ letter-spacing: -0.5px;
250
+ }
251
+ .gr-button-primary {
252
+ background: linear-gradient(135deg, #7c5cbf, #4fa3e0) !important;
253
+ border: none !important;
254
+ font-weight: 700 !important;
255
+ letter-spacing: 0.5px !important;
256
+ }
257
+ .gr-box, .gr-panel { background: #13162a !important; border: 1px solid #2a2d4a !important; }
258
+ label { color: #aab4ff !important; font-size: 0.82rem !important; }
259
+ .gr-input, .gr-dropdown { background: #1a1d2e !important; color: #e0e6ff !important; border-color: #3a3d5a !important; }
260
+ """
261
+
262
+ with gr.Blocks(css=css, title="Heterosis Prediction") as demo:
263
+
264
+ gr.Markdown("""
265
+ # 🌿 Heterosis Prediction
266
+ ### Deep Learning–based GEBV Prediction & Hybrid Screening
267
+ Upload your genotype/phenotype files, configure hyperparameters, and discover top-performing F1 hybrids.
268
+ """)
269
+
270
+ with gr.Row():
271
+ with gr.Column(scale=1):
272
+ gr.Markdown("### πŸ“‚ Input Files")
273
+ train_pheno_file = gr.File(label="Training Phenotype CSV (col 0 = ID, col 1 = trait value)")
274
+ train_geno_file = gr.File(label="Training Genotype CSV (row index = sample ID)")
275
+ parent_geno_file = gr.File(label="Parent Genotype CSV (row index = parent ID)")
276
+ test_geno_file = gr.File(label="Test Genotype CSV (optional)")
277
+
278
+ gr.Markdown("### βš™οΈ Parameters")
279
+ with gr.Row():
280
+ num_F1 = gr.Slider(1, 50, value=5, step=1, label="Top F1 hybrids to report")
281
+ num_P = gr.Slider(1, 30, value=5, step=1, label="Top parents to report")
282
+ with gr.Row():
283
+ k_folds = gr.Slider(2, 10, value=5, step=1, label="K-Fold CV splits")
284
+ epochs = gr.Slider(10, 500, value=100, step=10, label="Epochs")
285
+ with gr.Row():
286
+ batch_size = gr.Slider(8, 128, value=16, step=8, label="Batch size")
287
+ dropout_rate = gr.Slider(0.0, 0.5, value=0.2, step=0.05, label="Dropout rate")
288
+ with gr.Row():
289
+ l1_reg = gr.Number(value=0.001, label="L1 regularization")
290
+ l2_reg = gr.Number(value=0.001, label="L2 regularization")
291
+
292
+ run_btn = gr.Button("πŸš€ Run Prediction", variant="primary")
293
+
294
+ with gr.Column(scale=2):
295
+ gr.Markdown("### πŸ“Š Results")
296
+ with gr.Tabs():
297
+ with gr.Tab("Top F1 Hybrids"):
298
+ f1_table = gr.DataFrame(label="Top F1 Hybrid Combinations")
299
+ with gr.Tab("Top Parents"):
300
+ p_table = gr.DataFrame(label="Top Parent Lines by Mean GEBV")
301
+ with gr.Tab("Test Predictions"):
302
+ test_table = gr.DataFrame(label="Test Genotype GEBV Predictions")
303
+ with gr.Tab("Plots"):
304
+ plot_out = gr.Image(label="Hybrid Performance Visualisation", type="filepath")
305
+ with gr.Tab("Download CSVs"):
306
+ csv_out = gr.Files(label="Download result files")
307
+
308
+ gr.Markdown("### πŸ“‹ Training Log")
309
+ log_box = gr.Textbox(label="", lines=12, max_lines=20,
310
+ placeholder="Logs will appear here after training …",
311
+ show_copy_button=True)
312
+
313
+ gr.Markdown("""
314
+ ---
315
+ **Model architecture:** 8-layer DNN (512β†’512β†’256β†’128β†’64β†’32β†’16β†’8) with BatchNorm, LeakyReLU, Dropout & L1/L2 regularisation.
316
+ **Metrics:** MSE Β· RMSE Β· RΒ² Β· Pearson r evaluated via K-Fold CV.
317
+ **Heterosis indices computed:** Mid-Parent Heterosis (MPH) Β· Better-Parent Heterosis (BPH).
318
+ """)
319
+
320
+ run_btn.click(
321
+ fn=heterosis_predict,
322
+ inputs=[
323
+ num_F1, num_P,
324
+ train_pheno_file, train_geno_file, parent_geno_file, test_geno_file,
325
+ l1_reg, l2_reg, dropout_rate,
326
+ k_folds, epochs, batch_size
327
+ ],
328
+ outputs=[f1_table, p_table, test_table, plot_out, csv_out, log_box]
329
+ )
330
+
331
+ if __name__ == "__main__":
332
+ demo.launch()