import gradio as gr import matplotlib.pyplot as plt import numpy as np def calculate_and_plot(P, L, E, I): try: # Convert inputs to float to ensure math works P, L, E, I = float(P), float(L), float(E), float(I) # Create x-coordinates along the beam x = np.linspace(0, L, 100) y = [] # Calculate deflection at each point x for val in x: if val <= L/2: # Standard elastic curve eq for simply supported beam def_val = (P * val * (3 * L**2 - 4 * val**2)) / (48 * E * I) else: val_sym = L - val def_val = (P * val_sym * (3 * L**2 - 4 * val_sym**2)) / (48 * E * I) y.append(-def_val * 1000) # Convert to mm and make negative for downward view max_def = abs(min(y)) # Create Plot fig = plt.figure(figsize=(10, 4)) plt.plot(x, y, color='#2c3e50', linewidth=3, label="Deflected Beam") plt.axhline(0, color='black', linestyle='--', alpha=0.5, label="Original Axis") plt.fill_between(x, y, 0, color='#3498db', alpha=0.2) plt.title("Beam Deflection Profile", fontsize=14) plt.xlabel("Beam Length (m)") plt.ylabel("Deflection (mm)") plt.grid(True, linestyle=':', alpha=0.6) plt.legend() return round(max_def, 4), fig except ZeroDivisionError: return "Error: E or I cannot be zero", None except Exception as e: return f"Error: {str(e)}", None # Modern Gradio Interface with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# 🏗️ Structural Beam Deflection Lab") gr.Markdown("Analyze a simply supported beam with a central point load.") with gr.Row(): with gr.Column(scale=1): P_in = gr.Number(label="Point Load (N)", value=1000) L_in = gr.Number(label="Total Length (m)", value=5) E_in = gr.Number(label="Young's Modulus (Pa)", value=200e9) I_in = gr.Number(label="Moment of Inertia (m^4)", value=0.0001) btn = gr.Button("Run Analysis", variant="primary") with gr.Column(scale=2): result_mm = gr.Number(label="Max Deflection (mm)") plot_out = gr.Plot(label="Visual Graph") btn.click(calculate_and_plot, inputs=[P_in, L_in, E_in, I_in], outputs=[result_mm, plot_out]) if __name__ == "__main__": demo.launch()