Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
import gradio as gr
|
3 |
+
import json
|
4 |
+
import itertools
|
5 |
+
import numpy as np
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
from rcwa import Material, Layer, LayerStack, Source, Solver
|
8 |
+
import openai
|
9 |
+
import logging
|
10 |
+
import random
|
11 |
+
import os
|
12 |
+
|
13 |
+
# --- Logging ---
|
14 |
+
logging.basicConfig(level=logging.INFO)
|
15 |
+
logger = logging.getLogger(__name__)
|
16 |
+
|
17 |
+
# --- API Key ---
|
18 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
19 |
+
|
20 |
+
# --- Constants ---
|
21 |
+
start_wl = 0.32
|
22 |
+
stop_wl = 0.80
|
23 |
+
step_wl = 0.01
|
24 |
+
wavelengths = np.arange(start_wl, stop_wl + step_wl, step_wl)
|
25 |
+
materials = ['Si', 'Si3N4', 'SiO2', 'AlN']
|
26 |
+
|
27 |
+
# --- Spectrum Simulation ---
|
28 |
+
def simulate_spectrum(layer_order, thickness_nm=100):
|
29 |
+
source = Source(wavelength=start_wl)
|
30 |
+
reflection_layer = Layer(n=1.0)
|
31 |
+
transmission_layer = Layer(material=Material("Si"))
|
32 |
+
try:
|
33 |
+
layers = [Layer(material=Material(m), thickness=thickness_nm * 1e-3) for m in layer_order]
|
34 |
+
stack = LayerStack(*layers, incident_layer=reflection_layer, transmission_layer=transmission_layer)
|
35 |
+
solver = Solver(stack, source, (1, 1))
|
36 |
+
result = solver.solve(wavelength=wavelengths)
|
37 |
+
return np.array(result['TTot']).tolist()
|
38 |
+
except Exception as e:
|
39 |
+
print(f"Simulation failed for {layer_order}: {e}")
|
40 |
+
return None
|
41 |
+
|
42 |
+
def cosine_similarity(vec1, vec2):
|
43 |
+
a, b = np.array(vec1), np.array(vec2)
|
44 |
+
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
|
45 |
+
|
46 |
+
def find_best_permutation(materials, target_spectrum):
|
47 |
+
best_score, best_order = -1, None
|
48 |
+
for order in itertools.permutations(materials, 4):
|
49 |
+
spectrum = simulate_spectrum(order)
|
50 |
+
if spectrum is None:
|
51 |
+
continue
|
52 |
+
score = cosine_similarity(spectrum, target_spectrum)
|
53 |
+
if score > best_score:
|
54 |
+
best_score, best_order = score, order
|
55 |
+
return {
|
56 |
+
"best_order": list(best_order),
|
57 |
+
"cosine_score": float(best_score)
|
58 |
+
}
|
59 |
+
|
60 |
+
def run_agent_with_spectrum(target_spectrum):
|
61 |
+
tools = [{
|
62 |
+
"type": "function",
|
63 |
+
"function": {
|
64 |
+
"name": "find_best_permutation",
|
65 |
+
"description": "Find best layer order to match a transmission spectrum",
|
66 |
+
"parameters": {
|
67 |
+
"type": "object",
|
68 |
+
"properties": {
|
69 |
+
"materials": {"type": "array", "items": {"type": "string"}},
|
70 |
+
"target_spectrum": {"type": "array", "items": {"type": "number"}}
|
71 |
+
},
|
72 |
+
"required": ["materials", "target_spectrum"]
|
73 |
+
}
|
74 |
+
}
|
75 |
+
}]
|
76 |
+
messages = [
|
77 |
+
{"role": "system", "content": "You are a simulation agent that finds the best optical stack to match a target spectrum."},
|
78 |
+
{"role": "user", "content": f"Match this transmission spectrum with a 4-layer stack of Si, Si3N4, SiO2, AlN:\n{target_spectrum}"}
|
79 |
+
]
|
80 |
+
try:
|
81 |
+
response = openai.chat.completions.create(
|
82 |
+
model="gpt-4o",
|
83 |
+
messages=messages,
|
84 |
+
tools=tools,
|
85 |
+
tool_choice={"type": "function", "function": {"name": "find_best_permutation"}}
|
86 |
+
)
|
87 |
+
tool_call = response.choices[0].message.tool_calls[0]
|
88 |
+
args = json.loads(tool_call.function.arguments)
|
89 |
+
result = find_best_permutation(**args)
|
90 |
+
predicted_spectrum = simulate_spectrum(result["best_order"])
|
91 |
+
return {
|
92 |
+
"true_target": target_spectrum,
|
93 |
+
"predicted_spectrum": predicted_spectrum,
|
94 |
+
"result": result,
|
95 |
+
"tool_call": {
|
96 |
+
"function": tool_call.function.name,
|
97 |
+
"arguments": args
|
98 |
+
},
|
99 |
+
"raw_response": response.model_dump(),
|
100 |
+
"system_prompt": messages[0]["content"],
|
101 |
+
"user_prompt": messages[1]["content"]
|
102 |
+
}
|
103 |
+
except Exception as e:
|
104 |
+
return {
|
105 |
+
"true_target": target_spectrum,
|
106 |
+
"predicted_spectrum": None,
|
107 |
+
"result": find_best_permutation(materials, target_spectrum),
|
108 |
+
"tool_call": None,
|
109 |
+
"raw_response": {"error": str(e)},
|
110 |
+
"system_prompt": messages[0]["content"],
|
111 |
+
"user_prompt": messages[1]["content"]
|
112 |
+
}
|
113 |
+
|
114 |
+
def plot_spectra(wavelengths, target, predicted):
|
115 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
116 |
+
ax.plot(wavelengths, target, label="Target Spectrum", color="blue")
|
117 |
+
if predicted:
|
118 |
+
ax.plot(wavelengths, predicted, label="Predicted Spectrum", color="red", linestyle="--")
|
119 |
+
ax.set_xlabel("Wavelength (µm)")
|
120 |
+
ax.set_ylabel("Transmission")
|
121 |
+
ax.set_title("Spectrum Comparison")
|
122 |
+
ax.grid(True)
|
123 |
+
ax.legend()
|
124 |
+
return fig
|
125 |
+
|
126 |
+
with gr.Blocks(title="Optical Thin-Film Stack AI Agent") as demo:
|
127 |
+
gr.Markdown("""
|
128 |
+
# 🧠 Optical Thin-Film Stack AI Agent
|
129 |
+
|
130 |
+
This interactive demo shows an **AI agent using a physics-based simulator (RCWA)** to solve an inverse optics problem.
|
131 |
+
The AI agent calls RCWA to **recover the correct material ordering** of a thin-film stack by matching its optical transmission spectrum to a given input.
|
132 |
+
|
133 |
+
---
|
134 |
+
### ��️ Materials in the Stack: **Si** (high-index semiconductor), **Si₃N₄** (medium-index dielectric), **SiO₂** (low-index glass), **AlN** (wide-bandgap insulating ceramic)
|
135 |
+
---
|
136 |
+
""")
|
137 |
+
|
138 |
+
gr.Markdown("""
|
139 |
+
## 🔍 What's Happening Under the Hood
|
140 |
+
|
141 |
+
1. A **random 4-layer material stack** is generated from the materials above, where each material has a thickness of 100nm.
|
142 |
+
2. We simulate its **transmission spectrum** using **RCWA (Rigorous Coupled-Wave Analysis)** — a gold-standard method in computational optics.
|
143 |
+
3. The AI agent receives this spectrum and is asked: _\"What material order would produce this response?\"_
|
144 |
+
4. The AI agent invokes the tool `find_best_permutation(...)` — triggering a brute-force search using RCWA over all possible material orders.
|
145 |
+
5. The best match is returned, and we show both spectra and a cosine similarity score.
|
146 |
+
|
147 |
+
> 🧠 This isn't prompt-tuning. This is **agentic AI**, invoking a **verifiable physical simulator** as a tool.
|
148 |
+
""")
|
149 |
+
|
150 |
+
run_btn = gr.Button("🎲 Generate & Run")
|
151 |
+
true_order_box = gr.Textbox(label="True Layer Order For the 4 materials")
|
152 |
+
system_box = gr.Textbox(label="System Message to AI Agent", lines=2)
|
153 |
+
prompt_box = gr.Textbox(label="User Prompt to AI Agent", lines=4)
|
154 |
+
pred_order_box = gr.Textbox(label="AI Agent Predicted Layer Order")
|
155 |
+
score_box = gr.Textbox(label="Cosine Similarity")
|
156 |
+
plot_output = gr.Plot(label="Target vs Predicted Spectrum")
|
157 |
+
tool_output = gr.Textbox(label="Tool Call", lines=6)
|
158 |
+
raw_output = gr.Textbox(label="Raw GPT Response", lines=10)
|
159 |
+
|
160 |
+
def random_run():
|
161 |
+
true_order = random.sample(materials, 4)
|
162 |
+
spectrum = simulate_spectrum(true_order)
|
163 |
+
if spectrum is None:
|
164 |
+
return "Simulation failed", "", "", "", "", None, "", ""
|
165 |
+
result = run_agent_with_spectrum(spectrum)
|
166 |
+
plot = plot_spectra(wavelengths, spectrum, result["predicted_spectrum"])
|
167 |
+
return (
|
168 |
+
", ".join(true_order),
|
169 |
+
result["system_prompt"],
|
170 |
+
result["user_prompt"],
|
171 |
+
", ".join(result["result"]["best_order"]),
|
172 |
+
round(result["result"]["cosine_score"], 5),
|
173 |
+
plot,
|
174 |
+
json.dumps(result["tool_call"], indent=2),
|
175 |
+
json.dumps(result["raw_response"], indent=2)
|
176 |
+
)
|
177 |
+
|
178 |
+
run_btn.click(fn=random_run, inputs=[], outputs=[
|
179 |
+
true_order_box,
|
180 |
+
system_box,
|
181 |
+
prompt_box,
|
182 |
+
pred_order_box,
|
183 |
+
score_box,
|
184 |
+
plot_output,
|
185 |
+
tool_output,
|
186 |
+
raw_output
|
187 |
+
])
|
188 |
+
|
189 |
+
if __name__ == "__main__":
|
190 |
+
demo.launch()
|