Model (pmrf.Model)

class pmrf.models.Model(*, name=None, separator='_', metadata=<factory>, _z0=(50+0j), _param_groups=<factory>)[source]

Bases: Module

Overview

This base class is used to represent any computable RF network, referred to in ParamRF as a “Model”. This class is abstract and should not be instantiated directly. Derive from Model and override one of the primary property functions (e.g. __call__(), s(), a()).

The model is an Equinox Module (immutable, dataclass-like) and is treated as a JAX PyTree. Parameters are declared using standard dataclass field syntax with types like pmrf.Parameter.

Usage

  • Define new models by sub-classing the model and adding custom parameters and/or sub-models

  • Construct models by passing parameters and/or submodels to the initializer (like a dataclass).

  • Retrieve parameter information via methods such as named_params(), param_names(), flat_params(), etc..

  • Use with_xxx functions to modify fields, models and parameters within the model e.g. with_params(), with_fields().

  • Use “past tense” functions to modify the model in conjuction with another model or data e.g. terminated(), fitted().

See also the pmrf.fitting and pmrf.sampling modules for details on model fitting and sampling.

name

An optional name for the model instance.

Type:

str or None

separator

The separator character used when flattening nested parameter names (default is ‘_’).

Type:

str

metadata

A dictionary for storing arbitrary metadata associated with the model (e.g., fit results).

Type:

dict

Examples

A PiCLC network (“foundational” model with fixed parameters and equations):

import jax.numpy as jnp
import pmrf as prf

class PiCLC(prf.Model):
    C1: prf.Parameter = 1.0e-12
    L:  prf.Parameter = 1.0e-9
    C2: prf.Parameter = 1.0e-12

    def a(self, freq: prf.Frequency) -> jnp.ndarray:
        w = freq.w
        Y1, Y2, Y3 = (1j * w * self.C1), (1j * w * self.C2), 1 / (1j * w * self.L)
        return jnp.array([
            [1 + Y2 / Y3,        1 / Y3],
            [Y1 + Y2 + Y1*Y2/Y3, 1 + Y1 / Y3],
        ]).transpose(2, 0, 1)

An RLC network (“circuit” model with free parameters built using cascading)

import pmrf as prf
from pmrf.models import Resistor, Capacitor, Inductor, Cascade
from pmrf.parameters import Uniform

class RLC(prf.Model):
    res: Resistor = Resistor(Uniform(9.0, 11.0))
    ind: Inductor = Inductor(Uniform(0.0, 10.0, scale=1e-9))
    cap: Capacitor = Capacitor(Uniform(0.0, 10.0, scale=1e-12))

    def __call__(self) -> prf.Model:
        return self.res ** self.ind ** self.cap.terminated()
name: str | None = None
separator: str = '_'
metadata: dict
DEFAULT_NAMED_PARAMS = {}
DEFAULT_PARAM_NAMES = []
DEFAULT_PARAMS = []
property primary_function: Callable[[Frequency], Array]

The primary function (s or a) as a callable.

The primary function is the first overridden among PRIMARY_PROPERTIES, unless __call__ is overridden, in which case the primary function of the built model is returned.

Return type:

Callable[[Frequency], jnp.ndarray]

Raises:

NotImplementedError – If no primary property is overridden.

property primary_property: str

The primary property (e.g. "s", "a") as a string.

The primary property is the first overridden among PRIMARY_PROPERTIES, unless __call__ is overridden, in which case the primary property of the built model is returned.

Return type:

str

Raises:

NotImplementedError – If no primary property is overridden.

copy()[source]

Returns a deepcopy of self.

Return type:

Model

Parameters:

self (ModelT)

property number_of_ports: int

Number of ports.

Return type:

int

property nports: int

Alias of number_of_ports.

property port_tuples: list[tuple[int, int]]

All (m, n) port index pairs.

Return type:

list[tuple[int, int]]

property z0: Array

Internal characteristic impedance.

Return type:

jnp.ndarray

property num_params: int

Number of free parameters.

Return type:

int

property num_flat_params: int

Number of free, flattened parameters.

Return type:

int

__call__()[source]

Build the model.

This function should be over-ridden by sub-classes. It is useful in defining complex models that are built using several sub-models (as opposed to equation-based models).

Return type:

Model

Raises:

NotImplementedError – In the base class; override in derived classes to build a compositional representation.

primary(freq)[source]

Dispatch to the primary function for the given frequency.

Parameters:

freq (Frequency)

Return type:

Array

a(freq)[source]

Calculates the ABCD parameter matrix.

If only s() is implemented, this is calculated using the conversion pmrf.functions.conversions.s2a().

Parameters:

freq (Frequency) – Frequency grid.

Returns:

ABCD matrix with shape (nf, 2, 2).

Return type:

jnp.ndarray

Raises:

NotImplementedError – If neither a nor s is implemented in a subclass.

s(freq)[source]

Scattering parameter matrix.

If only a() is implemented, converts via pmrf.functions.conversions.a2s().

Parameters:

freq (Frequency) – Frequency grid.

Returns:

S-parameter matrix with shape (nf, n, n).

Return type:

jnp.ndarray

Raises:

NotImplementedError – If neither a nor s is implemented in a subclass.

children()[source]

Immediate submodels.

Return type:

list[Model]

submodels()[source]

All nested submodels (depth-first), excluding self.

Return type:

list[Model]

connected(others, ports)[source]

Return a version of the model with specified ports connected.

See :class:pmrf.models.containers.Connected.

Return type:

Model

Parameters:
  • others (Model | Sequence[Model])

  • ports (Sequence[int | Sequence[int]])

flipped()[source]

Return a version of the model with ports flipped.

Return type:

Model

terminated(load=None)[source]

Returns a new model that contains this 2-port model terminated in a 1-port load (default: SHORT).

Parameters:

load (Model, optional) – Load network. Defaults to a SHORT.

Return type:

Model

fitted(measured, **kwargs)[source]

Returns a new model fitted to measured data.

This is an alternative API to ParamRF’s fitting module. See the fit method for more details.

Internally, a fitter is first created using pmrf.fitting.Fitter(), and then fitter.fit(...)() is called, with the fitted model being returned. Fit results are stored in the model’s metadata with key ‘fit_results’.

Key-word arguments are split into ‘init’ and ‘fit’ key-word arguments appropriately.

Parameters:
  • measured (prf.NetworkCollection | skrf.Network | str) – The measured data.

  • **kwargs – Additional arguments forwarded to pmrf.fitting.Fitter() and pmrf.fitting.BaseFitter.fit().

  • self (ModelT)

Returns:

The fitted model.

Return type:

Model

with_submodels_fitted(measured, **kwargs)[source]

Returns a new model with its submodels fitted to measured data.

This is an alternative API to ParamRF’s fitting module. See the fit_submodels method for more details.

Internally, a fitter is first created using pmrf.fitting.Fitter(), and then fitter.fit_submodels(...)() is called, with the fitted model being returned. Fit results are stored in the model’s metadata with key ‘fit_results’.

Key-word arguments are split into ‘init’ and ‘fit’ key-word arguments appropriately.

Parameters:
  • measured (prf.NetworkCollection | skrf.Network | str) – The measured data.

  • **kwargs – Additional arguments forwarded to pmrf.fitting.Fitter() and pmrf.fitting.BaseFitter.fit_submodels().

  • self (ModelT)

Returns:

The fitted model.

Return type:

Model

named_params(include_fixed=False, submodels=None)[source]

Named model parameters as a dict.

Keys are fully-qualified parameter names. The order matches the internal flattened array order.

Parameters:
  • include_fixed (bool, default=False) – Include fixed parameters.

  • submodels (Model | Sequence[Model] | str | Sequence[str] | None, optional) – Restrict to parameters used by the given submodel(s). If strings are provided, getattr(self, name) is used.

Return type:

dict[str, Parameter]

named_param_values(scaled=False, **kwargs)[source]

Named model parameter values as a dict of jax arrays.

See named_params().

Parameters:
  • scaled (bool, default=False) – Whether or not to scale the returned values by the parameter scales.

  • **kwargs – Additional key-word arguments as in named_params().

Return type:

dict[str, jnp.ndarray]

param_names(*args, **kwargs)[source]

Return model parameter names as a list.

See named_params().

Return type:

list[str]

params(*args, **kwargs)[source]

Return model parameters as a list.

See named_params().

Return type:

list[Parameter]

params_values(*args, **kwargs)[source]

Return model parameter values as a list of jax arrays.

See named_param_values().

Return type:

list[Array]

named_flat_params(include_fixed=False, submodels=None)[source]

Named flattened model parameters as a dict.

Flat parameters are a de-vectorized version of the internal parameters of the model. The returned parameter objects therefore are not necessarily equal to the internal model objects.

Keys are fully-qualified parameter names with de-vectorized suffixes added. The order matches the internal flattened array order.

Parameters:
  • include_fixed (bool, default=False) – Include fixed parameters.

  • submodels (Model | Sequence[Model] | str | Sequence[str] | None, optional) – Restrict to parameters used by the given submodel(s). If strings are provided, getattr(self, name) is used.

Return type:

dict[str, Parameter]

named_flat_param_values(scaled=False, **kwargs)[source]

Named flattened model parameter values as a dict of jax arrays.

See named_flat_params().

Parameters:
  • scaled (bool, default=False) – Whether or not to scale the returned values by the parameter scales.

  • **kwargs – Additional key-word arguments as in named_params().

Return type:

dict[str, jnp.ndarray]

flat_param_names(*args, **kwargs)[source]

Return flattened parameter names as a list.

See named_flat_params().

Return type:

list[str]

flat_params(*args, **kwargs)[source]

Return flattened parameters as a list.

See named_flat_params().

Return type:

list[Parameter]

flat_param_values(*args, **kwargs)[source]

Return flattened model parameter values as a jax arrays.

See named_flat_param_values().

Return type:

Array

param_groups(include_fixed=False)[source]

Return all parameter groups relevant to this model.

This function is useful for fitters that need to take into account e.g. any constraints or correlated priors. Only groups that were create with the same flat flag are returned.

Currently, only groups for the current model are considered (i.e. groups in children models are ignored).

Parameters:

include_fixed (bool, default=False) – Include groups involving fixed parameters.

Return type:

list[ParameterGroup]

distribution()[source]

Joint distribution over (flattened) parameters.

Return type:

JointParameterDistribution

with_params(params=None, check_missing=False, check_unknown=False, fix_others=False, include_fixed=False, **param_kwargs)[source]

Return a new model with parameters updated.

This is a multi-purpose function that updates parameters differently based on the types pass.

Parameters:
  • params (dict[str, Parameter] | dict[str, float] | jnp.ndarray | None, optional) – Parameter updates. If an array, all values must be provided (matching flat_params order). You may also pass keyword args.

  • check_missing (bool, default=False) – Require that all model parameters are specified.

  • check_unknown (bool, default=False) – Error if unknown parameter keys are provided.

  • fix_others (bool, default=False) – Fix any parameters not explicitly passed.

  • include_fixed (bool, default=False) – Include fixed parameters when interpreting params mapping.

  • **param_kwargs (dict) – Additional parameter updates by name.

  • self (ModelT)

Return type:

ModelT

Raises:

Exception – If shape/order mismatches, unknown/missing names (when checked), or if arrays are found outside of Parameters.

with_fixed_params(params, check_unknown=True)[source]

Return a model with specified parameters fixed.

Parameters:
  • params (list[str]) – Parameter names to fix.

  • check_unknown (bool, default=True) – Error if any provided name does not exist.

  • self (ModelT)

Return type:

ModelT

with_free_params(params, fix_others=False)[source]

Free the specified parameters.

Parameters:
  • params (Sequence[str] | Sequence[Parameter]) – Parameters to set free.

  • fix_others (bool, default=True) – Fix parameters not specified.

  • self (ModelT)

Return type:

ModelT

with_free_params_only(*args, **kwargs)[source]

Returns a model with only the specified parameters freed.

This is an alias for calling :meth:with_free_params with fix_others=True.

See :meth:with_free_params.

Parameters:

self (ModelT)

Return type:

ModelT

with_param_groups(param_groups)[source]

Return a model with parameter groups appended.

Parameter groups can be used to specify relationships between parameters in the model, such as joint priors.

Parameters:
Return type:

ModelT

with_uniform_distributions(width_frac=0.01)[source]
classmethod with_defaults(*args, **kwargs)[source]

Return this model type with default initialization arguments.

This method is very useful in utilizing an existing model with default values, without having to create a new model type via inheritance.

Arguments are forwarded as if they were passed to __init__.

Return type:

type[Model]

with_models(models)[source]

Combines this model with free parameters in other models.

This is useful to combine separate models obtained from fitting the same initial model with different free parameters.

Parameters:
  • models (Model or Sequence[Model]) – The other models to combine this model with.

  • self (ModelT)

Return type:

Model

with_fields(*args, **kwargs)[source]

Return a copy of this model with dataclass-style field replacements.

Parameters are forwarded to dataclasses.replace().

Parameters:

self (ModelT)

Return type:

ModelT

with_submodel_fields(submodel, *args, **kwargs)[source]

Return a copy of this model with dataclass-style field replacements on a sub-model.

Parameters are forwarded to dataclasses.replace().

Parameters:
  • submodels (str) – The name of the submodel to replace the fields of.

  • self (ModelT)

  • submodel (str)

Return type:

ModelT

with_free_submodels(submodels, include_fixed=False, fix_others=False)[source]

Free all parameters in the given submodels.

Submodels parameters are obtained using param_names()., and subsequently freed using :meth:with_free_params.

Parameters:
  • submodels (Model | Sequence[Model] | str | Sequence[str]) – Submodels whose parameters should be free.

  • include_fixed (bool, default=False) – Also free parameters that are currently fixed in the submodels.

  • fix_others (bool, default=False) – Fix all other submodels.

  • self (ModelT)

Return type:

ModelT

with_fixed_submodels(submodels)[source]

Fixed all parameters in the given submodels.

Submodels parameters are obtained using param_names()., and subsequently fixed using :meth:with_fixed_params.

Parameters:
  • submodels (Model | Sequence[Model] | str | Sequence[str]) – Submodels whose parameters should be fixed.

  • self (ModelT)

Return type:

ModelT

to_skrf(frequency, sigma=0.0, **kwargs)[source]

Convert the model at frequencies to an skrf.Network.

The active primary property (self.primary_property) is used.

Parameters:
  • frequency (pmrf.Frequency | skrf.Frequency) – Frequency grid.

  • sigma (float, default=0.0) – If nonzero, add complex Gaussian noise with stdev sigma to s.

  • **kwargs – Forwarded to skrf.Network constructor.

Return type:

skrf.Network

write_hdf(group)[source]

Write model into an HDF5 group.

Parameters:

group (h5py.Group) – Target group. Two subgroups are created: raw and params.

classmethod read_hdf(group)[source]

Read model from an HDF5 group.

Parameters:

group (h5py.Group) – Group previously created via write_hdf().

Returns:

The decoded model, or None if decoding fails.

Return type:

ModelT | None

save(target)[source]

Serialize the model to disk in pickle format.

The recommended file extension for ParamRF models is .prf.

Parameters:
  • filepath (str) – Destination file path.

  • target (str | BinaryIO)

classmethod load(source)[source]

Load a model from a pickled file.

The recommended file extension for ParamRF models is .prf.

Parameters:
  • filepath (str) – Source JSON path.

  • source (str | BinaryIO)

Return type:

ModelT

export_touchstone(filename, frequency, sigma=0.0, **skrf_kwargs)[source]

Export the model response to a Touchstone file via scikit-rf.

Parameters:
  • filename (str)

  • frequency (Frequency | skrf.Frequency)

  • sigma (float, default=0.0) – Additive complex noise std for S-parameters.

  • **skrf_kwargs – Forwarded to skrf.Network.write_touchstone().

Returns:

Return value of Network.write_touchstone.

Return type:

Any

Parameters:
  • name (str | None)

  • separator (str)

  • metadata (dict)

  • _z0 (complex)

  • _param_groups (list[ParameterGroup])

Module-local helpers

These helpers live in pmrf.model but are re-exported at pmrf. Prefer the canonical docs at the root package page.

pmrf.models.wrap(func, *args, as_numpy=False)[source]

Wrap a function/method taking (model, frequency, *args, **kwargs) into one that accepts flat arrays.

The wrapper accepts (theta, [f], *args, **kwargs) where theta is a flat parameter array, and optionally f is a frequency array with a provided unit.

If a Frequency object is passed in *args, it is closed over and the wrapped function only accepts theta.

Supported call signatures:

  • wrap(userfunc, model, "MHz")

  • wrap(userfunc, model, freq)

  • wrap(model.userfunc, "MHz")

  • wrap(model.userfunc, freq)

Parameters:
  • func (callable) – Function or bound method taking (model, frequency, ...).

  • *args (tuple) – Variable length argument list. Expects either (model, Frequency), (model, unit_str), or just (Frequency,) / (unit_str,) if func is a bound method.

  • as_numpy (bool, optional) – If True, JIT the wrapper and convert inputs/outputs to NumPy arrays. Default is False.

Returns:

wrapper – Wrapped function accepting (theta_array, [f_array], *args, **kwargs).

Return type:

callable

Raises:

TypeError – If the frequency argument is neither a unit string nor a Frequency object.