-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek4_complete.py
More file actions
1651 lines (1383 loc) · 69.4 KB
/
week4_complete.py
File metadata and controls
1651 lines (1383 loc) · 69.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
═══════════════════════════════════════════════════════════════════
DIGITAL CONTROL SYSTEMS - INTEGRATED INTERACTIVE DEMONSTRATIONS
University of Kufa | Electrical Engineering Department
Dr. Ali Al-Ghanimi | Academic Year 2025
Weeks 4-6 Complete Coverage:
- Week 4: Z-Transform & Inverse Z-Transform
- Week 5: Pulse Transfer Functions
- Week 6: Stability Analysis I (Jury Test & Routh Criterion)
Source References:
- Chakrabortty et al., "Digital Control System Analysis & Design"
- DigitalControlTextBook.pdf (Ch. 3-4)
- DCS.pdf, lec_2.pdf, lec_4.pdf
- notes_A2_DiscreteSystems.pdf
═══════════════════════════════════════════════════════════════════
"""
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import cm
from scipy import signal
import control as ct
import pandas as pd
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')
# ═══════════════════════════════════════════════════════════════════
# PAGE CONFIGURATION
# ═══════════════════════════════════════════════════════════════════
st.set_page_config(
page_title="Digital Control Systems | Weeks 4-6 | Dr. Al-Ghanimi",
page_icon="🎓",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'mailto:alih.alghanimi@uokufa.edu.iq',
'About': 'Digital Control Systems - University of Kufa'
}
)
# Initialize session state
if 'session_id' not in st.session_state:
st.session_state.session_id = datetime.now().strftime("%Y%m%d_%H%M%S")
if 'view_count' not in st.session_state:
st.session_state.view_count = 0
# Custom CSS for enhanced UI
st.markdown("""
<style>
.main-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 2rem;
border-radius: 15px;
color: white;
text-align: center;
margin-bottom: 2rem;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.demo-card {
background: #f8f9fa;
padding: 1.5rem;
border-radius: 10px;
border-left: 5px solid #667eea;
margin: 1rem 0;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.success-box {
background: #d4edda;
padding: 1rem;
border-radius: 8px;
border-left: 4px solid #28a745;
margin: 1rem 0;
}
.warning-box {
background: #fff3cd;
padding: 1rem;
border-radius: 8px;
border-left: 4px solid #ffc107;
margin: 1rem 0;
}
.info-box {
background: #d1ecf1;
padding: 1rem;
border-radius: 8px;
border-left: 4px solid #17a2b8;
margin: 1rem 0;
}
.danger-box {
background: #f8d7da;
padding: 1rem;
border-radius: 8px;
border-left: 4px solid #dc3545;
margin: 1rem 0;
}
.formula-box {
background: #e8e9ea;
padding: 1rem;
border-radius: 8px;
border: 2px solid #6c757d;
margin: 1rem 0;
font-family: 'Courier New', monospace;
}
</style>
""", unsafe_allow_html=True)
# ═══════════════════════════════════════════════════════════════════
# HELPER FUNCTIONS - WEEK 4
# ═══════════════════════════════════════════════════════════════════
def z_transform(signal_type="step", a=1.0):
"""Calculate Z-transform for common signals"""
if signal_type == "step":
return f"Z[u[n]] = z/(z-1)", np.array([1, -1])
elif signal_type == "exponential":
return f"Z[a^n u[n]] = z/(z-{a:.2f})", np.array([1, -a])
elif signal_type == "ramp":
return f"Z[n u[n]] = z/(z-1)^2", np.array([1, -2, 1])
def draw_roc(ax, poles, roc_type="exterior"):
"""Draw Region of Convergence on complex plane"""
circle = plt.Circle((0, 0), 1, color='blue', fill=False, linewidth=2, linestyle='--')
ax.add_patch(circle)
if roc_type == "exterior":
max_pole = max(abs(p) for p in poles)
roc_circle = plt.Circle((0, 0), max_pole, color='green', fill=True, alpha=0.2)
ax.add_patch(roc_circle)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)
ax.axhline(y=0, color='k', linewidth=0.5)
ax.axvline(x=0, color='k', linewidth=0.5)
ax.set_xlabel('Real', fontweight='bold')
ax.set_ylabel('Imaginary', fontweight='bold')
def partial_fractions(num, den):
"""Decompose transfer function into partial fractions"""
residues, poles, k = signal.residue(num, den)
return residues, poles, k
def inverse_z_transform_methods(num, den, n_samples=20):
"""Compare different inverse Z-transform methods"""
# Method 1: Partial Fractions
residues, poles, _ = partial_fractions(num, den)
# Method 2: Long Division
sys = signal.TransferFunction(num, den, dt=True)
t, y_impulse = signal.dimpulse(sys, n=n_samples)
# Method 3: Direct calculation
n = np.arange(n_samples)
y_direct = np.zeros(n_samples)
for i, (r, p) in enumerate(zip(residues, poles)):
y_direct += r * (p ** n)
return n, y_impulse[0].flatten(), y_direct
# ═══════════════════════════════════════════════════════════════════
# HELPER FUNCTIONS - WEEK 5
# ═══════════════════════════════════════════════════════════════════
def diff_eq_to_tf(a_coeffs, b_coeffs):
"""Convert difference equation to transfer function"""
H_z = signal.TransferFunction(b_coeffs, a_coeffs, dt=True)
return H_z
def block_diagram_reduction(G1, G2, connection="series"):
"""Reduce block diagrams"""
if connection == "series":
return signal.TransferFunction(
np.polymul(G1.num, G2.num),
np.polymul(G1.den, G2.den),
dt=True
)
elif connection == "parallel":
num = np.polymul(G1.num, G2.den) + np.polymul(G2.num, G1.den)
den = np.polymul(G1.den, G2.den)
return signal.TransferFunction(num, den, dt=True)
elif connection == "feedback":
num = np.polymul(G1.num, G2.den)
den = np.polymul(G1.den, G2.den) + np.polymul(G1.num, G2.num)
return signal.TransferFunction(num, den, dt=True)
# ═══════════════════════════════════════════════════════════════════
# HELPER FUNCTIONS - WEEK 6 (ENHANCED)
# ═══════════════════════════════════════════════════════════════════
def evaluate_polynomial(coeffs, z_value):
"""Evaluate polynomial Q(z) at given z value"""
return np.sum(coeffs * (z_value ** np.arange(len(coeffs))))
def jury_test(coeffs):
"""
Comprehensive Jury stability test
Source: DigitalControlTextBook.pdf, Section 4.5, pp. 104-109
"""
n = len(coeffs) - 1
a = np.array(coeffs, dtype=float)
details = {
'conditions': [],
'jury_table': [],
'failed_at': None
}
# Condition 1: Q(1) > 0
Q1 = np.sum(a)
cond1_pass = Q1 > 0
details['conditions'].append({
'number': 1,
'description': 'Q(1) > 0',
'value': Q1,
'pass': cond1_pass
})
if not cond1_pass:
details['failed_at'] = 1
return False, details
# Condition 2: (-1)^n * Q(-1) > 0
Q_minus1 = evaluate_polynomial(a, -1)
cond2_value = ((-1)**n) * Q_minus1
cond2_pass = cond2_value > 0
details['conditions'].append({
'number': 2,
'description': f'(-1)^{n} Q(-1) > 0',
'value': cond2_value,
'pass': cond2_pass
})
if not cond2_pass:
details['failed_at'] = 2
return False, details
# Condition 3: |a0| < an
cond3_pass = abs(a[0]) < abs(a[n])
details['conditions'].append({
'number': 3,
'description': '|a0| < |an|',
'value': f'|{a[0]:.4f}| < |{a[n]:.4f}|',
'pass': cond3_pass
})
if not cond3_pass:
details['failed_at'] = 3
return False, details
# Build Jury table for n >= 2
if n >= 2:
# Initialize table rows
table_rows = []
table_rows.append(a.copy()) # Row 1: coefficients
table_rows.append(a[::-1].copy()) # Row 2: reversed coefficients
current_coeffs = a.copy()
condition_number = 4
for row_idx in range(n - 1):
# Create new row using determinants
new_row_len = len(current_coeffs) - 1
new_row = np.zeros(new_row_len)
for j in range(new_row_len):
# Calculate determinant: |a0 a_{n-j}|
# |an a_j |
det = current_coeffs[0] * current_coeffs[-(j+2)] - current_coeffs[-1] * current_coeffs[j]
new_row[j] = det
if new_row_len > 0:
# Check condition |b0| > |b_{n-1}|
cond_pass = abs(new_row[0]) > abs(new_row[-1])
details['conditions'].append({
'number': condition_number,
'description': f'Row {row_idx + 3}: |first| > |last|',
'value': f'|{new_row[0]:.4f}| > |{new_row[-1]:.4f}|',
'pass': cond_pass
})
if not cond_pass:
details['failed_at'] = condition_number
return False, details
condition_number += 1
table_rows.append(new_row.copy())
if new_row_len > 1:
table_rows.append(new_row[::-1].copy())
current_coeffs = new_row.copy()
if len(current_coeffs) <= 1:
break
details['jury_table'] = table_rows
return True, details
def bilinear_transform(coeffs_z):
"""
Apply bilinear transformation w = (z-1)/(z+1) or z = (1+w)/(1-w)
Source: Chakrabortty Ch.7, pp.234-236
For a polynomial Q(z) = sum(a_i * z^i), substitute z = (1+w)/(1-w)
and expand to get Q(w).
"""
# Ensure all coefficients are float type
coeffs_z = [float(c) for c in coeffs_z]
n = len(coeffs_z) - 1
# For simple 2nd order case (most common)
if n == 2:
a0, a1, a2 = coeffs_z
# Q(z) = a2*z^2 + a1*z + a0
# Substitute z = (1+w)/(1-w) and expand
# After algebra, Q(w) = b2*w^2 + b1*w + b0
b0 = float(a2 + a1 + a0)
b1 = float(2*(a2 - a0))
b2 = float(a2 - a1 + a0)
# Normalize
if abs(b2) > 1e-10:
return np.array([b0/b2, b1/b2, 1.0])
else:
return np.array([b0, b1, b2])
# For 3rd order
elif n == 3:
a0, a1, a2, a3 = coeffs_z
# After substitution and expansion
b0 = float(a3 + a2 + a1 + a0)
b1 = float(3*a3 + a2 - a1 - 3*a0)
b2 = float(3*a3 - a2 - a1 + 3*a0)
b3 = float(a3 - a2 + a1 - a0)
# Normalize
if abs(b3) > 1e-10:
return np.array([b0/b3, b1/b3, b2/b3, 1.0])
else:
return np.array([b0, b1, b2, b3])
# For higher orders, use general formula
else:
from scipy.special import comb
coeffs_w = np.zeros(n + 1)
for i in range(n + 1):
for k in range(n + 1):
# Coefficient contribution from binomial expansion
for j in range(k + 1):
if i == n - k + 2*j:
coeffs_w[i] += coeffs_z[k] * comb(k, j, exact=True) * ((-1)**(k-j))
# Normalize
if coeffs_w[-1] != 0:
coeffs_w = coeffs_w / coeffs_w[-1]
return coeffs_w
def routh_array(coeffs):
"""
Construct Routh array for stability analysis
Source: Chakrabortty Ch.7, pp.236-239
"""
n = len(coeffs) - 1
# Initialize array with proper size
cols = (n + 2) // 2 + 1
routh = np.zeros((n + 1, cols))
# First row: coefficients with even indices (in reverse order)
for i in range(0, len(coeffs), 2):
if i // 2 < cols:
routh[0, i // 2] = coeffs[n - i]
# Second row: coefficients with odd indices (in reverse order)
if n > 0:
for i in range(1, len(coeffs), 2):
if i // 2 < cols:
routh[1, i // 2] = coeffs[n - i]
# Calculate remaining rows
for i in range(2, n + 1):
for j in range(cols - 1):
if routh[i-1, 0] != 0:
if j + 1 < cols:
numerator = routh[i-2, 0] * routh[i-1, j+1] - routh[i-2, j+1] * routh[i-1, 0]
routh[i, j] = numerator / routh[i-1, 0]
else:
# Handle zero in first column by using small epsilon
eps = 1e-10
if j + 1 < cols:
numerator = routh[i-2, 0] * routh[i-1, j+1] - routh[i-2, j+1] * eps
routh[i, j] = numerator / eps
return routh
def check_routh_stability(routh):
"""Check stability from Routh array"""
first_col = routh[:, 0]
# Count sign changes in first column
sign_changes = 0
prev_sign = np.sign(first_col[0]) if first_col[0] != 0 else 1
for val in first_col[1:]:
if val != 0:
curr_sign = np.sign(val)
if prev_sign * curr_sign < 0:
sign_changes += 1
prev_sign = curr_sign
return sign_changes == 0, sign_changes
def find_stability_range(char_poly_coeffs, K_var_index, K_range):
"""Find stable range of parameter K"""
stable_range = []
for K in K_range:
test_coeffs = char_poly_coeffs.copy()
test_coeffs[K_var_index] = K
is_stable, _ = jury_test(test_coeffs)
if is_stable:
stable_range.append(K)
if stable_range:
return min(stable_range), max(stable_range)
return None, None
def draw_unit_circle(ax, title="Unit Circle"):
"""Draw unit circle for stability visualization"""
circle = plt.Circle((0, 0), 1, color='blue', fill=False, linewidth=2)
ax.add_patch(circle)
ax.axhline(y=0, color='k', linewidth=0.5)
ax.axvline(x=0, color='k', linewidth=0.5)
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)
ax.set_xlabel('Real', fontsize=12, fontweight='bold')
ax.set_ylabel('Imaginary', fontsize=12, fontweight='bold')
ax.set_title(title, fontsize=14, fontweight='bold')
# ═══════════════════════════════════════════════════════════════════
# MAIN HEADER
# ═══════════════════════════════════════════════════════════════════
st.markdown("""
<div class="main-header">
<h1>🎓 Digital Control Systems</h1>
<h2>Interactive Demonstrations: Weeks 4, 5 & 6</h2>
<p style="font-size: 1.1rem; margin-top: 1rem;">
<strong>Dr. Ali Al-Ghanimi</strong><br>
Electrical Engineering Department<br>
University of Kufa | Academic Year 2025
</p>
</div>
""", unsafe_allow_html=True)
# ═══════════════════════════════════════════════════════════════════
# SIDEBAR NAVIGATION
# ═══════════════════════════════════════════════════════════════════
with st.sidebar:
st.markdown("## 📚 Select Week")
week_selection = st.selectbox(
"Choose your week:",
["Week 4: Z-Transform & Inverse",
"Week 5: Pulse Transfer Functions",
"Week 6: Stability Analysis I"],
key="week_selector"
)
st.markdown("---")
# Demo selection based on week
if "Week 4" in week_selection:
st.markdown("### 📊 Week 4 Demos")
demo_selection = st.radio(
"Select Demo:",
["📊 Demo 1: Z-Transform Calculator",
"🎯 Demo 2: ROC Visualizer",
"🔄 Demo 3: Inverse Methods",
"📐 Demo 4: Partial Fractions",
"🔧 Demo 5: Properties"],
key="demo_nav_w4"
)
elif "Week 5" in week_selection:
st.markdown("### 🎯 Week 5 Demos")
demo_selection = st.radio(
"Select Demo:",
["📊 Demo 1: PTF Calculator",
"🎯 Demo 2: Block Diagram Analyzer",
"🔄 Demo 3: Difference Eq ↔ TF",
"📐 Demo 4: Closed-Loop Systems",
"🔧 Demo 5: Open/Closed Loop Comparison"],
key="demo_nav_w5"
)
else: # Week 6
st.markdown("### 🎯 Week 6 Demos")
demo_selection = st.radio(
"Select Demo:",
["📊 Demo 1: Unit Circle & Stability",
"🎯 Demo 2: Jury Test Step-by-Step",
"🔄 Demo 3: Parametric Stability (K Range)",
"📐 Demo 4: Bilinear Transformation",
"🔧 Demo 5: Routh Criterion in w-plane"],
key="demo_nav_w6"
)
st.markdown("---")
st.markdown("### 🎯 Learning Objectives")
if "Week 4" in week_selection:
with st.expander("Week 4 Objectives"):
st.markdown("""
1. ✅ Calculate z-transforms
2. ✅ Determine ROC
3. ✅ Apply inverse z-transform
4. ✅ Master partial fractions
5. ✅ Utilize transform properties
**References:** lec_2.pdf, lec_4.pdf, Chakrabortty Ch.2
""")
elif "Week 5" in week_selection:
with st.expander("Week 5 Objectives"):
st.markdown("""
1. ✅ Derive pulse transfer functions
2. ✅ Analyze block diagrams
3. ✅ Convert difference equations
4. ✅ Calculate closed-loop TF
5. ✅ Compare open vs closed loop
**References:** DCS.pdf, notes_A2.pdf, Chakrabortty Ch.4
""")
else: # Week 6
with st.expander("Week 6 Objectives"):
st.markdown("""
1. ✅ Apply Jury stability test
2. ✅ Construct Jury table systematically
3. ✅ Use bilinear transformation
4. ✅ Apply Routh-Hurwitz criterion
5. ✅ Find stable parameter ranges
6. ✅ Compare stability analysis methods
**References:** Chakrabortty Ch.7, DigitalControlTextBook Ch.4
""")
st.markdown("---")
st.markdown("### 💬 Contact")
st.markdown("""
📧 **Email:** ali.alghanimi@uokufa.edu.iq
🏢 **Office:** EE Building, Room 115
⏰ **Office Hours:** Sun-Thu 10:00-12:00
""")
st.markdown("---")
st.markdown("""
<div style='text-align: center; padding: 0.5rem;'>
<small>© 2025 University of Kufa</small>
</div>
""", unsafe_allow_html=True)
# ═══════════════════════════════════════════════════════════════════
# MAIN CONTENT AREA
# ═══════════════════════════════════════════════════════════════════
# Week 4 Demos
if "Week 4" in week_selection:
if "Demo 1" in demo_selection:
st.markdown("## 📊 Demo 1: Z-Transform Calculator")
st.markdown("Calculate Z-transforms of common discrete-time signals")
col1, col2 = st.columns([1, 2])
with col1:
st.markdown("### ⚙️ Signal Selection")
signal_type = st.selectbox(
"Select signal type:",
["Unit Step", "Exponential", "Ramp", "Impulse"],
key="z_sig_type"
)
if signal_type == "Exponential":
a = st.slider("Parameter a:", 0.1, 2.0, 0.5, 0.1, key="z_exp_param")
else:
a = 1.0
n_samples = st.slider("Samples to plot:", 10, 50, 20, key="z_samples")
with col2:
st.markdown("### 📈 Results")
if signal_type == "Unit Step":
z_expr = "z/(z-1)"
poles = [1.0]
signal_vals = np.ones(n_samples)
elif signal_type == "Exponential":
z_expr = f"z/(z-{a:.2f})"
poles = [a]
signal_vals = a ** np.arange(n_samples)
elif signal_type == "Ramp":
z_expr = "z/(z-1)²"
poles = [1.0, 1.0]
signal_vals = np.arange(n_samples)
else: # Impulse
z_expr = "1"
poles = []
signal_vals = np.zeros(n_samples)
signal_vals[0] = 1
st.latex(f"Z\\{{x[n]\\}} = {z_expr}")
# Plot signal and pole-zero
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# Time domain signal
ax1.stem(range(n_samples), signal_vals, basefmt=' ')
ax1.set_xlabel('n', fontweight='bold')
ax1.set_ylabel('x[n]', fontweight='bold')
ax1.set_title('Time Domain Signal', fontweight='bold')
ax1.grid(True, alpha=0.3)
# Pole-zero plot
draw_unit_circle(ax2, "Pole-Zero Plot")
for p in poles:
ax2.plot(p, 0, 'x', markersize=12, color='red', markeredgewidth=2)
ax2.plot(0, 0, 'o', markersize=8, color='blue')
plt.tight_layout()
st.pyplot(fig)
st.success(f"✅ Z-transform calculated for {signal_type.lower()} signal")
elif "Demo 2" in demo_selection:
st.markdown("## 🎯 Demo 2: ROC Visualizer")
st.markdown("Visualize Region of Convergence for different pole configurations")
col1, col2 = st.columns([1, 2])
with col1:
st.markdown("### ⚙️ Pole Configuration")
pole_config = st.selectbox(
"Select configuration:",
["Single Real Pole", "Complex Conjugate Pair", "Multiple Poles"],
key="roc_config"
)
if pole_config == "Single Real Pole":
pole_val = st.slider("Pole location:", -2.0, 2.0, 0.8, 0.1, key="roc_single")
poles = [pole_val]
elif pole_config == "Complex Conjugate Pair":
mag = st.slider("Magnitude:", 0.1, 1.5, 0.9, 0.1, key="roc_mag")
angle = st.slider("Angle (degrees):", 0, 180, 45, 15, key="roc_angle")
angle_rad = np.radians(angle)
poles = [mag * np.exp(1j*angle_rad), mag * np.exp(-1j*angle_rad)]
else:
poles = []
n_poles = st.number_input("Number of poles:", 2, 5, 3, key="roc_npoles")
for i in range(n_poles):
p = st.number_input(f"Pole {i+1}:", -2.0, 2.0, 0.5*(i+1), key=f"roc_p{i}")
poles.append(p)
roc_type = st.radio("ROC Type:", ["Exterior", "Interior", "Annular"], key="roc_type")
with col2:
st.markdown("### 📊 ROC Visualization")
fig, ax = plt.subplots(figsize=(8, 8))
# Draw unit circle
circle = plt.Circle((0, 0), 1, color='blue', fill=False, linewidth=2, linestyle='--')
ax.add_patch(circle)
# Draw ROC
if poles:
max_pole = max(abs(p) for p in poles)
min_pole = min(abs(p) for p in poles) if len(poles) > 1 else 0
if roc_type == "Exterior":
# ROC outside largest pole
ax.fill_between([-2, 2], -2, 2, where=np.ones(2),
color='green', alpha=0.2)
inner_circle = plt.Circle((0, 0), max_pole, color='white', fill=True)
ax.add_patch(inner_circle)
st.info(f"ROC: |z| > {max_pole:.2f}")
elif roc_type == "Interior":
# ROC inside smallest pole
roc_circle = plt.Circle((0, 0), min_pole if min_pole > 0 else max_pole,
color='green', fill=True, alpha=0.2)
ax.add_patch(roc_circle)
st.info(f"ROC: |z| < {min_pole if min_pole > 0 else max_pole:.2f}")
else: # Annular
if len(poles) > 1:
outer_circle = plt.Circle((0, 0), max_pole,
color='green', fill=True, alpha=0.2)
inner_circle = plt.Circle((0, 0), min_pole,
color='white', fill=True)
ax.add_patch(outer_circle)
ax.add_patch(inner_circle)
st.info(f"ROC: {min_pole:.2f} < |z| < {max_pole:.2f}")
# Plot poles
for p in poles:
if isinstance(p, complex):
ax.plot(p.real, p.imag, 'x', markersize=12,
color='red', markeredgewidth=2)
else:
ax.plot(p, 0, 'x', markersize=12,
color='red', markeredgewidth=2)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)
ax.axhline(y=0, color='k', linewidth=0.5)
ax.axvline(x=0, color='k', linewidth=0.5)
ax.set_xlabel('Real', fontweight='bold')
ax.set_ylabel('Imaginary', fontweight='bold')
ax.set_title('Region of Convergence', fontsize=14, fontweight='bold')
plt.tight_layout()
st.pyplot(fig)
elif "Demo 3" in demo_selection:
st.markdown("## 🔄 Demo 3: Inverse Z-Transform Methods")
st.markdown("Compare different inverse transform techniques")
col1, col2 = st.columns([1, 2])
with col1:
st.markdown("### ⚙️ Transfer Function")
example = st.selectbox(
"Select example:",
["Simple First Order", "Second Order", "Custom"],
key="inv_example"
)
if example == "Simple First Order":
num = [1]
den = [1, -0.8]
elif example == "Second Order":
num = [1, 0]
den = [1, -1.5, 0.5]
else:
st.markdown("**Numerator coefficients:**")
num_order = st.number_input("Order:", 0, 3, 1, key="inv_num_ord")
num = []
for i in range(num_order + 1):
c = st.number_input(f"b{i}:", -10.0, 10.0, 1.0 if i == 0 else 0.0,
key=f"inv_b{i}")
num.append(c)
st.markdown("**Denominator coefficients:**")
den_order = st.number_input("Order:", 1, 3, 2, key="inv_den_ord")
den = []
for i in range(den_order + 1):
c = st.number_input(f"a{i}:", -10.0, 10.0, 1.0 if i == 0 else 0.0,
key=f"inv_a{i}")
den.append(c)
n_samples = st.slider("Samples:", 10, 50, 25, key="inv_samples")
with col2:
st.markdown("### 📈 Comparison of Methods")
# Calculate inverse transforms
n, y_impulse, y_direct = inverse_z_transform_methods(num, den, n_samples)
# Partial fractions info
residues, poles, _ = partial_fractions(num, den)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))
# Plot impulse response
ax1.stem(n, y_impulse, basefmt=' ', label='Long Division', linefmt='b-')
ax1.stem(n + 0.1, y_direct, basefmt=' ', label='Partial Fractions', linefmt='r-')
ax1.set_xlabel('n', fontweight='bold')
ax1.set_ylabel('x[n]', fontweight='bold')
ax1.set_title('Inverse Z-Transform Results', fontweight='bold')
ax1.legend()
ax1.grid(True, alpha=0.3)
# Plot poles
ax2.scatter([p.real for p in poles], [p.imag for p in poles],
s=100, c='red', marker='x', linewidths=2)
circle = plt.Circle((0, 0), 1, color='blue', fill=False, linewidth=2)
ax2.add_patch(circle)
ax2.set_xlim(-1.5, 1.5)
ax2.set_ylim(-1.5, 1.5)
ax2.set_aspect('equal')
ax2.grid(True, alpha=0.3)
ax2.set_xlabel('Real', fontweight='bold')
ax2.set_ylabel('Imaginary', fontweight='bold')
ax2.set_title('Pole Locations', fontweight='bold')
plt.tight_layout()
st.pyplot(fig)
# Display partial fractions
st.markdown("#### Partial Fraction Decomposition:")
for i, (r, p) in enumerate(zip(residues, poles)):
st.latex(f"\\frac{{{r:.3f}}}{{z - {p:.3f}}}")
# Week 5 Demos
elif "Week 5" in week_selection:
if "Demo 1" in demo_selection:
st.markdown("## 📊 Demo 1: Pulse Transfer Function Calculator")
st.markdown("Calculate PTF from continuous system with ZOH")
col1, col2 = st.columns([1, 2])
with col1:
st.markdown("### ⚙️ System Parameters")
T = st.slider("Sampling Period (s):", 0.1, 2.0, 0.5, 0.1, key="ptf_T")
example = st.selectbox(
"System type:",
["First Order", "Second Order", "Integrator", "Custom"],
key="ptf_sys"
)
if example == "First Order":
K = st.slider("Gain K:", 0.1, 10.0, 1.0, 0.1, key="ptf_K1")
tau = st.slider("Time constant τ:", 0.1, 5.0, 1.0, 0.1, key="ptf_tau")
num_s = [K]
den_s = [tau, 1]
elif example == "Second Order":
K = st.slider("Gain K:", 0.1, 10.0, 1.0, 0.1, key="ptf_K2")
wn = st.slider("ωn:", 0.1, 10.0, 2.0, 0.1, key="ptf_wn")
zeta = st.slider("ζ:", 0.1, 2.0, 0.7, 0.1, key="ptf_zeta")
num_s = [K * wn**2]
den_s = [1, 2*zeta*wn, wn**2]
elif example == "Integrator":
K = st.slider("Gain K:", 0.1, 10.0, 1.0, 0.1, key="ptf_Ki")
num_s = [K]
den_s = [1, 0]
else:
st.markdown("Custom G(s) = b₀/(s² + a₁s + a₀)")
b0 = st.number_input("b₀:", 0.1, 10.0, 1.0, key="ptf_b0")
a1 = st.number_input("a₁:", 0.0, 10.0, 1.0, key="ptf_a1")
a0 = st.number_input("a₀:", 0.0, 10.0, 1.0, key="ptf_a0")
num_s = [b0]
den_s = [1, a1, a0]
with col2:
st.markdown("### 📊 Transfer Functions")
# Continuous system
G_s = signal.TransferFunction(num_s, den_s)
# Discretize with ZOH
G_z = signal.cont2discrete((num_s, den_s), T, method='zoh')
# Display
st.markdown("#### Continuous System G(s):")
num_str = " + ".join([f"{c:.2f}s^{i}" for i, c in enumerate(num_s[::-1])])
den_str = " + ".join([f"{c:.2f}s^{i}" for i, c in enumerate(den_s[::-1])])
st.latex(f"G(s) = \\frac{{{num_str}}}{{{den_str}}}")
st.markdown("#### Discrete System G(z):")
num_z_str = " + ".join([f"{c:.3f}z^{{{-i}}}" for i, c in enumerate(G_z[0].flatten())])
den_z_str = " + ".join([f"{c:.3f}z^{{{-i}}}" for i, c in enumerate(G_z[1])])
st.latex(f"G(z) = \\frac{{{num_z_str}}}{{{den_z_str}}}")
# Step response comparison
t_cont = np.linspace(0, 10*T, 200)
t_disc = np.arange(0, 10*T, T)
_, y_cont = signal.step(G_s, T=t_cont)
_, y_disc = signal.dstep(G_z, n=len(t_disc))
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(t_cont, y_cont, 'b-', label='Continuous', linewidth=2)
ax.step(t_disc, y_disc[0].flatten(), 'r-', where='post',
label='Discrete (ZOH)', linewidth=2)
ax.plot(t_disc, y_disc[0].flatten(), 'ro', markersize=8)
ax.set_xlabel('Time (s)', fontweight='bold')
ax.set_ylabel('Response', fontweight='bold')
ax.set_title('Step Response Comparison', fontsize=14, fontweight='bold')
ax.legend(fontsize=11)
ax.grid(True, alpha=0.3)
plt.tight_layout()
st.pyplot(fig)
elif "Demo 2" in demo_selection:
st.markdown("## 🎯 Demo 2: Block Diagram Analyzer")
st.markdown("Reduce and analyze block diagram configurations")
col1, col2 = st.columns([1, 2])
with col1:
st.markdown("### ⚙️ Configuration")
config = st.selectbox(
"Configuration:",
["Series", "Parallel", "Feedback"],
key="bd_config"
)
st.markdown("**G₁(z) Parameters:**")
g1_num = st.text_input("Numerator:", "1", key="bd_g1_num")
g1_den = st.text_input("Denominator:", "1 -0.8", key="bd_g1_den")
st.markdown("**G₂(z) Parameters:**")
g2_num = st.text_input("Numerator:", "0.5", key="bd_g2_num")
g2_den = st.text_input("Denominator:", "1 -0.5", key="bd_g2_den")
# Parse coefficients
try:
g1_num_coeffs = [float(x) for x in g1_num.split()]
g1_den_coeffs = [float(x) for x in g1_den.split()]
g2_num_coeffs = [float(x) for x in g2_num.split()]
g2_den_coeffs = [float(x) for x in g2_den.split()]
except:
st.error("Invalid coefficient format")
g1_num_coeffs = [1]
g1_den_coeffs = [1, -0.8]
g2_num_coeffs = [0.5]
g2_den_coeffs = [1, -0.5]
with col2:
st.markdown("### 📊 Block Diagram Analysis")
G1 = signal.TransferFunction(g1_num_coeffs, g1_den_coeffs, dt=True)
G2 = signal.TransferFunction(g2_num_coeffs, g2_den_coeffs, dt=True)
# Calculate equivalent transfer function
G_eq = block_diagram_reduction(G1, G2, config.lower())
# Display block diagram
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# Block diagram visualization
ax1.text(0.1, 0.5, 'R(z)', fontsize=12, ha='center')
if config == "Series":
ax1.add_patch(plt.Rectangle((0.2, 0.4), 0.2, 0.2,
fill=True, facecolor='lightblue'))
ax1.text(0.3, 0.5, 'G₁(z)', fontsize=12, ha='center')
ax1.add_patch(plt.Rectangle((0.5, 0.4), 0.2, 0.2,
fill=True, facecolor='lightgreen'))
ax1.text(0.6, 0.5, 'G₂(z)', fontsize=12, ha='center')
ax1.arrow(0.15, 0.5, 0.04, 0, head_width=0.03, color='black')
ax1.arrow(0.42, 0.5, 0.07, 0, head_width=0.03, color='black')
ax1.arrow(0.72, 0.5, 0.08, 0, head_width=0.03, color='black')
ax1.text(0.85, 0.5, 'Y(z)', fontsize=12, ha='center')
elif config == "Parallel":
ax1.add_patch(plt.Rectangle((0.3, 0.6), 0.2, 0.15,
fill=True, facecolor='lightblue'))
ax1.text(0.4, 0.675, 'G₁(z)', fontsize=12, ha='center')
ax1.add_patch(plt.Rectangle((0.3, 0.25), 0.2, 0.15,
fill=True, facecolor='lightgreen'))
ax1.text(0.4, 0.325, 'G₂(z)', fontsize=12, ha='center')
ax1.plot([0.2, 0.2], [0.325, 0.675], 'k-')
ax1.plot([0.6, 0.6], [0.325, 0.675], 'k-')
ax1.text(0.7, 0.5, '+', fontsize=16, ha='center')
ax1.text(0.85, 0.5, 'Y(z)', fontsize=12, ha='center')
else: # Feedback
ax1.add_patch(plt.Rectangle((0.3, 0.5), 0.2, 0.15,
fill=True, facecolor='lightblue'))
ax1.text(0.4, 0.575, 'G₁(z)', fontsize=12, ha='center')
ax1.add_patch(plt.Rectangle((0.4, 0.2), 0.2, 0.15,
fill=True, facecolor='lightgreen'))
ax1.text(0.5, 0.275, 'G₂(z)', fontsize=12, ha='center')
ax1.text(0.2, 0.575, '⊕', fontsize=16, ha='center')
ax1.plot([0.7, 0.7, 0.2], [0.575, 0.275, 0.275], 'k-')
ax1.text(0.85, 0.575, 'Y(z)', fontsize=12, ha='center')
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 1)
ax1.axis('off')
ax1.set_title(f'{config} Configuration', fontweight='bold')
# Pole-zero plot
poles_eq = np.roots(G_eq.den)
zeros_eq = np.roots(G_eq.num)
draw_unit_circle(ax2, "Equivalent System Poles & Zeros")
ax2.plot(poles_eq.real, poles_eq.imag, 'x', markersize=12,
color='red', markeredgewidth=2, label='Poles')
if len(zeros_eq) > 0: