forked from KJ7LNW/perl-PDL-IO-Touchstone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTouchstone.pm
1977 lines (1420 loc) · 49.9 KB
/
Touchstone.pm
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
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Copyright (C) 2022- eWheeler, Inc. L<https://www.linuxglobal.com/>
# Originally written by Eric Wheeler, KJ7LNW
# All rights reserved.
#
# All tradmarks, product names, logos, and brands are property of their
# respective owners and no grant or license is provided thereof.
package PDL::IO::Touchstone;
our $VERSION = '1.015';
use 5.010;
use strict;
use warnings;
use Carp;
use IO::Handle;
use PDL;
use PDL::LinearAlgebra;
use PDL::Constants qw(PI);
use constant RAD2DEG => 180/PI;
use constant DEG2RAD => PI/180;
BEGIN {
use Exporter;
our @ISA = ( @ISA, qw(Exporter) );
our @EXPORT = qw/rsnp wsnp/;
our @EXPORT_OK = qw/
rsnp_fh
wsnp_fh
rsnp_list_to_hash
rsnp_hash_to_list
rsnp_hash
rsnp_fh_hash
wsnp_hash
wsnp_fh_hash
n_ports
m_interpolate
f_uniformity
f_is_uniform
s_to_y
y_to_s
s_to_z
z_to_s
s_to_abcd
abcd_to_s
s_port_z
y_inductance
y_ind_nH
y_resistance
y_esr
y_capacitance
y_cap_pF
y_qfactor_l
y_qfactor_c
y_reactance_l
y_reactance_c
y_reactance
y_srf
y_srf_ideal
y_parallel
abcd_series
abcd_is_lossless
abcd_is_symmetrical
abcd_is_reciprocal
abcd_is_open_circuit
abcd_is_short_circuit
pos_vec
m_to_pos_vecs
pos_vecs_to_m
/;
our %EXPORT_TAGS = (ALL => [ @EXPORT, @EXPORT_OK ]);
}
sub rsnp
{
my ($fn, $args) = @_;
$args = { ($args ? %$args : () ), filename => $fn };
open(my $in, $fn) or croak "$fn: $!";
my @ret = rsnp_fh($in, $args);
close($in) or carp "$fn: $!";
return @ret;
}
sub rsnp_list_to_hash
{
my @data = @_;
my %data;
@data{qw/freqs m param_type z0_ref comments output_fmt funit orig_f_unit/} = @data;
return %data;
}
sub rsnp_hash_to_list
{
my %data = @_;
my @data = @data{qw/freqs m param_type z0_ref comments output_fmt funit orig_f_unit/};
return @data;
}
sub rsnp_fh
{
my ($in, $args) = @_;
my $class;
my $comments = '';
my ($orig_funit, $param_type, $fmt, $R, $z0);
my $n_ports;
my $fn = $args->{filename} // '(unknown file)';
my $EOF_REGEX = $args->{EOF_REGEX};
# Try to enforce the number of ports based on the filename extension.
$n_ports = $1 if ($fn =~ /\.s(\d+)p$/i);
my $n = 0;
my $line;
# start at -1 because it increments when a frequency is found.
my $row_idx = -1;
my $col_idx = 0;
my @comments;
my @cols;
my @f;
# input_line_number is a surprisingly slow call, so get it out of the loop:
$n = $in->input_line_number - 1;
while (defined($line = <$in>))
{
$n++;
last if (defined($EOF_REGEX) && $line =~ /$EOF_REGEX/);
last if $line =~ /^\s*!\s*Noise Parameters/i;
chomp($line);
$line =~ s/^\s+|\s+$//g;
next if !length($line);
# Skip % lines as found in MDIF files:
next if $line =~ /^\s*%/;
# Strip leading space so split() will work properly.
$line =~ s/^\s+//;
if ($line =~ /^!/)
{
push @comments, $line;
next;
}
# Strip any inline comments:
$line =~ s/!.*$//;
if ($line =~ s/^#\s*//)
{
($orig_funit, $param_type, $fmt, $R, $z0) = split /\s+/, $line;
$param_type = uc($param_type);
if ($param_type !~ /^[SYZTAGH]$/) {
croak "$fn:$n: $param_type-parameter type is not implemented.";
}
croak "$fn:$n: expected 'R' before z0, but found: $R" if $R ne 'R';
next;
}
if ($line !~ /^[0-9.+-]/)
{
die "$fn:$n: unexpected line $n: $line\n";
next;
}
my @params = split(/\s+/, $line);
# If the line has an odd number of elements then the first is the frequency
# because data lines are always in pairs:
if (scalar(@params) % 2)
{
$row_idx++;
if ($row_idx > 0)
{
# We want the possibly multi-line row that was
# just completed, not the new one that was just
# read in. $col_idx currently holds the number
# of columns from the previous frequency.
my $sqrt_n_params = sqrt($col_idx);
if (!defined($n_ports))
{
$n_ports = $sqrt_n_params;
}
if ($sqrt_n_params != $n_ports)
{
carp "$fn:$n: expected $n_ports fields of port data (based on filename .sNp extension), but found $sqrt_n_params in the file itself: $n_ports != $sqrt_n_params";
}
}
# Read the frequency off the front.
$f[$row_idx] = shift(@params);
$col_idx=0;
}
my @params_cx;
for (my $i = 0; $i < @params; $i += 2)
{
# The data format could be ri, ma, or db but there is
# always a pair of data. Place each in its own array
# and we will convert the format below.
push @{ $cols[$col_idx]->[0] }, $params[$i];
push @{ $cols[$col_idx]->[1] }, $params[$i+1];
$col_idx++;
}
}
# The 2-port versions need to be turned into a row-major format.
# All other port counts _are_ row-major (including the 1-port, I
# suppose).
if (@cols == 4)
{
my $t = $cols[2];
$cols[2] = $cols[1];
$cols[1] = $t;
}
# Convert input columns to PDLs
foreach my $c (@cols)
{
$c->[0] = pdl $c->[0];
$c->[1] = pdl $c->[1];
}
# Convert from R/I formats to native complex:
my @cx_cols = _cols_to_complex_cols($fmt, \@cols);
# Scale frequency unit:
my $funit = $args->{units} || 'Hz';
my $f = _si_scale_hz($orig_funit, $funit, pdl \@f);
my $m = _complex_cols_to_matrix(@cx_cols);
($f, $m) = m_interpolate($f, $m, $args);
# Make z0 an n-vector:
$z0 = zeroes($n_ports) + $z0;
return ($f, $m, $param_type, $z0, $comments, $fmt, $funit, $orig_funit);
}
sub rsnp_hash { return rsnp_list_to_hash(rsnp(@_)); }
sub rsnp_fh_hash { return rsnp_list_to_hash(rsnp_fh(@_)); }
sub wsnp
{
my @opts = @_;
my $fn = shift(@opts);
croak "filename must be defined" if !defined $fn;
open(my $out, '>', $fn) or croak "$fn: $!";
my $ret = wsnp_fh($out, @opts);
close($out);
return $ret;
}
sub wsnp_fh
{
my ($fd, $f, $m, $param_type, $z0, $comments, $fmt, $from_hz, $to_hz) = @_;
my $n_ports = n_ports($m);
my $n_freqs = $f->nelem;
if (ref($z0) eq 'PDL')
{
my $numz = $z0->nelem;
if ($numz > 1 && $numz != $n_ports)
{
croak("\$z0: must be single valued, or a vector of one z0 value per port: n_ports=$n_ports, z0=$z0");
}
elsif ($numz == $n_ports)
{
my $z01 = $z0->slice(0)->sclr;
my $zx = zeroes($numz)+$z01;
if (any $zx != $z0)
{
croak("All port impedances must be identical when writing Touchstone files: z0=$z0");
}
}
$z0 = $z0->slice(0)->sclr;
}
# Assume $f frequencies are in Hz if from_hz is not defined
# and always default writing in MHz if the user does not specify.
# This is consistent with rsnp() and common industry practice:
$from_hz //= 'Hz';
$to_hz //= 'MHz';
$fmt = lc $fmt;
# 2-port matrixes are column-major:
$m = $m->transpose if ($n_ports == 2);
# Big thanks to mohawk and sivoais for helping figure out the reshape here.
# $d is arranged so real and imag parts can be separated into their own
# columns with clump() for writing to the sNp file:
my $d = $m->dummy(0,1);
# $real and $imag are the real and imag parts:
my ($real, $imag);
if ($fmt eq 'ri')
{
$real = $d->re;
$imag = $d->im;
}
elsif ($fmt eq 'ma')
{
$real = $d->abs;
$imag = $d->carg * RAD2DEG;
}
elsif ($fmt eq 'db')
{
$real = 20*log($d->abs)/log(10);
$imag = $d->carg * RAD2DEG;
}
# Prepare real/imag values for interleaving:
my $ri = $real->append($imag);
# Create one row per frequency: (n_ports*2, n_freqs):
my $out = $ri->clump(0..2);
# Scale the input/output frequency:
$f = _si_scale_hz($from_hz, $to_hz, $f);
# Fix capitalization to meet Touchstone spec:
$param_type = uc($param_type); # S, Y, Z, T, G, H, A
$fmt = uc($fmt); # RI, MA, DB
$to_hz =~ s!^([kmgtpe]?)hz$!uc($1 // '') . "Hz"!ie;
# Format header and comments:
print $fd join("\n", map { "! $_" } @$comments) . "\n" if ($comments && @$comments);
print $fd "# $to_hz $param_type $fmt R $z0\n";
# $out is in touchstone-formatted order for each frequency with frequency as the first element:
# ie: [freq s11 21 s12 s11] < transposed for only for 2-port models.
$f = $f->reshape($n_freqs);
my @freqs = $f->dog;
for (my $i = 0; $i < $n_freqs; $i++)
{
# matrix at frequency $i:
my $fm = $out->slice(":,$i");
my $freq = $freqs[$i];
# More than 2 ports are printed on multiple lines,
# at least one line for each port.
if ($n_ports > 2)
{
$fm = $fm->reshape($n_ports*2,$n_ports);
}
# First, print the frequency:
print $fd $freq;
# foreach matrix row:
# TODO: This loop is a hotspot, maybe someone can optimize it!
# Using PDL::IO::Misc's `wcols` is probably a good idea
# but formating it for Touchstone's weird column format
# for n_ports >2 could be challenging.
foreach my $row ($fm->dog)
{
# No more than four data samples are allowed per line,
# so 4 RI pairs max. If there are 3 or 4 ports then
# break at the port count so the matrix is visible in
# the file. Iterate over the data in the row and put
# line breaks in the appropriate place:
my @data = $row->dog;
while (@data)
{
my $count = @data;
$count = $n_ports * 2 if $count > $n_ports * 2;
$count = 8 if $count > 8 || $n_ports == 2;
my @line;
push @line, splice(@data, 0, $count);
print $fd "\t" . join("\t", @line) . "\n";
}
}
}
# we don't close the file descriptor here, the caller (or `wsnp`) will.
}
sub wsnp_hash { return wsnp(rsnp_hash_to_list(@_)); }
sub wsnp_fh_hash { return wsnp_fh(rsnp_hash_to_list(@_)); }
# https://physics.stackexchange.com/questions/398988/converting-magnitude-ratio-to-complex-form
sub _cols_to_complex_cols
{
my ($fmt, $cols) = @_;
$fmt = lc $fmt;
my @cx;
foreach my $c (@$cols)
{
my $r = $c->[0];
my $i = $c->[1];
if ($fmt eq 'ri')
{
push @cx, $r + $i*i();
}
elsif ($fmt eq 'ma')
{
push @cx, $r*exp(i()*$i*DEG2RAD);
}
elsif ($fmt eq 'db')
{
my $r = 10**($r/20);
push @cx, $r*exp(i()*$i*DEG2RAD);
}
else
{
croak "Unknown s-parameter format: $fmt";
}
}
return @cx;
}
sub _complex_cols_to_matrix
{
my @cx = @_;
my $n = $cx[0]->nelem;
my $n_ports = sqrt(scalar @cx);
my $m = pdl \@cx;
$m = $m->mv(0, -1)->reshape($n_ports,$n_ports,$n);
}
sub _si_scale_hz
{
my ($from, $to, $n) = @_;
$from = lc $from;
$to = lc $to;
return $n if $from eq $to;
my %scale =
(
hz => 1,
khz => 1e3,
mhz => 1e6,
ghz => 1e9,
thz => 1e12,
);
$from = $scale{$from};
$to = $scale{$to};
my $fscale = $from/$to;
croak "Unknown frequency scale: $fscale" if !$fscale;
return $n*$fscale;
}
# http://qucs.sourceforge.net/tech/node98.html
sub s_to_y
{
my ($S, $z0) = @_;
my $n_ports = n_ports($S);
$z0 = pdl $z0 if (!ref($z0));
my $Z_ref = _to_diagonal($z0, $n_ports);
my $G_ref = _to_diagonal(1/sqrt($z0->re), $n_ports);
my $E = identity($n_ports);
my $Y = $G_ref->minv x ($S x $Z_ref + $Z_ref)->minv x ($E-$S) x $G_ref;
# Alternate conversion, not sure which is faster, both have the same
# number of matrix multiplications:
#my $Y = $G_ref->minv x $Z_ref->minv x ($S + $E)->minv x ($E-$S) x $G_ref;
#my $Y = $G_ref->minv x $Z_ref->minv x ($E-$S) x ($S + $E)->minv x $G_ref;
return $Y;
}
sub y_to_s
{
my ($Y, $z0) = @_;
my $n_ports = n_ports($Y);
$z0 = pdl $z0 if (!ref($z0));
my $Z_ref = _to_diagonal($z0, $n_ports);
my $G_ref = _to_diagonal(1/sqrt($z0->re), $n_ports);
my $E = identity($n_ports);
my $S = $G_ref x ($E - $Z_ref x $Y) x ($E + $Z_ref x $Y)->minv() x $G_ref->minv();
return $S;
}
# This could result in singularities:
sub s_to_z
{
my ($S, $z0) = @_;
# This tries to avoid a singularity, but not so successfully.
#my $Y = s_to_y($S, $z0);
#my $Z;
#eval {$Z = $Y->minv };
#return $Z;
my $n_ports = n_ports($S);
$z0 = pdl $z0 if (!ref($z0));
my $Z_ref = _to_diagonal($z0, $n_ports);
my $G_ref = _to_diagonal(1/sqrt($z0->re), $n_ports);
my $E = identity($n_ports);
# These are equivalent, the second one has a smaller error:
#my $Z = $G_ref->minv() x ($E - $S)->minv x ($S x $Z_ref + $Z_ref) x $G_ref;
my $Z = $G_ref->minv() x ($E - $S)->minv x ($S + $E) x $Z_ref x $G_ref;
return $Z;
}
sub z_to_s
{
my ($Z, $z0) = @_;
my $n_ports = n_ports($Z);
$z0 = pdl $z0 if (!ref($z0));
my $Z_ref = _to_diagonal($z0, $n_ports);
my $G_ref = _to_diagonal(1/sqrt($z0->re), $n_ports);
my $E = identity($n_ports);
my $S = $G_ref x ($Z - $Z_ref) x ($Z + $Z_ref)->minv x $G_ref->minv;
return $S;
# This is equivalent but can result in singularities:
# minv needs scalar context for return, so assign temp value
# for clarity as to what is happening:
#my $Y = $Z->minv;
#return y_to_s($Y, $z0);
}
sub s_to_abcd
{
my ($S, $z0) = @_;
my $n_ports = n_ports($S);
croak "A-matrix transforms only work with 2-port matrices" if $n_ports != 2;
# We don't really need it diagonal, but it makes the call compatible with other
# conversions if the caller has different impedances per port:
my $Z_ref = _to_diagonal($z0, $n_ports);
my $z01 = $Z_ref->slice(0,0)->reshape(1);
my $z02 = $Z_ref->slice(1,1)->reshape(1);
my $z01_conj = $z01->conj;
my $z02_conj = $z02->conj;
my ($S11, $S12, $S21, $S22) = m_to_pos_vecs($S);
# https://www.researchgate.net/publication/3118645
# "Conversions Between S, Z, Y, h, ABCD, and T Parameters
# which are Valid for Complex Source and Load Impedances"
# March 1994 IEEE Transactions on Microwave Theory and Techniques 42(2):205 - 211
# If this needs to be optimized in the future then:
# 1. Factor out the divisor
# 2. Separate each segment into its multiplicative or additive term
# 3. Use PDL magic to compose elements with multiplication and addition.
#
# For example, the first multiplicative term (I think) becomes:
# $ABCD_part_1 = (
# pdl([ [$z01_conj, $z01_conj],
# [1 , 1] ])
# + $S->slice(0,0) * pdl( [ [$z01, $z01],
# [-1, -1] ])
# )
#
# see https://m.perl.bot/p/qycs8z
return pos_vecs_to_m(
# A
(($z01_conj + $S11*$z01) * (1 - $S22) + $S12*$S21*$z01)
/ # over
(2*$S21*sqrt($z01->re * $z02->re)),
# B
(($z01_conj + $S11*$z01)*($z02_conj+$S22*$z02) - $S12*$S21*$z01*$z02)
/ # over
(2*$S21*sqrt($z01->re * $z02->re)),
# C
(( 1 - $S11 )*( 1 - $S22 ) - $S12*$S21)
/ # over
(2*$S21*sqrt($z01->re * $z02->re)),
# D
((1-$S11)*($z02_conj+$S22*$z02) + $S12*$S21*$z02)
/ # over
(2*$S21*sqrt($z01->re * $z02->re)),
);
}
sub abcd_to_s
{
my ($ABCD, $z0) = @_;
my $n_ports = n_ports($ABCD);
croak "A-matrix transforms only work with 2-port matrices" if $n_ports != 2;
# We don't really need it diagonal, but it makes the call compatible with other
# conversions if the caller has different impedances per port:
my $Z_ref = _to_diagonal($z0, $n_ports);
my $z01 = $Z_ref->slice(0,0)->reshape(1);
my $z02 = $Z_ref->slice(1,1)->reshape(1);
my $z01_conj = $z01->conj;
my $z02_conj = $z02->conj;
my ($A, $B, $C, $D) = m_to_pos_vecs($ABCD);
return pos_vecs_to_m(
# S11
($A*$z02 + $B - $C*$z01_conj*$z02 - $D*$z01_conj)
/ # over
($A*$z02 + $B + $C*$z01*$z02 + $D*$z01),
# S12
(2*($A*$D-$B*$C)*sqrt($z01->re * $z02->re))
/ # over
($A*$z02 + $B + $C*$z01*$z02 + $D*$z01),
# S21
(2*sqrt($z01->re * $z02->re))
/ # over
($A*$z02 + $B + $C*$z01*$z02 + $D*$z01),
# S22
(-$A*$z02_conj + $B - $C*$z01*$z02_conj + $D*$z01)
/ # over
($A*$z02 + $B + $C*$z01*$z02 + $D*$z01)
);
}
###############################################################################
# S-Parameter Calculations
# Return the complex port impedance vector for all frequencies given:
# - $S: S parameter matrix
# - $z0: vector impedances at each port
# - $port: the port we want.
#
# In a 2-port, this will provide the input or output impedance as follows:
# $z_in = s_port_z($S, 50, 1);
# $z_out = s_port_z($S, 50, 2);
sub s_port_z
{
my ($S, $z0, $port) = @_;
my $n_ports = n_ports($S);
$z0 = _to_diagonal($z0, $n_ports);
my $z_port = pos_vec($z0, $port, $port);
my $s_port = pos_vec($S, $port, $port);
return $z_port * ( (1+$s_port) / (1-$s_port) );
}
###############################################################################
# Y-Parameter Calculations
# Return a vector of inductance for each frequency in Henrys (H):
# $Y - the Y parameter matrix (N,N,M)
# $f_hz - a vector of frequencies (M)
sub y_inductance
{
my ($Y, $f_hz) = @_;
my $y12 = pos_vec($Y, 1, 2);
return -(1/$y12)->im / (2*PI*$f_hz);
}
# Return a vector of inductance for each frequency in nH:
sub y_ind_nH { return y_inductance(@_) * 1e9; }
# Return ESR in Ohms:
# $Y - the Y parameter matrix (N,N,M)
# Equation from here:
# https://mdpi-res.com/d_attachment/electronics/electronics-11-02029/article_deploy/electronics-11-02029.pdf
# "Analytic Design of on-Chip Spiral Inductor with Variable Line Width"
# See also:
# https://electronics.stackexchange.com/q/637472/256265
sub y_resistance
{
my ($Y) = @_;
my $y12 = pos_vec($Y, 1, 2);
return (-1/$y12)->re;
}
sub y_esr { return y_resistance(@_) }
# Return a vector of capacitance for each frequency in Farads (F):
# $Y - the Y parameter matrix (N,N,M)
# $f_hz - a vector of frequencies (M)
sub y_capacitance
{
my ($Y, $f_hz) = @_;
my $y11 = pos_vec($Y, 1, 1);
return $y11->im / (2*PI*$f_hz);
}
# Return a vector of capacitance it each frequency in picofarads (pF):
sub y_cap_pF { return y_capacitance(@_) * 1e12; }
# Return the inductive Q-factor vector for each frequency.
# All capacitive values are zeroed.
# $Y - the Y parameter matrix (N,N,M)
# $f_hz - a vector of frequencies (M)
#
# $Ql = y_qfactor_l($Y, $f_hz)
sub y_qfactor_l
{
my ($Y, $f_hz) = @_;
my $Xl = y_reactance_l($Y, $f_hz);
my $is_l = ($Xl > 0);
my $esr = y_resistance($Y);
my $Ql = ($is_l*$Xl)/$esr;
return $Ql;
}
# Return the capacitive Q-factor vector for each frequency.
# All inductive values are zeroed.
# $Y - the Y parameter matrix (N,N,M)
# $f_hz - a vector of frequencies (M)
#
# $Qc = y_qfactor_c($Y, $f_hz)
sub y_qfactor_c
{
my ($Y, $f_hz) = @_;
my $Xc = y_reactance_c($Y, $f_hz);
my $is_c = ($Xc > 0);
my $esr = y_resistance($Y);
my $Qc = ($is_c*$Xc)/$esr;
return $Qc;
}
# Return a vector of inductive reactance for each frequency:
# $Y - the Y parameter matrix (N,N,M)
# $f_hz - a vector of frequencies (M)
sub y_reactance_l
{
my ($Y, $f_hz) = @_;
return 2*PI*$f_hz*y_inductance($Y, $f_hz);
}
# Return a vector of capacitive reactance for each frequency:
# $Y - the Y parameter matrix (N,N,M)
# $f_hz - a vector of frequencies (M)
sub y_reactance_c
{
my ($Y, $f_hz) = @_;
return 1.0/(2*PI*$f_hz*y_capacitance($Y, $f_hz));
}
# Return a vector of total reactance for each frequency:
# $Y - the Y parameter matrix (N,N,M)
# $f_hz - a vector of frequencies (M)
sub y_reactance
{
my ($Y, $f_hz) = @_;
return y_reactance_l($Y, $f_hz) - y_reactance_c($Y, $f_hz);
}
# Return an array of PDLs, each representing a resonant frequency.
sub y_srf
{
my ($Y, $f_hz) = @_;
my $X = y_reactance($Y, $f_hz);
my ($counts, $vals) = ($X <=> 0)->rle;
my $f_idx = 0;
my @ret;
my $nelem = $X->nelem;
foreach my $c ($counts->dog)
{
$f_idx += $c;
push @ret, $f_hz->slice($f_idx-1) if $f_idx < $nelem;
}
if (wantarray)
{
return @ret;
}
else
{
return $ret[0];
}
}
# srf: Self-resonating frequency.
#
# This may not be accurate. While the equation is a classic
# SRF calculation (1/(2*pi*sqrt(LC)), srf should scan the frequency lines as follows:
# "The SRF is determined to be the frequency at which the insertion (S21)
# phase changes from negative through zero to positive."
# [ https://www.coilcraft.com/getmedia/8ef1bd18-d092-40e8-a3c8-929bec6adfc9/doc363_measuringsrf.pdf ]
#
# $Y - the Y parameter matrix (N,N,M)
# $f_hz - a vector of frequencies (M)
sub y_srf_ideal
{
my ($Y, $f_hz) = @_;
return 1/sqrt( abs 2*PI*y_inductance($Y, $f_hz)*y_capacitance($Y, $f_hz));
}
# Return a parallel representation from a list of (N,N,M) Y-Parameters
#
# @yparams: a list of (N,N,M) piddles
#
# Note: each yparam must be compatible in that:
# 1. The number of frequencies of each must be the same
# 2. The frequency values must correspond because inter-frequency
# interpolation is _not_ performed.
#
# For example, if you have the Y parameters for two capacitors $C1_y and $C2_y
# at 100pF then in parallel you will get a 200pF capacitor:
#
# $C_parallel_y = y_parallel($C1_y, $C2_y);
# and thus:
# 200 == y_cap_pF($C_parallel_y)
sub y_parallel
{
my @yparams = @_;
my $ret;
foreach my $y (@yparams)
{
if (!defined $ret)
{
$ret = $y;
}
else
{
$ret += $y;
}
}
return $ret;
}
###############################################################################
# ABCD-Parameter Calculations
# Return a series representation from a list of (N,N,M) ABCD-Parameters
#
# @abcd_params: a list of (N,N,M) piddles
#
# Note: each abcd_param must be compatible in that:
# 1. The number of frequencies of each must be the same
# 2. The frequency values must correspond because inter-frequency
# interpolation is _not_ performed.
#
# For example, if you have the ABCD parameters for two capacitors $C1_y and
# $C2_y at 100pF then in series you will get a 50pF capacitor:
#
# $C_series_abcd = abcd_series($C1_abcd, $C2_abcd);
# and thus:
# 50 == y_cap_pF($C_series_abcd)
sub abcd_series
{
my @abcd_params = @_;
my $ret;
foreach my $abcd (@abcd_params)
{
if (!defined $ret)
{
$ret = $abcd
}
else
{
$ret = $ret x $abcd;
}
}
return $ret;
}
sub abcd_is_lossless
{
my ($ABCD, $tolerance) = @_;
my ($A, $B, $C, $D) = m_to_pos_vecs($ABCD);
# How small should Im/Re be to be considered zero?
$tolerance //= 1e-6;
# Lossless when diagonal elements are purely Real and off-diagonal are
# purely imaginary: https://youtu.be/rfbvmGwN_8o
return (all(abs($A->im) < $tolerance) && all(abs($D->im) < $tolerance)
&& all(abs($B->re) < $tolerance) && all(abs($C->re) < $tolerance));
}
# See reference for symmetrical, reciprocal, open_circuit, short_circuit:
# https://resources.system-analysis.cadence.com/blog/msa2021-abcd-parameters-of-transmission-lines
sub abcd_is_symmetrical
{
my ($ABCD, $tolerance) = @_;