Renumbered
- class Renumbered(model, from_ports, to_ports=None, *, name=None, z0=50 + 0j)[source]
Bases:
ModelA container that re-numbers the ports of a given Model.
This is useful for creating complex network topologies by explicitly re-mapping the port indices of a sub-network.
- Variables:
- Parameters:
- renumber(p)[source]
Applies the port renumbering to a parameter matrix.
- Parameters:
p (jnp.ndarray) – The parameter matrix to renumber (e.g., S-parameters).
- Returns:
The renumbered parameter matrix.
- Return type:
jnp.ndarray
- a(freq)[source]
ABCD parameter matrix.
If a different parameter type is primary, this converts it to A.
- Parameters:
freq (Frequency) – Frequency grid.
- Returns:
ABCD matrix with shape
(nf, 2, 2).- Return type:
jnp.ndarray
- s(freq)[source]
Scattering parameter matrix.
If a different parameter type (a, z, y) is primary, this converts it to S.
Note that, in ParamRF, the power wave definition of S-parameters should be used. If you have a formulation in terms of another definition (such as traveling waves), simply use
pmrf.rf_functions.s2s()(orpmrf.rf_functions.renormalize_s()if you need to change impedance too).- Parameters:
freq (Frequency) – Frequency grid.
- Returns:
S-parameter matrix with shape
(nf, n, n).- Return type:
jnp.ndarray
- y(freq)[source]
Admittance (Y) parameter matrix.
If a different parameter type is primary, this converts it to Y.
- Parameters:
freq (Frequency) – Frequency grid.
- Returns:
Y matrix with shape
(nf, n, n).- Return type:
jnp.ndarray
- z(freq)[source]
Impedance (Z) parameter matrix.
If a different parameter type is primary, this converts it to Z.
- Parameters:
freq (Frequency) – Frequency grid.
- Returns:
Z matrix with shape
(nf, n, n).- Return type:
jnp.ndarray
- a_jacobian(freq)
Calculate the Jacobian of the ABCD-parameters with respect to free parameters.
See
func_jacobian().
- distribution(param_groups=True)
Joint distribution over (flattened) parameters.
- Parameters:
param_groups (bool, optional) – Whether or not to use the internal parameter groups to create the joint distribution. Defaults to
True.- Return type:
JointParameterDistribution
- export_touchstone(filename, frequency, sigma=0.0, **skrf_kwargs)
Export the model response to a Touchstone file via scikit-rf.
- flat_param_bounds(**kwargs)
Return flattened model parameter bounds as jax arrays.
Note that a minimum and maximum percentile is used to get the bounds for any non-uniform distribution.
Equivalent to getting the bounds from
distribution(), which key-word arguments are forwarded to.- Return type:
tuple[Array, Array]
- flat_param_names(*args, **kwargs)
Return flattened parameter names as a list.
See
named_flat_params().
- flat_param_values(*args, **kwargs)
Return flattened model parameter values as a jax arrays.
See
named_flat_param_values().- Return type:
Array
- flat_params(*args, **kwargs)
Return flattened parameters as a list.
See
named_flat_params().
- flipped(**kwargs)
Return a version of the model with ports flipped.
See
pmrf.models.composite.transformed.Flipped.- Return type:
- func_jacobian(func, freq)
Calculate the Jacobian of an arbitrary function with respect to free parameters.
This uses forward-mode automatic differentiation to compute the gradients of the provided function with respect to each free parameter in the model.
- Parameters:
- Returns:
A dictionary mapping flat parameter names to their gradient arrays. Each array has the same shape as the output of func.
- Return type:
- func_samples(func, freq, *, key, num_samples=1000)
Evaluates an arbitrary function over samples drawn from the model’s distribution.
- Parameters:
- Returns:
The function evaluated over all samples. Shape will be (num_samples, *func_output_shape).
- Return type:
jnp.ndarray
- func_sensitivity(func, freq)
Calculate the relative (normalized) sensitivity of an arbitrary function.
This computes the fractional change in the function’s output given a fractional change in each free parameter. Mathematically, it evaluates:
\[S_{rel} = \frac{\partial y}{\partial \theta} \frac{\theta}{y}\]- Parameters:
- Returns:
A dictionary mapping flat parameter names to their normalized sensitivity arrays. Each array has the same shape as the output of func.
- Return type:
- named_flat_param_values(scaled=False, return_floats=False, **kwargs)
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:
- named_flat_params(include_fixed=False, submodels=None)
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.
- named_param_values(scaled=False, **kwargs)
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:
- named_params(param_filter=None, *, include_fixed=False, submodels=None)
Named model parameters as a dict.
Keys are fully-qualified parameter names. The order matches the internal flattened array order.
- Parameters:
param_filter (str | Sequence[str] | Parameter | Sequence[Parameter] | Callable[[str], bool], default=None) – A filter indicating which parameters to return. For the default case, all parameters are returned.
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:
- property nports: int
Alias of
number_of_ports.
- param(name, *args, **kwargs)
Return a single model parameter by name.
See
named_params().
- param_groups(include_fixed=False, explicit_only=False)
Return all parameter groups relevant to this model, including submodels.
This function recursively traverses submodels to collect their parameter groups, adjusting parameter names to match the current model’s scope.
Priority is given to groups defined in the parent model. If a parameter is grouped explicitly in self._param_groups, it will be removed from any groups returned by submodels.
- Parameters:
include_fixed (bool, default=False) – Include groups involving fixed parameters.
- Return type:
- param_names(*args, **kwargs)
Return model parameter names as a list.
See
named_params().
- param_value(name, *args, **kwargs)
Return a single model parameter value by name as a single jax array.
See
named_param_values().- Parameters:
name (str)
- Return type:
Array
- param_values(*args, **kwargs)
Return model parameter values as a list of jax arrays.
See
named_param_values().- Return type:
list[Array]
- params(*args, **kwargs)
Return model parameters as a list.
See
named_params().
- partition(include_fixed=False, param_objects=False)
Partition model into (parameters, static) trees.
This is useful for internal use, or for inspecting the model and its parameters.
- plot_func(func, freq, *, ax=None, label=None, color=None, **kwargs)
Evaluate and plot an arbitrary function of the current model.
This method evaluates the provided function using the model’s current parameter values and plots the resulting response over frequency.
- Parameters:
func (Callable[[Model, Frequency], jnp.ndarray]) – Function to evaluate. Must take a Model and a Frequency object and return a jnp.ndarray of shape (n_freqs,).
freq (Frequency) – Frequency grid to evaluate over.
ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, the current axes (plt.gca()) are used.
label (str, optional) – Label for the plotted line (used in legends).
color (str, optional) – Color for the line. If None, uses the matplotlib color cycle.
**kwargs (dict) – Additional keyword arguments forwarded to matplotlib.pyplot.plot (e.g., linestyle, linewidth, alpha).
- Returns:
The axes containing the plot.
- Return type:
matplotlib.axes.Axes
- plot_func_samples(func, freq, *, key, num_samples=1000, contours=True, ax=None, label=None, color='C0', alpha=0.1)
Evaluate and plot a function over samples from the parameter distribution.
This method draws samples from the model’s joint parameter distribution, evaluates the provided function for each sample, and plots the resulting responses over frequency.
- Parameters:
func (Callable[[Model, Frequency], jnp.ndarray]) – Function to evaluate. Must take a Model and a Frequency object and return a jnp.ndarray of shape (n_freqs,).
freq (Frequency) – Frequency grid to evaluate over.
key (Array) – PRNG key for sampling the distribution.
num_samples (int, default=1000) – Number of samples to draw.
contours (bool, default=True) – If True, plots the mean response and filled contours corresponding to 1, 2, and 3 standard deviations. If False, plots all individual sample responses as transparent lines.
ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, the current axes (plt.gca()) are used.
label (str, optional) – Label for the mean line (used in legends).
color (str, default='C0') – Base color for the lines and shaded regions.
alpha (float, default=0.1) – Transparency of the individual lines (when contours=False).
- Returns:
The axes containing the plot.
- Return type:
matplotlib.axes.Axes
- primary(freq)
Dispatch to the primary function for the given frequency.
- Parameters:
freq (Frequency)
- Return type:
Array
- property primary_function: Callable[[Frequency], Array]
The primary function (
sora) 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:
- Raises:
NotImplementedError – If no primary property is overridden.
- renumbered(from_ports, to_ports=None, **kwargs)
Return a version of the model with ports renumbered.
See
pmrf.models.composite.transformed.Renumbered.- from_portstuple[int]
The original port indices that map to to_ports.
- to_portstuple[int]
The new port indices.
- s_jacobian(freq)
Calculate the Jacobian of the S-parameters with respect to free parameters.
See
func_jacobian().
- sampled(key=None, **kwargs)
Returns a new model with parameters sampled from this parameter’s distribution.
- Return type:
- terminated(load=None, **kwargs)
Returns a new model that contains this model terminated in another.
See
pmrf.models.composite.transformed.Terminated.
- tied(shared_model)
Return the model with self structurally tied to a shared model.
Same as with_tied_submodels but operates directly on self.
- to_skrf(frequency, sigma=0.0, **kwargs)
Convert the model at frequencies to an
skrf.Network.The active primary property (
self.primary_property) is used.
- with_all_params_fixed(**kwargs)
Returns a model with all parameters fixed.
This is an alias for calling
with_free_params()with fix_others=True and no parameters passed.See
`with_free_params`().
- with_all_params_free(**kwargs)
Returns a model with all parameters free.
This is an alias for calling
with_free_params()with all parameters passed.See
`with_free_params`().
- classmethod with_defaults(*args, **kwargs)
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__.
- with_demoted_param_groups()
Recursively demote parameter groups to the deepest possible submodel.
This method identifies parameter groups where every parameter belongs to the same immediate submodel. It moves those groups to the submodel, stripping the prefix. It then recursively calls this method on the submodels to ensure groups continue moving down the hierarchy as far as possible.
- Returns:
A new model instance with parameter groups distributed to their lowest relevant submodels.
- Return type:
Self
- Parameters:
self (Self)
- with_fields(*args, **kwargs)
Return a copy of this model with dataclass-style field replacements.
Parameters are forwarded to
dataclasses.replace().
- with_fixed_params(param_filter, free_others=False, **kwargs)
Return a model with specified parameters fixed.
This maps each parameter in the filter, calling
Parameter.as_fixed()on each.See
with_mapped_params().
- with_fixed_submodels(submodels)
Fix all parameters in the given submodels.
Submodels parameters are obtained using
param_names()., and subsequently fixed using`with_fixed_params`().
- with_free_params(param_filter, *, fix_others=False, **kwargs)
Free the specified parameters.
This maps each parameter in the filter, calling
Parameter.as_free()on each.See
with_mapped_params().
- with_free_params_only(param_filter, **kwargs)
Returns a model with only the specified parameters freed.
This is an alias for calling
with_free_params()with fix_others=True.See
`with_free_params`().
- with_free_submodels(submodels, include_fixed=False, fix_others=False)
Free all parameters in the given submodels.
Submodels parameters are obtained using
param_names()., and subsequently freed using`with_free_params`().- Parameters:
- Return type:
Self
- with_free_submodels_only(*args, **kwargs)
Returns a model with only the specified submodels freed.
This is an alias for calling
with_free_submodels()with fix_others=True.See
`with_free_params`().
- with_injected_params(submodel_attrs, shared_model)
Return a copy of the model with free parameters from a shared model injected into target submodels.
This method dynamically overrides the parameter values of internal submodels using the values from an external shared model. It is designed to be called during the forward pass (e.g., inside __call__) to enforce hard equality constraints on parameters that were structurally tied using
with_tied_submodels().- Parameters:
- Returns:
A new model instance with the updated parameter values injected.
- Return type:
Self
- with_mapped_distributions(mapper, dist_filter=None, *, map_others=None, param_groups=False)
Return a model with a function applied to its parameter distributions.
This method allows for bulk-updates of distributions, such as widening variances or changing distribution types.
If
param_groupsis False, the mapping is applied to the distributions of individual parameters (flattened).If
param_groupsis True, the mapping is applied to the distributions ofParameterGroupobjects. This mode is recursive: it will traverse the model tree and apply the mapping to all explicit parameter groups in all submodels.- Parameters:
mapper (Callable[[Distribution], Distribution]) – Function that takes a distribution and returns a new one.
dist_filter (Callable[[Distribution], bool] | None, default=None) – A predicate function. If provided, the mapping is only applied to distributions where
dist_filter(dist)is True. If None, applies to all.map_others (Callable[[Distribution], Distribution] | None, default=None) – An optional map to apply to all distributions NOT in the filter.
param_groups (bool, default=False) – If True, map distributions on parameter groups (recursively). If False, map distributions on individual parameters (flat).
self (Self)
- Returns:
A new model with updated distributions.
- Return type:
Self
- with_mapped_params(mapper, param_filter=None, *, map_others=None, prefixes=False, include_fixed=False)
Return a model with specified parameters mapped.
- Parameters:
mapper (Callable[[Parameter], Parameter]) – The map to apply to each parameter in the filter (or all if no filter).
param_filter (str | Sequence[str] | Callable[[str], bool] | None, default=None) – Parameter names to map. If None, applies mapper to all parameters.
map_others (Callable[[Parameter], Parameter] | None, default=None) – An optional map to apply to all parameters NOT in the filter.
prefixes (bool, default=False) – Specifies that, when a string or list of strings is passed in param_filter, these must be interpreted as parameter prefixes to map and not full path names. Defaults to False.
self (Self)
include_fixed (bool)
- Return type:
Self
- with_models(models)
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.
- with_name(name)
Return a copy of this model with a different name.
- with_no_param_groups()
Return a new model with all parameter groups removed recursively.
This clears the _param_groups of the current model and traverses all nested submodels (and sequences of submodels) to remove their parameter groups as well.
- Returns:
A new model instance with no parameter groups.
- Return type:
Self
- Parameters:
self (Self)
- with_param_groups(param_groups)
Return a model with parameter groups appended, replacing existing relationships.
This method implements an “atomic replacement” policy. If any parameter in an existing group is claimed by a new group, the entire existing group is removed.
This ensures that groups defining joint distributions are not left in an invalid broken state (e.g. having a dimension removed). Parameters that were in the removed group but not in the new group will revert to being ungrouped (handled by param_groups as singleton groups).
- Parameters:
param_groups (ParameterGroup or list[ParameterGroup]) – Group(s) to add.
self (Self)
- Return type:
Self
- with_params(params=None, check_missing=False, check_unknown=True, fix_others=False, include_fixed=False, **param_kwargs)
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_paramsorder). You may also pass keyword args.check_missing (bool, default=False) – Require that all model parameters are specified.
check_unknown (bool, default=True) – 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
paramsmapping.**param_kwargs (dict) – Additional parameter updates by name.
self (Self)
- Return type:
Self
- Raises:
Exception – If shape/order mismatches, unknown/missing names (when checked), or if arrays are found outside of Parameters.
- with_submodel_fields(submodel, *args, **kwargs)
Return a copy of this model with dataclass-style field replacements on a nested sub-model.
Parameters are forwarded to
dataclasses.replace().
- with_tied_submodels(submodel_attrs, shared_model)
Return a copy of the model with specified submodels structurally tied to a shared model.
This method prepares submodels to act as structural proxies during optimization. It prevents the optimizer from seeing duplicate free parameters by fixing the target submodel’s parameters. If the target submodel’s type matches the shared model, only the overlapping free parameters are fixed. If the types differ, the target submodel is entirely replaced by a fully fixed copy of the shared model.
This is typically used in __post_init__ to set up the model structure, and paired with
with_injected_params()during the forward pass.
- with_uniform_distributions(percentage, param_filter=None, *, respect_bounds=False, remove_param_groups=True, zero_values='keep', **kwargs)
Return a model with uniform distributions set centered on current parameter values.
The distributions are defined with bounds calculated as
value * (1.0 +/- percentage).- Parameters:
percentage (float) – The fractional width of the uniform distribution (e.g. 0.1 = 10%).
filter (str | Sequence[str] | Callable[[str], bool], default=None) – The parameters to be updated with new uniform distributions. For the default case, all are updated.
respect_bounds (bool, default=False) – Whether or not the min and max bounds of the current distributions should be respected. If True, new bounds will not go larger than past these bounds.
remove_param_groups (bool, default=True) – Whether to remove parameter groups recursively when setting the uniform distributions. Otherwise, the joint distribution of the model may not be the desired uniform distribution.
zero_values (str, default='keep') – How to treat zero values. Currently the only option is to keep them and their bounds as is.
param_filter (str | Sequence[str] | Parameter | Sequence[Parameter] | Callable[[str], bool])
- Returns:
A new model with updated parameter distributions.
- Return type:
Self
- y_jacobian(freq)
Calculate the Jacobian of the Y-parameters with respect to free parameters.
See
func_jacobian().
- z_jacobian(freq)
Calculate the Jacobian of the Z-parameters with respect to free parameters.
See
func_jacobian().