Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
import numpy as np
|
| 2 |
-
import pyvista as pv
|
| 3 |
import plotly.graph_objects as go
|
| 4 |
import gradio as gr
|
| 5 |
from scipy.spatial import Delaunay
|
|
|
|
| 6 |
|
| 7 |
def solve_and_plot_interactive(Lx: float,
|
| 8 |
Ly: float,
|
|
@@ -17,7 +17,7 @@ def solve_and_plot_interactive(Lx: float,
|
|
| 17 |
Solves the 2D heat equation and returns an interactive Plotly figure
|
| 18 |
that can be rendered in a web browser.
|
| 19 |
"""
|
| 20 |
-
# --- 1. Simulation Setup
|
| 21 |
x = np.linspace(0, Lx, Nx)
|
| 22 |
y = np.linspace(0, Ly, Ny)
|
| 23 |
dx, dy = x[1] - x[0], y[1] - y[0]
|
|
@@ -37,7 +37,7 @@ def solve_and_plot_interactive(Lx: float,
|
|
| 37 |
elif initial == "step":
|
| 38 |
u = np.where((X < Lx/2) & (Y < Ly/2), 1.0, 0.0)
|
| 39 |
|
| 40 |
-
# --- 2. Solve the Heat Equation
|
| 41 |
time_indices = np.linspace(0, Nt - 1, M, dtype=int)
|
| 42 |
U_slider = np.zeros((M, Nx, Ny))
|
| 43 |
store_idx = 0
|
|
@@ -64,14 +64,11 @@ def solve_and_plot_interactive(Lx: float,
|
|
| 64 |
store_idx += 1
|
| 65 |
|
| 66 |
# --- 3. Create a Plotly Figure for Web ---
|
| 67 |
-
# We use Delaunay triangulation to create the mesh faces for Plotly
|
| 68 |
points_2d = np.vstack([X.ravel(), Y.ravel()]).T
|
| 69 |
tri = Delaunay(points_2d)
|
| 70 |
|
| 71 |
-
# Create the figure
|
| 72 |
fig = go.Figure()
|
| 73 |
|
| 74 |
-
# Add one mesh trace for each time step. We'll make only the first one visible.
|
| 75 |
for i in range(M):
|
| 76 |
time_value = (time_indices[i] / (Nt-1)) * t_max if Nt > 1 else 0
|
| 77 |
z_data = U_slider[i, :, :].flatten()
|
|
@@ -82,53 +79,54 @@ def solve_and_plot_interactive(Lx: float,
|
|
| 82 |
intensity=z_data,
|
| 83 |
colorscale='Viridis',
|
| 84 |
name=f'Time: {time_value:.2f}s',
|
| 85 |
-
showscale=True if i == 0 else False,
|
| 86 |
-
visible=(i == 0)
|
| 87 |
)
|
| 88 |
)
|
| 89 |
|
| 90 |
-
# Create the slider
|
| 91 |
steps = []
|
| 92 |
for i in range(len(fig.data)):
|
| 93 |
time_value = (time_indices[i] / (Nt-1)) * t_max if Nt > 1 else 0
|
| 94 |
step = dict(
|
| 95 |
method="update",
|
| 96 |
-
args=[{"visible": [False] * len(fig.data)}],
|
| 97 |
label=f"{time_value:.2f}s"
|
| 98 |
)
|
| 99 |
-
step["args"][0]["visible"][i] = True
|
| 100 |
steps.append(step)
|
| 101 |
|
| 102 |
-
sliders = [dict(
|
| 103 |
-
active=0,
|
| 104 |
-
currentvalue={"prefix": "Time: "},
|
| 105 |
-
pad={"t": 50},
|
| 106 |
-
steps=steps
|
| 107 |
-
)]
|
| 108 |
|
| 109 |
-
# Update the layout of the figure
|
| 110 |
fig.update_layout(
|
| 111 |
title=f'2D Heat Eq — init={initial}, bc={bc}',
|
| 112 |
-
scene=dict(
|
| 113 |
-
xaxis_title='X',
|
| 114 |
-
yaxis_title='Y',
|
| 115 |
-
zaxis_title='Temperature'
|
| 116 |
-
),
|
| 117 |
sliders=sliders
|
| 118 |
)
|
| 119 |
|
| 120 |
return fig
|
| 121 |
|
| 122 |
|
| 123 |
-
# --- Gradio Interface Function ---
|
| 124 |
def gradio_interface(lx, ly, t_max, m_steps, gamma, nx, ny, initial, bc):
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
# --- Gradio UI Definition ---
|
| 134 |
with gr.Blocks(theme=gr.themes.Soft(), title="2D Heat Simulator") as demo:
|
|
@@ -138,13 +136,14 @@ with gr.Blocks(theme=gr.themes.Soft(), title="2D Heat Simulator") as demo:
|
|
| 138 |
with gr.Row():
|
| 139 |
with gr.Column(scale=1):
|
| 140 |
gr.Markdown("## Simulation Parameters")
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
| 148 |
|
| 149 |
with gr.Row():
|
| 150 |
initial_dropdown = gr.Dropdown(["gaussian", "random", "sinusoidal", "step"], value="gaussian", label="Initial")
|
|
@@ -153,7 +152,6 @@ with gr.Blocks(theme=gr.themes.Soft(), title="2D Heat Simulator") as demo:
|
|
| 153 |
run_btn = gr.Button("Run Simulation", variant="primary")
|
| 154 |
|
| 155 |
with gr.Column(scale=3):
|
| 156 |
-
# The output is now a gr.Plot component that will render the Plotly figure
|
| 157 |
plot_output = gr.Plot(label="Interactive Heatmap")
|
| 158 |
|
| 159 |
inputs_list = [lx_slider, ly_slider, t_slider, m_slider, gamma_slider,
|
|
@@ -162,14 +160,16 @@ with gr.Blocks(theme=gr.themes.Soft(), title="2D Heat Simulator") as demo:
|
|
| 162 |
run_btn.click(fn=gradio_interface, inputs=inputs_list, outputs=plot_output)
|
| 163 |
|
| 164 |
gr.Examples(
|
|
|
|
| 165 |
examples=[
|
| 166 |
-
[1.0, 1.0, 0.5, 30, 0.1,
|
| 167 |
-
[2.0, 1.0, 1.0,
|
| 168 |
],
|
| 169 |
inputs=inputs_list,
|
| 170 |
outputs=plot_output,
|
| 171 |
fn=gradio_interface,
|
| 172 |
-
cache_examples
|
|
|
|
| 173 |
)
|
| 174 |
|
| 175 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import numpy as np
|
|
|
|
| 2 |
import plotly.graph_objects as go
|
| 3 |
import gradio as gr
|
| 4 |
from scipy.spatial import Delaunay
|
| 5 |
+
import traceback
|
| 6 |
|
| 7 |
def solve_and_plot_interactive(Lx: float,
|
| 8 |
Ly: float,
|
|
|
|
| 17 |
Solves the 2D heat equation and returns an interactive Plotly figure
|
| 18 |
that can be rendered in a web browser.
|
| 19 |
"""
|
| 20 |
+
# --- 1. Simulation Setup ---
|
| 21 |
x = np.linspace(0, Lx, Nx)
|
| 22 |
y = np.linspace(0, Ly, Ny)
|
| 23 |
dx, dy = x[1] - x[0], y[1] - y[0]
|
|
|
|
| 37 |
elif initial == "step":
|
| 38 |
u = np.where((X < Lx/2) & (Y < Ly/2), 1.0, 0.0)
|
| 39 |
|
| 40 |
+
# --- 2. Solve the Heat Equation ---
|
| 41 |
time_indices = np.linspace(0, Nt - 1, M, dtype=int)
|
| 42 |
U_slider = np.zeros((M, Nx, Ny))
|
| 43 |
store_idx = 0
|
|
|
|
| 64 |
store_idx += 1
|
| 65 |
|
| 66 |
# --- 3. Create a Plotly Figure for Web ---
|
|
|
|
| 67 |
points_2d = np.vstack([X.ravel(), Y.ravel()]).T
|
| 68 |
tri = Delaunay(points_2d)
|
| 69 |
|
|
|
|
| 70 |
fig = go.Figure()
|
| 71 |
|
|
|
|
| 72 |
for i in range(M):
|
| 73 |
time_value = (time_indices[i] / (Nt-1)) * t_max if Nt > 1 else 0
|
| 74 |
z_data = U_slider[i, :, :].flatten()
|
|
|
|
| 79 |
intensity=z_data,
|
| 80 |
colorscale='Viridis',
|
| 81 |
name=f'Time: {time_value:.2f}s',
|
| 82 |
+
showscale=True if i == 0 else False,
|
| 83 |
+
visible=(i == 0)
|
| 84 |
)
|
| 85 |
)
|
| 86 |
|
|
|
|
| 87 |
steps = []
|
| 88 |
for i in range(len(fig.data)):
|
| 89 |
time_value = (time_indices[i] / (Nt-1)) * t_max if Nt > 1 else 0
|
| 90 |
step = dict(
|
| 91 |
method="update",
|
| 92 |
+
args=[{"visible": [False] * len(fig.data)}],
|
| 93 |
label=f"{time_value:.2f}s"
|
| 94 |
)
|
| 95 |
+
step["args"][0]["visible"][i] = True
|
| 96 |
steps.append(step)
|
| 97 |
|
| 98 |
+
sliders = [dict(active=0, currentvalue={"prefix": "Time: "}, pad={"t": 50}, steps=steps)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
|
|
|
| 100 |
fig.update_layout(
|
| 101 |
title=f'2D Heat Eq — init={initial}, bc={bc}',
|
| 102 |
+
scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Temperature'),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
sliders=sliders
|
| 104 |
)
|
| 105 |
|
| 106 |
return fig
|
| 107 |
|
| 108 |
|
| 109 |
+
# --- Gradio Interface Function with Error Handling ---
|
| 110 |
def gradio_interface(lx, ly, t_max, m_steps, gamma, nx, ny, initial, bc):
|
| 111 |
+
try:
|
| 112 |
+
nx, ny, m_steps = int(nx), int(ny), int(m_steps)
|
| 113 |
+
fig = solve_and_plot_interactive(
|
| 114 |
+
Lx=lx, Ly=ly, t_max=t_max, M=m_steps, Gamma=gamma, Nx=nx, Ny=ny,
|
| 115 |
+
initial=initial, bc=bc
|
| 116 |
+
)
|
| 117 |
+
# On success, return the figure to the Plot component
|
| 118 |
+
return fig
|
| 119 |
+
except Exception as e:
|
| 120 |
+
# If any error occurs, create a text-based error to show in the UI
|
| 121 |
+
# This prevents the app from crashing.
|
| 122 |
+
error_text = traceback.format_exc()
|
| 123 |
+
print(error_text) # Print the full error to the logs for debugging
|
| 124 |
+
# Return a placeholder Plotly figure with the error message
|
| 125 |
+
error_fig = go.Figure().update_layout(
|
| 126 |
+
title_text="⚠️ Application Error",
|
| 127 |
+
annotations=[dict(text=f"An error occurred: {e}", showarrow=False)]
|
| 128 |
+
)
|
| 129 |
+
return error_fig
|
| 130 |
|
| 131 |
# --- Gradio UI Definition ---
|
| 132 |
with gr.Blocks(theme=gr.themes.Soft(), title="2D Heat Simulator") as demo:
|
|
|
|
| 136 |
with gr.Row():
|
| 137 |
with gr.Column(scale=1):
|
| 138 |
gr.Markdown("## Simulation Parameters")
|
| 139 |
+
# Reduced max values to be safer on free hardware
|
| 140 |
+
lx_slider = gr.Slider(0.1, 5.0, 1.0, 0.1, label="Lx")
|
| 141 |
+
ly_slider = gr.Slider(0.1, 5.0, 1.0, 0.1, label="Ly")
|
| 142 |
+
nx_slider = gr.Slider(10, 80, 40, 1, label="Nx (Grid Points X)")
|
| 143 |
+
ny_slider = gr.Slider(10, 80, 40, 1, label="Ny (Grid Points Y)")
|
| 144 |
+
t_slider = gr.Slider(0.01, 2.0, 0.5, 0.01, label="t_max")
|
| 145 |
+
gamma_slider = gr.Slider(0.001, 1.0, 0.1, 0.001, label="Gamma")
|
| 146 |
+
m_slider = gr.Slider(10, 80, 30, 1, label="M (Time Steps)")
|
| 147 |
|
| 148 |
with gr.Row():
|
| 149 |
initial_dropdown = gr.Dropdown(["gaussian", "random", "sinusoidal", "step"], value="gaussian", label="Initial")
|
|
|
|
| 152 |
run_btn = gr.Button("Run Simulation", variant="primary")
|
| 153 |
|
| 154 |
with gr.Column(scale=3):
|
|
|
|
| 155 |
plot_output = gr.Plot(label="Interactive Heatmap")
|
| 156 |
|
| 157 |
inputs_list = [lx_slider, ly_slider, t_slider, m_slider, gamma_slider,
|
|
|
|
| 160 |
run_btn.click(fn=gradio_interface, inputs=inputs_list, outputs=plot_output)
|
| 161 |
|
| 162 |
gr.Examples(
|
| 163 |
+
# Using more modest values in the examples
|
| 164 |
examples=[
|
| 165 |
+
[1.0, 1.0, 0.5, 30, 0.1, 30, 30, "gaussian", "dirichlet"],
|
| 166 |
+
[2.0, 1.0, 1.0, 40, 0.05, 40, 20, "sinusoidal", "periodic"],
|
| 167 |
],
|
| 168 |
inputs=inputs_list,
|
| 169 |
outputs=plot_output,
|
| 170 |
fn=gradio_interface,
|
| 171 |
+
# Set cache_examples to False to prevent crashes on startup
|
| 172 |
+
cache_examples=False
|
| 173 |
)
|
| 174 |
|
| 175 |
if __name__ == "__main__":
|