API Reference¶
This page provides auto-generated documentation for the full public API of
touchstone.parser, built directly from the source code docstrings.
Main Package¶
Main package for parsing Touchstone (.sNp) files and analyzing S-parameters.
The touchstone.parser package is the primary public API surface. It
re-exports all important classes, functions, and enumerations so that
users can import directly from touchstone.parser:
from touchstone.parser import TouchstoneParser, TouchstoneData
from touchstone.parser import db_to_mag, normalize_frequency
- Classes:
TouchstoneParser: Static methods for parsing files, strings, and streams. TouchstoneData: The main container for parsed Touchstone data. TouchstoneOptions: Option line configuration (frequency unit, format, etc.). FrequencyUnit: Enumeration of supported frequency units. ParameterType: Enumeration of supported parameter types (S, Y, Z, G, H). DataFormat: Enumeration of supported data formats (RI, MA, DB). TouchstoneParserException: Exception raised for parse errors.
- Functions:
read_snp: Alias for
TouchstoneParser.parse(). parse_string: Alias forTouchstoneParser.parse_string(). write_snp: Write data to a Touchstone file. write_snp_to_string: Convert data to a Touchstone format string. normalize_frequency: Convert a frequency value to Hz. db_to_mag: Convert dB to linear magnitude. mag_to_db: Convert linear magnitude to dB. deg_to_rad: Convert degrees to radians. rad_to_deg: Convert radians to degrees. ma_to_complex: Convert magnitude/angle to complex. db_to_complex: Convert dB/angle to complex. ri_to_complex: Convert real/imaginary to complex.
Models¶
TouchstoneData¶
Data model for Touchstone parsed data.
This module contains the TouchstoneData dataclass, the primary
container for all data parsed from a Touchstone (.sNp) file. It holds
frequency arrays, S-parameter matrices, option line configuration,
comments, and metadata.
- class touchstone.parser.models.touchstone_data.TouchstoneData[source]¶
Bases:
objectStructured object representing parsed Touchstone (.sNp) data.
This is the main output of
TouchstoneParser.parse()andTouchstoneParser.parse_string(). It is an immutable (frozen) dataclass that provides rich access to the underlying data.- frequency¶
1-D NumPy array of frequency values in Hz.
- Type:
- s_parameters¶
3-D complex NumPy array of shape
(n_freq, n_ports, n_ports).- Type:
- options¶
The parsed option line configuration.
Example
>>> data = TouchstoneParser.parse("filter.s2p") >>> data.n_ports 2 >>> data.n_freq 201 >>> s21 = data.get_s(2, 1)
- options: TouchstoneOptions¶
- property z0: float¶
Reference impedance of the network in ohms.
- Returns:
The reference impedance from the option line.
- Return type:
- property unit: str¶
Frequency unit string (e.g.
'Hz','GHz').- Returns:
The frequency unit value from the option line.
- Return type:
- property parameter: str¶
Network parameter type string (e.g.
'S','Y').- Returns:
The parameter type value from the option line.
- Return type:
- property format: str¶
Data format string (e.g.
'MA','RI').- Returns:
The data format value from the option line.
- Return type:
- property n_ports: int¶
Number of ports in the network.
- Returns:
The number of ports, derived from the S-parameter matrix shape.
- Return type:
- property n_freq: int¶
Number of frequency points in the dataset.
- Returns:
The length of the frequency array.
- Return type:
- property frequencies: ndarray¶
Alias for
frequency(compatibility with .NET API).- Returns:
The frequency array in Hz.
- Return type:
- property count: int¶
Alias for
n_freq(compatibility with .NET API).- Returns:
The number of frequency points.
- Return type:
- __post_init__()[source]¶
Validate the data after initialization.
- Raises:
ValueError – If any of the required fields are
None, if the number of ports is less than 1, or if the frequency and S-parameter array lengths do not match.
- get_s(to_port, from_port)[source]¶
Get a specific S-parameter array across all frequencies.
Extracts the complex-valued parameter
S[to_port, from_port]for every frequency point.- Parameters:
- Returns:
1-D complex array of length
n_freq.- Return type:
- Raises:
IndexError – If port indices are out of range
[1, n_ports].
Example
>>> s21 = data.get_s(to_port=2, from_port=1)
- __getitem__(index)[source]¶
Access the
FrequencyPointat the given index.- Parameters:
index (int) – Zero-based index into the frequency array.
- Returns:
The frequency point containing the frequency value and the N × N S-parameter matrix at that index.
- Return type:
- get_parameter(row, col)[source]¶
Iterate over (frequency, NetworkParameter) pairs for a specific matrix entry.
- Parameters:
- Yields:
tuple – A 2-tuple of
(frequency_hz, NetworkParameter)for each frequency point.- Raises:
IndexError – If row or col is out of range
[1, n_ports].- Return type:
- where(predicate)[source]¶
Filter the data using a predicate function.
Creates a new
TouchstoneDatacontaining only the frequency points for which the predicate returnsTrue.- Parameters:
predicate (Callable[[FrequencyPoint], bool]) – A callable that takes a
FrequencyPointand returnsTrueto keep it.- Returns:
A new filtered instance.
- Return type:
Example
>>> import numpy as np >>> filtered = data.where(lambda pt: np.abs(pt[0, 0].value) < 0.5)
- to_insertion_loss()[source]¶
Calculate insertion loss from S21.
Insertion loss is computed as
-|S21|in dB (positive values indicate loss).- Returns:
Array of insertion loss values in dB.
- Return type:
- Raises:
ValueError – If the network has fewer than 2 ports.
- to_return_loss()[source]¶
Calculate return loss from S11.
Return loss is computed as
-|S11|in dB (positive values indicate better matching).- Returns:
Array of return loss values in dB.
- Return type:
- to_vswr()[source]¶
Calculate VSWR (Voltage Standing Wave Ratio) from S11.
VSWR is computed as
(1 + |S11|) / (1 - |S11|).- Returns:
Array of VSWR values (dimensionless, ≥ 1.0).
- Return type:
- in_frequency_range(min_hz, max_hz)[source]¶
Filter the data to a specific frequency range.
- Parameters:
- Returns:
A new instance containing only the points within the specified range.
- Return type:
Example
>>> passband = data.in_frequency_range(2.0e9, 3.0e9)
- to_csv_string(format=None, unit=None)[source]¶
Export the data to a CSV formatted string.
- Parameters:
format (DataFormat | None) – Optional
DataFormatto override the default. IfNone, uses the format fromoptions.unit (FrequencyUnit | None) – Optional
FrequencyUnitto override the default. IfNone, uses the unit fromoptions.
- Returns:
The CSV string representation of the data.
- Return type:
- to_csv(writer, format=None, unit=None)[source]¶
Write the data to a CSV file-like object or filepath.
- Parameters:
writer (Any) – A file path (
str) or a writable file-like object.format (DataFormat | None) – Optional
DataFormatto override the default.unit (FrequencyUnit | None) – Optional
FrequencyUnitto override the default.
- Return type:
None
TouchstoneOptions¶
Data classes representing options parsed from Touchstone files.
The option line (beginning with #) in a Touchstone file specifies the
frequency unit, parameter type, data format, and reference impedance.
This module defines the TouchstoneOptions dataclass to hold
those parsed values.
- class touchstone.parser.models.touchstone_options.TouchstoneOptions[source]¶
Bases:
objectRepresents the option line configuration parsed from a Touchstone file.
A Touchstone option line has the form:
# <frequency_unit> <parameter_type> <data_format> R <impedance>For example:
# GHz S MA R 50- frequency_unit¶
The frequency unit for data points. Defaults to
GHZ.
- parameter_type¶
The network parameter type. Defaults to
S.
- data_format¶
The data format for parameter values. Defaults to
MA.
- frequency_unit: FrequencyUnit = 'GHz'¶
- parameter_type: ParameterType = 'S'¶
- data_format: DataFormat = 'MA'¶
- __str__()[source]¶
Return the option line string representation.
- Returns:
A string formatted as a Touchstone option line, e.g.
# GHZ S MA R 50.0.- Return type:
- classmethod default()[source]¶
Create a TouchstoneOptions instance with default values.
- Returns:
Default options (GHz, S, MA, 50 Ω).
- Return type:
- __init__(frequency_unit=FrequencyUnit.GHZ, parameter_type=ParameterType.S, data_format=DataFormat.MA, reference_impedance=50.0)¶
- Parameters:
frequency_unit (FrequencyUnit)
parameter_type (ParameterType)
data_format (DataFormat)
reference_impedance (float)
- Return type:
None
NetworkParameter¶
NetworkParameter class representing a single complex S-parameter.
This module defines the NetworkParameter dataclass, which wraps
a single complex number and provides convenient access to its magnitude,
phase, and dB representation. It also supports arithmetic operations and
factory methods for creating parameters from different formats.
- class touchstone.parser.models.network_parameter.NetworkParameter[source]¶
Bases:
objectA single network parameter (e.g., S11) represented as a complex number.
This immutable dataclass provides rich access to the underlying complex value, including magnitude (linear and dB), phase (radians and degrees), real/imaginary decomposition, and arithmetic operators.
Example
>>> param = NetworkParameter(complex(0.5, -0.3)) >>> param.magnitude_db -4.86... >>> param.phase_degrees -30.96...
- property real: float¶
The real component of the parameter.
- Returns:
The real part of the complex value.
- Return type:
- property imaginary: float¶
The imaginary component of the parameter.
- Returns:
The imaginary part of the complex value.
- Return type:
- property magnitude: float¶
The linear magnitude (absolute value) of the parameter.
- Returns:
|value|, always non-negative.- Return type:
- property magnitude_db: float¶
The magnitude of the parameter in decibels (dB).
Computed as
20 * log10(|value|).- Returns:
Magnitude in dB. Returns
-infif magnitude is zero.- Return type:
- property phase_radians: float¶
The phase angle in radians.
- Returns:
Phase angle in the range
(-π, π].- Return type:
- property phase_degrees: float¶
The phase angle in degrees.
- Returns:
Phase angle in the range
(-180, 180].- Return type:
- classmethod from_real_imaginary(real, imaginary)[source]¶
Create a NetworkParameter from real and imaginary parts.
- Parameters:
- Returns:
A new instance with
value = real + j*imaginary.- Return type:
- classmethod from_magnitude_angle(magnitude, angle_degrees)[source]¶
Create a NetworkParameter from linear magnitude and angle.
- Parameters:
- Returns:
A new instance created via polar-to-rectangular conversion.
- Return type:
- classmethod from_decibel_angle(magnitude_db, angle_degrees)[source]¶
Create a NetworkParameter from magnitude in dB and angle.
First converts dB to linear magnitude, then delegates to
from_magnitude_angle().- Parameters:
- Returns:
A new instance.
- Return type:
- conjugate()[source]¶
Return the complex conjugate of this parameter.
- Returns:
A new instance with the conjugated value.
- Return type:
- reciprocal()[source]¶
Return the reciprocal (
1 / value) of this parameter.- Returns:
A new instance with the reciprocal value.
- Return type:
- Raises:
ZeroDivisionError – If the value is zero.
- __add__(other)[source]¶
Add two parameters or a parameter and a scalar.
- Parameters:
other (NetworkParameter | complex | float | int) – Another
NetworkParameter, complex, float, or int.- Returns:
The sum as a new instance.
- Return type:
- __sub__(other)[source]¶
Subtract a parameter or scalar from this parameter.
- Parameters:
other (NetworkParameter | complex | float | int) – Another
NetworkParameter, complex, float, or int.- Returns:
The difference as a new instance.
- Return type:
- __mul__(other)[source]¶
Multiply this parameter by another parameter or scalar.
- Parameters:
other (NetworkParameter | complex | float | int) – Another
NetworkParameter, complex, float, or int.- Returns:
The product as a new instance.
- Return type:
- __truediv__(other)[source]¶
Divide this parameter by another parameter or scalar.
- Parameters:
other (NetworkParameter | complex | float | int) – Another
NetworkParameter, complex, float, or int.- Returns:
The quotient as a new instance.
- Return type:
- approximately_equals(other, tolerance=1e-09)[source]¶
Check if two parameters are approximately equal.
- Parameters:
other (NetworkParameter) – The other
NetworkParameterto compare.tolerance (float) – The maximum allowed absolute difference. Defaults to
1e-9.
- Returns:
Trueif|self.value - other.value| <= tolerance.- Return type:
- __eq__(other)[source]¶
Check exact equality with another NetworkParameter.
- Parameters:
other (Any) – The object to compare.
- Returns:
Trueif other is aNetworkParameterwith an identical complex value.- Return type:
FrequencyPoint¶
FrequencyPoint class representing a single frequency point and its S-parameters.
A FrequencyPoint encapsulates one row of a Touchstone dataset —
a single frequency value together with its N × N matrix of complex
network parameters.
- class touchstone.parser.models.frequency_point.FrequencyPoint[source]¶
Bases:
objectEncapsulates a single frequency point and its N × N matrix of network parameters.
- _s_parameters¶
The N × N complex NumPy array of S-parameters at this frequency.
- Type:
- Raises:
ValueError – If the frequency is negative or the S-parameter array is not a square matrix.
Example
>>> point = data[0] # first frequency point >>> point.frequency_hz 1000000000.0 >>> point.number_of_ports 2 >>> s11 = point[0, 0]
- __post_init__()[source]¶
Validate inputs after initialization.
- Raises:
ValueError – If frequency is negative or S-parameters are not a square matrix.
- property number_of_ports: int¶
The number of ports (N for an N × N matrix).
- Returns:
The dimension of the S-parameter matrix.
- Return type:
- get_parameter_matrix()[source]¶
Get a defensive copy of the complex S-parameter matrix.
Returns a copy so that external code cannot mutate the internal state of this frozen dataclass.
- Returns:
An N × N complex array.
- Return type:
- __getitem__(indices)[source]¶
Access a specific network parameter by
[row, col]index.- Parameters:
indices (tuple[int, int]) – A tuple of
(row, col)indices, 0-indexed.- Returns:
The network parameter at the specified index.
- Return type:
- Raises:
IndexError – If indices are not a 2-tuple or are out of range.
- __str__()[source]¶
Return a human-readable string representation.
- Returns:
A string showing the frequency and port count.
- Return type:
Enumerations¶
Data formats supported by Touchstone files.
Touchstone files can represent network parameter data in three different
numerical formats. This module defines the DataFormat enumeration
used to distinguish between them.
- class touchstone.parser.models.data_format.DataFormat[source]¶
Bases:
EnumEnum representing the data format of the network parameters.
Each Touchstone file specifies how parameter values are encoded in its option line. The three supported formats are:
- RI¶
Real/Imaginary — parameters stored as
(real, imaginary)pairs.
- MA¶
Magnitude/Angle — parameters stored as
(linear_magnitude, angle_degrees)pairs.
- DB¶
Decibel/Angle — parameters stored as
(magnitude_dB, angle_degrees)pairs.
- RI = 'RI'¶
- MA = 'MA'¶
- DB = 'DB'¶
Frequency units supported by Touchstone files.
The option line of a Touchstone file specifies the frequency unit used
for all data points. This module defines the FrequencyUnit
enumeration for the four supported units.
- class touchstone.parser.models.frequency_unit.FrequencyUnit[source]¶
Bases:
EnumEnum representing the frequency unit used in a Touchstone file.
The frequency unit determines how raw frequency values in the data section are interpreted. All values are internally normalized to Hz during parsing.
- HZ¶
Hertz (1 Hz).
- KHZ¶
Kilohertz (1 × 10³ Hz).
- MHZ¶
Megahertz (1 × 10⁶ Hz).
- GHZ¶
Gigahertz (1 × 10⁹ Hz).
- HZ = 'Hz'¶
- KHZ = 'kHz'¶
- MHZ = 'MHz'¶
- GHZ = 'GHz'¶
Network parameter types supported by Touchstone files.
Touchstone files can contain different types of network parameters.
This module defines the ParameterType enumeration for the
five standard types specified in the Touchstone format.
- class touchstone.parser.models.parameter_type.ParameterType[source]¶
Bases:
EnumEnum representing the network parameter type.
The parameter type is specified on the option line and determines how the data values are interpreted.
- S¶
Scattering parameters (S-parameters).
- Y¶
Admittance parameters (Y-parameters).
- Z¶
Impedance parameters (Z-parameters).
- G¶
Hybrid-G parameters.
- H¶
Hybrid-H parameters.
- S = 'S'¶
- Y = 'Y'¶
- Z = 'Z'¶
- G = 'G'¶
- H = 'H'¶
Parsing¶
TouchstoneParser¶
Core Touchstone file parser.
This module contains the TouchstoneParser class, which provides
static methods for reading Touchstone (.sNp) files from disk, strings,
or streams and converting them into TouchstoneData objects.
- class touchstone.parser.parsing.touchstone_parser.TouchstoneParser[source]¶
Bases:
objectParser for reading Touchstone (.sNp) files into structured data.
All methods are static — there is no need to instantiate this class.
Example
>>> data = TouchstoneParser.parse("filter.s2p") >>> data.n_ports 2
- static detect_port_count(filename)[source]¶
Detect the number of ports from the filename extension.
Parses the
.sNpextension to extract the port countN.- Parameters:
filename (str) – The name of the file (e.g.
'filter.s2p').- Returns:
The detected number of ports.
- Return type:
- Raises:
TouchstoneParserException – If the extension does not match the
.sNppattern.ValueError – If the filename is null or empty.
Example
>>> TouchstoneParser.detect_port_count("amp.s4p") 4
- static parse(filepath)[source]¶
Parse a Touchstone file from disk.
The port count is auto-detected from the file extension.
- Parameters:
filepath (str) – Absolute or relative path to the
.sNpfile.- Returns:
The fully parsed data.
- Return type:
- Raises:
TouchstoneParserException – If the file extension is invalid.
ValueError – If filepath is empty.
FileNotFoundError – If the file does not exist.
Example
>>> data = TouchstoneParser.parse("filter.s2p")
- static parse_string(content, n_ports=0, filename=None)[source]¶
Parse Touchstone data from a string.
- Parameters:
- Returns:
The parsed data.
- Return type:
Example
>>> data = TouchstoneParser.parse_string(raw_text, n_ports=2)
- static parse_stream(stream, filename=None)[source]¶
Parse Touchstone data from a text stream.
If a filename is provided, the port count is detected from its extension. Otherwise, it is auto-detected from the data.
- Parameters:
- Returns:
The parsed data.
- Return type:
Example
>>> import io >>> stream = io.StringIO(raw_text) >>> data = TouchstoneParser.parse_stream(stream, filename="test.s2p")
- async static parse_async(filepath)[source]¶
Asynchronously parse a Touchstone file from disk.
Delegates to
parse()in a background thread usingasyncio.to_thread().- Parameters:
filepath (str) – Path to the
.sNpfile.- Returns:
The parsed data.
- Return type:
Example
>>> data = await TouchstoneParser.parse_async("filter.s2p")
TouchstoneParserException¶
Custom exceptions for the Touchstone parser.
This module defines TouchstoneParserException, raised when the
parser encounters invalid or unexpected content in a Touchstone file.
- exception touchstone.parser.parsing.touchstone_parser_exception.TouchstoneParserException[source]¶
Bases:
ExceptionException raised for errors during Touchstone file parsing.
When a line number is provided, it is appended to the error message for easier debugging.
- line_number¶
The 1-based line number where the error occurred, or
Noneif not applicable.
- Parameters:
message – A human-readable description of the error.
line_number – Optional 1-based line number where the error occurred.
Example
>>> raise TouchstoneParserException("Invalid value", line_number=42) TouchstoneParserException: Invalid value (Line 42)
OptionLineParser¶
Parser for the option line in Touchstone files.
The option line starts with # and specifies the frequency unit,
parameter type, data format, and reference impedance. This module
provides the OptionLineParser class with a static
parse() method.
- class touchstone.parser.parsing.option_line_parser.OptionLineParser[source]¶
Bases:
objectParses the
#option line from a Touchstone file.The option line format is:
# <frequency_unit> <parameter_type> <data_format> R <impedance>Tokens can appear in any order. Missing tokens are filled with Touchstone defaults (GHz, S, MA, R 50).
Example
>>> opts = OptionLineParser.parse("# GHz S MA R 50") >>> opts.frequency_unit <FrequencyUnit.GHZ: 'GHz'>
- static parse(line)[source]¶
Parse a Touchstone option line into a
TouchstoneOptionsobject.- Parameters:
line (str) – The option line string, including the leading
#(e.g.,'# GHz S MA R 50'). Inline comments (text after!) are stripped.- Returns:
The parsed options with all fields populated.
- Return type:
DataLineTokenizer¶
Tokenizer for parsing numerical data from Touchstone files.
This module provides the DataLineTokenizer class, which extracts
floating-point numbers from data lines while skipping comments and
option lines.
- class touchstone.parser.parsing.data_line_tokenizer.DataLineTokenizer[source]¶
Bases:
objectUtility class for tokenizing numerical data from Touchstone file lines.
Data lines in a Touchstone file contain whitespace- or comma-separated floating-point numbers. Comment lines (starting with
!) and option lines (starting with#) are skipped.Example
>>> lines = ["# GHz S MA R 50", "1.0 0.9 -10.0"] >>> list(DataLineTokenizer.get_numbers(lines)) [1.0, 0.9, -10.0]
- static get_numbers(lines)[source]¶
Yield all numeric values found in the data lines.
Processes each line by stripping inline comments (
!), skipping option lines (#) and blank lines, and parsing the remaining whitespace/comma-separated tokens as floats.- Parameters:
lines (Iterable[str]) – An iterable of string lines from a Touchstone file.
- Yields:
float – Each parsed numerical value, in order of appearance.
- Raises:
TouchstoneParserException – If a token cannot be parsed as a float, with the line number included in the message.
- Return type:
Utilities¶
Frequency Converter¶
Utility for frequency conversions.
This module provides functions to convert frequency values between different units (Hz, kHz, MHz, GHz) and to normalize frequencies to Hz.
- touchstone.parser.utilities.frequency_converter.get_multiplier(unit)[source]¶
Get the multiplier to convert a frequency value to Hz.
- Parameters:
unit (str | FrequencyUnit) – A frequency unit as a string (
'Hz','kHz','MHz','GHz') or aFrequencyUnitenum member.- Returns:
The multiplier (e.g.,
1e9for GHz). Returns1.0for unrecognized units.- Return type:
Example
>>> get_multiplier("GHz") 1000000000.0 >>> get_multiplier(FrequencyUnit.MHZ) 1000000.0
- touchstone.parser.utilities.frequency_converter.normalize_frequency(freq, unit)[source]¶
Normalize a frequency value to Hz.
Multiplies the given frequency by the appropriate unit multiplier to convert it to Hertz.
- Parameters:
freq (float) – The frequency value in the specified unit.
unit (str | FrequencyUnit) – The frequency unit (e.g.,
'GHz'orFrequencyUnit.GHZ).
- Returns:
The frequency in Hz.
- Return type:
Example
>>> normalize_frequency(2.4, "GHz") 2400000000.0
- touchstone.parser.utilities.frequency_converter.from_hz(value, unit)[source]¶
Convert a frequency value from Hz to the specified unit.
- Parameters:
value (float) – The frequency in Hz.
unit (str | FrequencyUnit) – The target frequency unit (e.g.,
'MHz'orFrequencyUnit.MHZ).
- Returns:
The frequency in the target unit.
- Return type:
Example
>>> from_hz(2.4e9, "GHz") 2.4
- touchstone.parser.utilities.frequency_converter.convert(value, from_unit, to_unit)[source]¶
Convert a frequency value from one unit to another.
Internally normalizes to Hz and then converts to the target unit.
- Parameters:
value (float) – The frequency value in
from_unit.from_unit (str | FrequencyUnit) – The source frequency unit.
to_unit (str | FrequencyUnit) – The destination frequency unit.
- Returns:
The frequency in
to_unit.- Return type:
Example
>>> convert(2400, "MHz", "GHz") 2.4
Network Parameter Extensions¶
Math utilities for network parameter conversions.
This module provides functions for converting between different representations of RF network parameters: dB ↔ linear magnitude, degrees ↔ radians, and various formats to complex numbers.
- touchstone.parser.utilities.network_parameter_extensions.db_to_mag(db)[source]¶
Convert decibels (dB) to linear magnitude.
Computes
10^(dB / 20).- Parameters:
db (Any) – The dB value(s). Can be a scalar, list, or NumPy array.
- Returns:
The corresponding linear magnitude(s), same type as input.
- Return type:
Example
>>> db_to_mag(-3) 0.7079... >>> db_to_mag(0) 1.0
- touchstone.parser.utilities.network_parameter_extensions.mag_to_db(mag)[source]¶
Convert linear magnitude to decibels (dB).
Computes
20 * log10(mag).- Parameters:
mag (Any) – The linear magnitude value(s). Must be positive. Can be a scalar, list, or NumPy array.
- Returns:
The corresponding dB value(s), same type as input.
- Return type:
Example
>>> mag_to_db(1.0) 0.0 >>> mag_to_db(0.5) -6.0206...
- touchstone.parser.utilities.network_parameter_extensions.deg_to_rad(deg)[source]¶
Convert degrees to radians.
- Parameters:
deg (Any) – Angle(s) in degrees. Can be a scalar, list, or NumPy array.
- Returns:
Angle(s) in radians, same type as input.
- Return type:
Example
>>> deg_to_rad(180) 3.14159...
- touchstone.parser.utilities.network_parameter_extensions.rad_to_deg(rad)[source]¶
Convert radians to degrees.
- Parameters:
rad (Any) – Angle(s) in radians. Can be a scalar, list, or NumPy array.
- Returns:
Angle(s) in degrees, same type as input.
- Return type:
Example
>>> import numpy as np >>> rad_to_deg(np.pi) 180.0
- touchstone.parser.utilities.network_parameter_extensions.ma_to_complex(mag, angle_deg)[source]¶
Convert magnitude and angle (degrees) to a complex number.
Uses the formula:
mag * (cos(θ) + j·sin(θ))whereθ = radians(angle_deg).- Parameters:
- Returns:
The complex number representation.
- Return type:
Example
>>> ma_to_complex(1.0, 0.0) (1+0j)
- touchstone.parser.utilities.network_parameter_extensions.db_to_complex(db, angle_deg)[source]¶
Convert magnitude (dB) and angle (degrees) to a complex number.
First converts dB to linear magnitude, then delegates to
ma_to_complex().- Parameters:
- Returns:
The complex number representation.
- Return type:
Example
>>> db_to_complex(0.0, 0.0) (1+0j)
- touchstone.parser.utilities.network_parameter_extensions.ri_to_complex(real, imag)[source]¶
Convert real and imaginary parts to a complex number.
- Parameters:
- Returns:
real + j*imag.- Return type:
Example
>>> ri_to_complex(0.5, -0.3) (0.5-0.3j)
- touchstone.parser.utilities.network_parameter_extensions.vswr_from_s11(s11)[source]¶
Calculate VSWR from the S11 reflection coefficient.
Computes
(1 + |S11|) / (1 - |S11|), with a small epsilon to avoid division by zero when|S11| ≈ 1.- Parameters:
s11 (Any) – Complex reflection coefficient value(s). Can be a scalar, list, or NumPy array.
- Returns:
VSWR value(s), dimensionless and ≥ 1.0.
- Return type:
Example
>>> vswr_from_s11(0.0) 1.0 >>> vswr_from_s11(0.5) 3.0
TouchstoneData Extensions¶
Extension methods for analyzing TouchstoneData objects.
This module provides standalone functions for common RF analysis tasks such as extracting magnitude and phase, computing insertion loss, return loss, VSWR, filtering by frequency range, and accessing specific S-parameter indices.
- touchstone.parser.utilities.touchstone_data_extensions.get_magnitude(data, to_port, from_port, db=True)[source]¶
Get magnitude of S-parameters across all frequencies.
- Parameters:
data (TouchstoneData) – The Touchstone data to analyze.
to_port (int) – The target (output) port, 1-indexed.
from_port (int) – The source (input) port, 1-indexed.
db (bool) – If
True, returns magnitude in dB. IfFalse, returns linear magnitude. Defaults toTrue.
- Returns:
Array of magnitude values.
- Return type:
Example
>>> mag_db = get_magnitude(data, 2, 1, db=True)
- touchstone.parser.utilities.touchstone_data_extensions.get_phase(data, to_port, from_port, deg=True)[source]¶
Get phase of S-parameters across all frequencies.
- Parameters:
data (TouchstoneData) – The Touchstone data to analyze.
to_port (int) – The target (output) port, 1-indexed.
from_port (int) – The source (input) port, 1-indexed.
deg (bool) – If
True, returns phase in degrees. IfFalse, returns phase in radians. Defaults toTrue.
- Returns:
Array of phase values.
- Return type:
Example
>>> phase_deg = get_phase(data, 1, 1, deg=True)
- touchstone.parser.utilities.touchstone_data_extensions.to_insertion_loss(data)[source]¶
Compute insertion loss from S21.
Insertion loss is
-|S21|in dB, so that positive values indicate signal attenuation.- Parameters:
data (TouchstoneData) – The Touchstone data (must have ≥ 2 ports).
- Returns:
Array of insertion loss values in dB.
- Return type:
- Raises:
ValueError – If the data has fewer than 2 ports.
- touchstone.parser.utilities.touchstone_data_extensions.to_return_loss(data)[source]¶
Compute return loss from S11.
Return loss is
-|S11|in dB, so that positive values indicate better impedance matching.- Parameters:
data (TouchstoneData) – The Touchstone data.
- Returns:
Array of return loss values in dB.
- Return type:
- touchstone.parser.utilities.touchstone_data_extensions.to_vswr(data)[source]¶
Compute VSWR (Voltage Standing Wave Ratio) from S11.
VSWR is calculated as
(1 + |S11|) / (1 - |S11|).- Parameters:
data (TouchstoneData) – The Touchstone data.
- Returns:
Array of VSWR values (dimensionless, ≥ 1.0).
- Return type:
- touchstone.parser.utilities.touchstone_data_extensions.in_frequency_range(data, min_hz, max_hz)[source]¶
Filter data to a specific frequency range in Hz.
Creates a new
TouchstoneDatacontaining only the frequency points within[min_hz, max_hz](inclusive).- Parameters:
data (TouchstoneData) – The original Touchstone data.
min_hz (float) – Minimum frequency in Hz (inclusive).
max_hz (float) – Maximum frequency in Hz (inclusive).
- Returns:
A new filtered instance.
- Return type:
Example
>>> passband = in_frequency_range(data, 2e9, 3e9)
- touchstone.parser.utilities.touchstone_data_extensions.get_s11(data)[source]¶
Get an iterable of
(frequency_hz, NetworkParameter)for S11.Convenience shortcut for
data.get_parameter(1, 1).- Parameters:
data (TouchstoneData) – The Touchstone data.
- Returns:
Frequency/parameter pairs.
- Return type:
Iterable[tuple[float, NetworkParameter]]
- touchstone.parser.utilities.touchstone_data_extensions.get_s21(data)[source]¶
Get an iterable of
(frequency_hz, NetworkParameter)for S21.Convenience shortcut for
data.get_parameter(2, 1).- Parameters:
data (TouchstoneData) – The Touchstone data (must have ≥ 2 ports).
- Returns:
Frequency/parameter pairs.
- Return type:
Iterable[tuple[float, NetworkParameter]]
- touchstone.parser.utilities.touchstone_data_extensions.get_s12(data)[source]¶
Get an iterable of
(frequency_hz, NetworkParameter)for S12.Convenience shortcut for
data.get_parameter(1, 2).- Parameters:
data (TouchstoneData) – The Touchstone data (must have ≥ 2 ports).
- Returns:
Frequency/parameter pairs.
- Return type:
Iterable[tuple[float, NetworkParameter]]
- touchstone.parser.utilities.touchstone_data_extensions.get_s22(data)[source]¶
Get an iterable of
(frequency_hz, NetworkParameter)for S22.Convenience shortcut for
data.get_parameter(2, 2).- Parameters:
data (TouchstoneData) – The Touchstone data (must have ≥ 2 ports).
- Returns:
Frequency/parameter pairs.
- Return type:
Iterable[tuple[float, NetworkParameter]]
- touchstone.parser.utilities.touchstone_data_extensions.get_frequencies_in(data, unit)[source]¶
Get all frequencies converted to the specified unit.
- Parameters:
data (TouchstoneData) – The Touchstone data.
unit – The target frequency unit (string or
FrequencyUnit).
- Returns:
Array of frequency values in the specified unit.
- Return type:
Example
>>> freqs_ghz = get_frequencies_in(data, "GHz")
- touchstone.parser.utilities.touchstone_data_extensions.min_frequency_hz(data)[source]¶
Get the minimum frequency in Hz.
- Parameters:
data (TouchstoneData) – The Touchstone data.
- Returns:
The minimum frequency value.
- Return type:
- Raises:
ValueError – If the data contains no frequency points.
- touchstone.parser.utilities.touchstone_data_extensions.max_frequency_hz(data)[source]¶
Get the maximum frequency in Hz.
- Parameters:
data (TouchstoneData) – The Touchstone data.
- Returns:
The maximum frequency value.
- Return type:
- Raises:
ValueError – If the data contains no frequency points.
Touchstone Writer¶
Utilities for writing Touchstone data back to the .sNp file format.
This module provides write_snp() and write_snp_to_string()
for exporting TouchstoneData
back to the standard Touchstone text format with round-trip fidelity.
- touchstone.parser.utilities.touchstone_writer.write_snp(data, filepath, options=None)[source]¶
Write Touchstone data to a file.
- Parameters:
data (TouchstoneData) – The
TouchstoneDatato write.filepath (str) – The destination file path (e.g.,
'output.s2p').options (TouchstoneOptions | None) – Optional
TouchstoneOptionsto override the export format. IfNone, usesdata.options.
- Return type:
None
Example
>>> write_snp(data, "output.s2p")
- touchstone.parser.utilities.touchstone_writer.write_snp_to_string(data, options=None)[source]¶
Convert Touchstone data to its string representation.
Produces a valid Touchstone file content string including comments, the option line, and all data rows.
- Parameters:
data (TouchstoneData) – The
TouchstoneDatato convert.options (TouchstoneOptions | None) – Optional
TouchstoneOptionsto override the export format. IfNone, usesdata.options.
- Returns:
The raw Touchstone file content as a string.
- Return type:
Example
>>> content = write_snp_to_string(data) >>> print(content[:50]) # GHZ S MA R 50.0