SalZa2004 commited on
Commit
e0e9f44
Β·
1 Parent(s): 9136275

added app.py

Browse files
Files changed (1) hide show
  1. app.py +200 -0
app.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py (in project root)
2
+ import os
3
+ import sys
4
+ from pathlib import Path
5
+ import gradio as gr
6
+ import pandas as pd
7
+
8
+ # Add project to path
9
+ PROJECT_ROOT = Path(__file__).parent
10
+ sys.path.insert(0, str(PROJECT_ROOT))
11
+
12
+ # Disable HF progress bars
13
+ os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
14
+ os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
15
+
16
+ from core.config import EvolutionConfig
17
+ from core.evolution.evolution import MolecularEvolution
18
+
19
+ def generate_molecules(target_cn, minimize_ysi, optimization_mode, generations, population_size):
20
+ """Run the genetic algorithm and return results."""
21
+
22
+ try:
23
+ # Create config
24
+ config = EvolutionConfig(
25
+ target_cn=float(target_cn),
26
+ maximize_cn=(optimization_mode == "Maximize CN"),
27
+ minimize_ysi=minimize_ysi,
28
+ generations=int(generations),
29
+ population_size=int(population_size)
30
+ )
31
+
32
+ # Run evolution
33
+ evolution = MolecularEvolution(config)
34
+ final_df, pareto_df = evolution.evolve()
35
+
36
+ # Prepare outputs
37
+ if final_df.empty:
38
+ return "❌ No valid molecules generated", None, None
39
+
40
+ # Format results
41
+ summary = f"""
42
+ βœ… **Generation Complete!**
43
+
44
+ - Total molecules: {len(final_df)}
45
+ - Best CN: {final_df.iloc[0]['cn']:.2f}
46
+ - Best CN error: {final_df.iloc[0]['cn_error']:.2f}
47
+ """
48
+
49
+ if minimize_ysi and 'ysi' in final_df.columns:
50
+ summary += f"\n- Best YSI: {final_df.iloc[0]['ysi']:.2f}"
51
+ summary += f"\n- Pareto front size: {len(pareto_df) if not pareto_df.empty else 0}"
52
+
53
+ # Return top 20 for display
54
+ display_cols = ['rank', 'smiles', 'cn', 'cn_error']
55
+ if 'ysi' in final_df.columns:
56
+ display_cols.append('ysi')
57
+ display_cols.extend(['bp', 'density', 'lhv', 'dynamic_viscosity'])
58
+
59
+ available_cols = [c for c in display_cols if c in final_df.columns]
60
+
61
+ top_molecules = final_df.head(20)[available_cols]
62
+ pareto_molecules = pareto_df.head(20)[available_cols] if not pareto_df.empty else None
63
+
64
+ return summary, top_molecules, pareto_molecules
65
+
66
+ except Exception as e:
67
+ return f"❌ Error: {str(e)}", None, None
68
+
69
+
70
+ # Create Gradio interface
71
+ with gr.Blocks(title="Biofuel Molecule Generator", theme=gr.themes.Soft()) as demo:
72
+
73
+ gr.Markdown("""
74
+ # πŸ”¬ Biofuel Molecule Generator
75
+
76
+ Generate optimal fuel molecules using AI-powered genetic algorithms.
77
+
78
+ **Features:**
79
+ - Multi-objective optimization (Cetane Number + Yield Sooting Index)
80
+ - Realistic chemical mutations (CREM)
81
+ - Constraint satisfaction (BP, density, viscosity, LHV)
82
+ - Pareto-optimal solutions
83
+ """)
84
+
85
+ with gr.Row():
86
+ with gr.Column(scale=1):
87
+ gr.Markdown("### βš™οΈ Configuration")
88
+
89
+ # Optimization mode
90
+ optimization_mode = gr.Radio(
91
+ choices=["Target CN", "Maximize CN"],
92
+ value="Target CN",
93
+ label="Optimization Mode",
94
+ info="Target: Match specific CN | Maximize: Find highest CN"
95
+ )
96
+
97
+ # Target CN (only used in Target mode)
98
+ target_cn = gr.Slider(
99
+ minimum=40,
100
+ maximum=80,
101
+ value=50,
102
+ step=1,
103
+ label="Target Cetane Number",
104
+ info="Desired CN value (used in Target mode)"
105
+ )
106
+
107
+ # YSI minimization
108
+ minimize_ysi = gr.Checkbox(
109
+ value=True,
110
+ label="Minimize Yield Sooting Index (YSI)",
111
+ info="Reduce soot formation (environmental impact)"
112
+ )
113
+
114
+ gr.Markdown("### 🧬 Algorithm Parameters")
115
+
116
+ generations = gr.Slider(
117
+ minimum=3,
118
+ maximum=10,
119
+ value=6,
120
+ step=1,
121
+ label="Generations",
122
+ info="More generations = better optimization (slower)"
123
+ )
124
+
125
+ population_size = gr.Slider(
126
+ minimum=20,
127
+ maximum=100,
128
+ value=50,
129
+ step=10,
130
+ label="Population Size",
131
+ info="More molecules = better exploration (slower)"
132
+ )
133
+
134
+ gr.Markdown("""
135
+ ⚠️ **Note:** Larger settings take longer (5-15 minutes)
136
+
137
+ **Recommended:**
138
+ - Quick test: 3 gen, 20 pop (~2 min)
139
+ - Standard: 6 gen, 50 pop (~8 min)
140
+ - Best results: 10 gen, 100 pop (~20 min)
141
+ """)
142
+
143
+ generate_btn = gr.Button("πŸš€ Generate Molecules", variant="primary", size="lg")
144
+
145
+ with gr.Column(scale=2):
146
+ gr.Markdown("### πŸ“Š Results")
147
+
148
+ summary_output = gr.Markdown(label="Summary")
149
+
150
+ with gr.Tabs():
151
+ with gr.Tab("πŸ† Best Candidates"):
152
+ top_output = gr.Dataframe(
153
+ label="Top 20 Molecules",
154
+ interactive=False,
155
+ wrap=True
156
+ )
157
+
158
+ with gr.Tab("πŸ“ˆ Pareto Front"):
159
+ pareto_output = gr.Dataframe(
160
+ label="Non-dominated Solutions (CN vs YSI trade-offs)",
161
+ interactive=False,
162
+ wrap=True
163
+ )
164
+
165
+ # Button click
166
+ generate_btn.click(
167
+ fn=generate_molecules,
168
+ inputs=[target_cn, minimize_ysi, optimization_mode, generations, population_size],
169
+ outputs=[summary_output, top_output, pareto_output]
170
+ )
171
+
172
+ # Examples
173
+ gr.Markdown("### πŸ’‘ Example Configurations")
174
+ gr.Examples(
175
+ examples=[
176
+ [50, True, "Target CN", 6, 50], # Standard multi-objective
177
+ [60, False, "Target CN", 5, 30], # Single objective (CN only)
178
+ [50, True, "Maximize CN", 10, 100], # Maximize with YSI constraint
179
+ ],
180
+ inputs=[target_cn, minimize_ysi, optimization_mode, generations, population_size],
181
+ label="Try these presets"
182
+ )
183
+
184
+ gr.Markdown("""
185
+ ---
186
+ ### πŸ“š About
187
+
188
+ This tool uses:
189
+ - **Machine Learning**: 6 property prediction models (RΒ² > 0.90)
190
+ - **Genetic Algorithm**: CREM-based mutations for chemical validity
191
+ - **Multi-Objective Optimization**: Pareto fronts for trade-off analysis
192
+
193
+ **Citation:** Salvina Za, [University], 2026
194
+
195
+ [GitHub](https://github.com/SalZa2004/Biofuel-Optimiser-ML) | [Paper](link-when-published)
196
+ """)
197
+
198
+ # Launch
199
+ if __name__ == "__main__":
200
+ demo.launch()