import gradio as gr import matplotlib.pyplot as plt import numpy as np def calculate_deflection_and_plot(P, L, E, I): try: # Convert to float P, L, E, I = float(P), float(L), float(E), float(I) # x-axis (beam length) x = np.linspace(0, L, 100) y = [] # Calculate deflection for each point x for val in x: if val <= L/2: # Elastic curve for 0 to mid-span def_val = (P * val * (3 * L**2 - 4 * val**2)) / (48 * E * I) else: # Symmetry for mid-span to end 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 downward max_def = abs(min(y)) # Create Plot fig, ax = plt.subplots(figsize=(10, 4)) ax.plot(x, y, color='red', linewidth=2, label="Deflected Beam") ax.axhline(0, color='black', linewidth=1) ax.set_title("Simply Supported Beam: Central Point Load") ax.set_xlabel("Length (m)") ax.set_ylabel("Deflection (mm)") ax.grid(True, linestyle='--') ax.legend() return round(max_def, 4), fig except Exception as e: return f"Error: {str(e)}", None # UI Setup with gr.Blocks() as demo: gr.Markdown("# 🔩 Mechanical Beam Analysis") with gr.Row(): with gr.Column(): p_val = gr.Number(label="Load (Newtons)", value=1000) l_val = gr.Number(label="Length (m)", value=5) e_val = gr.Number(label="Young's Modulus (Pa)", value=200e9) i_val = gr.Number(label="Moment of Inertia (m^4)", value=0.0001) run_btn = gr.Button("Generate Plot", variant="primary") with gr.Column(): res_val = gr.Number(label="Max Deflection (mm)") plot_val = gr.Plot(label="Deflection Visual") run_btn.click( calculate_deflection_and_plot, inputs=[p_val, l_val, e_val, i_val], outputs=[res_val, plot_val] ) if __name__ == "__main__": demo.launch()