Touchstone.pm

filter: Statementstmt 90.0% 18 / 20 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.5% 25 / 27 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« MDIF.pm ↑ Summary
1 # This program is free software; you can redistribute it and/or modify
2 # it under the terms of the GNU General Public License as published by
3 # the Free Software Foundation; either version 3 of the License, or
4 # (at your option) any later version.
5 #
6 # This program is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # GNU Library General Public License for more details.
10 #
11 # You should have received a copy of the GNU General Public License
12 # along with this program; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
14 #
15 # Copyright (C) 2022- eWheeler, Inc. L<https://www.linuxglobal.com/>
16 # Originally written by Eric Wheeler, KJ7LNW
17 # All rights reserved.
18 #
19 # All tradmarks, product names, logos, and brands are property of their
20 # respective owners and no grant or license is provided thereof.
21  
22 package PDL::IO::Touchstone;
23 our $VERSION = '1.013';
24  
25 1 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 1 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 1 ▶use PDL;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 1 ▶use PDL::LinearAlgebra;
Subroutine BEGIN: called CC=1 SCAR=2.6
35 use PDL::Constants qw(PI);
36  
37 use constant RAD2DEG => 180/PI;
38 use constant DEG2RAD => PI/180;
39  
40 BEGIN {
41 use Exporter;
42 our @ISA = ( @ISA, qw(Exporter) );
43 our @EXPORT = qw/rsnp wsnp/;
44 our @EXPORT_OK = qw/
45 rsnp_fh
46 wsnp_fh
47  
48 rsnp_list_to_hash
49 rsnp_hash_to_list
50  
51 rsnp_hash
52 rsnp_fh_hash
53  
54 wsnp_hash
55 wsnp_fh_hash
56  
57 n_ports
58 m_interpolate
59 f_uniformity
60 f_is_uniform
61  
62 s_to_y
63 y_to_s
64  
65 s_to_z
66 z_to_s
67  
68 s_to_abcd
69 abcd_to_s
70  
71 s_port_z
72  
73 y_inductance
74 y_ind_nH
75 y_resistance
76 y_esr
77 y_capacitance
78 y_cap_pF
79 y_qfactor_l
80 y_qfactor_c
81 y_reactance_l
82 y_reactance_c
83 y_reactance
84 y_srf
85 y_srf_ideal
86 y_parallel
87 abcd_series
88 abcd_is_lossless
89 abcd_is_symmetrical
90 abcd_is_reciprocal
91 abcd_is_open_circuit
92 abcd_is_short_circuit
93  
94 pos_vec
95 m_to_pos_vecs
96 pos_vecs_to_m
97 /;
98  
99 our %EXPORT_TAGS = (ALL => [ @EXPORT, @EXPORT_OK ]);
100 }
101  
102 sub rsnp
103 {
104 my ($fn, $args) = @_;
105  
106 $args = { ($args ? %$args : () ), filename => $fn };
107  
108 open(my $in, $fn) or croak "$fn: $!";
109  
110 my @ret = rsnp_fh($in, $args);
111  
112 close($in) or carp "$fn: $!";
113  
114 return @ret;
115 }
116  
117 sub rsnp_list_to_hash
118 {
119 my @data = @_;
120 my %data;
121 @data{qw/freqs m param_type z0_ref comments output_fmt funit orig_f_unit/} = @data;
122  
123 return %data;
124 }
125  
126 sub rsnp_hash_to_list
127 {
128 my %data = @_;
129  
130 my @data = @data{qw/freqs m param_type z0_ref comments output_fmt funit orig_f_unit/};
131  
132 return @data;
133 }
134  
135 sub rsnp_fh
136 {
137 my ($in, $args) = @_;
138  
139 my $class;
140 my $comments = '';
141 my ($orig_funit, $param_type, $fmt, $R, $z0);
142 my $n_ports;
143  
144 my $fn = $args->{filename} // '(unknown file)';
145  
146 my $EOF_REGEX = $args->{EOF_REGEX};
147  
148 # Try to enforce the number of ports based on the filename extension.
149 $n_ports = $1 if ($fn =~ /s(\d+)p/i);
150  
151 my $n = 0;
152 my $line;
153  
154 # start at -1 because it increments when a frequency is found.
155 my $row_idx = -1;
156 my $col_idx = 0;
157 my @comments;
158 my @cols;
159 my @f;
160  
161 # input_line_number is a surprisingly slow call, so get it out of the loop:
162 $n = $in->input_line_number - 1;
163  
164 while (defined($line = <$in>))
165 {
166 $n++;
167  
168 last if (defined($EOF_REGEX) && $line =~ /$EOF_REGEX/);
169  
170 last if $line =~ /^\s*!\s*Noise Parameters/i;
171  
172 chomp($line);
173  
174 $line =~ s/^\s+|\s+$//g;
175  
176 next if !length($line);
177  
178 # Skip % lines as found in MDIF files:
179 next if $line =~ /^\s*%/;
180  
181 # Strip leading space so split() will work properly.
182 $line =~ s/^\s+//;
183  
184 if ($line =~ /^!/)
185 {
186 push @comments, $line;
187 next;
188 }
189  
190 # Strip any inline comments:
191 $line =~ s/!.*$//;
192  
193 if ($line =~ s/^#\s*//)
194 {
195 ($orig_funit, $param_type, $fmt, $R, $z0) = split /\s+/, $line;
196  
197 $param_type = uc($param_type);
198 if ($param_type !~ /^[SYZTAGH]$/) {
199 croak "$fn:$n: $param_type-parameter type is not implemented.";
200 }
201  
202 croak "$fn:$n: expected 'R' before z0, but found: $R" if $R ne 'R';
203 next;
204 }
205  
206 if ($line !~ /^[0-9.+-]/)
207 {
208 die "$fn:$n: unexpected line $n: $line\n";
209 next;
210 }
211  
212 my @params = split(/\s+/, $line);
213  
214 # If the line has an odd number of elements then the first is the frequency
215 # because data lines are always in pairs:
216 if (scalar(@params) % 2)
217 {
218 $row_idx++;
219  
220 if ($row_idx > 0)
221 {
222 # We want the possibly multi-line row that was
223 # just completed, not the new one that was just
224 # read in. $col_idx currently holds the number
225 # of columns from the previous frequency.
226 my $sqrt_n_params = sqrt($col_idx);
227 if (!defined($n_ports))
228 {
229 $n_ports = $sqrt_n_params;
230 }
231  
232 if ($sqrt_n_params != $n_ports)
233 {
234 croak "$fn:$n: expected $n_ports fields of port data but found $sqrt_n_params: $n_ports != $sqrt_n_params";
235 }
236 }
237  
238 # Read the frequency off the front.
239 $f[$row_idx] = shift(@params);
240 $col_idx=0;
241 }
242  
243 my @params_cx;
244  
245 for (my $i = 0; $i < @params; $i += 2)
246 {
247 # The data format could be ri, ma, or db but there is
248 # always a pair of data. Please each in its own array
249 # and we will convert the format below.
250 push @{ $cols[$col_idx]->[0] }, $params[$i];
251 push @{ $cols[$col_idx]->[1] }, $params[$i+1];
252  
253 $col_idx++;
254 }
255  
256 }
257  
258 # The 2-port versions need to be turned into a row-major format.
259 # All other port counts _are_ row-major (including the 1-port, I
260 # suppose).
261 if (@cols == 4)
262 {
263 my $t = $cols[2];
264 $cols[2] = $cols[1];
265 $cols[1] = $t;
266 }
267  
268 # Convert input columns to PDLs
269 foreach my $c (@cols)
270 {
271 $c->[0] = pdl $c->[0];
272 $c->[1] = pdl $c->[1];
273 }
274  
275 # Convert from R/I formats to native complex:
276 my @cx_cols = _cols_to_complex_cols($fmt, \@cols);
277  
278 # Scale frequency unit:
279 my $funit = $args->{units} || 'Hz';
280 my $f = _si_scale_hz($orig_funit, $funit, pdl \@f);
281  
282 my $m = _complex_cols_to_matrix(@cx_cols);
283  
284 ($f, $m) = m_interpolate($f, $m, $args);
285  
286 # Make z0 an n-vector:
287 $z0 = zeroes($n_ports) + $z0;
288  
289 return ($f, $m, $param_type, $z0, $comments, $fmt, $funit, $orig_funit);
290 }
291  
292 sub rsnp_hash { return rsnp_list_to_hash(rsnp(@_)); }
293 sub rsnp_fh_hash { return rsnp_list_to_hash(rsnp_fh(@_)); }
294  
295 sub wsnp
296 {
297 my @opts = @_;
298 my $fn = shift(@opts);
299  
300 croak "filename must be defined" if !defined $fn;
301  
302 open(my $out, '>', $fn) or croak "$fn: $!";
303  
304 my $ret = wsnp_fh($out, @opts);
305  
306 close($out);
307  
308 return $ret;
309 }
310  
311 sub wsnp_fh
312 {
313 my ($fd, $f, $m, $param_type, $z0, $comments, $fmt, $from_hz, $to_hz) = @_;
314  
315 my $n_ports = n_ports($m);
316 my $n_freqs = $f->nelem;
317  
318 if (ref($z0) eq 'PDL')
319 {
320 my $numz = $z0->nelem;
321  
322 if ($numz > 1 && $numz != $n_ports)
323 {
324 croak("\$z0: must be single valued, or a vector of one z0 value per port: n_ports=$n_ports, z0=$z0");
325 }
326 elsif ($numz == $n_ports)
327 {
328 my $z01 = $z0->slice(0)->sclr;
329  
330 my $zx = zeroes($numz)+$z01;
331 if (any $zx != $z0)
332 {
333 croak("All port impedances must be identical when writing Touchstone files: z0=$z0");
334 }
335 }
336  
337 $z0 = $z0->slice(0)->sclr;
338 }
339  
340 # Assume $f frequencies are in Hz if from_hz is not defined
341 # and always default writing in MHz if the user does not specify.
342 # This is consistent with rsnp() and common industry practice:
343 $from_hz //= 'Hz';
344 $to_hz //= 'MHz';
345  
346 $fmt = lc $fmt;
347  
348 # 2-port matrixes are column-major:
349 $m = $m->transpose if ($n_ports == 2);
350  
351 # Big thanks to mohawk and sivoais for helping figure out the reshape here.
352 # $d is arranged so real and imag parts can be separated into their own
353 # columns with clump() for writing to the sNp file:
354 my $d = $m->dummy(0,1);
355
356  
357 # $real and $imag are the real and imag parts:
358 my ($real, $imag);
359 if ($fmt eq 'ri')
360 {
361 $real = $d->re;
362 $imag = $d->im;
363 }
364 elsif ($fmt eq 'ma')
365 {
366 $real = $d->abs;
367 $imag = $d->carg * RAD2DEG;
368 }
369 elsif ($fmt eq 'db')
370 {
371 $real = 20*log($d->abs)/log(10);
372 $imag = $d->carg * RAD2DEG;
373 }
374  
375 # Prepare real/imag values for interleaving:
376 my $ri = $real->append($imag);
377  
378 # Create one row per frequency: (n_ports*2, n_freqs):
379 my $out = $ri->clump(0..2);
380  
381 # Scale the input/output frequency:
382 $f = _si_scale_hz($from_hz, $to_hz, $f);
383  
384 # Fix capitalization to meet Touchstone spec:
385 $param_type = uc($param_type); # S, Y, Z, T, G, H, A
386 $fmt = uc($fmt); # RI, MA, DB
387 $to_hz =~ s!^([kmgtpe]?)hz$!uc($1 // '') . "Hz"!ie;
388  
389 # Format header and comments:
390 print $fd join("\n", map { "! $_" } @$comments) . "\n" if ($comments && @$comments);
391 print $fd "# $to_hz $param_type $fmt R $z0\n";
392  
393 # $out is in touchstone-formated order for each frequency with frequency as the first element:
394 # ie: [freq s11 21 s12 s11] < transposed for only for 2-port models.
395
396 $f = $f->reshape($n_freqs);
397 my @freqs = $f->dog;
398  
399 for (my $i = 0; $i < $n_freqs; $i++)
400 {
401 # matrix at frequency $i:
402 my $fm = $out->slice(":,$i");
403 my $freq = $freqs[$i];
404  
405 # More than 2 ports are printed on multiple lines,
406 # at least one line for each port.
407 if ($n_ports > 2)
408 {
409 $fm = $fm->reshape($n_ports*2,$n_ports);
410 }
411  
412 # First, print the frequency:
413 print $fd $freq;
414  
415 # foreach matrix row:
416 # TODO: This loop is a hotspot, maybe someone can optimize it!
417 # Using PDL::IO::Misc's `wcols` is probably a good idea
418 # but formating it for Touchstone's weird column format
419 # for n_ports >2 could be challenging.
420 foreach my $row ($fm->dog)
421 {
422 # No more than four data samples are allowed per line,
423 # so 4 RI pairs max. If there are 3 or 4 ports then
424 # break at the port count so the matrix is visible in
425 # the file. Iterate over the data in the row and put
426 # line breaks in the appropriate place:
427 my @data = $row->dog;
428 while (@data)
429 {
430 my $count = @data;
431 $count = $n_ports * 2 if $count > $n_ports * 2;
432 $count = 8 if $count > 8 || $n_ports == 2;
433  
434 my @line;
435 push @line, shift @data while ($count--);
436  
437 print $fd "\t" . join("\t", @line) . "\n";
438 }
439  
440 }
441 }
442  
443 # we don't close the file descriptor here, the caller (or `wsnp`) will.
444 }
445  
446 sub wsnp_hash { return wsnp(rsnp_hash_to_list(@_)); }
447 sub wsnp_fh_hash { return wsnp_fh(rsnp_hash_to_list(@_)); }
448  
449 # https://physics.stackexchange.com/questions/398988/converting-magnitude-ratio-to-complex-form
450 sub _cols_to_complex_cols
451 {
452 my ($fmt, $cols) = @_;
453  
454 $fmt = lc $fmt;
455 my @cx;
456  
457 foreach my $c (@$cols)
458 {
459 my $r = $c->[0];
460 my $i = $c->[1];
461 if ($fmt eq 'ri')
462 {
463 push @cx, $r + $i*i();
464 }
465 elsif ($fmt eq 'ma')
466 {
467 push @cx, $r*exp(i()*$i*DEG2RAD);
468 }
469 elsif ($fmt eq 'db')
470 {
471 my $r = 10**($r/20);
472 push @cx, $r*exp(i()*$i*DEG2RAD);
473 }
474 else
475 {
476 croak "Unknown s-parameter format: $fmt";
477 }
478 }
479  
480 return @cx;
481 }
482  
483 sub _complex_cols_to_matrix
484 {
485 my @cx = @_;
486  
487 my $n = $cx[0]->nelem;
488 my $n_ports = sqrt(scalar @cx);
489  
490 my $m = pdl \@cx;
491 $m = $m->mv(0, -1)->reshape($n_ports,$n_ports,$n);
492 }
493  
494 sub _si_scale_hz
495 {
496 my ($from, $to, $n) = @_;
497  
498 $from = lc $from;
499 $to = lc $to;
500  
501 return $n if $from eq $to;
502  
503 my %scale =
504 (
505 hz => 1,
506 khz => 1e3,
507 mhz => 1e6,
508 ghz => 1e9,
509 thz => 1e12,
510 );
511  
512 $from = $scale{$from};
513 $to = $scale{$to};
514  
515 my $fscale = $from/$to;
516  
517 croak "Unknown frequency scale: $fscale" if !$fscale;
518  
519 return $n*$fscale;
520 }
521  
522 # http://qucs.sourceforge.net/tech/node98.html
523 sub s_to_y
524 {
525 my ($S, $z0) = @_;
526  
527 my $n_ports = n_ports($S);
528  
529 $z0 = pdl $z0 if (!ref($z0));
530  
531 my $Z_ref = _to_diagonal($z0, $n_ports);
532 my $G_ref = _to_diagonal(1/sqrt($z0->re), $n_ports);
533 my $E = identity($n_ports);
534  
535 my $Y = $G_ref->minv x ($S x $Z_ref + $Z_ref)->minv x ($E-$S) x $G_ref;
536  
537 # Alternate conversion, not sure which is faster, both have the same
538 # number of matrix multiplications:
539 #my $Y = $G_ref->minv x $Z_ref->minv x ($S + $E)->minv x ($E-$S) x $G_ref;
540 #my $Y = $G_ref->minv x $Z_ref->minv x ($E-$S) x ($S + $E)->minv x $G_ref;
541  
542 return $Y;
543 }
544  
545 sub y_to_s
546 {
547 my ($Y, $z0) = @_;
548  
549 my $n_ports = n_ports($Y);
550  
551 $z0 = pdl $z0 if (!ref($z0));
552  
553 my $Z_ref = _to_diagonal($z0, $n_ports);
554 my $G_ref = _to_diagonal(1/sqrt($z0->re), $n_ports);
555 my $E = identity($n_ports);
556  
557 my $S = $G_ref x ($E - $Z_ref x $Y) x ($E + $Z_ref x $Y)->minv() x $G_ref->minv();
558  
559 return $S;
560 }
561  
562 # This could result in singularities:
563 sub s_to_z
564 {
565 my ($S, $z0) = @_;
566  
567 # This tries to avoid a singularity, but not so successfully.
568 #my $Y = s_to_y($S, $z0);
569 #my $Z;
570 #eval {$Z = $Y->minv };
571 #return $Z;
572  
573 my $n_ports = n_ports($S);
574  
575 $z0 = pdl $z0 if (!ref($z0));
576  
577 my $Z_ref = _to_diagonal($z0, $n_ports);
578 my $G_ref = _to_diagonal(1/sqrt($z0->re), $n_ports);
579 my $E = identity($n_ports);
580  
581 # These are equivalent, the second one has a smaller error:
582 #my $Z = $G_ref->minv() x ($E - $S)->minv x ($S x $Z_ref + $Z_ref) x $G_ref;
583 my $Z = $G_ref->minv() x ($E - $S)->minv x ($S + $E) x $Z_ref x $G_ref;
584  
585 return $Z;
586 }
587  
588 sub z_to_s
589 {
590 my ($Z, $z0) = @_;
591  
592 my $n_ports = n_ports($Z);
593  
594 $z0 = pdl $z0 if (!ref($z0));
595  
596 my $Z_ref = _to_diagonal($z0, $n_ports);
597 my $G_ref = _to_diagonal(1/sqrt($z0->re), $n_ports);
598 my $E = identity($n_ports);
599  
600 my $S = $G_ref x ($Z - $Z_ref) x ($Z + $Z_ref)->minv x $G_ref->minv;
601 return $S;
602  
603 # This is equivalent but can result in singularities:
604 # minv needs scalar context for return, so assign temp value
605 # for clarity as to what is happening:
606 #my $Y = $Z->minv;
607 #return y_to_s($Y, $z0);
608 }
609  
610 sub s_to_abcd
611 {
612 my ($S, $z0) = @_;
613  
614 my $n_ports = n_ports($S);
615  
616 croak "A-matrix transforms only work with 2-port matrices" if $n_ports != 2;
617  
618 # We don't really need it diagonal, but it makes the call compatable with other
619 # conversions if the caller has different impedances per port:
620 my $Z_ref = _to_diagonal($z0, $n_ports);
621 my $z01 = $Z_ref->slice(0,0)->reshape(1);
622 my $z02 = $Z_ref->slice(1,1)->reshape(1);
623  
624 my $z01_conj = $z01->conj;
625 my $z02_conj = $z02->conj;
626  
627 my ($S11, $S12, $S21, $S22) = m_to_pos_vecs($S);
628  
629 # https://www.researchgate.net/publication/3118645
630 # "Conversions Between S, Z, Y, h, ABCD, and T Parameters
631 # which are Valid for Complex Source and Load Impedances"
632 # March 1994 IEEE Transactions on Microwave Theory and Techniques 42(2):205 - 211
633  
634 # If this needs to be optimized in the future then:
635 # 1. Factor out the divisor
636 # 2. Separate each segment into its multiplicative or additive term
637 # 3. Use PDL magic to compose elements with multiplication and addition.
638 #
639 # For example, the first multiplicative term (I think) becomes:
640 # $ABCD_part_1 = (
641 # pdl([ [$z01_conj, $z01_conj],
642 # [1 , 1] ])
643 # + $S->slice(0,0) * pdl( [ [$z01, $z01],
644 # [-1, -1] ])
645 # )
646 #
647 # see https://m.perl.bot/p/qycs8z
648 return pos_vecs_to_m(
649 # A
650 (($z01_conj + $S11*$z01) * (1 - $S22) + $S12*$S21*$z01)
651 / # over
652 (2*$S21*sqrt($z01->re * $z02->re)),
653  
654 # B
655 (($z01_conj + $S11*$z01)*($z02_conj+$S22*$z02) - $S12*$S21*$z01*$z02)
656 / # over
657 (2*$S21*sqrt($z01->re * $z02->re)),
658  
659 # C
660 (( 1 - $S11 )*( 1 - $S22 ) - $S12*$S21)
661 / # over
662 (2*$S21*sqrt($z01->re * $z02->re)),
663  
664 # D
665 ((1-$S11)*($z02_conj+$S22*$z02) + $S12*$S21*$z02)
666 / # over
667 (2*$S21*sqrt($z01->re * $z02->re)),
668 );
669 }
670  
671 sub abcd_to_s
672 {
673 my ($ABCD, $z0) = @_;
674  
675 my $n_ports = n_ports($ABCD);
676  
677 croak "A-matrix transforms only work with 2-port matrices" if $n_ports != 2;
678  
679 # We don't really need it diagonal, but it makes the call compatable with other
680 # conversions if the caller has different impedances per port:
681 my $Z_ref = _to_diagonal($z0, $n_ports);
682 my $z01 = $Z_ref->slice(0,0)->reshape(1);
683 my $z02 = $Z_ref->slice(1,1)->reshape(1);
684  
685 my $z01_conj = $z01->conj;
686 my $z02_conj = $z02->conj;
687  
688 my ($A, $B, $C, $D) = m_to_pos_vecs($ABCD);
689  
690 return pos_vecs_to_m(
691 # S11
692 ($A*$z02 + $B - $C*$z01_conj*$z02 - $D*$z01_conj)
693 / # over
694 ($A*$z02 + $B + $C*$z01*$z02 + $D*$z01),
695  
696 # S12
697 (2*($A*$D-$B*$C)*sqrt($z01->re * $z02->re))
698 / # over
699 ($A*$z02 + $B + $C*$z01*$z02 + $D*$z01),
700  
701 # S21
702 (2*sqrt($z01->re * $z02->re))
703 / # over
704 ($A*$z02 + $B + $C*$z01*$z02 + $D*$z01),
705  
706 # S22
707 (-$A*$z02_conj + $B - $C*$z01*$z02_conj + $D*$z01)
708 / # over
709 ($A*$z02 + $B + $C*$z01*$z02 + $D*$z01)
710 );
711 }
712  
713 ###############################################################################
714 # S-Parameter Calculations
715  
716 # Return the complex port impedance vector for all frequencies given:
717 # - $S: S paramter matrix
718 # - $z0: vector impedances at each port
719 # - $port: the port we want.
720 #
721 # In a 2-port, this will provide the input or output impedance as follows:
722 # $z_in = s_port_z($S, 50, 1);
723 # $z_out = s_port_z($S, 50, 2);
724 sub s_port_z
725 {
726 my ($S, $z0, $port) = @_;
727  
728 my $n_ports = n_ports($S);
729  
730 $z0 = _to_diagonal($z0, $n_ports);
731  
732 my $z_port = pos_vec($z0, $port, $port);
733 my $s_port = pos_vec($S, $port, $port);
734  
735 return $z_port * ( (1+$s_port) / (1-$s_port) );
736 }
737  
738 ###############################################################################
739 # Y-Parameter Calculations
740  
741 # Return a vector of inductance for each frequency in Henrys (H):
742 # $Y - the Y parameter matrix (N,N,M)
743 # $f_hz - a vector of frequencies (M)
744 sub y_inductance
745 {
746 my ($Y, $f_hz) = @_;
747  
748 my $y12 = pos_vec($Y, 1, 2);
749  
750 return -(1/$y12)->im / (2*PI*$f_hz);
751 }
752  
753 # Return a vector of inductance for each frequency in nH:
754 sub y_ind_nH { return y_inductance(@_) * 1e9; }
755  
756 # Return ESR in Ohms:
757 # $Y - the Y parameter matrix (N,N,M)
758 # Equation from here:
759 # https://mdpi-res.com/d_attachment/electronics/electronics-11-02029/article_deploy/electronics-11-02029.pdf
760 # "Analytic Design of on-Chip Spiral Inductor with Variable Line Width"
761 # See also:
762 # https://electronics.stackexchange.com/q/637472/256265
763 sub y_resistance
764 {
765 my ($Y) = @_;
766  
767 my $y12 = pos_vec($Y, 1, 2);
768  
769 return (-1/$y12)->re;
770 }
771  
772 sub y_esr { return y_resistance(@_) }
773  
774  
775 # Return a vector of capacitance for each frequency in Farads (F):
776 # $Y - the Y parameter matrix (N,N,M)
777 # $f_hz - a vector of frequencies (M)
778 sub y_capacitance
779 {
780 my ($Y, $f_hz) = @_;
781  
782 my $y11 = pos_vec($Y, 1, 1);
783  
784 return $y11->im / (2*PI*$f_hz);
785 }
786  
787 # Return a vector of capacitance it each frequency in picofarads (pF):
788 sub y_cap_pF { return y_capacitance(@_) * 1e12; }
789  
790 # Return the inductive Q-factor vector for each frequency.
791 # All capacitive values are zeroed.
792 # $Y - the Y parameter matrix (N,N,M)
793 # $f_hz - a vector of frequencies (M)
794 #
795 # $Ql = y_qfactor_l($Y, $f_hz)
796 sub y_qfactor_l
797 {
798 my ($Y, $f_hz) = @_;
799  
800 my $Xl = y_reactance_l($Y, $f_hz);
801  
802 my $is_l = ($Xl > 0);
803  
804 my $esr = y_resistance($Y);
805 my $Ql = ($is_l*$Xl)/$esr;
806  
807 return $Ql;
808 }
809  
810 # Return the capacitive Q-factor vector for each frequency.
811 # All inductive values are zeroed.
812 # $Y - the Y parameter matrix (N,N,M)
813 # $f_hz - a vector of frequencies (M)
814 #
815 # $Qc = y_qfactor_c($Y, $f_hz)
816 sub y_qfactor_c
817 {
818 my ($Y, $f_hz) = @_;
819  
820 my $Xc = y_reactance_c($Y, $f_hz);
821  
822 my $is_c = ($Xc > 0);
823  
824 my $esr = y_resistance($Y);
825 my $Qc = ($is_c*$Xc)/$esr;
826  
827 return $Qc;
828 }
829  
830 # Return a vector of inductive reactance for each frequency:
831 # $Y - the Y parameter matrix (N,N,M)
832 # $f_hz - a vector of frequencies (M)
833 sub y_reactance_l
834 {
835 my ($Y, $f_hz) = @_;
836  
837 return 2*PI*$f_hz*y_inductance($Y, $f_hz);
838 }
839  
840 # Return a vector of capacitive reactance for each frequency:
841 # $Y - the Y parameter matrix (N,N,M)
842 # $f_hz - a vector of frequencies (M)
843 sub y_reactance_c
844 {
845 my ($Y, $f_hz) = @_;
846  
847 return 1.0/(2*PI*$f_hz*y_capacitance($Y, $f_hz));
848 }
849  
850 # Return a vector of total reactance for each frequency:
851 # $Y - the Y parameter matrix (N,N,M)
852 # $f_hz - a vector of frequencies (M)
853 sub y_reactance
854 {
855 my ($Y, $f_hz) = @_;
856  
857 return y_reactance_l($Y, $f_hz) - y_reactance_c($Y, $f_hz);
858 }
859  
860 # Return an array of PDLs, each representing a resonant frequency.
861 sub y_srf
862 {
863 my ($Y, $f_hz) = @_;
864  
865 my $X = y_reactance($Y, $f_hz);
866  
867 my ($counts, $vals) = ($X <=> 0)->rle;
868  
869 my $f_idx = 0;
870 my @ret;
871 my $nelem = $X->nelem;
872  
873 foreach my $c ($counts->dog)
874 {
875 $f_idx += $c;
876 push @ret, $f_hz->slice($f_idx-1) if $f_idx < $nelem;
877 }
878  
879 if (wantarray)
880 {
881 return @ret;
882 }
883 else
884 {
885 return $ret[0];
886 }
887 }
888  
889  
890 # srf: Self-resonating frequency.
891 #
892 # This may not be accurate. While the equation is a classic
893 # SRF calculation (1/(2*pi*sqrt(LC)), srf should scan the frequency lines as follows:
894 # "The SRF is determined to be the frequency at which the insertion (S21)
895 # phase changes from negative through zero to positive."
896 # [ https://www.coilcraft.com/getmedia/8ef1bd18-d092-40e8-a3c8-929bec6adfc9/doc363_measuringsrf.pdf ]
897 #
898 # $Y - the Y parameter matrix (N,N,M)
899 # $f_hz - a vector of frequencies (M)
900 sub y_srf_ideal
901 {
902 my ($Y, $f_hz) = @_;
903  
904 return 1/sqrt( abs 2*PI*y_inductance($Y, $f_hz)*y_capacitance($Y, $f_hz));
905 }
906  
907 # Return a parallel representation from a list of (N,N,M) Y-Parameters
908 #
909 # @yparams: a list of (N,N,M) piddles
910 #
911 # Note: each yparam must be compatible in that:
912 # 1. The number of frequencies of each must be the same
913 # 2. The frequency values must correspond because inter-frequency
914 # interpolation is _not_ performed.
915 #
916 # For example, if you have the Y parameters for two capacitors $C1_y and $C2_y
917 # at 100pF then in parallel you will get a 200pF capacitor:
918 #
919 # $C_parallel_y = y_parallel($C1_y, $C2_y);
920 # and thus:
921 # 200 == y_cap_pF($C_parallel_y)
922 sub y_parallel
923 {
924 my @yparams = @_;
925  
926 my $ret;
927 foreach my $y (@yparams)
928 {
929 if (!defined $ret)
930 {
931 $ret = $y;
932 }
933 else
934 {
935 $ret += $y;
936 }
937 }
938  
939 return $ret;
940 }
941  
942 ###############################################################################
943 # ABCD-Parameter Calculations
944  
945 # Return a series representation from a list of (N,N,M) ABCD-Parameters
946 #
947 # @abcd_params: a list of (N,N,M) piddles
948 #
949 # Note: each abcd_param must be compatible in that:
950 # 1. The number of frequencies of each must be the same
951 # 2. The frequency values must correspond because inter-frequency
952 # interpolation is _not_ performed.
953 #
954 # For example, if you have the ABCD parameters for two capacitors $C1_y and
955 # $C2_y at 100pF then in series you will get a 50pF capacitor:
956 #
957 # $C_series_abcd = abcd_series($C1_abcd, $C2_abcd);
958 # and thus:
959 # 50 == y_cap_pF($C_series_abcd)
960 sub abcd_series
961 {
962 my @abcd_params = @_;
963  
964 my $ret;
965 foreach my $abcd (@abcd_params)
966 {
967 if (!defined $ret)
968 {
969 $ret = $abcd
970 }
971 else
972 {
973 $ret = $ret x $abcd;
974 }
975 }
976  
977 return $ret;
978 }
979  
980 sub abcd_is_lossless
981 {
982 my ($ABCD, $tolerance) = @_;
983  
984 my ($A, $B, $C, $D) = m_to_pos_vecs($ABCD);
985  
986 # How small should Im/Re be to be considered zero?
987 $tolerance //= 1e-6;
988  
989 # Lossless when diagonal elements are purely Real and off-diagonal are
990 # purely imaginary: https://youtu.be/rfbvmGwN_8o
991 return (all(abs($A->im) < $tolerance) && all(abs($D->im) < $tolerance)
992 && all(abs($B->re) < $tolerance) && all(abs($C->re) < $tolerance));
993 }
994  
995 # See reference for symmetrical, reciprocal, open_circuit, short_circuit:
996 # https://resources.system-analysis.cadence.com/blog/msa2021-abcd-parameters-of-transmission-lines
997 sub abcd_is_symmetrical
998 {
999 my ($ABCD, $tolerance) = @_;
1000  
1001 my ($A, $B, $C, $D) = m_to_pos_vecs($ABCD);
1002  
1003 # How small should Im/Re be to be considered zero?
1004 $tolerance //= 1e-6;
1005  
1006 # A =~ D:
1007 return all abs($A - $D) < $tolerance;
1008 }
1009  
1010 sub abcd_is_reciprocal
1011 {
1012 my ($ABCD, $tolerance) = @_;
1013  
1014 my ($A, $B, $C, $D) = m_to_pos_vecs($ABCD);
1015  
1016 # How small should Im/Re be to be considered zero?
1017 $tolerance //= 1e-6;
1018  
1019 # AD-BC=1
1020 return all abs($ABCD->det()) < $tolerance;
1021 }
1022  
1023 sub abcd_is_open_circuit
1024 {
1025 my ($ABCD, $tolerance) = @_;
1026  
1027 my ($A, $B, $C, $D) = m_to_pos_vecs($ABCD);
1028  
1029 # How small should Im/Re be to be considered zero?
1030 $tolerance //= 1e-6;
1031  
1032 # A=C=0
1033 return (all(abs($A) < $tolerance) && all(abs($C) < $tolerance));
1034 }
1035  
1036 sub abcd_is_short_circuit
1037 {
1038 my ($ABCD, $tolerance) = @_;
1039  
1040 my ($A, $B, $C, $D) = m_to_pos_vecs($ABCD);
1041  
1042 # How small should Im/Re be to be considered zero?
1043 $tolerance //= 1e-6;
1044  
1045 # B=D=0
1046 return (all(abs($B) < $tolerance) && all abs($D) < $tolerance);
1047 }
1048  
1049 ###############################################################################
1050 # Public Helper Functions
1051  
1052 # Return the number of ports in an (N,N,M) matrix where N is the port
1053 # count and M is the number of frequencies.
1054 sub n_ports
1055 {
1056 my $m = shift;
1057  
1058 my @dims = $m->slice(':,:,0')->dims;
1059  
1060 croak "matrix must be square $m" if ($dims[0] != $dims[1]);
1061  
1062 return $dims[0];
1063 }
1064  
1065 # Given a PDL of frequencies and a N,N,M piddle of X-parameters, re-scale
1066 # and return $m based on $args.
1067 sub m_interpolate
1068 {
1069 my ($f, $m, $args) = @_;
1070  
1071 croak "caller must expect an array!" if !wantarray;
1072  
1073 my $f_new = $f;
1074 my $quiet;
1075  
1076 if (ref($args) eq 'HASH')
1077 {
1078 $quiet = $args->{quiet};
1079  
1080 if (defined $args->{freq_range})
1081 {
1082 $args = $args->{freq_range};
1083 }
1084 else
1085 {
1086 $args = "";
1087 }
1088 }
1089  
1090 # Not an elsif, the hash above could have had { range => [] } !
1091 if (ref($args) eq 'ARRAY')
1092 {
1093 $args = join(',', @$args);
1094 }
1095  
1096 # Interpolate frequency range and input data:
1097 if (ref($args) eq 'PDL')
1098 {
1099 $f_new = $args;
1100 }
1101 elsif (!ref($args) && length($args))
1102 {
1103 $f_new = [];
1104  
1105 $args =~ s/\s+//g;
1106 foreach my $set (split /,/, $args)
1107 {
1108 if ($set =~ /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/)
1109 {
1110 push @$f_new, $set;
1111 }
1112 elsif ($set =~ /^([^-]+)-([^x]+)x(\d+)$/)
1113 {
1114 my ($start, $end, $count) = ($1, $2, $3);
1115 my $range = $end - $start;
1116  
1117 if ($count <= 1)
1118 {
1119 if (abs($end - $start) < 1e-6)
1120 {
1121 push @$f_new, $start;
1122 }
1123 else
1124 {
1125 croak "Invalid element: $start-$end x$count";
1126 }
1127 }
1128 else
1129 {
1130 # Count is known to be > 1, so no div-by-zero:
1131 my $step = $range/($count-1);
1132  
1133 push @$f_new, map { $start + $step*$_ } (0 .. $count-1);
1134 }
1135 }
1136 elsif ($set =~ /^([^+]+)\+=([^x]+)x(\d+)$/)
1137 {
1138 my ($start, $step, $count) = ($1, $2, $3);
1139 push @$f_new, map { $start + $step*$_ } (0 .. $count-1);
1140 }
1141 else
1142 {
1143 croak "Invalid range specification ($args) at '$set'";
1144 }
1145  
1146 }
1147  
1148 # Sort in ascending order, just in case:
1149 $f_new = pdl(sort { $a <=> $b } @$f_new);
1150 }
1151 elsif (ref($args))
1152 {
1153 croak "\$args is invalid, ref=" . ref($args);
1154 }
1155 else
1156 {
1157 # Do nothing, just return the original values.
1158 return ($f, $m);
1159 }
1160  
1161 # At this point $f_new has frequencies to interpolate:
1162 my @cx_cols = m_to_pos_vecs($m);
1163 my @cx_cols_new;
1164 foreach my $cx (@cx_cols)
1165 {
1166 my ($cx_new, $err) = _interpolate($f_new, $f, $cx);
1167 if (!$quiet && any $err != 0)
1168 {
1169 carp "Frequency range for interpolation is below/beyond reference frequencies."
1170 }
1171 push @cx_cols_new, $cx_new;
1172 }
1173  
1174 return ($f_new, pos_vecs_to_m(@cx_cols_new));
1175 }
1176  
1177 # Return the maximum difference between an ideal uniformally-spaced frequency set
1178 # and the frequency set provided. For example:
1179 # $f = [ 1, 2, 3 , 4 ] would return 0.0
1180 # $f = [ 1, 2, 2.5, 4 ] would return 0.5
1181 sub f_uniformity
1182 {
1183 my ($f) = @_;
1184  
1185 my $f_min = $f->slice(0);
1186 my $f_max = $f->slice(-1);
1187 my $f_count = $f->nelem;
1188  
1189 my $f_step = ($f_max - $f_min) / ($f_count-1);
1190  
1191 my $f_new = sequence($f_count) * $f_step + $f_min;
1192  
1193 return max(abs($f-$f_new));
1194 }
1195  
1196 # Return true if the provided frequency set is uniform within a Hz value.
1197 # We assume $f is provided in Hz, so adjust $tolerance_hz accordingly if
1198 # $f is in a different unit.
1199 sub f_is_uniform
1200 {
1201 my ($f, $tolerance_hz) = @_;
1202  
1203 $tolerance_hz //= 1;
1204  
1205 return f_uniformity($f) < $tolerance_hz;
1206 }
1207  
1208 ###############################################################################
1209 # Private Helper Functions
1210  
1211 # Return the number of measurements in the n,n,m pdl:
1212 # This value will be equal to the number of frequencies:
1213 sub _n_meas
1214 {
1215 my $m = shift;
1216  
1217 my @dims = $m->dims;
1218  
1219 croak "matrix must be square $m" if ($dims[0] != $dims[1]);
1220 croak "matrix must have a 3rd dimension" if @dims < 3;
1221  
1222 return $dims[2];
1223 }
1224  
1225 # Converts a NxNxM pdl where M is the number of frequency samples to a
1226 # N^2-length list of M-sized vectors, each representing a row-ordered position
1227 # in the NxN matrix. ROW ORDERED!
1228 #
1229 # This enables mutiplying vector positions for things like 2-port S-to-T
1230 # conversion.
1231 #
1232 # For example:
1233 # my ($S11, $S12, $S21, $S22) = m_to_pos_vecs($S)
1234 #
1235 # $T11 = -$S->det / $S21
1236 # $T12 = ...
1237 # $T21 = ...
1238 # $T22 = ...
1239 #
1240 # @sivoais on irc.perl.org/#pdl calls these "index slices":
1241 sub m_to_pos_vecs
1242 {
1243 my $m = shift;
1244  
1245 return $m->dummy(0,1)->clump(0..2)->transpose->dog;
1246 }
1247  
1248 # inverse of m_to_pos_vecs:
1249 # $m = pos_vecs_to_m(m_to_pos_vecs($m))
1250 #
1251 # for example, re-compose $T from the above:
1252 # $T = pos_vecs_to_m($T11, $T12, $T21, $T22)
1253 sub pos_vecs_to_m
1254 {
1255 my @veclist = @_;
1256 my $n = sqrt(scalar(@veclist));
1257 my ($m) = $veclist[0]->dims;
1258  
1259 return cat(@veclist)->transpose->reshape($n,$n,$m)
1260 }
1261  
1262 # Return the position vector at (i,j).
1263 # Note that i,j start at 1 so this is the first element:
1264 # $s11 = pos_vec($S, 1, 1)
1265 sub pos_vec
1266 {
1267 my ($m, $i, $j) = @_;
1268  
1269 my $n_ports = n_ports($m);
1270  
1271 croak "position indexes (i,j) must be defined" if !defined($i) || !defined($j);
1272 croak "position indexes start at 1: i=$i j=$j" if $i < 1 || $j < 1;
1273 croak "requested position index than the matrix: i=$i > $n_ports" if ($i> $n_ports);
1274 croak "requested position index than the matrix: j=$j > $n_ports" if ($j> $n_ports);
1275  
1276 my @pos_vecs = m_to_pos_vecs($m);
1277  
1278 # Expect port numbers like (1,1) or (2,1) but perl expects indexes at 0:
1279 $i--;
1280 $j--;
1281  
1282 return $pos_vecs[$i * $n_ports + $j];
1283 }
1284  
1285 # Create a diagonal matrix of size n from a scalar or vector $v.
1286 #
1287 # For example, $v can represent charectaristic impedance at each port either as:
1288 # * a perl scalar value
1289 # * a 0-dim pdl like pdl( 5+2*i() )
1290 # * a 1-dim single-element pdl like pdl( [5+2*i()] )
1291 # * a 1-dim pdl representing the charectaristic impedance at each port
1292 #
1293 # In any case, the return value is an (N,N) pdl whith charectaristic impedances
1294 # for each port along the diagonal:
1295 # [50 0]
1296 # [ 0 50]
1297 sub _to_diagonal
1298 {
1299 my ($v, $n_ports) = @_;
1300  
1301 my $ret;
1302  
1303 $v = pdl $v if (!ref($v));
1304  
1305 croak "v must be a PDL or scalar" if (ref($v) ne 'PDL');
1306  
1307 my @dims = $v->dims;
1308  
1309 if (!@dims || (@dims == 1 && $dims[0] == 1))
1310 {
1311 $ret = zeroes($n_ports,$n_ports);
1312 $ret->diagonal(0,1) .= $v;
1313 }
1314 elsif (@dims == 1 && $dims[0] == $n_ports)
1315 {
1316 $ret = stretcher($v);
1317 }
1318 else
1319 {
1320 croak "\$v must be either a scalar or vector of size $n_ports: $v"
1321 }
1322  
1323 return $ret;
1324 }
1325  
1326 sub _interpolate
1327 {
1328 my ($xi, $x, $y) = @_;
1329  
1330 #return interpolate($xi, $x, $y);
1331  
1332 my $y_re = $y->re;
1333 my $y_im = $y->im;
1334  
1335 my ($yi_re, $err1) = interpolate($xi, $x, $y_re);
1336 my ($yi_im, $err2) = interpolate($xi, $x, $y_im);
1337  
1338 return ($yi_re+$yi_im*i(), $err1+$err2);
1339 }
1340  
1341 1;
1342  
1343 __END__
« MDIF.pm ↑ Summary