-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrf_performance.py
More file actions
2327 lines (1948 loc) · 97.8 KB
/
rf_performance.py
File metadata and controls
2327 lines (1948 loc) · 97.8 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
"""
RF Performance Analysis Module
Professional signal-level interference analysis with quantitative dBc/dBm calculations
Based on standard RF engineering nonlinearity analysis
Mathematical Foundation:
Polynomial nonlinearity model: V₀ = a₀ + a₁Vᵢ + a₂Vᵢ² + a₃Vᵢ³ + a₄Vᵢ⁴ + a₅Vᵢ⁵
Two-tone analysis: Vᵢ = V₁cos(ω₁t) + V₂cos(ω₂t)
Based on industry standard measurements and typical RF system performance
"""
import math
from dataclasses import dataclass
from typing import Dict, List, Tuple, Optional
import pandas as pd
import numpy as np
from constants import (
get_technology_thresholds,
PA_CLASS_CORRECTIONS,
HARMONIC_ENGINEERING_LIMITS,
IMD_SATURATION_OFFSET_DB,
FILTER_MAX_REJECTION,
)
from calculator import assess_risk_severity_quantitative
@dataclass
class SystemParameters:
"""
Comprehensive RF system parameters for professional interference analysis
All parameters are user-editable and saveable for different system configurations
"""
# === TX Power Levels (User Editable) ===
lte_tx_power: float = 23.0 # dBm - LTE maximum TX power
wifi_tx_power: float = 18.0 # dBm - WiFi TX power
ble_tx_power: float = 10.0 # dBm - BLE TX power
halow_tx_power: float = 20.0 # dBm - HaLow TX power
# === RF System Isolation & Path Loss (User Editable) ===
antenna_isolation: float = 25.0 # dB - Physical antenna separation/isolation
pcb_isolation: float = 20.0 # dB - PCB layout isolation (traces, ground planes)
shield_isolation: float = 0.0 # dB - Additional RF shielding (0 = no shield)
# === Filtering & Attenuation (User Editable) ===
tx_harmonic_filtering_db: float = 40.0 # dB - TX harmonic suppression filtering
rx_preselector_filtering_db: float = 0.0 # dB - RX preselector filtering
out_of_band_rejection_db: float = 60.0 # dB - Filter out-of-band rejection
# === Technology-Specific Path Loss ===
lte_to_gnss_coupling_db: float = -10.0 # dB - Additional LTE→GNSS coupling loss
wifi_ble_isolation_db: float = 10.0 # dB - Wi-Fi/BLE triplexer isolation
cellular_wifi_isolation_db: float = 15.0 # dB - Cellular/Wi-Fi isolation
# === System Linearity Characteristics (User Editable) ===
# Based on real RF system parameters - HD levels calculated from these
iip3_dbm: float = -10.0 # dBm - Input-referred 3rd order intercept (system linearity)
iip2_dbm: float = 20.0 # dBm - Input-referred 2nd order intercept
oip3_dbm: float = 10.0 # dBm - Output-referred 3rd order intercept
compression_point_dbm: float = 5.0 # dBm - 1dB compression point
# === Power Amplifier Characteristics ===
pa_efficiency: float = 0.35 # PA efficiency (affects linearity vs power)
pa_class: str = "AB" # PA class (A, AB, B, C) affects harmonic behavior
bias_point_optimized: bool = True # Whether PA bias is optimized for linearity
# === Receiver Sensitivities (Technology Standards) ===
lte_sensitivity: float = -105.0 # dBm - LTE receiver sensitivity
wifi_sensitivity: float = -85.0 # dBm - WiFi receiver sensitivity
ble_sensitivity: float = -95.0 # dBm - BLE receiver sensitivity
gnss_sensitivity: float = -150.0 # dBm - GNSS receiver sensitivity (critical)
halow_sensitivity: float = -90.0 # dBm - HaLow receiver sensitivity
rx_p1db_dbm: float = -25.0 # dBm - Receiver 1dB compression point (typical LNA)
# === Environmental & System Parameters ===
temperature_celsius: float = 25.0 # °C - Operating temperature
noise_figure_db: float = 6.0 # dB - System noise figure
thermal_noise_density_dbm_hz: float = -174.0 # dBm/Hz - Thermal noise density
# === Duty Cycle Parameters (for TDM coexistence analysis) ===
lte_duty_cycle: float = 0.5 # LTE uplink duty cycle (~50% for TDD, 100% for FDD)
wifi_duty_cycle: float = 0.4 # WiFi CSMA/CA average duty cycle (~40%)
ble_duty_cycle: float = 0.05 # BLE hopping duty cycle (~5% per channel)
gnss_duty_cycle: float = 1.0 # GNSS always receiving
halow_duty_cycle: float = 0.3 # HaLow typical duty cycle
# === Coupling Factor ===
coupling_factor: float = 0.3 # Inter-path coupling (0.0-1.0), used in isolation model
# === TX Filter Model (GH #16) ===
tx_filter_type: str = "butterworth" # TX filter type: butterworth, chebyshev, saw, baw
tx_filter_order: int = 5 # TX filter order (1-9)
# === Antenna Separation (GH #17) ===
antenna_separation_mm: float = 20.0 # Physical separation between antennas in mm
coupling_type: str = "antenna" # Coupling type: antenna, pcb_trace, board_level
# === Phase Noise / Reciprocal Mixing (GH #30) ===
lo_phase_noise_dbc_hz: float = -100.0 # dBc/Hz - LO phase noise at 100 kHz offset
# === User Configuration Metadata ===
configuration_name: str = "Default" # User-defined configuration name
configuration_notes: str = "" # User notes about this configuration
def __post_init__(self):
"""Validate physical parameter ranges (GH #26)."""
if self.antenna_isolation < 0:
raise ValueError(f"antenna_isolation must be >= 0, got {self.antenna_isolation}")
if self.pcb_isolation < 0:
raise ValueError(f"pcb_isolation must be >= 0, got {self.pcb_isolation}")
if self.shield_isolation < 0:
raise ValueError(f"shield_isolation must be >= 0, got {self.shield_isolation}")
if not 0.0 <= self.coupling_factor <= 1.0:
raise ValueError(f"coupling_factor must be in [0, 1], got {self.coupling_factor}")
if self.noise_figure_db < 0:
raise ValueError(f"noise_figure_db must be >= 0, got {self.noise_figure_db}")
if self.tx_filter_order < 1 or self.tx_filter_order > 9:
raise ValueError(f"tx_filter_order must be 1-9, got {self.tx_filter_order}")
if self.antenna_separation_mm <= 0:
raise ValueError(f"antenna_separation_mm must be > 0, got {self.antenna_separation_mm}")
@dataclass
class QuantitativeResult:
"""Comprehensive quantitative interference result with dBc/dBm levels"""
frequency_mhz: float
product_type: str
aggressors: List[str]
victims: List[str]
# Power levels
aggressor_power_dbm: float
interference_level_dbc: float # Relative to carrier (dBc)
interference_at_tx_dbm: float # At transmitter output (dBm)
interference_at_victim_dbm: float # At victim input after isolation (dBm)
# Victim analysis
victim_sensitivity_dbm: float
interference_margin_db: float # Positive = safe, negative = interference
desensitization_db: float # Receiver desensitization (dB)
# Risk assessment
risk_level: str # Critical/High/Medium/Low/Negligible
risk_symbol: str # 🔴🟠🟡🔵✅
# Mathematical foundation
mathematical_formula: str # Underlying nonlinearity equation
# Blocking / P1dB compression analysis (GH #28)
blocking_risk_level: str = 'Safe' # Critical/High/Medium/Low/Safe
blocking_risk_emoji: str = '\u2705' # Emoji for blocking risk
blocking_p1db_margin_db: float = 99.0 # Margin to P1dB (dB)
blocking_description: str = '' # Human-readable blocking assessment
def calculate_hd3_from_iip3(tx_power_dbm: float, iip3_dbm: float, pa_class: str = "AB") -> float:
"""
Calculate 3rd harmonic distortion from TX power and IIP3
Standard RF formula: HD3_dBc = 2 × (P_TX - IIP3) + correction_factors
Real systems have additional factors based on PA design and bias point.
Args:
tx_power_dbm: Transmitter power in dBm
iip3_dbm: Input-referred 3rd order intercept point in dBm
pa_class: Power amplifier class (affects linearity behavior)
Returns:
HD3 level in dBc (negative value)
"""
# Basic 3rd order calculation
power_delta = tx_power_dbm - iip3_dbm
hd3_basic = -2 * power_delta # Negative because it's dBc below carrier
# PA class correction factors (from constants.py, GH #24)
hd3_correction = PA_CLASS_CORRECTIONS.get(pa_class, 0.0)
# Power level corrections (realistic PA behavior)
if power_delta < 5: # Low power operation - better linearity
hd3_correction += 5.0 # 5 dB better than theory
elif power_delta > 15: # High power - compression effects
hd3_correction -= 3.0 # 3 dB worse than theory
hd3_dbc = hd3_basic + hd3_correction
# Physical limits: Real PAs range from -20 to -70 dBc
hd3_dbc = max(min(hd3_dbc, -20.0), -70.0)
return hd3_dbc
def calculate_hd2_from_iip2(tx_power_dbm: float, iip2_dbm: float, bias_optimized: bool = True) -> float:
"""
Calculate 2nd harmonic distortion from TX power and IIP2
Standard RF formula: HD2_dBc = (P_TX - IIP2) + correction_factors
2nd order is linear with power (not quadratic like 3rd order)
Args:
tx_power_dbm: Transmitter power in dBm
iip2_dbm: Input-referred 2nd order intercept point in dBm
bias_optimized: Whether PA bias is optimized for linearity
Returns:
HD2 level in dBc (negative value)
"""
# Basic 2nd order calculation (linear with power)
power_delta = tx_power_dbm - iip2_dbm
hd2_basic = -power_delta # Negative because it's dBc below carrier
# Bias optimization correction
# Optimization provides push-pull cancellation benefit; non-optimized is at theoretical baseline
bias_correction = 3.0 if bias_optimized else 0.0
# Device symmetry effects (HD2 very sensitive to balance)
if power_delta < 10: # Conservative power - good balance
symmetry_correction = 3.0 # 3 dB better than theory
elif power_delta > 20: # High power - mismatch dominates
symmetry_correction = -5.0 # 5 dB worse than theory
else:
symmetry_correction = 0.0
hd2_dbc = hd2_basic + bias_correction + symmetry_correction
# Physical limits: HD2 typically -15 to -60 dBc
hd2_dbc = max(min(hd2_dbc, -15.0), -60.0)
return hd2_dbc
def calculate_higher_order_harmonics(hd2_dbc: float, hd3_dbc: float,
tx_power_dbm: float = 20.0, iip3_dbm: float = -10.0) -> tuple:
"""
Calculate 4th and 5th harmonics from fundamental 2nd/3rd order performance
CORRECTED: Uses polynomial coefficient ratios instead of empirical offsets.
From polynomial analysis (a₂=0.0562, a₃=0.01, a₄=0.0018, a₅=0.001):
- HD4 relative to HD2: 20*log10(a₄/a₂) = 20*log10(0.0018/0.0562) = -29.9 dB
- HD5 relative to HD3: 20*log10(a₅/a₃) = 20*log10(0.001/0.01) = -20.0 dB
Note: Previous values of -20 dB (HD4) and -15 dB (HD5) were ~20 dB too optimistic.
Args:
hd2_dbc: 2nd harmonic level in dBc
hd3_dbc: 3rd harmonic level in dBc
tx_power_dbm: TX power for compression effects
iip3_dbm: IIP3 for compression effects
Returns:
(hd4_dbc, hd5_dbc): 4th and 5th harmonic levels in dBc
"""
# CORRECTED: Use polynomial coefficient ratios (PhD-level review finding)
# HD4 from a₄/a₂ ratio: 20*log10(0.0018/0.0562) ≈ -29.9 dB
# Using -30.0 dB as practical value (was incorrectly -20 dB)
hd4_polynomial_offset = 30.0
hd4_dbc = hd2_dbc - hd4_polynomial_offset
# HD5 from a₅/a₃ ratio: 20*log10(0.001/0.01) = -20.0 dB
# Using -20.0 dB as practical value (was incorrectly -15 dB)
hd5_polynomial_offset = 20.0
hd5_dbc = hd3_dbc - hd5_polynomial_offset
# Add power-dependent compression effects for high-power operation
# When operating close to or above compression, higher-order products grow faster
power_delta = tx_power_dbm - iip3_dbm
if power_delta > 10: # Operating in compression region
compression_factor = (power_delta - 10) * 0.15 # 0.15 dB per dB above threshold
hd4_dbc += compression_factor * 0.5 # HD4 grows slower
hd5_dbc += compression_factor * 0.3 # HD5 grows slowest
# Physical limits for higher orders (don't go below noise floor)
hd4_dbc = max(hd4_dbc, -85.0)
hd5_dbc = max(hd5_dbc, -90.0)
return hd4_dbc, hd5_dbc
def calculate_total_isolation(
antenna_isolation_db: float,
pcb_isolation_db: float,
shield_isolation_db: float,
frequency_mhz: float = 1000.0,
coupling_factor: float = 0.3
) -> float:
"""
Calculate total system isolation accounting for parallel coupling paths.
CORRECTED: Simple additive model (A + B + C) overestimates isolation by 5-15 dB.
Real isolation is limited by the weakest path plus diminishing returns from additional paths.
Model: Total = min_isolation + correction_for_additional_paths + frequency_effects
Physical basis:
- RF energy follows the path of least resistance (lowest isolation)
- Additional isolation mechanisms provide diminishing returns due to coupling
- High frequencies can have worse isolation due to PCB parasitic coupling
Args:
antenna_isolation_db: Physical antenna separation/isolation (dB)
pcb_isolation_db: PCB layout isolation (dB)
shield_isolation_db: Additional RF shielding (dB), 0 = no shield
frequency_mhz: Operating frequency for frequency-dependent effects
coupling_factor: Coupling between isolation mechanisms (0.0-1.0, default 0.3)
Returns:
Total effective isolation in dB
"""
# Collect non-zero isolation contributions
isolations = [antenna_isolation_db, pcb_isolation_db, shield_isolation_db]
isolations = [i for i in isolations if i > 0]
if not isolations:
return 0.0
# Minimum isolation is the weakest (limiting) path
min_isolation = min(isolations)
# Additional isolation from other paths with diminishing returns
additional = 0.0
for iso in sorted(isolations)[1:]:
# Each additional path adds limited benefit due to coupling
# Maximum contribution is ~6 dB per path (coupling-limited)
path_contribution = min(iso - min_isolation, 6.0) * (1.0 - coupling_factor)
additional += path_contribution * 0.5 # 50% diminishing factor
# Frequency-dependent effects on isolation
# Higher frequencies often have WORSE isolation due to:
# - PCB trace coupling increases with frequency
# - Antenna near-field effects change
# - Shield effectiveness can decrease
if frequency_mhz > 3000:
freq_factor = -3.0 # High freq = worse isolation
elif frequency_mhz > 2000:
freq_factor = -2.0
elif frequency_mhz > 1000:
freq_factor = -1.0
elif frequency_mhz > 500:
freq_factor = 0.0 # Reference frequency range
else:
freq_factor = 1.0 # Lower freq = slightly better isolation
total_isolation = min_isolation + additional + freq_factor
# Physical limits: isolation can't exceed ~60 dB in practical systems
# and can't be negative
return max(0.0, min(total_isolation, 60.0))
def calculate_harmonic_isolation_adjustment(
fundamental_freq_mhz: float,
harmonic_order: int,
antenna_type: str = "default"
) -> float:
"""
Calculate isolation adjustment for harmonic frequencies.
CORRECTED: Previous model assumed isolation IMPROVES at harmonics (wrong).
Reality: Antenna patterns at harmonics are unpredictable and often WORSE.
Physical basis:
- Antenna gain pattern changes dramatically at harmonic frequencies
- Multi-mode operation can increase coupling at some harmonics
- Free-space path loss helps at very high frequencies (>6 GHz)
Args:
fundamental_freq_mhz: Fundamental frequency in MHz
harmonic_order: 2, 3, 4, or 5
antenna_type: "patch", "dipole", "helical", or "default"
Returns:
Isolation adjustment in dB (negative = worse isolation)
"""
harmonic_freq = fundamental_freq_mhz * harmonic_order
# Antenna-specific harmonic isolation behavior
# Based on antenna radiation pattern changes at harmonics
adjustments = {
"patch": {
2: -2.0, # Patch 2H: higher-order mode, often worse
3: -4.0, # Patch 3H: significant pattern distortion
4: -3.0, # Patch 4H: mixed behavior
5: -5.0 # Patch 5H: complex multi-mode
},
"dipole": {
2: +2.0, # Dipole 2H: full-wave mode, can be better
3: -2.0, # Dipole 3H: 3/2 wavelength, variable
4: +1.0, # Dipole 4H: 2-wavelength, can be better
5: -3.0 # Dipole 5H: complex pattern
},
"helical": {
2: -1.0, # Helical 2H: frequency-dependent
3: -2.0, # Helical 3H: pattern degradation
4: -3.0, # Helical 4H: significant change
5: -4.0 # Helical 5H: complex
},
"default": {
2: -1.0, # Conservative default: slight degradation
3: -2.0, # Default: moderate degradation
4: -2.0, # Default: moderate degradation
5: -3.0 # Default: worse at higher harmonics
}
}
ant_adj = adjustments.get(antenna_type, adjustments["default"])
base_adjustment = ant_adj.get(harmonic_order, -2.0)
# High frequency harmonics (>6 GHz) benefit from free-space path loss
if harmonic_freq > 6000:
base_adjustment += 4.0 # Significant FSPL benefit
elif harmonic_freq > 4000:
base_adjustment += 2.0 # Moderate FSPL benefit
return base_adjustment
def calculate_rx_filter_rejection(
interference_freq_mhz: float,
rx_center_freq_mhz: float,
rx_bandwidth_mhz: float,
filter_order: int = 5,
filter_type: str = "butterworth"
) -> float:
"""
Calculate receiver filter attenuation based on frequency offset.
Uses standard filter response curves:
- In-band (within 0.5×BW): 0 dB rejection
- Transition band (0.5-2×BW): Gradual rolloff
- Stop band (>2×BW): Full rejection per filter type
Butterworth: 20×n dB/decade (where n = filter order)
Chebyshev: ~24×n dB/decade (steeper transition)
SAW: Sharp transition, moderate ultimate rejection
BAW: Similar to SAW with slightly better rejection
Args:
interference_freq_mhz: Interference frequency in MHz
rx_center_freq_mhz: Receiver center frequency in MHz
rx_bandwidth_mhz: Receiver 3dB bandwidth in MHz
filter_order: Filter order (typical: 3-7 for practical filters)
filter_type: "butterworth", "chebyshev", "saw", or "baw"
Returns:
Filter rejection in dB (positive value = attenuation)
"""
# Guard against invalid inputs that could cause math errors
if rx_bandwidth_mhz <= 0 or interference_freq_mhz <= 0 or rx_center_freq_mhz <= 0:
return 0.0
freq_offset = abs(interference_freq_mhz - rx_center_freq_mhz)
corner_freq = rx_bandwidth_mhz / 2.0
# In-band: no rejection
if freq_offset <= corner_freq:
return 0.0
# Normalized frequency offset (relative to corner frequency)
normalized_offset = freq_offset / corner_freq
# Filter-specific response characteristics
if filter_type == "chebyshev":
# Chebyshev: steeper transition, ripple in passband
if normalized_offset <= 2.0:
# Transition band - faster rolloff than Butterworth
rolloff_rate = filter_order * 24.0 # dB/decade
rejection = rolloff_rate * math.log10(normalized_offset) * 0.7
else:
# Stop band
rejection = filter_order * 24.0 * math.log10(normalized_offset)
max_rejection = FILTER_MAX_REJECTION['chebyshev']
elif filter_type == "saw":
# SAW filter: sharp transition, moderate rejection
if normalized_offset <= 1.5:
# Sharp transition band
rejection = filter_order * 15.0 * (normalized_offset - 1.0)
else:
# Stop band
rejection = filter_order * 8.0 + 20.0 * math.log10(normalized_offset / 1.5)
max_rejection = FILTER_MAX_REJECTION['saw']
elif filter_type == "baw":
# BAW filter: similar to SAW, slightly better
if normalized_offset <= 1.5:
rejection = filter_order * 16.0 * (normalized_offset - 1.0)
else:
rejection = filter_order * 9.0 + 22.0 * math.log10(normalized_offset / 1.5)
max_rejection = FILTER_MAX_REJECTION['baw']
else: # butterworth (default)
# Butterworth: maximally flat, 20×n dB/decade rolloff
if normalized_offset <= 2.0:
# Transition band
rolloff_rate = filter_order * 20.0 # dB/decade
rejection = rolloff_rate * math.log10(normalized_offset) * 0.5
else:
# Stop band
rejection = filter_order * 20.0 * math.log10(normalized_offset)
max_rejection = FILTER_MAX_REJECTION['butterworth']
# Apply realistic limits
return min(max(rejection, 0.0), max_rejection)
def estimate_coupling_factor(
freq_mhz: float,
separation_mm: float = 20.0,
coupling_type: str = 'antenna'
) -> float:
"""
Estimate coupling factor based on frequency and physical separation.
Coupling increases when antenna/PCB dimensions are comparable to wavelength.
Args:
freq_mhz: Operating frequency in MHz
separation_mm: Physical separation between antennas in mm
coupling_type: 'antenna' (far-field), 'pcb_trace' (near-field), 'board_level' (substrate)
Returns:
Coupling factor (0.0-1.0)
"""
if freq_mhz <= 0 or separation_mm <= 0:
return 0.3 # Safe default
# Wavelength in mm
wavelength_mm = 300000.0 / freq_mhz
# Ratio of separation to wavelength (key coupling parameter)
sep_ratio = separation_mm / wavelength_mm
if coupling_type == 'pcb_trace':
# Near-field: strong coupling at all frequencies, decreases with separation
base_coupling = 0.7 * math.exp(-sep_ratio * 2.0)
elif coupling_type == 'board_level':
# Substrate coupling: moderate, frequency-dependent
base_coupling = 0.4 * math.exp(-sep_ratio * 1.5)
else: # 'antenna'
# Far-field: peaks when separation ~ wavelength/4 to wavelength
if sep_ratio < 0.25:
base_coupling = 0.8 # Very close: strong coupling
elif sep_ratio < 1.0:
base_coupling = 0.5 * (1.0 - sep_ratio) # Moderate
else:
base_coupling = 0.1 / sep_ratio # Falls off with distance
return max(0.01, min(1.0, base_coupling))
def calculate_reciprocal_mixing(
aggressor_power_dbm: float,
freq_offset_hz: float,
lo_phase_noise_dbc_hz: float = -100.0,
rx_bandwidth_hz: float = 20e6
) -> dict:
"""
Calculate reciprocal mixing noise contribution.
When a strong signal is near the desired frequency, the LO's phase noise
skirts spread the interferer's energy across the receiver's IF bandwidth.
Critical for GNSS where cellular signals can be 100+ dB stronger.
Formula: P_rm = P_agg + L(f_offset) + 10*log10(B_rx)
where L(f_offset) is phase noise at the frequency offset in dBc/Hz
Args:
aggressor_power_dbm: Aggressor power at receiver input (dBm)
freq_offset_hz: Frequency offset between aggressor and victim (Hz)
lo_phase_noise_dbc_hz: LO phase noise at reference offset (dBc/Hz)
rx_bandwidth_hz: Receiver bandwidth (Hz)
Returns:
dict with reciprocal mixing analysis
"""
if freq_offset_hz <= 0 or rx_bandwidth_hz <= 0:
return {
'reciprocal_mixing_dbm': -200.0,
'phase_noise_at_offset_dbc_hz': lo_phase_noise_dbc_hz,
'is_significant': False,
'description': 'Invalid parameters',
}
# Phase noise profile: -20 dB/decade from reference
# Reference: -100 dBc/Hz at 100 kHz offset (typical)
ref_offset_hz = 100e3 # 100 kHz reference
# Phase noise at actual offset (simplified -20 dB/decade model)
if freq_offset_hz < 1e3: # Very close: flat region
phase_noise_at_offset = lo_phase_noise_dbc_hz + 20.0 # Close-in is worse
elif freq_offset_hz < ref_offset_hz:
# -20 dB/decade slope toward reference
phase_noise_at_offset = lo_phase_noise_dbc_hz + 20.0 * math.log10(ref_offset_hz / freq_offset_hz)
else:
# -20 dB/decade slope beyond reference
phase_noise_at_offset = lo_phase_noise_dbc_hz - 20.0 * math.log10(freq_offset_hz / ref_offset_hz)
# Reciprocal mixing power
rm_power_dbm = aggressor_power_dbm + phase_noise_at_offset + 10 * math.log10(rx_bandwidth_hz)
# Is it significant? Compare to typical GNSS noise floor (~-174 + 30 = -144 dBm in 1 MHz)
is_significant = rm_power_dbm > -140.0
# Determine if reciprocal mixing dominates
description = f'RM: {rm_power_dbm:.1f} dBm (PN={phase_noise_at_offset:.0f} dBc/Hz at {freq_offset_hz/1e6:.1f} MHz offset)'
return {
'reciprocal_mixing_dbm': rm_power_dbm,
'phase_noise_at_offset_dbc_hz': phase_noise_at_offset,
'freq_offset_hz': freq_offset_hz,
'rx_bandwidth_hz': rx_bandwidth_hz,
'is_significant': is_significant,
'description': description,
}
def apply_duty_cycle_correction(
desensitization_db_continuous: float,
aggressor_duty_cycle: float,
victim_integration_time_ms: float = 10.0
) -> float:
"""
Reduce effective desensitization for intermittent interference.
For non-continuous (pulsed/TDM) interference, the time-averaged impact
is reduced compared to continuous interference.
Formula: Desens_avg = Desens_cont + 10×log₁₀(duty_cycle)
This applies when:
- Aggressor is intermittent (TDD, hopping, CSMA/CA)
- Victim has integration time longer than pulse period
Physical basis:
- Power averaging: Time-averaged interference power is reduced
- Receiver AGC: May not respond to short pulses
- Error correction: Can recover from burst errors
Args:
desensitization_db_continuous: Desensitization for continuous interference (dB)
aggressor_duty_cycle: Fraction of time aggressor is transmitting (0.0-1.0)
victim_integration_time_ms: Victim receiver integration time (ms)
Returns:
Adjusted desensitization in dB
"""
# Continuous interference (duty cycle ≥ 95%)
if aggressor_duty_cycle >= 0.95:
return desensitization_db_continuous
# Very low duty cycle (≤ 1%) - nearly negligible
if aggressor_duty_cycle <= 0.01:
return 0.0
# Clamp duty cycle to valid range
duty_cycle = max(0.01, min(0.99, aggressor_duty_cycle))
# Time-averaging reduction: 10×log₁₀(duty_cycle)
# Example: 50% duty cycle = -3 dB, 10% duty cycle = -10 dB
duty_cycle_reduction_db = 10 * math.log10(duty_cycle)
# Apply the reduction
adjusted_desensitization = desensitization_db_continuous + duty_cycle_reduction_db
# Minimum desensitization: even brief interference has some effect
# Use 10% of continuous desensitization as floor
min_desensitization = desensitization_db_continuous * 0.1
return max(adjusted_desensitization, min_desensitization, 0.0)
def get_technology_duty_cycle(band_code: str, system_params: SystemParameters) -> float:
"""
Get duty cycle for a specific technology/band.
Args:
band_code: Band code (e.g., 'LTE_B1', 'WiFi_2G', 'BLE')
system_params: System parameters with duty cycle values
Returns:
Duty cycle as fraction (0.0-1.0)
"""
band_upper = band_code.upper()
# TDD LTE bands (bidirectional on same frequency)
tdd_lte_bands = ['B38', 'B39', 'B40', 'B41', 'B42', 'B43', 'B44', 'B48']
tdd_nr_bands = ['N38', 'N41', 'N77', 'N78', 'N79']
if any(tdd in band_upper for tdd in tdd_lte_bands + tdd_nr_bands):
return system_params.lte_duty_cycle # TDD LTE/NR ~50%
elif 'LTE' in band_upper or 'NR_N' in band_upper or '5G' in band_upper:
return 1.0 # FDD LTE is continuous in its band
elif any(wifi in band_upper for wifi in ['WIFI', 'WI-FI', 'WLAN']):
return system_params.wifi_duty_cycle # WiFi CSMA/CA ~40%
elif 'BLE' in band_upper or 'BLUETOOTH' in band_upper:
return system_params.ble_duty_cycle # BLE hopping ~5%
elif 'HALOW' in band_upper:
return system_params.halow_duty_cycle # HaLow ~30%
elif any(gnss in band_upper for gnss in ['GNSS', 'GPS']):
return 1.0 # GNSS is receive-only, always on
elif any(ism in band_upper for ism in ['ISM', 'ZIGBEE', 'THREAD', 'MATTER']):
return 0.2 # Low-power IoT protocols ~20%
elif any(lora in band_upper for lora in ['LORA', 'SIGFOX']):
return 0.01 # LPWAN very low duty cycle ~1%
else:
return 0.5 # Conservative default
def calculate_imd_from_intercept(
p_in_dbm: float,
iip_n_dbm: float,
order: int,
p1db_dbm: Optional[float] = None
) -> float:
"""
Calculate IMD power using standard RF intercept point formulas.
CORRECTED: Uses proper two-tone IMD equations instead of empirical HD scaling.
Includes saturation clamp to prevent unphysical results when P_in >= IIP.
Standard RF formulas (two equal-power tones):
- IM2: P_IM2 = 2×P_in - IIP2 (beat products: f1±f2)
- IM3: P_IM3 = 3×P_in - 2×IIP3 (intermod: 2f1±f2, 2f2±f1)
- IM5: P_IM5 = 5×P_in - 4×IIP5 ≈ 5×P_in - 4×(IIP3+10)
- IM7: P_IM7 = 7×P_in - 6×IIP7 ≈ 7×P_in - 6×(IIP3+15)
Reference: IEEE microwave theory, 3GPP TS 36.104
Args:
p_in_dbm: Input power per tone in dBm
iip_n_dbm: Input intercept point for the relevant order (IIP2, IIP3, etc.) in dBm
order: IMD order (2, 3, 4, 5, 7)
p1db_dbm: Optional P1dB compression point for more precise saturation clamping
Returns:
IMD product power in dBm
"""
if order == 2:
# IM2: beat products (f1+f2, f1-f2)
# P_IM2 = 2×P_in - IIP2
p_imd = 2 * p_in_dbm - iip_n_dbm
elif order == 3:
# IM3: 2f1±f2, 2f2±f1 products (most important for close-in interference)
# P_IM3 = 3×P_in - 2×IIP3
p_imd = 3 * p_in_dbm - 2 * iip_n_dbm
elif order == 4:
# IM4: derived from IM2 mixing, typically 15-20 dB below IM2
im2_power = 2 * p_in_dbm - iip_n_dbm
p_imd = im2_power - 18.0 # IM4 typically 18 dB below IM2
elif order == 5:
# IM5: 3f1±2f2, 3f2±2f1 products
# P_IM5 = 5×P_in - 4×IIP5
# IIP5 is typically IIP3 + 10 dB
iip5_estimated = iip_n_dbm + 10.0
p_imd = 5 * p_in_dbm - 4 * iip5_estimated
elif order == 7:
# IM7: 4f1±3f2, 4f2±3f1 products
# P_IM7 = 7×P_in - 6×IIP7
# IIP7 is typically IIP3 + 15-20 dB
iip7_estimated = iip_n_dbm + 15.0
p_imd = 7 * p_in_dbm - 6 * iip7_estimated
else:
# Generic higher order approximation
iipn_estimated = iip_n_dbm + (order - 3) * 5.0
p_imd = order * p_in_dbm - (order - 1) * iipn_estimated
# Saturation clamp: IM products cannot exceed fundamental power in compression.
# Use P1dB if provided for precise clamping, otherwise P_in + offset (GH #24).
if p1db_dbm is not None:
saturation_limit = p1db_dbm + IMD_SATURATION_OFFSET_DB
else:
saturation_limit = p_in_dbm + IMD_SATURATION_OFFSET_DB
p_imd = min(p_imd, saturation_limit)
return p_imd
def calculate_system_harmonic_levels(tx_power_dbm: float, system_params: SystemParameters,
papr_db: float = 0.0) -> dict:
"""
Calculate all harmonic distortion levels from fundamental system parameters
This is the CORRECT RF engineering approach:
Input: TX power + System linearity characteristics (IIP3/IIP2)
Output: Calculated harmonic performance levels
GH #18: PAPR modulation model -- higher PAPR means the signal has larger
peaks which drive the PA harder and generate more harmonics. The PAPR
contribution is applied as an additive dBc correction: 30% of PAPR is added
to the harmonic levels (making them less negative / stronger).
Args:
tx_power_dbm: TX power level in dBm
system_params: System parameters including IIP3, IIP2, PA characteristics
papr_db: Peak-to-Average Power Ratio in dB (0 for constant-envelope signals)
Returns:
Dictionary with all calculated HD levels and metadata
"""
# Calculate fundamental harmonics from real RF linearity at average power
hd2_dbc = calculate_hd2_from_iip2(
tx_power_dbm,
system_params.iip2_dbm,
system_params.bias_point_optimized
)
hd3_dbc = calculate_hd3_from_iip3(
tx_power_dbm,
system_params.iip3_dbm,
system_params.pa_class
)
# Calculate higher order harmonics with compression effects
hd4_dbc, hd5_dbc = calculate_higher_order_harmonics(
hd2_dbc, hd3_dbc, tx_power_dbm, system_params.iip3_dbm
)
# GH #18: PAPR correction -- higher PAPR drives more harmonics
# 30% of PAPR contributes as an additive dBc worsening (less negative = stronger)
papr_correction = papr_db * 0.3
hd2_dbc += papr_correction
hd3_dbc += papr_correction
hd4_dbc += papr_correction
hd5_dbc += papr_correction
return {
'hd2_dbc': hd2_dbc,
'hd3_dbc': hd3_dbc,
'hd4_dbc': hd4_dbc,
'hd5_dbc': hd5_dbc,
'calculation_method': 'Calculated from IIP3/IIP2 + TX Power (polynomial coefficients)',
'tx_power_dbm': tx_power_dbm,
'papr_db': papr_db,
'papr_correction_db': papr_correction,
'iip3_dbm': system_params.iip3_dbm,
'iip2_dbm': system_params.iip2_dbm,
'pa_class': system_params.pa_class
}
def calculate_harmonic_level_quantitative(fundamental_power_dbm: float, harmonic_order: int,
system_params: SystemParameters, fundamental_freq_mhz: float = 1000.0,
papr_db: float = 0.0) -> Tuple[float, float, str, str]:
"""
Calculate harmonic interference level using polynomial analysis
Mathematical Foundation based on 5th-order polynomial:
V_0 = a_1*V + a_2*V^2 + a_3*V^3 + a_4*V^4 + a_5*V^5
From polynomial analysis table:
- 2H (HD2): ~-32.1 dBc (pure a_2*V^2 term)
- 3H (HD3): ~-60.4 dBc (pure a_3*V^3 term)
- 4H (HD4): ~-73.0 dBc (pure a_4*V^4 term, estimated)
- 5H (HD5): ~-84.0 dBc (pure a_5*V^5 term, estimated)
Includes frequency-dependent path loss: 20*log10(f_harm/f_fund)
GH #16: TX filter rejection is now computed from calculate_rx_filter_rejection
using the actual harmonic frequency, TX center frequency, and TX filter parameters.
GH #18: PAPR is passed through to calculate_system_harmonic_levels to model
modulation-dependent harmonic generation.
Args:
fundamental_power_dbm: Fundamental TX power in dBm
harmonic_order: 2, 3, 4, or 5
system_params: System parameters with isolation and nonlinearity
fundamental_freq_mhz: Actual fundamental frequency in MHz
papr_db: Peak-to-Average Power Ratio in dB (default 0.0)
Returns:
(harmonic_level_dbc, harmonic_at_victim_dbm, formula, coefficient_used)
"""
# Polynomial analysis results for pure harmonic terms
# Based on coefficients: a_2=0.0562, a_3=0.01, a_4=0.0018, a_5=0.001
polynomial_harmonics = {
2: {
'reference_dbc': -32.1, # HD2 from table: 2.5E-02 = -32.1 dB relative to signal
'formula': f"2H = a₂V²",
'coeff': 'a₂ = 0.0562'
},
3: {
'reference_dbc': -60.4, # HD3 from table: -9.4E-04 = -60.4 dB
'formula': f"3H = a₃V³",
'coeff': 'a₃ = 0.01'
},
4: {
'reference_dbc': -73.0, # HD4 estimated from table: -2.2E-04 = -73 dB
'formula': f"4H = a₄V⁴",
'coeff': 'a₄ = 0.0018'
},
5: {
'reference_dbc': -84.0, # HD5 estimated from table: 6.3E-05 = -84 dB
'formula': f"5H = a₅V⁵",
'coeff': 'a₅ = 0.001'
}
}
if harmonic_order not in polynomial_harmonics:
raise ValueError(f"Harmonic order {harmonic_order} not supported (2-5 only)")
poly_data = polynomial_harmonics[harmonic_order]
reference_dbc = poly_data['reference_dbc']
formula = poly_data['formula']
coeff = poly_data['coeff']
# Calculate harmonic levels from real system parameters (GH #18: with PAPR)
calculated_harmonics = calculate_system_harmonic_levels(
fundamental_power_dbm, system_params, papr_db=papr_db
)
# Use calculated harmonic level instead of fixed input values
harmonic_dbc_mapping = {
2: calculated_harmonics['hd2_dbc'],
3: calculated_harmonics['hd3_dbc'],
4: calculated_harmonics['hd4_dbc'],
5: calculated_harmonics['hd5_dbc']
}
# Get the calculated harmonic level for this order
harmonic_dbc = harmonic_dbc_mapping[harmonic_order]
# Step 1: Calculate harmonic power at TX output (before filtering)
harmonic_at_tx_dbm = fundamental_power_dbm + harmonic_dbc
# Step 2: Apply TX harmonic filtering
# GH #16: Use frequency-dependent TX filter model when fundamental frequency is known
harmonic_freq_mhz = fundamental_freq_mhz * harmonic_order
tx_bw_mhz = 20.0 # Typical LTE channel bandwidth
# Calculate TX filter rejection at the harmonic frequency using the filter model
tx_filter_rejection = calculate_rx_filter_rejection(
harmonic_freq_mhz, fundamental_freq_mhz, tx_bw_mhz * 2,
system_params.tx_filter_order, system_params.tx_filter_type
)
# Use the greater of: frequency-dependent model or the legacy static value
# This ensures the filter model never produces less rejection than the baseline
base_tx_filter_db = system_params.tx_harmonic_filtering_db
total_tx_filter_db = max(tx_filter_rejection, base_tx_filter_db)
harmonic_after_tx_filter_dbm = harmonic_at_tx_dbm - total_tx_filter_db
# Step 3: Calculate path loss with CORRECTED isolation model
# (harmonic_freq_mhz already calculated above for TX filter)
# CORRECTED: Use coupling-aware isolation model (not simple additive)
base_isolation_db = calculate_total_isolation(
system_params.antenna_isolation,
system_params.pcb_isolation,
system_params.shield_isolation,
harmonic_freq_mhz,
system_params.coupling_factor
)
# CORRECTED: Apply harmonic-specific isolation adjustment
# Previous model assumed isolation IMPROVES at harmonics (wrong direction)
harmonic_isolation_adj = calculate_harmonic_isolation_adjustment(
fundamental_freq_mhz, harmonic_order, "default"
)
total_isolation_db = max(0.0, base_isolation_db + harmonic_isolation_adj)
# Step 4: Calculate harmonic at victim input (before RX filtering)
harmonic_at_victim_input_dbm = harmonic_after_tx_filter_dbm - total_isolation_db
# Step 5: Apply RX out-of-band rejection (realistic values)
# Harmonics are typically far from victim RX passband but don't over-suppress
base_rx_rejection_db = system_params.out_of_band_rejection_db
# Moderate additional RX rejection for higher harmonics (realistic filter slope effect)
harmonic_rx_rejection = {
2: base_rx_rejection_db * 0.5, # Reduced rejection for 2H
3: base_rx_rejection_db * 0.7, # Some rejection for 3H
4: base_rx_rejection_db * 0.8, # More rejection for 4H
5: base_rx_rejection_db * 0.9 # Most rejection for 5H
}
total_rx_rejection_db = harmonic_rx_rejection.get(harmonic_order, base_rx_rejection_db * 0.5)
harmonic_at_victim_final_dbm = harmonic_at_victim_input_dbm - total_rx_rejection_db
# Step 6: Calculate final dBc relative to fundamental at victim
fundamental_at_victim_dbm = fundamental_power_dbm - base_isolation_db
final_harmonic_dbc = harmonic_at_victim_final_dbm - fundamental_at_victim_dbm
# Sanity check based on polynomial analysis and engineering limits (GH #24)
min_harmonic_dbc = HARMONIC_ENGINEERING_LIMITS.get(harmonic_order, -50.0)
if final_harmonic_dbc > min_harmonic_dbc:
final_harmonic_dbc = min_harmonic_dbc
harmonic_at_victim_final_dbm = fundamental_at_victim_dbm + final_harmonic_dbc
return (final_harmonic_dbc, harmonic_at_victim_final_dbm, formula, coeff)
def calculate_imd_level_quantitative(power1_dbm: float, power2_dbm: float,
imd_order: str, system_params: SystemParameters) -> Tuple[float, float, str, str]:
"""
Calculate intermodulation product level using detailed polynomial analysis
Mathematical Foundation based on 5th-order polynomial expansion:
V₀ = a₁V + a₂V² + a₃V³ + a₄V⁴ + a₅V⁵