Debian Codegraph @

skrf/io/touchstone.py

raw symbols SCIP
1 """
2 .. module:: skrf.io.touchstone
3
4 ========================================
5 touchstone (:mod:`skrf.io.touchstone`)
6 ========================================
7
8 Touchstone class and utilities
9
10 .. autosummary::
11 :toctree: generated/
12
13 Touchstone
14
15 Functions related to reading/writing touchstones.
16 -------------------------------------------------
17
18 .. autosummary::
19 :toctree: generated/
20
21 hfss_touchstone_2_gamma_z0
22 hfss_touchstone_2_media
23 hfss_touchstone_2_network
24 read_zipped_touchstones
25
26 """
27 from __future__ import annotations
28
29 import os
30 import re
31 import typing
32 import warnings
33 import zipfile
34 from collections.abc import Callable
35 from dataclasses import dataclass, field
36 from functools import cached_property
37 from pathlib import Path
38 from typing import Literal
39
40 import numpy as np
41
42 from ..constants import FREQ_UNITS, S_DEF_HFSS_DEFAULT, S_DEFINITIONS, SparamFormatT
43 from ..media import DefinedGammaZ0
44 from ..network import Network
45 from ..util import get_fid
46
47
48 def remove_prefix(text: str, prefix: str) -> str:
49 if text.startswith(prefix):
50 return text[len(prefix) :]
51 return text
52
53
54 @dataclass
55 class ParserState:
56 """Class to hold dynamic variables while parsing the touchstone file.
57 """
58 rank: int | None = None
59 option_line_parsed: bool = False
60 hfss_gamma: list[list[float]] = field(default_factory=list)
61 hfss_impedance: list[list[float]] = field(default_factory=list)
62 comments: list[str] = field(default_factory=list)
63 comments_after_option_line: list[str] = field(default_factory=list)
64 matrix_format: str = "full"
65 parse_network: bool = True
66 _parse_noise: bool = False
67 f: list[float] = field(default_factory=list)
68 f_noise: list[float] = field(default_factory=list)
69 s: list[float] = field(default_factory=list)
70 noise: list[float] = field(default_factory=list)
71 two_port_order_legacy: bool = True
72 number_noise_freq: int = 0
73 port_names: dict[int, str] = field(default_factory=dict)
74 ansys_data_type: str | None = None
75 mixed_mode_order: list[str] | None = None
76 frequency_unit: str = "ghz"
77 parameter: str = "s"
78 format: str = "ma"
79 resistance: complex = complex(50)
80
81 @property
82 def n_ansys_impedance_values(self) -> int:
83 """Returns the number of port impedances returned by Ansys HFSS.
84
85 Currently this function returns rank * 2.
86
87 Returns:
88 int: number of impedance values.
89 """
90 # See https://github.com/scikit-rf/scikit-rf/issues/354 for details.
91 #if self.ansys_data_type == "terminal":
92 # return self.rank**2 * 2
93
94 return self.rank * 2
95
96 @cached_property
97 def numbers_per_line(self) -> int:
98 """Returns data points per frequency point.
99
100 Returns:
101 int: Number of data points per frequency point.
102 """
103 if self.matrix_format == "full":
104 return self.rank**2 * 2
105 return self.rank*(self.rank+1)
106
107 @property
108 def parse_noise(self) -> bool:
109 """Returns true if the parser expects noise data.
110
111 Returns:
112 bool: True, if noise data is expected.
113 """
114 return self._parse_noise
115
116 @parse_noise.setter
117 def parse_noise(self, x: bool) -> None:
118 self.parse_network = False
119 self._parse_noise = x
120
121 @property
122 def frequency_mult(self) -> float:
123 _units = {k.lower(): v for k,v in FREQ_UNITS.items()}
124 return _units[self.frequency_unit]
125
126 def parse_port(self, line: str):
127 """Regex parser for port names.
128
129 Args:
130 line (str): Touchstone line.
131 """
132 m = re.match(r"! Port\[(\d+)\]\s*=\s*(.*)$", line)
133 if m:
134 self.port_names[int(m.group(1)) - 1] = m.group(2)
135
136 def append_comment(self, line: str) -> None:
137 """Append comment, and append appropriate comment list.
138
139 Args:
140 line (str): Line to parse
141 """
142 if self.option_line_parsed:
143 self.comments_after_option_line.append(line)
144 else:
145 self.comments.append(line)
146
147 def parse_option_line(self, line: str) -> None:
148 """Parse the option line starting with #
149
150 Args:
151 line (str): Line to parse
152
153 Raises:
154 ValueError: If option line contains invalid options.
155
156 """
157 if self.option_line_parsed:
158 return
159 toks = line.lower()[1:].strip().split()
160 # fill the option line with the missing defaults
161 toks.extend(["ghz", "s", "ma", "r", "50"][len(toks) :])
162 self.frequency_unit = toks[0]
163 self.parameter = toks[1]
164 self.format = toks[2]
165 self.resistance = complex(toks[4])
166 err_msg = ""
167 if self.frequency_unit not in ["hz", "khz", "mhz", "ghz"]:
168 err_msg = f"ERROR: illegal frequency_unit {self.frequency_unit}\n"
169 if self.parameter not in "syzgh":
170 err_msg = f"ERROR: illegal parameter value {self.parameter}\n"
171 if self.format not in typing.get_args(SparamFormatT):
172 err_msg = f"ERROR: illegal format value {self.format}\n"
173
174 if err_msg:
175 raise ValueError(err_msg)
176
177 self.option_line_parsed = True
178
179
180 class Touchstone:
181 """
182 Class to read touchstone s-parameter files.
183
184 The reference for writing this class is the draft of the
185 Touchstone(R) File Format Specification Rev 2.0 [#]_ and
186 Touchstone(R) File Format Specification Version 2.0 [#]_
187
188 References
189 ----------
190 .. [#] https://ibis.org/interconnect_wip/touchstone_spec2_draft.pdf
191 .. [#] https://ibis.org/touchstone_ver2.0/touchstone_ver2_0.pdf
192 """
193
194 def __init__(self, file: str | Path | typing.TextIO, encoding: str | None = None):
195 """
196 constructor
197
198 Parameters
199 ----------
200 file : str, Path, or file-object
201 touchstone file to load
202 encoding : str, optional
203 define the file encoding to use. Default value is None,
204 meaning the encoding is guessed (ANSI, UTF-8 or Latin-1).
205
206 Examples
207 --------
208 From filename
209
210 >>> t = rf.Touchstone('network.s2p')
211
212 File encoding can be specified to help parsing the special characters:
213
214 >>> t = rf.Touchstone('network.s2p', encoding='ISO-8859-1')
215
216 From file-object
217
218 >>> file = open('network.s2p')
219 >>> t = rf.Touchstone(file)
220
221 From a io.StringIO object
222
223 >>> link = 'https://raw.githubusercontent.com/scikit-rf/scikit-rf/master/examples/
224 basic_touchstone_plotting/horn antenna.s1p'
225 >>> r = requests.get(link)
226 >>> stringio = io.StringIO(r.text)
227 >>> stringio.name = 'horn.s1p' # must be provided for the Touchstone parser
228 >>> horn = rf.Touchstone(stringio)
229
230 """
231 ## file format version.
232 # Defined by default to 1.0, since version number can be omitted in V1.0 format
233 self._version = "1.0"
234 ## comments in the file header
235 self.comments = ""
236 ## unit of the frequency (Hz, kHz, MHz, GHz)
237 self.frequency_unit = None
238 ## number of frequency points
239 self.frequency_nb = None
240 ## s-parameter type (S,Y,Z,G,H)
241 self.parameter = None
242 ## s-parameter format (MA, DB, RI)
243 self.format = None
244 ## reference resistance, global setup
245 self.resistance = None
246 ## reference impedance for each s-parameter
247 self.reference = None
248
249 ## numpy array of original noise data
250 self.noise = None
251
252 ## kind of s-parameter data (s1p, s2p, s3p, s4p)
253 self.rank = None
254 ## Store port names in a list if they exist in the file
255 self.port_names = None
256
257 self.comment_variables = None
258 # Does the input file has HFSS per frequency port impedances
259 self.has_hfss_port_impedances = False
260 self.gamma = None
261 self.z0 = None
262 self.s_def = None
263 self.port_modes = np.array([])
264
265 # open the file depending on encoding
266 # Guessing the encoding by trial-and-error, unless specified encoding
267 try:
268 try:
269 if encoding is not None:
270 fid = get_fid(file, encoding=encoding)
271 self.filename = fid.name
272 self.load_file(fid)
273 else:
274 # Assume default encoding
275 fid = get_fid(file)
276 self.filename = fid.name
277 self.load_file(fid)
278 except Exception as e:
279 fid.close()
280 raise e
281
282 except UnicodeDecodeError:
283 # Unicode fails -> Force Latin-1
284 fid = get_fid(file, encoding="ISO-8859-1")
285 self.filename = fid.name
286 self.load_file(fid)
287
288 except ValueError:
289 # Assume Microsoft UTF-8 variant encoding with BOM
290 fid = get_fid(file, encoding="utf-8-sig")
291 self.filename = fid.name
292 self.load_file(fid)
293
294 except Exception as e:
295 raise ValueError("Something went wrong by the file opening") from e
296
297 finally:
298 fid.close()
299
300 @staticmethod
301 def _parse_n_floats(*, line: str, fid: typing.TextIO, n: int, before_comment: bool) -> list[float]:
302 """Parse a specified number of floats either in our outside a comment.
303
304 Args:
305 line (str): Actual line to parse.
306 fid (typing.TextIO): File descriptor to get new lines if necessary.
307 n (int): Number of floats to parse.
308 before_comment (bool): True, if the floats should get parsed in or outside a comment.
309
310 Returns:
311 list[float]: The parsed float values
312 """
313 def get_part_of_line(line: str) -> str:
314 """Return either the part after or before a exclamation mark.
315
316 Args:
317 line (str): Line to parse.
318
319 Returns:
320 str: string subset.
321 """
322 if before_comment:
323 return line.partition("!")[0]
324 else:
325 return line.rpartition("!")[2]
326
327 values = get_part_of_line(line).split()
328 ret = []
329 while True:
330 if len(ret) == n:
331 break
332
333 if not values:
334 values = get_part_of_line(fid.readline()).split()
335 try:
336 ret.append(float(values.pop(0)))
337 except ValueError:
338 pass
339
340 return ret
341
342 @property
343 def version(self) -> str:
344 """The version string.
345
346 Returns:
347 str: Version
348 """
349 return self._version
350
351 @version.setter
352 def version(self, x: str) -> None:
353 self._version = x
354 if x == "2.0":
355 self._parse_dict.update(self._parse_dict_v2)
356
357 def _parse_file(self, fid: typing.TextIO) -> ParserState:
358 """
359 Parse the raw file and generate an structured view.
360
361 Parameters
362 ----------
363 fid : file object
364
365 Returns
366 -------
367 state: File content as ParserState
368
369 """
370 state = ParserState()
371
372 # Check the filename extension.
373 # Should be .sNp for Touchstone format V1.0, and .ts for V2
374 extension = self.filename.split(".")[-1].lower()
375
376 m = re.match(r"[ghsyz](\d+)p", extension)
377 if m:
378 state.rank = int(m.group(1))
379 elif extension != "ts":
380 for line in fid:
381 if re.search(r'^\s*\!', line) is not None:
382 continue
383
384 if not re.search(r'^\[Version\]', line):
385 msg = (f"{self.filename} does not have a s-parameter extension ({extension})."
386 "Please, correct the extension to of form: 'sNp', where N is any integer for Touchstone v1,"
387 "or make sure input file is Touchstone v2.")
388 raise ValueError(msg)
389 else:
390 fid.seek(0)
391 break
392
393 # Lookup dictionary for parser
394 # Dictionary has string keys and values contains functions which
395 # need the current line as string argument. The type hints allow
396 # the IDE to provide full typing support
397 # Take care of the order of the elements when inserting new key words.
398 self._parse_dict: dict[str, Callable[[str], None]] = {
399 "[version]": lambda x: setattr(self, "version", x.split()[1]),
400 "#": lambda x: state.parse_option_line(x),
401 "! gamma": lambda x: state.hfss_gamma.append(
402 self._parse_n_floats(line=x, fid=fid, n=state.rank * 2, before_comment=False)
403 ),
404 "! port impedance": lambda x: state.hfss_impedance.append(
405 self._parse_n_floats(
406 line=remove_prefix(x.lower(), "! port impedance"),
407 fid=fid,
408 n=state.n_ansys_impedance_values,
409 before_comment=False,
410 )
411 ),
412 "! port": state.parse_port,
413 "! terminal data exported": lambda _: setattr(state, "ansys_data_type", "terminal"),
414 "! modal data exported": lambda _: setattr(state, "ansys_data_type", "modal"),
415 "!": state.append_comment,
416 }
417
418 self._parse_dict_v2: dict[str, Callable[[str], None]] = {
419 "[number of ports]": lambda x: setattr(state, "rank", int(x.split()[3])),
420 "[reference]": lambda x: setattr(
421 state, "resistance", self._parse_n_floats(line=x, fid=fid, n=state.rank, before_comment=True)
422 ),
423 "[number of frequencies]": lambda x: setattr(self, "frequency_nb", int(x.split()[3])),
424 "[matrix format]": lambda x: setattr(state, "matrix_format", x.split()[2].lower()),
425 "[network data]": lambda _: setattr(state, "parse_network", True),
426 "[noise data]": lambda _: setattr(state, "parse_noise", True),
427 "[two-port data order]": lambda x: setattr(state, "two_port_order_legacy", "21_12" in x),
428 "[number of noise frequencies]": lambda x: setattr(
429 state, "number_noise_freq", int(x.partition("]")[2].strip())
430 ),
431 "[mixed-mode order]": lambda line: setattr(state, "mixed_mode_order", line.lower().split()[2:]),
432 "[end]": lambda x: None,
433 }
434
435 while True:
436 line = fid.readline()
437 if not line:
438 break
439
440 # some malformed Touchstone files have leading spaces, strip them,
441 # otherwise we can't identify the keywords in option lines.
442 line_l = line.strip()
443 if not line_l:
444 continue
445
446 is_data_line = True
447 # Avoid traversing the self._parse_dict for each line by checking the first letter
448 # {"!", "#", "["} covers all the first letters of the key of the current self._parse_dict
449 if line_l[0] in {"!", "#", "["}:
450 for k, v in self._parse_dict.items():
451 if line_l.lower().startswith(k):
452 v(line_l)
453 is_data_line = False
454 break
455 if is_data_line:
456 if "!" in line:
457 line = line.partition("!")[0]
458 values = list(map(float, line.split()))
459 if not values:
460 continue
461
462 if (
463 state.f
464 and len(state.s) % state.numbers_per_line == 0
465 and values[0] < state.f[-1]
466 and state.rank == 2
467 and self.version == "1.0"
468 ):
469 state.parse_noise = True
470
471 if state.parse_network:
472 if len(state.s) % state.numbers_per_line == 0:
473 state.f.append(values.pop(0))
474 state.s.extend(values)
475
476 elif state.parse_noise:
477 state.noise.append(values)
478
479 return state
480
481 def load_file(self, fid: typing.TextIO):
482 """
483 Load the touchstone file into the internal data structures.
484
485 Parameters
486 ----------
487 fid : file object
488
489 """
490
491 state = self._parse_file(fid=fid)
492
493 self.comments = "\n".join([line.strip()[1:] for line in state.comments])
494 self.comments_after_option_line = "\n".join([line.strip()[1:] for line in state.comments_after_option_line])
495 self.rank = state.rank
496 self.frequency_unit = state.frequency_unit
497 self.parameter = state.parameter
498 self.format = state.format
499 self.resistance = state.resistance
500
501 if state.port_names:
502 self.port_names = [""] * state.rank
503 for k, v in state.port_names.items():
504 self.port_names[k] = v
505
506 if state.hfss_gamma:
507 self.gamma = np.array(state.hfss_gamma).view(np.complex128)
508
509
510 # Impedance is parsed in the following order:
511 # - HFSS comments for each frequency point and each port.
512 # - TS v2 Reference keyword for each port.
513 # - Reference impedance from option line.
514 if state.hfss_impedance:
515 self.z0 = np.array(state.hfss_impedance).view(np.complex128)
516 # Comment the line in, when we need when to expect port impedances in NxN format.
517 # See https://github.com/scikit-rf/scikit-rf/issues/354 for details.
518 #if state.ansys_data_type == "terminal":
519 # self.z0 = np.diagonal(self.z0.reshape(-1, self.rank, self.rank), axis1=1, axis2=2)
520
521 self.s_def = S_DEF_HFSS_DEFAULT
522 self.has_hfss_port_impedances = True
523 # Load the reference impedance convention from the comments
524 for s_def in S_DEFINITIONS:
525 if f'S-parameter uses the {s_def} definition' in self.comments:
526 self.s_def = s_def
527 elif self.reference is None:
528 self.z0 = np.broadcast_to(self.resistance, (len(state.f), state.rank)).copy()
529 else:
530 self.z0 = np.empty((len(state.f), state.rank), dtype=complex).fill(self.reference)
531
532 self.f = np.array(state.f)
533 if not len(self.f):
534 self.s = np.empty((0, state.rank, state.rank))
535 return
536
537 raw = np.array(state.s).reshape(len(self.f), -1)
538
539 if self.format == "db":
540 raw[:, 0::2] = 10 ** (raw[:, 0::2] / 20.0)
541
542 if self.format in (["ma", "db"]):
543 s_flat = raw[:, 0::2] * np.exp(1j * raw[:, 1::2] * np.pi / 180)
544 elif self.format == "ri":
545 s_flat = raw.view(np.complex128)
546
547 self.s_flat = s_flat
548
549 self.s = np.empty((len(self.f), state.rank * state.rank), dtype=complex)
550 if state.matrix_format == "full":
551 self.s[:] = s_flat
552 else:
553 index = np.tril_indices(state.rank) if state.matrix_format == "lower" else np.triu_indices(state.rank)
554 index_flat = np.ravel_multi_index(index, (state.rank, state.rank))
555 self.s[:, index_flat] = s_flat
556
557 if state.rank == 2 and state.two_port_order_legacy:
558 self.s = np.transpose(self.s.reshape((-1, state.rank, state.rank)), axes=(0, 2, 1))
559 else:
560 self.s = self.s.reshape((-1, state.rank, state.rank))
561
562 if state.matrix_format == "upper":
563 index_lower = np.tril_indices(state.rank)
564 self.s[(...,*index_lower)] = self.s.transpose(0, 2, 1)[(...,*index_lower)]
565 elif state.matrix_format == "lower":
566 index_upper = np.triu_indices(state.rank)
567 self.s[(...,*index_upper)] = self.s.transpose(0, 2, 1)[(...,*index_upper)]
568
569 self.port_modes = np.array(["S"] * state.rank)
570 if state.mixed_mode_order:
571 new_order = [None] * state.rank
572 for i, mm in enumerate(state.mixed_mode_order):
573 if mm.startswith("s"):
574 new_order[i] = int(mm[1:]) - 1
575 else:
576 p1, p2 = sorted([int(e) - 1 for e in mm[1:].split(",")])
577
578 if mm.startswith("d"):
579 new_order[i] = p1
580 else:
581 new_order[i] = p2
582 self.port_modes[new_order[i]] = mm[0].upper()
583
584 order = np.arange(self.rank, dtype=int)
585 self.s[:, new_order, :] = self.s[:, order, :]
586 self.s[:, :, new_order] = self.s[:, :, order]
587 self.z0[:, self.port_modes == "D"] *= 2
588 self.z0[:, self.port_modes == "C"] /= 2
589
590 if self.parameter in ["g", "h", "y", "z"]:
591 if self.version == "1.0":
592 self.s = self.s * self.z0[:,:, None]
593
594 func_name = f"{self.parameter}2s"
595 from .. import network
596 self.s: np.ndarray = getattr(network, func_name)(self.s, self.z0)
597
598
599 # multiplier from the frequency unit
600 self.frequency_mult = state.frequency_mult
601
602 if state.noise:
603 self.noise = np.array(state.noise)
604 self.noise[:, 0] *= self.frequency_mult
605
606 self.f *= self.frequency_mult
607
608 @property
609 def sparameters(self) -> np.ndarray:
610 """Touchstone data in tabular format.
611
612 Returns:
613 np.ndarray: Frequency and data array.
614 """
615 warnings.warn("This method is deprecated and will be removed.", DeprecationWarning, stacklevel=2)
616 return np.hstack((self.f[:, None], self.s_flat.view(np.float64).reshape(len(self.f), -1)))
617
618 def get_comments(self, ignored_comments: list[str]=None) -> str:
619 """
620 Returns the comments which appear anywhere in the file.
621
622 Comment lines containing ignored comments are removed.
623 By default these are comments which contain special meaning within
624 skrf and are not user comments.
625
626 Returns
627 -------
628 processed_comments : string
629
630 """
631 if ignored_comments is None:
632 ignored_comments = ["Created with skrf"]
633 processed_comments = ""
634 if self.comments is None:
635 self.comments = ""
636 for comment_line in self.comments.split("\n"):
637 for ignored_comment in ignored_comments:
638 if ignored_comment in comment_line:
639 comment_line = None
640 if comment_line:
641 processed_comments = processed_comments + comment_line + "\n"
642 return processed_comments
643
644 def get_comment_variables(self) -> dict[str, str]:
645 """
646 Convert hfss variable comments to a dict of vars.
647
648 Returns
649 -------
650 var_dict : dict (numbers, units)
651 Dictionary containing the comments
652 """
653 comments = self.comments
654 p1 = re.compile(r"\w* = \w*.*")
655 p2 = re.compile(r"\s*(\d*\.?\d*)\s*(\w*)")
656 var_dict = {}
657 for k in re.findall(p1, comments):
658 try:
659 var, value = k.split("=")
660 var = var.rstrip()
661 var_dict[var] = p2.match(value).groups()
662 except ValueError:
663 pass
664 return var_dict
665
666 def get_format(self, format: Literal[SparamFormatT, Literal["orig"]]="ri") -> str:
667 """
668 Returns the file format string used for the given format.
669
670 This is useful to get some information.
671
672 Returns
673 -------
674 format : string
675
676 """
677 if format == "orig":
678 frequency = self.frequency_unit
679 format = self.format
680 else:
681 frequency = "hz"
682 return f"{frequency} {self.parameter} {format.upper()} r {self.resistance}"
683
684 def get_sparameter_names(self, format: SparamFormatT = "ri") -> list[str]:
685 """
686 Generate a list of column names for the s-parameter data.
687 The names are different for each format.
688
689 Parameters
690 ----------
691 format : str
692 Format: ri, ma, db
693
694 Returns
695 -------
696 names : list
697 list of strings
698
699 """
700 warnings.warn("This method is deprecated and will be removed.", DeprecationWarning, stacklevel=2)
701 return self.get_sparameter_data(format).keys()
702
703 def get_sparameter_data(self, format: SparamFormatT = "ri") -> dict[str, np.ndarray]:
704 """
705 Get the data of the s-parameter with the given format.
706
707 Parameters
708 ----------
709 format : str
710 Format: ri, ma, db
711
712 supported formats are:
713 ri: data in real/imaginary
714 ma: data in magnitude and angle (degree)
715 db: data in log magnitude and angle (degree)
716
717 Returns
718 -------
719 ret: list
720 list of numpy.arrays
721
722 """
723 warnings.warn("This method is deprecated and will be removed.", DeprecationWarning, stacklevel=2)
724 ret = {"frequency": self.f}
725 for j in range(self.rank):
726 for k in range(self.rank):
727 prefix = f"S{j+1}{k+1}"
728 val = self.s[:, j, k]
729 if self.rank == 2 and self.filename.split(".")[-1].lower() == "s2p":
730 prefix = f"S{k+1}{j+1}"
731 val = self.s[:, k, j]
732
733 if format == "ri":
734 ret[f"{prefix}R"] = val.real
735 ret[f"{prefix}I"] = val.imag
736 elif format == "ma":
737 ret[f"{prefix}M"] = np.abs(val)
738 ret[f"{prefix}A"] = np.angle(val, deg=True)
739 elif format == "db":
740 ret[f"{prefix}DB"] = 20 * np.log10(np.abs(val))
741 ret[f"{prefix}A"] = np.angle(val, deg=True)
742
743 return ret
744
745 def get_sparameter_arrays(self) -> tuple[np.ndarray, np.ndarray]:
746 """
747 Returns the s-parameters as a tuple of arrays.
748
749 The first element is the frequency vector (in Hz) and the s-parameters are a 3d numpy array.
750 The values of the s-parameters are complex number.
751
752 Returns
753 -------
754 param : tuple of arrays
755
756 Examples
757 --------
758 >>> f, a = self.sgetparameter_arrays()
759 >>> s11 = a[:, 0, 0]
760
761 """
762 return self.f, self.s
763
764 def get_noise_names(self):
765 raise NotImplementedError("not yet implemented")
766
767 def get_noise_data(self):
768 # TBD = 1
769 # noise_frequency = noise_values[:,0]
770 # noise_minimum_figure = noise_values[:,1]
771 # noise_source_reflection = noise_values[:,2]
772 # noise_source_phase = noise_values[:,3]
773 # noise_normalized_resistance = noise_values[:,4]
774 raise NotImplementedError("not yet implemented")
775
776 def get_gamma_z0(self):
777 """
778 Extracts Z0 and Gamma comments from touchstone file (if provided).
779
780 Returns
781 -------
782 gamma : complex np.ndarray
783 complex propagation constant
784 z0 : np.ndarray
785 complex port impedance
786 """
787 return self.gamma, self.z0
788
789
790 def hfss_touchstone_2_gamma_z0(filename: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
791 """
792 Extracts Z0 and Gamma comments from touchstone file.
793
794 Takes a HFSS-style Touchstone file with Gamma and Z0 comments and
795 extracts a triplet of arrays being: (frequency, Gamma, Z0)
796
797 Parameters
798 ----------
799 filename : string
800 the HFSS-style Touchstone file
801
802
803 Returns
804 -------
805 f : np.ndarray
806 frequency vector (in Hz)
807 gamma : complex np.ndarray
808 complex propagation constant
809 z0 : np.ndarray
810 complex port impedance
811
812 Examples
813 --------
814 >>> f,gamm,z0 = rf.hfss_touchstone_2_gamma_z0('line.s2p')
815 """
816 ntwk = Network(filename)
817
818 return ntwk.frequency.f, ntwk.gamma, ntwk.z0
819
820
821 def hfss_touchstone_2_media(filename: str) -> list[DefinedGammaZ0]:
822 """
823 Creates a :class:`~skrf.media.Media` object from a a HFSS-style Touchstone file with Gamma and Z0 comments.
824
825 Parameters
826 ----------
827 filename : string
828 the HFSS-style Touchstone file
829
830 Returns
831 -------
832 my_media : :class:`~skrf.media.media.Media` object
833 the transmission line model defined by the gamma, and z0
834 comments in the HFSS file.
835
836 Examples
837 --------
838 >>> port1_media, port2_media = rf.hfss_touchstone_2_media('line.s2p')
839
840 See Also
841 --------
842 hfss_touchstone_2_gamma_z0 : returns gamma, and z0
843 """
844 ntwk = Network(filename)
845
846 freq = ntwk.frequency
847 gamma = ntwk.gamma
848 z0 = ntwk.z0
849
850 media_list = []
851
852 for port_n in range(gamma.shape[1]):
853 media_list.append(DefinedGammaZ0(frequency=freq, gamma=gamma[:, port_n], z0=z0[:, port_n]))
854
855 return media_list
856
857
858 def hfss_touchstone_2_network(filename: str) -> Network:
859 """
860 Creates a :class:`~skrf.Network` object from a a HFSS-style Touchstone file.
861
862 Parameters
863 ----------
864 filename : string
865 the HFSS-style Touchstone file
866
867 Returns
868 -------
869 my_network : :class:`~skrf.network.Network` object
870 the n-port network model
871
872 Examples
873 --------
874 >>> my_network = rf.hfss_touchstone_2_network('DUT.s2p')
875
876 See Also
877 --------
878 hfss_touchstone_2_gamma_z0 : returns gamma, and z0
879 """
880 my_network = Network(file=filename)
881 return my_network
882
883
884 def read_zipped_touchstones(ziparchive: zipfile.ZipFile, dir: str = "") -> dict[str, Network]:
885 """
886 similar to skrf.io.read_all_networks, which works for directories but only for Touchstones in ziparchives.
887
888 Parameters
889 ----------
890 ziparchive : :class:`zipfile.ZipFile`
891 an zip archive file, containing Touchstone files and open for reading
892 dir : str
893 the directory of the ziparchive to read networks from, default is "" which reads only the root directory
894
895 Returns
896 -------
897 dict
898 keys are touchstone filenames without extensions
899 values are network objects created from the touchstone files
900 """
901 networks = dict()
902 for fname in ziparchive.namelist(): # type: str
903 directory = os.path.split(fname)[0]
904 if dir == directory and re.search(r"s\d+p$", fname.lower()):
905 network = Network.zipped_touchstone(fname, ziparchive)
906 networks[network.name] = network
907 return networks