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 for TouchstoneParser.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: object

Structured object representing parsed Touchstone (.sNp) data.

This is the main output of TouchstoneParser.parse() and TouchstoneParser.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:

numpy.ndarray

s_parameters

3-D complex NumPy array of shape (n_freq, n_ports, n_ports).

Type:

numpy.ndarray

options

The parsed option line configuration.

Type:

touchstone.parser.models.touchstone_options.TouchstoneOptions

comments

List of comment strings extracted from the file.

Type:

List[str]

filename

The original filename, if known.

Type:

str | None

metadata

Arbitrary metadata dictionary for user extensions.

Type:

Dict[str, Any]

Example

>>> data = TouchstoneParser.parse("filter.s2p")
>>> data.n_ports
2
>>> data.n_freq
201
>>> s21 = data.get_s(2, 1)
frequency: ndarray
s_parameters: ndarray
options: TouchstoneOptions
comments: List[str]
filename: str | None = None
metadata: Dict[str, Any]
property z0: float

Reference impedance of the network in ohms.

Returns:

The reference impedance from the option line.

Return type:

float

property unit: str

Frequency unit string (e.g. 'Hz', 'GHz').

Returns:

The frequency unit value from the option line.

Return type:

str

property parameter: str

Network parameter type string (e.g. 'S', 'Y').

Returns:

The parameter type value from the option line.

Return type:

str

property format: str

Data format string (e.g. 'MA', 'RI').

Returns:

The data format value from the option line.

Return type:

str

property n_ports: int

Number of ports in the network.

Returns:

The number of ports, derived from the S-parameter matrix shape.

Return type:

int

property n_freq: int

Number of frequency points in the dataset.

Returns:

The length of the frequency array.

Return type:

int

property frequencies: ndarray

Alias for frequency (compatibility with .NET API).

Returns:

The frequency array in Hz.

Return type:

numpy.ndarray

property count: int

Alias for n_freq (compatibility with .NET API).

Returns:

The number of frequency points.

Return type:

int

__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:
  • to_port (int) – The target (output) port number, 1-indexed.

  • from_port (int) – The source (input) port number, 1-indexed.

Returns:

1-D complex array of length n_freq.

Return type:

numpy.ndarray

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 FrequencyPoint at 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:

FrequencyPoint

get_parameter(row, col)[source]

Iterate over (frequency, NetworkParameter) pairs for a specific matrix entry.

Parameters:
  • row (int) – The row index of the parameter matrix, 1-indexed.

  • col (int) – The column index of the parameter matrix, 1-indexed.

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:

Iterable[Tuple[float, NetworkParameter]]

where(predicate)[source]

Filter the data using a predicate function.

Creates a new TouchstoneData containing only the frequency points for which the predicate returns True.

Parameters:

predicate (Callable[[FrequencyPoint], bool]) – A callable that takes a FrequencyPoint and returns True to keep it.

Returns:

A new filtered instance.

Return type:

TouchstoneData

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:

numpy.ndarray

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:

numpy.ndarray

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:

numpy.ndarray

in_frequency_range(min_hz, max_hz)[source]

Filter the data to a specific frequency range.

Parameters:
  • min_hz (float) – Minimum frequency in Hz (inclusive).

  • max_hz (float) – Maximum frequency in Hz (inclusive).

Returns:

A new instance containing only the points within the specified range.

Return type:

TouchstoneData

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 DataFormat to override the default. If None, uses the format from options.

  • unit (FrequencyUnit | None) – Optional FrequencyUnit to override the default. If None, uses the unit from options.

Returns:

The CSV string representation of the data.

Return type:

str

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 DataFormat to override the default.

  • unit (FrequencyUnit | None) – Optional FrequencyUnit to override the default.

Return type:

None

__repr__()[source]

Return a developer-friendly string representation.

Returns:

A string showing the number of ports, frequency points, and frequency range.

Return type:

str

__init__(frequency, s_parameters, options=<factory>, comments=<factory>, filename=None, metadata=<factory>)
Parameters:
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: object

Represents 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.

Type:

touchstone.parser.models.frequency_unit.FrequencyUnit

parameter_type

The network parameter type. Defaults to S.

Type:

touchstone.parser.models.parameter_type.ParameterType

data_format

The data format for parameter values. Defaults to MA.

Type:

touchstone.parser.models.data_format.DataFormat

reference_impedance

The reference impedance in ohms. Defaults to 50.0.

Type:

float

frequency_unit: FrequencyUnit = 'GHz'
parameter_type: ParameterType = 'S'
data_format: DataFormat = 'MA'
reference_impedance: float = 50.0
__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:

str

classmethod default()[source]

Create a TouchstoneOptions instance with default values.

Returns:

Default options (GHz, S, MA, 50 Ω).

Return type:

TouchstoneOptions

__init__(frequency_unit=FrequencyUnit.GHZ, parameter_type=ParameterType.S, data_format=DataFormat.MA, reference_impedance=50.0)
Parameters:
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: object

A 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.

value

The complex-valued network parameter.

Type:

complex

Example

>>> param = NetworkParameter(complex(0.5, -0.3))
>>> param.magnitude_db
-4.86...
>>> param.phase_degrees
-30.96...
value: complex
property real: float

The real component of the parameter.

Returns:

The real part of the complex value.

Return type:

float

property imaginary: float

The imaginary component of the parameter.

Returns:

The imaginary part of the complex value.

Return type:

float

property magnitude: float

The linear magnitude (absolute value) of the parameter.

Returns:

|value|, always non-negative.

Return type:

float

property magnitude_db: float

The magnitude of the parameter in decibels (dB).

Computed as 20 * log10(|value|).

Returns:

Magnitude in dB. Returns -inf if magnitude is zero.

Return type:

float

property phase_radians: float

The phase angle in radians.

Returns:

Phase angle in the range (-π, π].

Return type:

float

property phase_degrees: float

The phase angle in degrees.

Returns:

Phase angle in the range (-180, 180].

Return type:

float

classmethod from_real_imaginary(real, imaginary)[source]

Create a NetworkParameter from real and imaginary parts.

Parameters:
  • real (float) – The real component.

  • imaginary (float) – The imaginary component.

Returns:

A new instance with value = real + j*imaginary.

Return type:

NetworkParameter

classmethod from_magnitude_angle(magnitude, angle_degrees)[source]

Create a NetworkParameter from linear magnitude and angle.

Parameters:
  • magnitude (float) – The linear magnitude (non-negative).

  • angle_degrees (float) – The phase angle in degrees.

Returns:

A new instance created via polar-to-rectangular conversion.

Return type:

NetworkParameter

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:
  • magnitude_db (float) – The magnitude in decibels.

  • angle_degrees (float) – The phase angle in degrees.

Returns:

A new instance.

Return type:

NetworkParameter

conjugate()[source]

Return the complex conjugate of this parameter.

Returns:

A new instance with the conjugated value.

Return type:

NetworkParameter

reciprocal()[source]

Return the reciprocal (1 / value) of this parameter.

Returns:

A new instance with the reciprocal value.

Return type:

NetworkParameter

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:

NetworkParameter

__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:

NetworkParameter

__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:

NetworkParameter

__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:

NetworkParameter

approximately_equals(other, tolerance=1e-09)[source]

Check if two parameters are approximately equal.

Parameters:
Returns:

True if |self.value - other.value| <= tolerance.

Return type:

bool

__eq__(other)[source]

Check exact equality with another NetworkParameter.

Parameters:

other (Any) – The object to compare.

Returns:

True if other is a NetworkParameter with an identical complex value.

Return type:

bool

__init__(value)
Parameters:

value (complex)

Return type:

None

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: object

Encapsulates a single frequency point and its N × N matrix of network parameters.

frequency_hz

The frequency value in Hz (must be non-negative).

Type:

float

_s_parameters

The N × N complex NumPy array of S-parameters at this frequency.

Type:

numpy.ndarray

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]
frequency_hz: float
__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:

int

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:

numpy.ndarray

__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:

NetworkParameter

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:

str

__repr__()[source]

Return a developer-friendly string representation.

Returns:

Same as __str__().

Return type:

str

__init__(frequency_hz, _s_parameters)
Parameters:
Return type:

None

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: Enum

Enum 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: Enum

Enum 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: Enum

Enum 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: object

Parser 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 .sNp extension to extract the port count N.

Parameters:

filename (str) – The name of the file (e.g. 'filter.s2p').

Returns:

The detected number of ports.

Return type:

int

Raises:

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 .sNp file.

Returns:

The fully parsed data.

Return type:

TouchstoneData

Raises:

Example

>>> data = TouchstoneParser.parse("filter.s2p")
static parse_string(content, n_ports=0, filename=None)[source]

Parse Touchstone data from a string.

Parameters:
  • content (str) – The raw Touchstone file content as a string.

  • n_ports (int) – Number of ports. Pass 0 to auto-detect from the data (default).

  • filename (str | None) – Optional filename for metadata purposes.

Returns:

The parsed data.

Return type:

TouchstoneData

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:
  • stream (TextIO) – A readable text stream (e.g., io.StringIO).

  • filename (str | None) – Optional filename for port detection and metadata.

Returns:

The parsed data.

Return type:

TouchstoneData

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 using asyncio.to_thread().

Parameters:

filepath (str) – Path to the .sNp file.

Returns:

The parsed data.

Return type:

TouchstoneData

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: Exception

Exception 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 None if 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)
__init__(message, line_number=None)[source]
Parameters:
  • message (str)

  • line_number (int | None)

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: object

Parses 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 TouchstoneOptions object.

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:

TouchstoneOptions

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: object

Utility 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]
__init__()[source]

Initialize the DataLineTokenizer (no-op).

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:

Iterator[float]

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 a FrequencyUnit enum member.

Returns:

The multiplier (e.g., 1e9 for GHz). Returns 1.0 for unrecognized units.

Return type:

float

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' or FrequencyUnit.GHZ).

Returns:

The frequency in Hz.

Return type:

float

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' or FrequencyUnit.MHZ).

Returns:

The frequency in the target unit.

Return type:

float

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:
Returns:

The frequency in to_unit.

Return type:

float

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:

Any

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:

Any

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:

Any

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:

Any

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:
  • mag (float) – Linear magnitude (non-negative).

  • angle_deg (float) – Phase angle in degrees.

Returns:

The complex number representation.

Return type:

complex

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:
  • db (float) – Magnitude in decibels.

  • angle_deg (float) – Phase angle in degrees.

Returns:

The complex number representation.

Return type:

complex

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:
  • real (float) – The real part.

  • imag (float) – The imaginary part.

Returns:

real + j*imag.

Return type:

complex

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:

Any

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. If False, returns linear magnitude. Defaults to True.

Returns:

Array of magnitude values.

Return type:

numpy.ndarray

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. If False, returns phase in radians. Defaults to True.

Returns:

Array of phase values.

Return type:

numpy.ndarray

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:

numpy.ndarray

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:

numpy.ndarray

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:

numpy.ndarray

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 TouchstoneData containing 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:

TouchstoneData

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:
Returns:

Array of frequency values in the specified unit.

Return type:

numpy.ndarray

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:

float

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:

float

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 TouchstoneData to write.

  • filepath (str) – The destination file path (e.g., 'output.s2p').

  • options (TouchstoneOptions | None) – Optional TouchstoneOptions to override the export format. If None, uses data.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 TouchstoneData to convert.

  • options (TouchstoneOptions | None) – Optional TouchstoneOptions to override the export format. If None, uses data.options.

Returns:

The raw Touchstone file content as a string.

Return type:

str

Example

>>> content = write_snp_to_string(data)
>>> print(content[:50])
# GHZ S MA R 50.0