blib/lib/PDL/IO/Touchstone.pm

filter: Statementstmt 96.3% 158 / 164 Branchbran 81.8% 54 / 66 Conditioncond 75.0% 9 / 12 MC/DCmcdc 57.1% 4 / 7 Subroutinesub 100% 14 / 14 Podpod 100% 3 / 3 totaltotal 90.9% 242 / 266 CC 42 SCAR 25.5
CC
42
Cov
91%
rsnp
18.4
wsnp_fh
18.1
_cols_to_matrix
5.0
CRAP 12.8
↑ 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 4 $VERSION = 1.001;
24  
25 4 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 4 ▶use PDL;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 4 ▶use PDL::Ops;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 4 ▶use PDL::Constants qw(PI);
Subroutine BEGIN: called CC=1 SCAR=0.0
34  
35 BEGIN {
36 4 ▶ use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 4 ▶ our @ISA = ( @ISA, qw(Exporter) );
Subroutine BEGIN: called CC=1 SCAR=0.0
38 4 our @EXPORT = qw/rsnp wsnp/;
39 }
40  
41 sub rsnp
42 {
43 53 ▶ my ($fn, $args) = @_;
Subroutine rsnp: called CC=18 SCAR=29.1
Pod documented
44  
45 53 my $class;
46 53 my $comments = '';
47 53 my ($orig_funit, $param_type, $fmt, $R, $z0);
48 53 my $n_ports;
49  
50 # Try to enforce the number of ports based on the filename extension.
51 53 ▶ $n_ports = $1 if ($fn =~ /s(\d+)p/i);
Branch: 1 branch
BranchTrueFalseTotal
if $fn =~ /s(\d+)p/i 2 51 53
52  
53 53 ▶ open(my $in, $fn) or croak "$fn: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $in, $fn or croak("${fn}: $!") 0 53 53
54  
55 53 my $n = 0;
56 53 my $line;
57  
58 my $hz;
59  
60 # start at -1 because it increments when a frequency is found.
61 53 my $row_idx = -1;
62 53 my $col_idx = 0;
63 53 my @comments;
64 my @cols;
65 53 my @f;
66 53 ▶ while (defined($line = <$in>))
Branch: 1 branch
BranchTrueFalseTotal
if (defined($line = readline $in)) 4601 53 4654
67 {
68 4601 chomp($line);
69 4601 $n++;
70  
71 4601 $line =~ s/^\s+|\s+$//g;
72  
73 4601 ▶ next if !length($line);
Branch: 1 branch
BranchTrueFalseTotal
unless length $line 1 4600 4601
74  
75 # Strip leading space so split() will work properly.
76 4600 $line =~ s/^\s+//;
77  
78 4600 ▶ if ($line =~ /^!/)
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^!/) 200 4400 4600
79 {
80 200 push @comments, $line;
81 200 next;
82 }
83  
84 # Strip any inline comments:
85 4400 $line =~ s/!.*$//;
86  
87 4400 ▶ if ($line =~ s/^#\s*//)
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ s/^#\s*//) 53 4347 4400
88 {
89 53 ($orig_funit, $param_type, $fmt, $R, $z0) = split /\s+/, $line;
90  
91 53 $param_type = uc($param_type);
92 53 ▶ if ($param_type !~ /^[SYZTAGH]$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($param_type =~ /^[SYZTAGH]$/) 0 53 53
93 0 croak "$fn:$n: $param_type-parameter type is not implemented.";
94 }
95  
96 53 ▶ croak "$fn:$n: expected 'R' before z0, but found: $R" if $R ne 'R';
Branch: 1 branch
BranchTrueFalseTotal
if $R ne "R" 0 53 53
97 53 next;
98 }
99  
100 4347 ▶ if ($line !~ /^[0-9.+-]/)
Branch: 1 branch
BranchTrueFalseTotal
unless ($line =~ /^[0-9.+-]/) 0 4347 4347
101 {
102 0 die "$fn:$n: unexpected line $n: $line\n";
103 0 next;
104 }
105  
106 4347 my @params = split(/\s+/, $line);
107  
108 # If the line has an odd number of elements then the first is the frequency
109 # because data lines are always in pairs:
110 4347 ▶ if (scalar(@params) % 2)
Branch: 1 branch
BranchTrueFalseTotal
if (scalar(@params) % 2) 611 3736 4347
111 {
112 611 $row_idx++;
113  
114 611 ▶ if ($row_idx > 0)
Branch: 1 branch
BranchTrueFalseTotal
if ($row_idx > 0) 558 53 611
115 {
116 # We want the possibly multi-line row that was
117 # just completed, not the new one that was just
118 # read in. $col_idx currently holds the number
119 # of columns from the previous frequency.
120 558 my $sqrt_n_params = sqrt($col_idx);
121 558 ▶ if (!defined($n_ports))
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $n_ports) 51 507 558
122 {
123 51 $n_ports = $sqrt_n_params;
124 }
125  
126 558 ▶ if ($sqrt_n_params != $n_ports)
Branch: 1 branch
BranchTrueFalseTotal
if ($sqrt_n_params != $n_ports) 0 558 558
127 {
128 0 croak "$fn:$n: expected $n_ports fields of port data but found $sqrt_n_params: $n_ports != $sqrt_n_params";
129 }
130 }
131  
132 611 $hz = shift(@params);
133 611 $f[$row_idx] = $hz;
134 611 $col_idx=0;
135 }
136  
137 4347 my @params_cx;
138  
139 4347 ▶ for (my $i = 0; $i < @params; $i += 2)
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @params) 14649 4347 18996
140 {
141 # The data format could be ri, ma, or db but there is
142 # always a pair of data. Please each in its own array
143 # and we will convert the format below.
144 14649 push @{ $cols[$col_idx]->[0] }, $params[$i];
145 14649 push @{ $cols[$col_idx]->[1] }, $params[$i+1];
146  
147 14649 $col_idx++;
148 }
149  
150 }
151  
152 # The 2-port versions need to be turned into a row-major format.
153 # All other port counts _are_ row-major (including the 1-port, I
154 # suppose).
155 53 ▶ if (@cols == 4)
Branch: 1 branch
BranchTrueFalseTotal
if (@cols == 4) 11 42 53
156 {
157 11 my $t = $cols[2];
158 11 $cols[2] = $cols[1];
159 11 $cols[1] = $t;
160 }
161  
162 53 foreach my $c (@cols)
163 {
164 1432 $c->[0] = pdl $c->[0];
165 1432 $c->[1] = pdl $c->[1];
166 }
167  
168 53 my $m = _cols_to_matrix($fmt, \@cols);
169  
170 53 my $f = pdl \@f;
171  
172 53 my $funit;
173 53 ▶ if ($args->{units})
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{'units'}) { } 0 53 53
174 {
175 0 $funit = $args->{units};
176 }
177 else
178 {
179 53 $funit = 'Hz'
180 }
181  
182 53 $f = _si_scale_hz($orig_funit, $funit, $f);
183 53 return ($f, $m, $param_type, $z0, $comments, $fmt, $funit, $orig_funit);
184 }
185  
186 sub wsnp
187 {
188 50 ▶ my @opts = @_;
Subroutine wsnp: called CC=3 SCAR=11.2
Pod documented
189 50 my $fn = shift(@opts);
190  
191 50 ▶ croak "filename must be defined" if !defined $fn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fn 0 50 50
192  
193 50 ▶ open(my $out, '>', $fn) or croak "$fn: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $out, ">", $fn or croak("${fn}: $!") 0 50 50
194  
195 50 my $ret = wsnp_fh($out, @opts);
196  
197 50 close($out);
198  
199 50 return $ret;
200 }
201  
202 sub wsnp_fh
203 {
204 50 ▶ my ($fd, $f, $m, $param_type, $z0, $comments, $fmt, $from_hz, $to_hz) = @_;
Subroutine wsnp_fh: called CC=18 SCAR=29.0
Pod documented
205  
206 50 my ($n_ports) = $m->index(0)->dims;
207 50 my $n_freqs = $f->nelem;
208  
209 # Assume $f frequencies are in Hz if from_hz is not defined
210 # and always default writing in MHz if the user does not specify.
211 # This is consistent with rsnp() and common industry practice:
212 50 ▶ $from_hz //= 'Hz';
Condition100%2/2
$from_hz //= "Hz"
l!l
545
MC/DC100%1/1
$from_hz //= "Hz"
$from_hz
Truth table100%2/2
A
A= $from_hz
Aresult
11
00
213 50 ▶ $to_hz //= 'MHz';
Condition100%2/2
$to_hz //= "MHz"
l!l
545
MC/DC100%1/1
$to_hz //= "MHz"
$to_hz
Truth table100%2/2
A
A= $to_hz
Aresult
11
00
214  
215 50 $fmt = lc $fmt;
216  
217 # 2-port matrixes are column-major:
218 50 ▶ $m = $m->transpose if ($n_ports == 2);
Branch: 1 branch
BranchTrueFalseTotal
if $n_ports == 2 9 41 50
219  
220 # Big thanks to mohawk and sivoais for helping figure out the reshape here.
221 # $d is arranged so real and imag parts can be separated into their own
222 # columns with clump() for writing to the sNp file:
223 50 my $d = $m->dummy(0,1);
224 50 ▶ if ($fmt eq 'ri')
Branch: 3 branches
BranchTrueFalseTotal
if ($fmt eq 'ri') { } 20 30 50
elsif ($fmt eq 'ma') { } 15 15 30
elsif ($fmt eq 'db') { } 15 0 15
225 {
226 20 $a = $d->re;
227 20 $b = $d->im;
228 }
229 elsif ($fmt eq 'ma')
230 {
231 15 $a = $d->abs;
232 15 $b = $d->carg * 180 / PI;
233 }
234 elsif ($fmt eq 'db')
235 {
236 15 $a = 20*log($d->abs)/log(10);
237 15 $b = $d->carg * 180 / PI;
238 }
239  
240 # Prepare real/imag values for interleaving:
241 50 my $ab = $a->append($b);
242  
243 # Create one row per frequency: (n_ports*2, n_freqs):
244 50 my $out = $ab->clump(0..2);
245  
246 # Scale the input/output frequency:
247 50 $f = _si_scale_hz($from_hz, $to_hz, $f);
248  
249 # Fix capitalization to meet Touchstone spec:
250 50 $param_type = uc($param_type); # S, Y, Z, T, G, H, A
251 50 $fmt = uc($fmt); # RI, MA, DB
252 50 ▶ $to_hz =~ s!^([kmgtpe]?)hz$!uc($1 // '') . "Hz"!ie;
Condition50%1/2
$1 // ""
l!l
500
MC/DC0%0/1
$1 // ""
$1
Truth table50%1/2
A
A= $1
Aresult
11
00
253  
254 # Format header and comments:
255 50 ▶ print $fd join("\n", map { "! $_" } @$comments) . "\n" if ($comments && @$comments);
Branch: 1 branch
BranchTrueFalseTotal
if $comments and @$comments 50 0 50
Condition33%1/3
$comments and @$comments
!ll&&!rl&&r
0050
MC/DC0%0/2
$comments and @$comments
$comments @$comments
Truth table33%1/3
A and B
A= $commentsB= @$comments
ABresult
0X0
100
111
256 50 print $fd "# $to_hz $param_type $fmt R $z0\n";
257  
258 # $out is in touchstone-formated order for each frequency with frequency as the first element:
259 # ie: [freq s11 21 s12 s11] < transposed for only for 2-port models.
260
261 50 ▶ for (my $i = 0; $i < $n_freqs; $i++)
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n_freqs) 500 50 550
262 {
263 # matrix at frequency $i:
264 500 my $fm = $out->slice(":,$i");
265 500 my $freq = $f->slice("$i")->sclr;
266  
267 # More than 2 ports are printed on multiple lines,
268 # at least one line for each port.
269 500 ▶ if ($n_ports > 2)
Branch: 1 branch
BranchTrueFalseTotal
if ($n_ports > 2) 320 180 500
270 {
271 320 $fm = $fm->reshape($n_ports*2,$n_ports);
272 }
273  
274 500 print $fd $freq;
275  
276 # foreach matrix row:
277 500 foreach my $row ($fm->dog)
278 {
279 # No more than four data samples are allowed per line,
280 # so 4 RI pairs max. If there are 3 or 4 ports then
281 # break at the port count so the matrix is visible in
282 # the file. Iterate over the data in the row and put
283 # line breaks in the appropriate place:
284 2060 my @data = $row->dog;
285 2060 ▶ while (@data)
Branch: 1 branch
BranchTrueFalseTotal
if (@data) 4210 2060 6270
286 {
287 4210 my $count = @data;
288 4210 ▶ $count = $n_ports * 2 if $count > $n_ports * 2;
Branch: 1 branch
BranchTrueFalseTotal
if $count > $n_ports * 2 90 4120 4210
289 4210 ▶ $count = 8 if $count > 8 || $n_ports == 2;
Branch: 1 branch
BranchTrueFalseTotal
if $count > 8 or $n_ports == 2 2240 1970 4210
Condition100%3/3
$count > 8 or $n_ports == 2
l!l&&r!l&&!r
2150901970
MC/DC100%2/2
$count > 8 or $n_ports == 2
$count > 8 $n_ports == 2
Truth table100%3/3
A or B
A= $count > 8B= $n_ports == 2
ABresult
1X1
011
000
290  
291 4210 my @line;
292 4210 ▶ push @line, shift @data while ($count--);
Branch: 1 branch
BranchTrueFalseTotal
$count-- and do { push @line, shift @data } 28300 4210 32510
293  
294 4210 print $fd "\t" . join("\t", @line) . "\n";
295 }
296  
297 }
298 }
299  
300 # we don't close the file descriptor here, the caller (or `wsnp`) will.
301 }
302  
303 # https://physics.stackexchange.com/questions/398988/converting-magnitude-ratio-to-complex-form
304 sub _cols_to_matrix
305 {
306 53 ▶ my ($fmt, $cols) = @_;
Subroutine _cols_to_matrix: called CC=5 SCAR=16.1
307  
308 53 $fmt = lc $fmt;
309 53 my @cx;
310 53 my $n = $cols->[0][0]->nelem;
311 53 my $n_ports = sqrt(scalar @$cols);
312  
313 53 foreach my $c (@$cols)
314 {
315 1432 my $a = $c->[0];
316 1432 my $b = $c->[1];
317 1432 ▶ if ($fmt eq 'ri')
Branch: 3 branches
BranchTrueFalseTotal
if ($fmt eq 'ri') { } 635 797 1432
elsif ($fmt eq 'ma') { } 390 407 797
elsif ($fmt eq 'db') { } 407 0 407
318 {
319 635 push @cx, $a + $b*i();
320 }
321 elsif ($fmt eq 'ma')
322 {
323 390 push @cx, $a*exp(i()*$b*PI()/180);
324 }
325 elsif ($fmt eq 'db')
326 {
327 407 my $a = 10**($a/20);
328 407 push @cx, $a*exp(i()*$b*PI()/180);
329 }
330 else
331 {
332 0 croak "Unknown s-parameter format: $fmt";
333 }
334 }
335  
336 53 my $m = pdl \@cx;
337 53 $m = $m->mv(0, -1)->reshape($n_ports,$n_ports,$n);
338 }
339  
340 sub _si_scale_hz
341 {
342 103 ▶ my ($from, $to, $n) = @_;
Subroutine _si_scale_hz: called CC=2 SCAR=7.0
343  
344 103 my %scale =
345 (
346 hz => 1,
347 khz => 1e3,
348 mhz => 1e6,
349 ghz => 1e9,
350 thz => 1e12,
351 );
352  
353 103 $from = $scale{lc($from)};
354 103 $to = $scale{lc($to)};
355  
356 103 my $fscale = $from/$to;
357  
358 103 ▶ croak "Unknown frequency scale: $fscale" if !$fscale;
Branch: 1 branch
BranchTrueFalseTotal
unless $fscale 0 103 103
359  
360 103 return $n*$fscale;
361 }
362  
363 4 1;
364  
365 __END__
↑ Summary