| """
|
| Gradio Interface for DC Circuit Analysis Calculator
|
| A user-friendly interface for electrical engineering calculations with AI-powered result explanations.
|
| """
|
|
|
| import gradio as gr
|
| import json
|
| from circuit_calculator import Resistor, CircuitConfiguration, DCCircuitAnalyzer
|
| import os
|
|
|
|
|
| def explain_results(results: dict) -> str:
|
| """
|
| Generate a human-readable explanation of the calculation results using a simple template-based approach.
|
| In a production environment, this would use an LLM API.
|
| """
|
| if results['status'] != 'success':
|
| return f"❌ **Calculation Error**\n\n{results.get('error_message', 'Unknown error occurred')}"
|
|
|
|
|
| equivalent = results['equivalent_circuit']
|
| series = results['series_analysis']
|
| parallel = results['parallel_analysis']
|
| power = results['power_analysis']
|
| safety = results['safety_analysis']
|
| validation = results['validation']
|
|
|
|
|
| explanation = f"""
|
| ## ⚡ **DC Circuit Analysis Results**
|
|
|
| ### **Key Findings:**
|
| - **Total Resistance:** {equivalent['total_resistance_ohms']:.2f} Ω
|
| - **Total Current:** {equivalent['total_current_A']:.3f} A
|
| - **Total Power:** {equivalent['total_power_W']:.3f} W
|
|
|
| ### **Circuit Safety Assessment:**
|
| {'✅ **SAFE** - All components within ratings' if safety['all_safe'] else '⚠️ **UNSAFE** - Some components exceed ratings'}
|
|
|
| **Power Utilization:**
|
| - **Critical Issues:** {len(safety['critical_issues'])} component(s) exceeding power ratings
|
| - **Warnings:** {len(safety['warnings'])} component(s) near power limits
|
|
|
| ### **Engineering Interpretation:**
|
|
|
| **Circuit Behavior:**
|
| The circuit draws {equivalent['total_current_A']:.3f} A from the {results['circuit_configuration']['voltage_source_V']:.1f}V source, consuming {equivalent['total_power_W']:.3f} W total power. {'This is a safe operating condition.' if safety['all_safe'] else 'Some components may overheat and fail.'}
|
|
|
| **Series Section Analysis:**
|
| The series resistors (total {series['total_resistance']:.1f} Ω) carry the full circuit current of {series['total_current']:.3f} A, dissipating {series['total_power']:.3f} W total.
|
|
|
| **Parallel Section Analysis:**
|
| The parallel branches share the voltage drop of {parallel['voltage_across_parallel']:.2f} V. {'Each branch carries current proportional to its resistance.' if parallel['branches'] else 'No parallel branches present.'}
|
|
|
| **Power Distribution:**
|
| - Series section: {power['series_power']:.3f} W ({power['series_power']/power['total_power_supplied']*100:.1f}%)
|
| - Parallel section: {power['parallel_power']:.3f} W ({power['parallel_power']/power['total_power_supplied']*100:.1f}%)
|
| - Power balance error: {power['power_balance_error']:.6f} W
|
|
|
| ### **Design Recommendations:**
|
| """
|
|
|
|
|
| if not safety['all_safe']:
|
| explanation += "\n- **CRITICAL:** Replace or reduce power in components exceeding ratings\n"
|
| for issue in safety['critical_issues']:
|
| explanation += f" - {issue}\n"
|
|
|
| if safety['has_warnings']:
|
| explanation += "\n- **WARNING:** Monitor components near power limits\n"
|
| for warning in safety['warnings']:
|
| explanation += f" - {warning}\n"
|
|
|
| if safety['all_safe']:
|
| explanation += "\n- ✅ All components operating within safe limits\n"
|
| if power['efficiency_percent'] > 95:
|
| explanation += "- Circuit efficiency is excellent\n"
|
| elif power['efficiency_percent'] < 80:
|
| explanation += "- Consider optimizing circuit for better efficiency\n"
|
|
|
| explanation += f"""
|
| ### **Technical Details:**
|
| - **Circuit Efficiency:** {power['efficiency_percent']:.1f}%
|
| - **Power Balance Error:** {power['power_balance_error']:.6f} W
|
| - **Series Resistors:** {len(series['resistors'])} components
|
| - **Parallel Branches:** {len(parallel['branches'])} branches
|
|
|
| ---
|
| *This analysis assumes ideal components and DC steady-state conditions. For AC or transient analysis, consult additional tools.*
|
| """
|
|
|
| return explanation
|
|
|
|
|
| def calculate_circuit_analysis(voltage_source,
|
| r1_resistance, r1_power_rating,
|
| r2_resistance, r2_power_rating,
|
| r3_resistance, r3_power_rating,
|
| r4_resistance, r4_power_rating):
|
| """
|
| Main calculation function called by Gradio interface
|
| """
|
| try:
|
|
|
| series_resistors = [
|
| Resistor("R1", float(r1_resistance), float(r1_power_rating)),
|
| Resistor("R4", float(r4_resistance), float(r4_power_rating))
|
| ]
|
|
|
| parallel_branches = [
|
| [Resistor("R2", float(r2_resistance), float(r2_power_rating))],
|
| [Resistor("R3", float(r3_resistance), float(r3_power_rating))]
|
| ]
|
|
|
|
|
| config = CircuitConfiguration(
|
| voltage_source=float(voltage_source),
|
| series_resistors=series_resistors,
|
| parallel_branches=parallel_branches
|
| )
|
|
|
|
|
| analyzer = DCCircuitAnalyzer(config)
|
| results = analyzer.perform_analysis()
|
|
|
|
|
| if results['status'] == 'success':
|
| equivalent = results['equivalent_circuit']
|
| series = results['series_analysis']
|
| parallel = results['parallel_analysis']
|
| power = results['power_analysis']
|
|
|
| numerical_results = f"""
|
| ## 📊 **Circuit Analysis Results**
|
|
|
| ### **Equivalent Circuit:**
|
| - **Total Resistance:** {equivalent['total_resistance_ohms']:.2f} Ω
|
| - **Total Current:** {equivalent['total_current_A']:.3f} A
|
| - **Total Power:** {equivalent['total_power_W']:.3f} W
|
|
|
| ### **Series Resistors:**
|
| - **R1:** {series['resistors'][0]['voltage_drop']:.2f}V, {series['resistors'][0]['current']:.3f}A, {series['resistors'][0]['power_dissipated']:.3f}W
|
| - **R4:** {series['resistors'][1]['voltage_drop']:.2f}V, {series['resistors'][1]['current']:.3f}A, {series['resistors'][1]['power_dissipated']:.3f}W
|
|
|
| ### **Parallel Branches:**
|
| - **Branch 1 (R2):** {parallel['branches'][0]['resistors'][0]['voltage_drop']:.2f}V, {parallel['branches'][0]['resistors'][0]['current']:.3f}A, {parallel['branches'][0]['resistors'][0]['power_dissipated']:.3f}W
|
| - **Branch 2 (R3):** {parallel['branches'][1]['resistors'][0]['voltage_drop']:.2f}V, {parallel['branches'][1]['resistors'][0]['current']:.3f}A, {parallel['branches'][1]['resistors'][0]['power_dissipated']:.3f}W
|
|
|
| ### **Power Analysis:**
|
| - **Series Power:** {power['series_power']:.3f} W
|
| - **Parallel Power:** {power['parallel_power']:.3f} W
|
| - **Efficiency:** {power['efficiency_percent']:.1f}%
|
| """
|
| else:
|
| numerical_results = f"❌ **Calculation Error:** {results.get('error_message', 'Unknown error')}"
|
|
|
|
|
| explanation = explain_results(results)
|
|
|
| return numerical_results, explanation
|
|
|
| except Exception as e:
|
| error_msg = f"❌ **Error:** {str(e)}"
|
| return error_msg, "Please check your input values and try again."
|
|
|
|
|
| def create_interface():
|
| """Create the Gradio interface"""
|
|
|
| with gr.Blocks(
|
| title="DC Circuit Analysis Calculator",
|
| theme=gr.themes.Soft(),
|
| css="""
|
| .gradio-container {
|
| max-width: 1200px !important;
|
| }
|
| .result-box {
|
| background-color: #f8f9fa !important;
|
| border: 1px solid #dee2e6 !important;
|
| border-radius: 8px !important;
|
| padding: 15px !important;
|
| margin: 10px 0 !important;
|
| }
|
| .result-box * {
|
| color: #333333 !important;
|
| }
|
| .result-box h1, .result-box h2, .result-box h3, .result-box h4, .result-box h5, .result-box h6 {
|
| color: #333333 !important;
|
| }
|
| .result-box p, .result-box li, .result-box span, .result-box div {
|
| color: #333333 !important;
|
| }
|
| .markdown {
|
| color: #333333 !important;
|
| }
|
| .markdown * {
|
| color: #333333 !important;
|
| }
|
| """
|
| ) as interface:
|
|
|
| gr.Markdown("""
|
| # ⚡ DC Circuit Analysis Calculator
|
|
|
| A deterministic, first-principles calculator for series-parallel DC circuit analysis.
|
| This tool performs electrical engineering calculations and provides AI-powered explanations of the results.
|
|
|
| **Circuit Topology:** Voltage Source → R1 (series) → [R2, R3] (parallel) → R4 (series)
|
|
|
| **How to use:**
|
| 1. Enter voltage source and resistor values
|
| 2. Click "Calculate" to perform the analysis
|
| 3. Review numerical results and detailed explanations
|
| """)
|
|
|
| with gr.Row():
|
| with gr.Column(scale=1):
|
| gr.Markdown("### 🔋 Voltage Source")
|
| voltage_source = gr.Number(
|
| label="Voltage Source (V)",
|
| value=12.0,
|
| minimum=0.1,
|
| maximum=1000,
|
| step=0.1,
|
| info="DC voltage source"
|
| )
|
|
|
| gr.Markdown("### 🔌 Series Resistors")
|
| r1_resistance = gr.Number(
|
| label="R1 Resistance (Ω)",
|
| value=100,
|
| minimum=1,
|
| maximum=1000000,
|
| step=1,
|
| info="First series resistor"
|
| )
|
| r1_power_rating = gr.Number(
|
| label="R1 Power Rating (W)",
|
| value=0.25,
|
| minimum=0.01,
|
| maximum=1000,
|
| step=0.01,
|
| info="Power rating for R1"
|
| )
|
| r4_resistance = gr.Number(
|
| label="R4 Resistance (Ω)",
|
| value=50,
|
| minimum=1,
|
| maximum=1000000,
|
| step=1,
|
| info="Second series resistor"
|
| )
|
| r4_power_rating = gr.Number(
|
| label="R4 Power Rating (W)",
|
| value=0.5,
|
| minimum=0.01,
|
| maximum=1000,
|
| step=0.01,
|
| info="Power rating for R4"
|
| )
|
|
|
| gr.Markdown("### 🔀 Parallel Resistors")
|
| r2_resistance = gr.Number(
|
| label="R2 Resistance (Ω)",
|
| value=200,
|
| minimum=1,
|
| maximum=1000000,
|
| step=1,
|
| info="First parallel resistor"
|
| )
|
| r2_power_rating = gr.Number(
|
| label="R2 Power Rating (W)",
|
| value=0.25,
|
| minimum=0.01,
|
| maximum=1000,
|
| step=0.01,
|
| info="Power rating for R2"
|
| )
|
| r3_resistance = gr.Number(
|
| label="R3 Resistance (Ω)",
|
| value=300,
|
| minimum=1,
|
| maximum=1000000,
|
| step=1,
|
| info="Second parallel resistor"
|
| )
|
| r3_power_rating = gr.Number(
|
| label="R3 Power Rating (W)",
|
| value=0.25,
|
| minimum=0.01,
|
| maximum=1000,
|
| step=0.01,
|
| info="Power rating for R3"
|
| )
|
|
|
| calculate_btn = gr.Button("⚡ Calculate", variant="primary", size="lg")
|
|
|
| with gr.Column(scale=1):
|
| gr.Markdown("### 📊 Numerical Results")
|
| numerical_output = gr.Markdown(
|
| value="Enter parameters and click 'Calculate' to see results.",
|
| elem_classes=["result-box"]
|
| )
|
|
|
| gr.Markdown("### 🤖 AI Explanation")
|
| explanation_output = gr.Markdown(
|
| value="Detailed explanation will appear here after calculation.",
|
| elem_classes=["result-box"]
|
| )
|
|
|
|
|
| gr.Markdown("### 📋 Quick Examples")
|
| with gr.Row():
|
| example_basic = gr.Button("Basic Circuit", variant="secondary")
|
| example_high_power = gr.Button("High Power Circuit", variant="secondary")
|
| example_low_voltage = gr.Button("Low Voltage Circuit", variant="secondary")
|
|
|
|
|
| calculate_btn.click(
|
| fn=calculate_circuit_analysis,
|
| inputs=[
|
| voltage_source,
|
| r1_resistance, r1_power_rating,
|
| r2_resistance, r2_power_rating,
|
| r3_resistance, r3_power_rating,
|
| r4_resistance, r4_power_rating
|
| ],
|
| outputs=[numerical_output, explanation_output]
|
| )
|
|
|
|
|
| def load_basic_example():
|
| return (12.0, 100, 0.25, 200, 0.25, 300, 0.25, 50, 0.5)
|
|
|
| def load_high_power_example():
|
| return (24.0, 50, 1.0, 100, 0.5, 150, 0.5, 25, 1.0)
|
|
|
| def load_low_voltage_example():
|
| return (3.3, 220, 0.125, 470, 0.125, 680, 0.125, 330, 0.125)
|
|
|
| example_basic.click(
|
| fn=load_basic_example,
|
| outputs=[voltage_source, r1_resistance, r1_power_rating, r2_resistance, r2_power_rating,
|
| r3_resistance, r3_power_rating, r4_resistance, r4_power_rating]
|
| )
|
|
|
| example_high_power.click(
|
| fn=load_high_power_example,
|
| outputs=[voltage_source, r1_resistance, r1_power_rating, r2_resistance, r2_power_rating,
|
| r3_resistance, r3_power_rating, r4_resistance, r4_power_rating]
|
| )
|
|
|
| example_low_voltage.click(
|
| fn=load_low_voltage_example,
|
| outputs=[voltage_source, r1_resistance, r1_power_rating, r2_resistance, r2_power_rating,
|
| r3_resistance, r3_power_rating, r4_resistance, r4_power_rating]
|
| )
|
|
|
|
|
| gr.Markdown("""
|
| ---
|
| **⚠️ Disclaimer:** This calculator is for educational and preliminary design purposes only.
|
| For final circuit design, consult a licensed electrical engineer.
|
|
|
| **🔬 Methodology:** Based on Ohm's Law, Kirchhoff's Laws, and series-parallel circuit analysis for DC steady-state conditions.
|
| """)
|
|
|
| return interface
|
|
|
|
|
|
|
| if __name__ == "__main__":
|
|
|
| interface = create_interface()
|
| interface.launch() |