-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclasse2
More file actions
executable file
·1860 lines (1508 loc) · 78.8 KB
/
classe2
File metadata and controls
executable file
·1860 lines (1508 loc) · 78.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
#!/usr/bin/python
import argparse
import bisect
import decimal
import itertools
import json
import commentjson
import math
import random
import re
import sys
import time
from bisect import bisect_left
from collections import OrderedDict
from datetime import datetime, timezone
from decimal import Decimal, getcontext
from functools import lru_cache
from itertools import combinations_with_replacement
from math import isclose
debug_enabled = False
def convert_h_to_nh(value):
return value * 1e9
def convert_mh_to_nh(value):
return value * 1e6
def convert_h_to_uh(inductance_h):
return inductance_h * 1e6
def convert_uh_to_h(inductance_uh):
return inductance_uh * 1e-6
def convert_nh_to_uh(inductance_nh):
return inductance_nh * 1e-3
def convert_uh_to_nh(inductance_uh):
return inductance_uh * 1e3
def convert_ma_to_a(value_ma):
return value_ma / 1000
# Inductance conversions
def convert_h_to_mh(value_h):
return value_h * 1000
def convert_h_to_uh(value_h):
return value_h * 1e6
def convert_h_to_nh(value_h):
return value_h * 1e9
def convert_mh_to_h(value_mh):
return value_mh / 1000
def convert_uh_to_h(value_uh):
return value_uh / 1e6
def convert_nh_to_h(value_nh):
return value_nh / 1e9
# Frequency conversions
def convert_hz_to_khz(value_hz):
return value_hz / 1000
def convert_hz_to_mhz(value_hz):
return value_hz / 1e6
def convert_hz_to_ghz(value_hz):
return value_hz / 1e9
def convert_khz_to_hz(value_khz):
return value_khz * 1000
def convert_mhz_to_hz(value_mhz):
return value_mhz * 1e6
def convert_ghz_to_hz(value_ghz):
return value_ghz * 1e9
# Resistance conversions
def convert_ohms_to_kohms(value_ohms):
return value_ohms / 1000
def convert_ohms_to_mohms(value_ohms):
return value_ohms / 1e6
def convert_kohms_to_ohms(value_kohms):
return value_kohms * 1000
def convert_mohms_to_ohms(value_mohms):
return value_mohms * 1e6
# Current conversions
def convert_a_to_ma(value_a):
return value_a * 1000
def convert_a_to_ua(value_a):
return value_a * 1e6
def convert_ma_to_a(value_ma):
return value_ma / 1000
def convert_ua_to_a(value_ua):
return value_ua / 1e6
# Voltage conversions
def convert_v_to_mv(value_v):
return value_v * 1000
def convert_v_to_uv(value_v):
return value_v * 1e6
def convert_mv_to_v(value_mv):
return value_mv / 1000
def convert_uv_to_v(value_uv):
return value_uv / 1e6
# Capacitance conversions
def convert_f_to_mf(value_f):
return value_f * 1000
def convert_f_to_uf(value_f):
return value_f * 1e6
def convert_f_to_nf(value_f):
return value_f * 1e9
def convert_f_to_pf(value_f):
return value_f * 1e12
def convert_mf_to_f(value_mf):
return value_mf / 1000
def convert_uf_to_f(value_uf):
return value_uf / 1e6
def convert_nf_to_f(value_nf):
return value_nf / 1e9
def convert_pf_to_f(value_pf):
return value_pf / 1e12
# Power conversions
def convert_w_to_mw(value_w):
return value_w * 1000
def convert_w_to_kw(value_w):
return value_w / 1000
def convert_mw_to_w(value_mw):
return value_mw / 1000
def convert_kw_to_w(value_kw):
return value_kw * 1000
# Updated formatting functions
def format_power_value(value_w):
if value_w >= 1000:
return f"{convert_w_to_kw(value_w):.2f}kW"
elif value_w >= 1:
return f"{value_w:.2f}W"
else:
return f"{convert_w_to_mw(value_w):.2f}mW"
def format_voltage_value(value_v):
if value_v >= 1000:
return f"{value_v / 1000:.2f}kV"
elif value_v >= 1:
return f"{value_v:.2f}V"
elif value_v >= 0.001:
return f"{convert_v_to_mv(value_v):.2f}mV"
else:
return f"{convert_v_to_uv(value_v):.2f}µV"
def format_capacitance_value(value_f):
if value_f >= 1:
return f"{value_f:.2f}F"
elif value_f >= 1e-3:
return f"{convert_f_to_mf(value_f):.2f}mF"
elif value_f >= 1e-6:
return f"{convert_f_to_uf(value_f):.2f}µF"
elif value_f >= 1e-9:
return f"{convert_f_to_nf(value_f):.2f}nF"
else:
return f"{convert_f_to_pf(value_f):.2f}pF"
class ClassETopologyGenerator:
def __init__(self):
self.pi = math.pi
def class_e_topology_generate_inverse(self, power, voltage, center_freq, bandwidth, mosfet_data, q_factor, L1=None):
omega = 2 * math.pi * center_freq
L1_min = 0.1 * voltage**2 / (omega * power)
if L1 is None:
L1 = L1_min
L1_status = "calculated"
else:
L1_status = "user-specified"
L1 = parse_inductance(L1)
if L1 < L1_min:
print(f"Warning: User-specified L1 ({L1:.2e}H) is less than the calculated minimum ({L1_min:.2e}H)")
if L1 < L1_min:
raise ValueError(f"L1 is too small. Minimum value: {L1_min:.3e} H")
R = 0.5768 * voltage**2 / power
C2 = 0.1836 / (omega * R)
C1 = 1 / (omega**2 * L1) - C2
L2 = R / (omega * 1.1525)
if q_factor is None:
q_factor = math.sqrt(L1 / C1) / R
duty_cycle = 0.5
efficiency = 0.9 # Theoretical maximum for Class E
return { 'L1': L1, 'C1': C1, 'R': R, 'C2': C2, 'L2': L2, 'Q': q_factor, 'duty_cycle': duty_cycle, 'efficiency': efficiency, "L1_status": L1_status, "L1_min": L1_min }
def class_e_topology_generate_infinite(self, output_power_watts, pa_voltage_volts, center_frequency_hz, bandwidth_hz, mosfet_data, Q, L1=None):
w0 = 2 * math.pi * center_frequency_hz
Vo = 0 # Assume 0V for MOSFETs
Coss = mosfet_data['coss_pf'] * 1e-12
R = 0.576801 * ((pa_voltage_volts - Vo)**2 / output_power_watts) * (1.0000086 - (0.414396 / Q) - (0.577501 / (Q**2)) + (0.205967 / (Q**3)))
L1_min = ((math.pi**2 + 4) * R) / w0
if L1 is None:
L1 = ((math.pi**2 + 4) * R) / w0 # Minimum value for L1
L1_status = "calculated"
else:
L1_status = "user-specified"
L1 = parse_inductance(L1)
if L1 < L1_min:
print(f"Warning: User-specified L1 ({L1:.2e}H) is less than the calculated minimum ({L1_min:.2e}H)")
# C1 calculation uses Raab's 2001 formula
C1 = (1 / (34.2219 * center_frequency_hz * R)) * (0.99866 + (0.91424 / Q) - (1.03175 / (Q**2))) + (0.6 / ((2 * math.pi * center_frequency_hz)**2 * L1))
L2 = (Q * R) / w0
C2 = (1 / (w0 * R)) * (1 / (Q - 0.104823)) * (1.00121 + 1.01468 / (Q - 1.7879))
return { "L1": L1, "L2": L2, "C1": C1, "C2": C2, "R": R, "L1_status": L1_status, "L1_min": L1_min }
def class_e_topology_generate_finite(self, output_power_watts, pa_voltage_volts, center_frequency_hz, bandwidth_hz, mosfet_data, Q, L1=None):
w0 = 2 * self.pi * center_frequency_hz
Vo = 0 # Assume 0V for MOSFETs
Coss = mosfet_data['coss_pf'] * 1e-12
R = 0.576801 * ((pa_voltage_volts - Vo)**2 / output_power_watts) * (1.0000086 - (0.414396 / Q) - (0.577501 / (Q**2)) + (0.205967 / (Q**3)))
C1 = (1 / (34.2219 * center_frequency_hz * R)) * (0.99866 + (0.91424 / Q) - (1.03175 / (Q**2))) - Coss
L2 = (1.15 * R) / w0
C2 = (1 / (w0 * R)) * (1 / (Q - 0.104823)) * (1.00121 + 1.01468 / (Q - 1.7879))
if L1 is None:
L1 = (0.1836 * R) / w0
L1_status = "calculated"
else:
L1_optimal = (0.1836 * R) / w0
L1_status = "user-specified"
if abs(L1 - L1_optimal) / L1_optimal > 0.1: # If L1 differs by more than 10% from optimal
print(f"Warning: User-specified L1 ({L1:.2e}H) differs significantly from the calculated optimal value ({L1_optimal:.2e}H)")
return { "L1": L1, "L2": L2, "C1": C1, "C2": C2, "R": R, "L1_status": L1_status }
def calculate_operating_parameters(self, pa_voltage_volts, center_frequency_hz, Q, R):
peak_vds = pa_voltage_volts * 3.56 / 0.8
bandwidth = center_frequency_hz / Q
# Estimate harmonics (simplified model)
# These are rough estimates and may not be accurate for all designs
second_harmonic = -20 * math.log10(Q) # dB below fundamental
third_harmonic = -30 * math.log10(Q) # dB below fundamental
# Calculate drain efficiency (simplified estimate)
# This is a theoretical maximum, actual efficiency will be lower
drain_efficiency = 100 * (math.pi**2 / 4 + 1) / (math.pi**2 / 2 + 2) # in percentage
# Calculate maximum drain current (simplified estimate)
max_drain_current = (2 * math.pi * pa_voltage_volts) / (math.pi**2 * R)
return { "peak_vds": peak_vds, "bandwidth": bandwidth, "second_harmonic": second_harmonic, "third_harmonic": third_harmonic, "drain_efficiency": drain_efficiency, "max_drain_current": max_drain_current }
from itertools import combinations_with_replacement
def get_utc_date():
# Get the current UTC time
utc_now = datetime.now(timezone.utc)
# Format the date string
# This format closely mimics the output of the 'date' command
return utc_now.strftime("%a %b %d %H:%M:%S UTC %Y")
def convert_mhz_to_hz(frequency_mhz):
return frequency_mhz * 1e6
def convert_f_to_pf(value_f):
return value_f * 1e12
def convert_pf_to_f(value_pf):
return value_pf * 1e-12
def convert_h_to_uh(value_h):
return value_h * 1e6
def convert_uh_to_h(value_uh):
return value_uh * 1e-6
def debug_print(*args, **kwargs):
if debug_enabled:
print("DEBUG: ", *args, file=sys.stderr, **kwargs)
def load_components(filename='components.json'):
with open(filename, 'r') as f:
return json.load(f)
COMPONENTS = load_components()
def format_frequency_range(min_frequency_mhz, max_frequency_mhz):
if min_frequency_mhz >= 1000:
return f"{format_number_for_clarity(min_frequency_mhz/1000,True)}-{format_number_for_clarity(max_frequency_mhz/1000,True)}GHz"
elif max_frequency_mhz >= 1000:
return f"{format_number_for_clarity(min_frequency_mhz,True)}MHz-{format_number_for_clarity(max_frequency_mhz/1000,True)}GHz"
else:
return f"{format_number_for_clarity(min_frequency_mhz,True)}-{format_number_for_clarity(max_frequency_mhz,True)}MHz"
def get_max_frequency(bands):
return max(FREQUENCY_BANDS[band]['end'] for band in bands)
def format_band_with_range(band):
band_data = FREQUENCY_BANDS[band]
formatted_range = format_frequency_range(band_data['start'], band_data['end'])
return f"{band} ({formatted_range})"
def convert_to_uh(value_str):
if value_str.endswith('nH'):
return round(float(value_str[:-2]) / 1000, 3) # Convert nH to µH and round to 3 decimal places
elif value_str.endswith('µH'):
return round(float(value_str[:-2]), 3) # Round to 3 decimal places
else:
return round(float(value_str), 3) # Assume it's already in µH and round
def load_inductor_data():
debug_print("Loading inductor data...")
with open('inductors.json', 'r') as f:
return commentjson.load(f)
def preprocess_inductors(inductors_data):
preprocessed_data = []
error_count = 0
total_count = 0
for manufacturer, models in inductors_data.items():
for model, data in models.items():
total_count += 1
try:
inductance_uh = convert_to_uh(data['inductance'])
# Check for valid inductance
if inductance_uh <= 0:
raise ValueError(f"Invalid inductance value: {data['inductance']}")
# Check for valid DCR (DC Resistance)
dcr = data.get('dcr', None)
if dcr is not None:
if not isinstance(dcr, (int, float)) or dcr < 0:
raise ValueError(f"Invalid DCR value: {dcr}")
# Check for valid IDC (DC Current)
idc = data.get('idc', None)
if idc is not None:
if not isinstance(idc, (int, float)) or idc <= 0 or idc == float('inf'):
raise ValueError(f"Invalid IDC value: {idc}")
# Check for valid SRF (Self-Resonant Frequency)
srf = data.get('srf', None)
if srf is not None:
if not isinstance(srf, (int, float)) or srf <= 0:
raise ValueError(f"Invalid SRF value: {srf}")
preprocessed_data.append((model, inductance_uh))
except KeyError as e:
print(f"Error: Missing required data for {manufacturer} {model}: {str(e)}")
error_count += 1
except ValueError as e:
print(f"Error: Invalid data for {manufacturer} {model}: {str(e)}")
error_count += 1
except Exception as e:
print(f"Unexpected error processing {manufacturer} {model}: {str(e)}")
error_count += 1
debug_print(f"preprocess_inductors() complete - {len(preprocessed_data)} valid entries, {error_count} errors out of {total_count} total entries.")
return preprocessed_data
def prune_inductors_by_srf_for_target_frequency_bands(inductors_h, frequency_bands, bands):
max_freq = max(band['end'] for band_name, band in frequency_bands.items() if band_name in bands)
srf_factor = 2 # This factor determines how much higher the SRF should be compared to max_freq
pruned = [ind for ind in inductors_h if estimate_srf_optimistic(ind) > max_freq * srf_factor]
debug_print(f"prune_inductors_by_srf_for_target_frequency_bands() for bands {bands} means maximum frequency {max_freq}MHz")
debug_print(f"prune_inductors_by_srf_for_target_frequency_bands() reduced available inductors from {len(inductors_h)} to {len(pruned)}")
return pruned
INDUCTORS = load_inductor_data()
PREPROCESSED_INDUCTORS = preprocess_inductors(INDUCTORS)
def load_inductor_srf_range_data():
data = INDUCTORS
inductor_srf_ranges = {}
for manufacturer, inductors in data.items():
for part_number, inductor in inductors.items():
if isinstance(inductor, dict) and 'inductance' in inductor and 'srf_mhz' in inductor:
inductance_str = inductor['inductance']
debug_print(f"Inductance was {inductance_str}")
if inductance_str.endswith('nH'):
inductance = convert_nh_to_uh(float(inductance_str[:-2])) # Convert nH to µH
elif inductance_str.endswith('µH'):
inductance = float(inductance_str[:-2])
else:
print(f"WARNING: Unknown unit or unitless inductance string value '{inductance_str}'!")
inductance = float(inductance_str)
debug_print(f"Inductance is now {inductance}")
srf = float(inductor['srf_mhz'])
if inductance not in inductor_srf_ranges:
inductor_srf_ranges[inductance] = [srf, srf] # [min, max]
else:
inductor_srf_ranges[inductance][0] = min(inductor_srf_ranges[inductance][0], srf)
inductor_srf_ranges[inductance][1] = max(inductor_srf_ranges[inductance][1], srf)
debug_print("Loaded SRF ranges:")
for inductance, srf_range in sorted(inductor_srf_ranges.items()):
debug_print(f" {inductance}µH: {srf_range[0]}-{srf_range[1]}MHz")
return inductor_srf_ranges
INDUCTOR_SRF_RANGES = load_inductor_srf_range_data()
def get_srf_range(inductance_h):
inductance_uh = convert_h_to_uh(inductance_h)
keys = sorted(INDUCTOR_SRF_RANGES.keys())
idx = bisect.bisect_left(keys, inductance_uh)
if idx == 0:
return INDUCTOR_SRF_RANGES[keys[0]]
elif idx == len(keys):
return INDUCTOR_SRF_RANGES[keys[-1]]
else:
lower_key = keys[idx-1]
upper_key = keys[idx]
lower_range = INDUCTOR_SRF_RANGES[lower_key]
upper_range = INDUCTOR_SRF_RANGES[upper_key]
# Interpolate
factor = (inductance_uh - lower_key) / (upper_key - lower_key)
min_srf = lower_range[0] + (upper_range[0] - lower_range[0]) * factor
max_srf = lower_range[1] + (upper_range[1] - lower_range[1]) * factor
return (min_srf, max_srf)
def estimate_srf_optimistic(inductance_h):
return get_srf_range(inductance_h)[1]
def estimate_srf_pessimistic(inductance_h):
return get_srf_range(inductance_h)[0]
def calculate_inductor_configuration_srf_safety_factor(inductance):
if inductance < 1e-8: # Less than 10nH
return 2.5
elif inductance < 1e-7: # Less than 100nH
return 2.0
elif inductance < 1e-6: # Less than 1µH
return 1.5
else:
return 1.2
def parallel_combination(v1, v2):
return (v1 * v2) / (v1 + v2)
def series_combination(*values):
return sum(values)
def generate_inductor_configurations(target_value_h, inductors_h, frequency_bands, max_components=3, max_configurations=15, bands=None, min_current_ma=None, min_accuracy='0.85'):
configurations = []
# first reduce to inductors with viable SRF
pruned_inductors = prune_inductors_by_srf_for_target_frequency_bands(inductors_h, frequency_bands, bands)
# now sort the result
sorted_inductors_h = sorted(set(pruned_inductors))
# figure out the maximum operating frequency
max_freq_mhz = max(band['end'] for band_name, band in frequency_bands.items() if band_name in bands)
# Convert min_accuracy to float
min_accuracy = float(min_accuracy)
debug_print(f"Target inductance: {convert_h_to_uh(target_value_h):.2f}µH")
debug_print(f"Max frequency: {max_freq_mhz}MHz")
debug_print(f"Min current: {min_current_ma if min_current_ma else 'None'}mA")
debug_print(f"Min accuracy: {min_accuracy:.2%}")
debug_print(f"Available inductors: {[format_inductance_value(ind) for ind in sorted_inductors_h]}")
def calculate_total_inductance(config):
return sum(config)
def evaluate_configuration(config):
total_value_h = calculate_total_inductance(config)
accuracy = 1 - abs(total_value_h - target_value_h) / target_value_h
if accuracy >= min_accuracy:
try:
srf_mhz = min(estimate_srf_optimistic(ind) for ind in config)
dcr_ohm = sum(get_inductor_properties(ind)[1] for ind in config)
idc_ma = min(get_inductor_properties(ind)[2] for ind in config)
debug_print(f"Config: {[format_inductance_value(ind) for ind in config]}, Value: {convert_h_to_uh(total_value_h):.2f}µH, Accuracy: {accuracy*100:.2f}%, SRF: {srf_mhz}MHz, DCR: {dcr_ohm:.2f}Ω, IDC: {idc_ma:.0f}mA")
if srf_mhz >= max_freq_mhz * 3 and (min_current_ma is None or idc_ma >= min_current_ma):
debug_print(f"idc_ma {idc_ma} >= min_current_ma {min_current_ma} ... Configuration added!")
configurations.append((config, total_value_h, srf_mhz, dcr_ohm, idc_ma, accuracy))
return True
else:
debug_print(f"Configuration rejected: SRF requirement: {srf_mhz >= max_freq_mhz * 3}, Current requirement: {idc_ma >= min_current_ma if min_current_ma else True}")
except ValueError:
debug_print(f"Configuration rejected: Invalid inductor value in {[format_inductance_value(ind) for ind in config]}")
return False
for num_parts in range(1, max_components + 1):
debug_print(f"Generating configurations with {num_parts} parts")
for config in combinations_with_replacement(sorted_inductors_h, num_parts):
evaluate_configuration(config)
debug_print(f"Configurations found after {num_parts} parts: {len(configurations)}")
if len(configurations) >= max_configurations:
debug_print(f"Max configurations ({max_configurations}) reached or exceeded. Stopping search.")
break
debug_print(f"Total configurations found: {len(configurations)}")
# Sort configurations
configurations.sort(key=lambda x: (
len(x[0]), # Total part count
len(set(x[0])), # Unique part count
-x[5] # Negative accuracy (for descending order)
))
return [(config, value, srf, dcr, idc) for config, value, srf, dcr, idc, _ in configurations[:max_configurations]]
def calculate_total_inductance(variant):
return 1 / sum(1 / sum(branch) for branch in variant)
for num_parts in range(1, max_components + 1):
series_configs = generate_multi_part_configs(target_value_h, sorted_inductors_h, num_parts)
for config in series_configs:
for variant in generate_parallel_variants(config):
try:
total_value = calculate_total_inductance(variant)
accuracy = 1 - abs(total_value - target_value_h) / target_value_h
if accuracy >= min_accuracy:
srf = min(estimate_srf_optimistic(ind) for branch in variant for ind in branch)
if srf > max_freq * 3:
dcr = 1 / sum(1 / sum(get_inductor_properties(ind)[1] for ind in branch) for branch in variant)
idc = sum(min(get_inductor_properties(ind)[2] for ind in branch) for branch in variant)
if min_current is None or idc >= min_current * 1000:
configurations.append((variant, total_value, srf))
except ValueError as e:
print(f"Warning: Skipping configuration due to error: {e}")
continue
configurations.sort(key=lambda x: (
-abs(x[1] - target_value_h) / target_value_h, # Negative accuracy (for descending order)
sum(len(branch) for branch in x[0]), # Total part count
len(set(ind for branch in x[0] for ind in branch)), # Unique part count
-x[2] # Negative SRF (for descending order)
))
return configurations[:max_configurations]
def generate_parallel_variants(config):
variants = []
for n in range(2, min(len(config) + 1, 5)): # Consider up to 4 parallel strings
if len(config) % n == 0:
variant = [config[i:i+len(config)//n] for i in range(0, len(config), len(config)//n)]
if len(variant) >= 2: # Only include true parallel configurations
variants.append(variant)
return variants
def find_precise_match(target_value, inductors):
target_float = parse_inductance(target_value)
return next((ind for ind in inductors if abs(ind - target_float) < 1e-9), None)
def generate_multi_part_configs(target_value_h, inductors_h, num_parts, tolerance=0.05):
configs = []
min_inductor_value = (target_value_h / num_parts) * 0.1 # 10% of average part value
for combo in combinations_with_replacement(inductors_h, num_parts):
if combo[0] < min_inductor_value:
continue
total = sum(combo)
accuracy = 1 - abs(total - target_value_h) / target_value_h
if accuracy >= (1 - tolerance):
configs.append(list(combo))
if len(configs) >= 1000:
break
return configs
def count_unique_parts(config):
return len(set(config))
def is_valid_configuration(config_h, frequency_bands, bands):
debug_print(f"Checking validity of configuration: {config_h}")
srf_mhz = calculate_inductor_configuration_srf(config_h)
debug_print(f"Calculated SRF: {srf_mhz} MHz")
max_freq = max(frequency_bands[band]['end'] for band in bands)
debug_print(f"Maximum frequency for selected bands: {max_freq} MHz")
if srf_mhz < max_freq * 3:
debug_print(f"Configuration rejected: SRF {srf_mhz} MHz is less than 3 times max frequency {max_freq} MHz")
return False
debug_print(f"Configuration accepted: SRF {srf_mhz} MHz is at least 3 times max frequency {max_freq} MHz")
return True
def calculate_inductor_configuration_srf(config):
# This function needs to be implemented based on your specific requirements
# For now, we'll use a placeholder implementation
return min(get_inductor_properties(ind)[0] for ind in config)
def get_inductor_properties(inductance, tolerance=1e-06):
closest_match = None
min_difference = float('inf')
for manufacturer, models in INDUCTORS.items():
for model, data in models.items():
current_inductance = parse_inductance(data['inductance'])
difference = abs(current_inductance - inductance)
if difference < min_difference:
min_difference = difference
closest_match = data
if closest_match and min_difference <= tolerance:
return closest_match['srf_mhz'], closest_match['dcr_ohms'], closest_match['idc_ma']
else:
raise ValueError(f"No matching inductor found for inductance {inductance}µH within tolerance {tolerance}")
def generate_combinations(target_values, tolerance=0.1, max_configs=3):
def generate_for_single(target, component_type):
configurations = []
for value in COMPONENTS['inductors_uh' if component_type.startswith('L') else 'capacitors_pf']:
std_value = value * (1e-6 if component_type.startswith('L') else 1e-12)
error = abs(std_value - target) / target
if error <= tolerance:
configurations.append((error, (std_value,), 1, 1))
return sorted(configurations, key=lambda x: x[0])[:max_configs]
all_configs = [generate_for_single(target, component_type)
for component_type, target in target_values.items()]
return list(itertools.product(*all_configs))[:max_configs]
def format_configuration(config, component_type):
error, parts, esr_factor, current_factor = config
if component_type == 'L':
formatted_value = format_inductance_value(sum(parts) * 1e-6)
parts_str = ' + '.join(format_inductance_value(p * 1e-6) for p in parts)
else: # component_type == 'C'
formatted_value = format_capacitance_value(sum(parts) * 1e-12)
parts_str = ' + '.join(format_capacitance_value(p * 1e-12) for p in parts)
# Determine ESR description
if esr_factor == 1:
esr_desc = "ESR=standard"
elif esr_factor < 1:
esr_desc = "ESR=reduced"
else:
esr_desc = f"ESR=sum"
# Determine current handling description
if current_factor == 1:
current_desc = "I=normal"
elif current_factor == 0.5:
current_desc = "I=half"
elif current_factor < 1:
current_desc = f"I=smallest"
else:
current_desc = f"I={current_factor:.2f}x(?)"
return f"({error:.2f}% error) {formatted_value} ({parts_str}) [{esr_desc}] [{current_desc}]"
def evaluate_configuration(L2, C1, C2, target_L2, target_C1, target_C2, center_freq):
L2_error = abs(L2 - target_L2) / target_L2
C1_error = abs(C1 - target_C1) / target_C1
C2_error = abs(C2 - target_C2) / target_C2
total_error = L2_error + C1_error + C2_error
L2_srf = estimate_srf_optimistic(L2)
srf_margin = L2_srf / center_freq
return total_error, srf_margin
def find_closest_standard_value(target_value, standard_values):
return min(standard_values, key=lambda x: abs(x - target_value))
def generate_matching_network_configs(matching_network, matching_network_type, standard_capacitors, standard_inductors, center_freq):
debug_print(f"generate_matching_network_configs input:")
debug_print(f" matching_network = {matching_network}")
debug_print(f" matching_network_type = {matching_network_type}")
debug_print(f" standard_capacitors = {standard_capacitors[:5]}... (first 5 elements)")
debug_print(f" standard_inductors = {standard_inductors[:5]}... (first 5 elements)")
debug_print(f" center_freq = {center_freq}")
configs = []
component_values = dict(matching_network)
# Precise configuration
precise_config = {}
for component, value in component_values.items():
if component.startswith('C'):
std_values = standard_capacitors
value_converted = convert_f_to_pf(value)
else:
std_values = standard_inductors
value_converted = convert_h_to_uh(value)
debug_print(f"Converting {component}: {value} to {value_converted} {'pF' if component.startswith('C') else 'µH'}")
combination, error, comb_type = find_best_component_combination(value_converted, std_values)
precise_config[component] = (combination, error, comb_type)
debug_print(f"Precise {component}: ideal={value_converted:.6f}, actual={sum(combination):.6f}, error={error:.6f}%")
precise_config['type'] = 'precise'
precise_config['error'] = max(v[1] for v in precise_config.values() if isinstance(v, tuple))
debug_print(f"Precise configuration total error: {precise_config['error']:.6f}%")
configs.append(precise_config)
# Approximate configurations
for component in component_values.keys():
approx_config = {}
for comp, val in component_values.items():
if comp.startswith('C'):
std_values = standard_capacitors
val_converted = convert_f_to_pf(val)
else:
std_values = standard_inductors
val_converted = convert_h_to_uh(val)
if comp == component:
# For the current component, find a simpler combination
combination, error, comb_type = find_best_component_combination(val_converted, std_values, max_components=2)
else:
# For other components, use the closest standard value
closest = min(std_values, key=lambda x: abs(x - val_converted))
combination, error, comb_type = (closest,), calculate_error_percentage(val_converted, closest), 'single'
approx_config[comp] = (combination, error, comb_type)
debug_print(f"Approx {comp}: ideal={val_converted:.6f}, actual={sum(combination):.6f}, error={error:.6f}%")
approx_config['type'] = f'approximate_{component}'
approx_config['error'] = max(v[1] for v in approx_config.values() if isinstance(v, tuple))
debug_print(f"Approximate configuration ({component}) total error: {approx_config['error']:.6f}%")
configs.append(approx_config)
# Sort configurations by error and return top 3
sorted_configs = sorted(configs, key=lambda x: x['error'])[:3]
for i, config in enumerate(sorted_configs):
debug_print(f"Configuration {i+1} type: {config['type']}, error: {config['error']:.6f}%")
for comp, value in config.items():
if comp != 'type' and comp != 'error':
if isinstance(value, tuple) and len(value) == 3:
combination, error, comb_type = value
debug_print(f" {comp}: {combination}, error: {error:.6f}%, type: {comb_type}")
else:
debug_print(f" {comp}: {value} (unexpected format)")
return sorted_configs
def find_next_best_standard_value(target_value, standard_values, closest_value):
sorted_values = sorted(standard_values, key=lambda x: abs(x - target_value))
return sorted_values[sorted_values.index(closest_value) + 1]
def find_best_component_combination(target_value, standard_values, max_components=3):
debug_print(f"find_best_component_combination input:")
debug_print(f" target_value = {target_value}")
debug_print(f" standard_values = {standard_values[:5]}... (first 5 elements)")
debug_print(f" max_components = {max_components}")
# Determine the scale of the target value
scale = 10 ** math.floor(math.log10(target_value))
scaled_target = target_value / scale
scaled_standards = [v / scale for v in standard_values if v / scale <= 10 * scaled_target]
best_combination = None
min_error = float('inf')
combination_type = None
for num_components in range(1, max_components + 1):
for combination in itertools.combinations_with_replacement(scaled_standards, num_components):
# Try series combination
series_sum = sum(combination)
series_error = abs(series_sum - scaled_target) / scaled_target * 100
# Try parallel combination
parallel_sum = 1 / sum(1/c for c in combination)
parallel_error = abs(parallel_sum - scaled_target) / scaled_target * 100
if series_error < min_error:
min_error = series_error
best_combination = combination
combination_type = 'series'
if parallel_error < min_error:
min_error = parallel_error
best_combination = combination
combination_type = 'parallel'
# Scale the best combination back to the original scale
best_combination = tuple(v * scale for v in best_combination)
debug_print(f"find_best_component_combination output:")
debug_print(f" best_combination = {best_combination}")
debug_print(f" min_error = {min_error}%")
debug_print(f" combination_type = {combination_type}")
return best_combination, min_error, combination_type
def calculate_error_percentage(ideal, actual):
error = abs(ideal - actual) / ideal * 100
# debug_print(f"calculate_error_percentage(ideal={ideal}, actual={actual})")
# debug_print(f"calculate_error_percentage() returning {error}")
return error
def rebalance_matching_network(C1, L, C2, standard_capacitors, standard_inductors):
debug_print(f"standard_capacitors = {standard_capacitors[:5]}... (first 5 elements)")
debug_print(f"standard_inductors = {standard_inductors[:5]}... (first 5 elements)")
def rebalance_matching_network(component_values, matching_network_type, approx_values, fixed_component, standard_capacitors, standard_inductors):
debug_print(f"rebalance_matching_network input:")
debug_print(f" component_values = {component_values}")
debug_print(f" matching_network_type = {matching_network_type}")
debug_print(f" approx_values = {approx_values}")
debug_print(f" fixed_component = {fixed_component}")
debug_print(f" standard_capacitors = {standard_capacitors}")
debug_print(f" standard_inductors = {standard_inductors}")
# Implement rebalancing logic here
# For now, we'll just return the approx_values as is
return approx_values
def rank_matching_network_configs(configs, ideal_components):
for config in configs:
errors = []
for comp, value in config.items():
if comp != 'type':
ideal_value = ideal_components[comp]
errors.append(calculate_error_percentage(ideal_value, value[0]))
config['max_error'] = max(errors)
return sorted(configs, key=lambda x: x['max_error'])
def find_closest(arr, target):
pos = bisect_left(arr, target)
if pos == 0:
return arr[0]
if pos == len(arr):
return arr[-1]
before = arr[pos - 1]
after = arr[pos]
if after - target < target - before:
return after
else:
return before
def evaluate_configuration(L2, C1, C2, target_L2, target_C1, target_C2, center_freq):
L2_error = abs(L2 - target_L2) / target_L2
C1_error = abs(C1 - target_C1) / target_C1
C2_error = abs(C2 - target_C2) / target_C2
total_error = L2_error + C1_error + C2_error
L2_srf = estimate_srf_optimistic(L2)
srf_margin = L2_srf / center_freq
return total_error, srf_margin
def find_combinations(target, values, max_components=2, tolerance=0.05, is_inductor=False):
combinations = []
# Single component
closest = find_closest(values, target)
combinations.append((closest, 'single', f'{format_number(closest)}'))
if max_components >= 2:
# Parallel combinations
for i, v1 in enumerate(values):
for v2 in values[i:]:
combined = parallel_combination(v1, v2)
if abs(combined - target) / target <= tolerance:
v1_str = format_inductance_value(v1) if is_inductor else format_capacitance_value(v1)
v2_str = format_inductance_value(v2) if is_inductor else format_capacitance_value(v2)
combinations.append((combined, 'parallel', f'{v1_str} || {v2_str}'))
# Series combinations
for i, v1 in enumerate(values):
for v2 in values[i:]:
combined = series_combination(v1, v2)
if abs(combined - target) / target <= tolerance:
v1_str = format_inductance_value(v1) if is_inductor else format_capacitance_value(v1)
v2_str = format_inductance_value(v2) if is_inductor else format_capacitance_value(v2)
combinations.append((combined, 'series', f'{v1_str} + {v2_str}'))
combinations.sort(key=lambda x: abs(x[0] - target))
return combinations[:5] # Return top 5 combinations
def check_srf_margin(srf_margin):
return srf_margin >= 3, "Good" if srf_margin >= 3 else "Concern"
def esr_multiplier(config_type, component_count):
if config_type == 'single':
return 1
elif config_type == 'series':
return component_count
elif config_type == 'parallel':
return 1 / component_count
else:
return 1 # Default case
def current_multiplier(config_type, component_count):
if config_type == 'single':
return 1
elif config_type == 'series':
return 1 / component_count
elif config_type == 'parallel':
return component_count
else:
return 1 # Default case
def find_best_configurations(target_L2, target_C1, target_C2, center_freq, num_results=3):
L2_values = [x * 1e-6 for x in COMPONENTS['inductors_uh']]
C_values = [x * 1e-12 for x in COMPONENTS['capacitors_pf']]
L2_combinations = find_combinations(target_L2, L2_values, is_inductor=True)
C1_combinations = find_combinations(target_C1, C_values, is_inductor=False)
C2_combinations = find_combinations(target_C2, C_values, is_inductor=False)
configurations = []
for L2, L2_type, L2_desc in L2_combinations:
for C1, C1_type, C1_desc in C1_combinations:
for C2, C2_type, C2_desc in C2_combinations:
error, srf_margin = evaluate_configuration(L2, C1, C2, target_L2, target_C1, target_C2, center_freq)
component_count = sum(2 if config_type != 'single' else 1 for config_type in [L2_type, C1_type, C2_type])
configurations.append((L2, C1, C2, L2_type, L2_desc, C1_type, C1_desc, C2_type, C2_desc, error, srf_margin, component_count))
configurations.sort(key=lambda x: (x[9], -x[10], x[11])) # Sort by error (ascending), SRF margin (descending), and component count (ascending)
return configurations[:num_results]
def calculate_auto_q(band_data):
f_lower = band_data['start'] * 1e6 # Convert to Hz
f_upper = band_data['end'] * 1e6 # Convert to Hz
f_center = (f_upper + f_lower) / 2
natural_bandwidth = f_upper - f_lower
desired_bandwidth = 1.2 * natural_bandwidth
auto_q = f_center / desired_bandwidth
return auto_q
def parse_frequency(value_str):
if value_str is None:
return None
units = {
'h': 1, 'mh': 1e-3, 'uh': 1e-6, 'nh': 1e-9, 'ph': 1e-12,
'hz': 1, 'khz': 1e3, 'mhz': 1e6, 'ghz': 1e9
}
value, unit = re.match(r'([\d.]+)\s*([a-z]+)', value_str.lower()).groups()
return float(value) * units[unit]
def parse_current(value_str):
debug_print(f"parse_current() called with value_str='{value_str}'")
value_str = value_str.lower()
if value_str.endswith('ma'):
return float(value_str[:-2]) / 1000
elif value_str.endswith('m'): # Add this case for 'mA' without the 'A'
return float(value_str[:-1]) / 1000
elif value_str.endswith('ua'):
return float(value_str[:-2]) / 1000000
elif value_str_str.endswith('a'):
return float(value_str[:-1])
else:
try:
return float(value_str)
except ValueError:
raise ValueError(f"Invalid current value_str: {value}")
def parse_inductance(value_str):
getcontext().prec = 15 # Set precision to 15 significant digits
#debug_print(f"Parsing inductance value_str: {value}")
if isinstance(value_str, (int, float)):
return to_float(Decimal(value_str))