MonsterBoyTabs commited on
Commit
097d8e4
·
verified ·
1 Parent(s): 245d5d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -185
app.py CHANGED
@@ -5,198 +5,95 @@ import pandas as pd
5
  import plotly.graph_objects as go
6
  from scipy.signal import square, sawtooth
7
 
8
- # Configuration for visual simulator
9
- DIODE_DROPS = {"Silicon": 0.7, "Germanium": 0.3, "Ideal": 0.0}
10
- COMPONENTS = {
11
- "AC Source": {"symbol": "~", "orientation": True},
12
- "DC Source": {"symbol": "⎓", "orientation": True},
13
- "Resistor": {"symbol": "⬦", "orientation": True},
14
- "Diode": {"symbol": "→", "orientation": True}
15
- }
16
 
17
- # Initialize session state for visual simulator
18
- if "circuit" not in st.session_state:
19
- st.session_state.circuit = []
20
- if "connections" not in st.session_state:
21
- st.session_state.connections = []
22
- if "selected_component" not in st.session_state:
23
- st.session_state.selected_component = None
 
 
 
 
 
24
 
25
- def draw_schematic():
26
- fig = go.Figure()
27
-
28
- # Draw components
29
- for idx, comp in enumerate(st.session_state.circuit):
30
- x = comp["position"][0]
31
- y = comp["position"][1]
32
- fig.add_annotation(
33
- x=x,
34
- y=y,
35
- text=COMPONENTS[comp["type"]]["symbol"],
36
- showarrow=False,
37
- font=dict(size=20),
38
- xref="x",
39
- yref="y"
40
- )
41
- if comp["type"] == "Diode":
42
- fig.add_annotation(
43
- x=x,
44
- y=y,
45
- text="|" if comp["orientation"] == "reverse" else "",
46
- showarrow=False,
47
- font=dict(size=20),
48
- xshift=10
49
- )
50
-
51
- # Draw connections
52
- for connection in st.session_state.connections:
53
- fig.add_trace(go.Scatter(
54
- x=[connection[0][0], connection[1][0]],
55
- y=[connection[0][1], connection[1][1]],
56
- mode="lines",
57
- line=dict(color="black", width=2)
58
- ))
59
-
60
- fig.update_layout(
61
- xaxis=dict(visible=False, range=[0, 10]),
62
- yaxis=dict(visible=False, range=[0, 10]),
63
- margin=dict(l=0, r=0, t=0, b=0),
64
- height=400
65
- )
66
- return fig
67
 
 
68
  def analyze_circuit():
69
- # Simplified circuit analysis (series only)
70
- voltage = 0
71
- current = 0
72
- results = []
73
-
74
- if not st.session_state.circuit:
75
- return pd.DataFrame()
76
-
77
- # Find power source
78
- source = next((c for c in st.session_state.circuit if c["type"] in ["AC Source", "DC Source"]), None)
79
- if not source:
80
- return pd.DataFrame()
81
-
82
- # Calculate parameters
83
- total_resistance = sum(c["value"] for c in st.session_state.circuit if c["type"] == "Resistor")
84
- diode_drop = 0
85
- for comp in st.session_state.circuit:
86
- if comp["type"] == "Diode":
87
- if comp["orientation"] == "forward":
88
- diode_drop += DIODE_DROPS[comp["subtype"]]
89
-
90
- if source["type"] == "DC Source":
91
- voltage = source["value"] - diode_drop
92
- current = voltage / total_resistance if total_resistance > 0 else 0
93
- else:
94
- pass # AC analysis placeholder
95
-
96
  return pd.DataFrame({
97
- "Total Voltage": [voltage],
98
- "Current": [current],
99
- "Resistance": [total_resistance],
100
- "Diode Drop": [diode_drop]
101
  })
102
 
103
- # Main app
104
- st.title("Circuit Simulator Suite")
105
-
106
- # Create tabs
107
- tab1, tab2 = st.tabs(["CircuitJS Simulator", "Visual Circuit Simulator"])
108
-
109
- with tab1:
110
- st.header("Interactive Circuit Simulator (CircuitJS1)")
111
- circuitjs_html = """
112
- <div>
113
- <iframe src="https://www.falstad.com/circuit/circuitjs.html"
114
- width="100%"
115
- height="600px"
116
- style="border:none;">
117
- </iframe>
118
- </div>
119
- """
120
- html(circuitjs_html, height=600)
121
- st.markdown("""
122
- ### Instructions:
123
- 1. Use the CircuitJS1 simulator above to design and simulate electrical circuits.
124
- 2. You can add components, connect them, and simulate the circuit in real-time.
125
- 3. Explore the menu options in CircuitJS1 for advanced features.
126
- """)
127
-
128
- with tab2:
129
- st.header("🔌 Visual Circuit Simulator")
130
- st.markdown("Build your circuit by placing components and connecting them")
131
-
132
- # Visual simulator components
133
- with st.expander("🛠️ Component Toolbox"):
134
- col1, col2, col3 = st.columns(3)
135
- with col1:
136
- comp_type = st.selectbox("Component Type", list(COMPONENTS.keys()))
137
- with col2:
138
- if comp_type in ["Resistor"]:
139
- value = st.number_input("Value (Ω)", 1, 1000, 1000)
140
- elif comp_type in ["DC Source"]:
141
- value = st.number_input("Voltage (V)", 1.0, 24.0, 5.0)
142
- else:
143
- value = None
144
- with col3:
145
- if comp_type == "Diode":
146
- subtype = st.selectbox("Diode Type", list(DIODE_DROPS.keys()))
147
- orientation = st.selectbox("Orientation", ["forward", "reverse"])
148
- else:
149
- subtype = None
150
- orientation = "forward"
151
-
152
- if st.button("Add to Board"):
153
- st.session_state.circuit.append({
154
- "type": comp_type,
155
- "value": value,
156
- "subtype": subtype,
157
- "orientation": orientation,
158
- "position": [5, 5]
159
- })
160
 
161
- st.subheader("Circuit Board")
162
- fig = draw_schematic()
163
- st.plotly_chart(fig, use_container_width=True)
 
 
 
 
 
164
 
165
- if st.button("▶️ Run Analysis"):
166
- results = analyze_circuit()
167
- if not results.empty:
168
- st.subheader("🔍 Analysis Results")
169
- st.dataframe(results)
170
-
171
- if "AC Source" in [c["type"] for c in st.session_state.circuit]:
172
- st.subheader("📈 Waveform Visualization")
173
- waveform_type = st.selectbox("Select Waveform Type", ["Sine", "Square", "Triangular"])
174
- t = np.linspace(0, 0.05, 1000)
175
- if waveform_type == "Sine":
176
- wave = np.sin(2 * np.pi * 50 * t)
177
- elif waveform_type == "Square":
178
- wave = square(2 * np.pi * 50 * t)
179
- else:
180
- wave = sawtooth(2 * np.pi * 50 * t)
181
-
182
- fig_wave = go.Figure()
183
- fig_wave.add_trace(go.Scatter(x=t, y=wave))
184
- st.plotly_chart(fig_wave)
185
- else:
186
- st.error("Invalid circuit configuration")
187
 
188
- with st.expander("❓ How to use"):
189
- st.markdown("""
190
- 1. **Add Components**:
191
- - Select component type and parameters
192
- - Click 'Add to Board'
193
- - Drag components on the canvas (positioning not fully implemented)
194
-
195
- 2. **Connect Components**:
196
- - Click on component terminals to connect them
197
- - Create complete circuits with power sources
198
-
199
- 3. **Run Analysis**:
200
- - Get voltage, current, and resistance values
201
- - View waveforms for AC circuits
202
- """)
 
 
5
  import plotly.graph_objects as go
6
  from scipy.signal import square, sawtooth
7
 
8
+ # Title of the app
9
+ st.title("Circuit Simulator with Waveform Analysis")
 
 
 
 
 
 
10
 
11
+ # Embed CircuitJS1
12
+ st.header("Build Your Circuit")
13
+ circuitjs_html = """
14
+ <div>
15
+ <iframe src="https://www.falstad.com/circuit/circuitjs.html"
16
+ width="100%"
17
+ height="600px"
18
+ style="border:none;">
19
+ </iframe>
20
+ </div>
21
+ """
22
+ html(circuitjs_html, height=600)
23
 
24
+ # Add a description or instructions
25
+ st.markdown("""
26
+ ### Instructions:
27
+ 1. Use the CircuitJS1 simulator above to design and simulate electrical circuits.
28
+ 2. You can add components, connect them, and simulate the circuit in real-time.
29
+ 3. Explore the menu options in CircuitJS1 for advanced features.
30
+ """)
31
+
32
+ # Analysis and Waveform Section
33
+ st.header("Circuit Analysis and Waveform Visualization")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ # Dummy analysis function (replace with actual analysis logic)
36
  def analyze_circuit():
37
+ # Placeholder for analysis logic
38
+ # For now, we'll return dummy data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  return pd.DataFrame({
40
+ "Total Voltage (V)": [5.0],
41
+ "Current (A)": [0.01],
42
+ "Resistance (Ω)": [500],
43
+ "Diode Drop (V)": [0.7]
44
  })
45
 
46
+ # Waveform generation function
47
+ def generate_waveform(waveform_type):
48
+ t = np.linspace(0, 0.05, 1000) # Time vector
49
+ if waveform_type == "Sine":
50
+ wave = np.sin(2 * np.pi * 50 * t) # 50 Hz sine wave
51
+ elif waveform_type == "Square":
52
+ wave = square(2 * np.pi * 50 * t) # 50 Hz square wave
53
+ elif waveform_type == "Triangular":
54
+ wave = sawtooth(2 * np.pi * 50 * t) # 50 Hz triangular wave
55
+ else:
56
+ wave = np.zeros_like(t) # Default to zero
57
+ return t, wave
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
+ # Run Analysis Button
60
+ if st.button("▶️ Run Analysis"):
61
+ # Perform circuit analysis
62
+ results = analyze_circuit()
63
+
64
+ # Display analysis results
65
+ st.subheader("🔍 Analysis Results")
66
+ st.dataframe(results)
67
 
68
+ # Waveform visualization
69
+ st.subheader("📈 Waveform Visualization")
70
+ waveform_type = st.selectbox("Select Waveform Type", ["Sine", "Square", "Triangular"])
71
+ t, wave = generate_waveform(waveform_type)
72
+
73
+ # Plot waveform
74
+ fig = go.Figure()
75
+ fig.add_trace(go.Scatter(x=t, y=wave, mode="lines", name=waveform_type))
76
+ fig.update_layout(
77
+ title=f"{waveform_type} Waveform",
78
+ xaxis_title="Time (s)",
79
+ yaxis_title="Amplitude",
80
+ template="plotly_white"
81
+ )
82
+ st.plotly_chart(fig)
 
 
 
 
 
 
 
83
 
84
+ # Instructions for Analysis
85
+ with st.expander("❓ How to use"):
86
+ st.markdown("""
87
+ 1. **Build Your Circuit**:
88
+ - Use the CircuitJS1 simulator above to design your circuit.
89
+ - Add components like resistors, capacitors, diodes, etc.
90
+ - Simulate the circuit to ensure it works as expected.
91
+
92
+ 2. **Run Analysis**:
93
+ - Click the "Run Analysis" button to get the circuit's electrical properties.
94
+ - View the observation table for voltage, current, and resistance.
95
+
96
+ 3. **Waveform Visualization**:
97
+ - Select a waveform type (Sine, Square, Triangular) to visualize.
98
+ - The waveform will be displayed based on the circuit's AC behavior.
99
+ """)