Debian Codegraph @

skrf/vectorFitting.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import logging
4 import os
5 import warnings
6 from timeit import default_timer as timer
7 from typing import TYPE_CHECKING, Any
8
9 import numpy as np
10 from scipy.integrate import trapezoid
11
12 from .util import Axes, axes_kwarg
13
14 # imports for type hinting
15 if TYPE_CHECKING:
16 from .network import Network
17
18
19 logger = logging.getLogger(__name__)
20
21
22 class VectorFitting:
23 """
24 This class provides a Python implementation of the Vector Fitting algorithm and various functions for the fit
25 analysis, passivity evaluation and enforcement, and export of SPICE equivalent circuits.
26
27 Parameters
28 ----------
29 network : :class:`skrf.network.Network`
30 Network instance of the :math:`N`-port holding the frequency responses to be fitted, for example a
31 scattering, impedance or admittance matrix.
32
33 Examples
34 --------
35 Load the `Network`, create a `VectorFitting` instance, perform the fit with a given number of real and
36 complex-conjugate starting poles:
37
38 >>> nw_3port = skrf.Network('my3port.s3p')
39 >>> vf = skrf.VectorFitting(nw_3port)
40 >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4)
41
42 Notes
43 -----
44 The fitting code is based on the original algorithm [#Gustavsen_vectfit]_ and on two improvements for relaxed pole
45 relocation [#Gustavsen_relaxed]_ and efficient (fast) solving [#Deschrijver_fast]_. See also the Vector Fitting
46 website [#vectfit_website]_ for further information and download of the papers listed below. A Matlab implementation
47 is also available there for reference.
48
49 References
50 ----------
51 .. [#Gustavsen_vectfit] B. Gustavsen, A. Semlyen, "Rational Approximation of Frequency Domain Responses by Vector
52 Fitting", IEEE Transactions on Power Delivery, vol. 14, no. 3, pp. 1052-1061, July 1999,
53 DOI: https://doi.org/10.1109/61.772353
54
55 .. [#Gustavsen_relaxed] B. Gustavsen, "Improving the Pole Relocating Properties of Vector Fitting", IEEE
56 Transactions on Power Delivery, vol. 21, no. 3, pp. 1587-1592, July 2006,
57 DOI: https://doi.org/10.1109/TPWRD.2005.860281
58
59 .. [#Deschrijver_fast] D. Deschrijver, M. Mrozowski, T. Dhaene, D. De Zutter, "Marcomodeling of Multiport Systems
60 Using a Fast Implementation of the Vector Fitting Method", IEEE Microwave and Wireless Components Letters,
61 vol. 18, no. 6, pp. 383-385, June 2008, DOI: https://doi.org/10.1109/LMWC.2008.922585
62
63 .. [#vectfit_website] Vector Fitting website: https://www.sintef.no/projectweb/vectorfitting/
64 """
65
66 def __init__(self, network: Network):
67 self.network = network
68 """ Instance variable holding the Network to be fitted. This is the Network passed during initialization,
69 which may be changed or set to *None*. """
70
71 self.poles = None
72 """ Instance variable holding the list of fitted poles. It will be initialized by :func:`vector_fit` or
73 :func:`auto_fit`. This array is 1-dimensional with shape :math:`(K)`, where :math:`K_{real} + K_{complex}` is
74 the number of real and complex-conjugate poles. This implies that only one part of a complex-conjugate pair is
75 stored in this array (the one with the positive imaginary part). When calculating the model response in
76 pole-residue form, the missing part of each complex-conjugate pair has to be added manually. See the source
77 code of :func:`get_model_response()` as an example. """
78
79 self.residues = None
80 """ Instance variable holding the list of fitted residues. It will be initialized by :func:`vector_fit` or
81 :func:`auto_fit`. This array is 2-dimensional with shape :math:`(M, K)`, where :math:`M = N_{ports}^2` is the
82 number of frequency responses of the fitted network, and :math:`K` is the number of real and complex-conjugate
83 poles. See the documentation of :attr:`poles` for details about complex-conjugate pairs. The residues of the
84 individual frequency responses are stacked in row-major format (C-like), for example `[[S11_1, S11_2, ...],
85 [S12_1, S12_2, ...], [S21_1, S21_2, ...], [S22_1, S22_2, ...]]` for a 2-port network. """
86
87 self.proportional_coeff = None
88 """ Instance variable holding the list of fitted proportional coefficients. It will be initialized by
89 :func:`vector_fit` or :func:`auto_fit`. This array is 1-dimensional with shape :math:`M`, where
90 :math:`M = N_{ports}^2` is the number of frequency responses of the fitted network, and :math:`K` is the number
91 of real and complex-conjugate poles. See the documentation of :attr:`poles` for details about complex-conjugate
92 pairs. The proportional coefficient of the individual frequency responses are stacked in row-major format
93 (C-like), for example `[S11, S12, S21, S22]` for a 2-port network. """
94
95 self.constant_coeff = None
96 """ Instance variable holding the list of fitted constants. It will be initialized by :func:`vector_fit` or
97 :func:`auto_fit`. This array is 1-dimensional with shape :math:`M`, where :math:`M = N_{ports}^2` is the number
98 of frequency responses of the fitted network, and :math:`K` is the number of real and complex-conjugate poles.
99 See the documentation of :attr:`poles` for details about complex-conjugate pairs. The constants of the
100 individual frequency responses are stacked in row-major format (C-like), for example `[S11, S12, S21, S22]` for
101 a 2-port network. """
102
103 self.max_iterations = 100
104 """ Instance variable specifying the maximum number of iterations for the fitting process and for the passivity
105 enforcement. To be changed by the user before calling :func:`vector_fit` and/or :func:`passivity_enforce`. """
106
107 self.max_tol = 1e-6
108 """ Instance variable specifying the convergence criterion in terms of relative tolerance. To be changed by the
109 user before calling :func:`vector_fit`. """
110
111 self.wall_clock_time = 0
112 """ Instance variable holding the wall-clock time (in seconds) consumed by the most recent fitting process with
113 :func:`vector_fit`. Subsequent calls of :func:`vector_fit` will overwrite this value. """
114
115 self.d_res_history = []
116 self.delta_max_history = []
117 self.history_max_sigma = []
118 self.history_cond_A = []
119 self.history_rank_deficiency = []
120
121 @staticmethod
122 def get_spurious(poles: np.ndarray, residues: np.ndarray, n_freqs: int = 101, gamma: float = 0.03) -> np.ndarray:
123 """
124 Classifies fitted pole-residue pairs as spurious or not spurious. The implementation is based on the evaluation
125 of band-limited energy norms (p=2) of the resonance curves of individual pole-residue pairs, as proposed in
126 [#Grivet-Talocia]_.
127
128 Parameters
129 ----------
130 poles : ndarray, shape (N)
131 Array of fitted poles
132
133 residues : ndarray, shape (M, N)
134 Array of fitted residues
135
136 n_freqs : int, optional
137 Number of frequencies for the evaluation. The frequency range is chosen automatically and the default
138 101 frequencies should be appropriate in most cases.
139
140 gamma : float, optional
141 Sensitivity threshold for the classification. Typical values range from 0.01 to 0.05.
142
143 Returns
144 -------
145 ndarray, bool, shape (M)
146 Boolean array having the same shape as :attr:`poles`. `True` marks the respective pole as spurious.
147
148 References
149 ----------
150 .. [#Grivet-Talocia] S. Grivet-Talocia and M. Bandinu, "Improving the convergence of vector fitting for
151 equivalent circuit extraction from noisy frequency responses," in IEEE Transactions on Electromagnetic
152 Compatibility, vol. 48, no. 1, pp. 104-120, Feb. 2006, DOI: https://doi.org/10.1109/TEMC.2006.870814
153 """
154
155 omega_eval = np.linspace(np.min(poles.imag) / 3, np.max(poles.imag) * 3, n_freqs)
156 h = (residues[:, None, :] / (1j * omega_eval[:, None] - poles)
157 + np.conj(residues[:, None, :]) / (1j * omega_eval[:, None] - np.conj(poles)))
158 norm2 = np.sqrt(trapezoid(h.real ** 2 + h.imag ** 2, omega_eval, axis=1))
159 spurious = np.all(norm2 / np.mean(norm2) < gamma, axis=0)
160 return spurious
161
162 @staticmethod
163 def get_model_order(poles: np.ndarray) -> int:
164 """
165 Returns the model order calculated with :math:`N_{real} + 2 N_{complex}` for a given set of poles.
166
167 Parameters
168 ----------
169 poles: ndarray
170 The poles of the model as a list or NumPy array.
171
172 Returns
173 -------
174 order: int
175 """
176 # poles.imag != 0 is True(1) for complex poles, False (0) for real poles.
177 # Adding one to each element gives 2 columns for complex and 1 column for real poles.
178 return np.sum((poles.imag != 0) + 1)
179
180 def vector_fit(self, n_poles_real: int = 2, n_poles_cmplx: int = 2, init_pole_spacing: str = 'lin',
181 parameter_type: str = 's', fit_constant: bool = True, fit_proportional: bool = False) -> None:
182 """
183 Main work routine performing the vector fit. The results will be stored in the class variables
184 :attr:`poles`, :attr:`residues`, :attr:`proportional_coeff` and :attr:`constant_coeff`.
185
186 Parameters
187 ----------
188 n_poles_real : int, optional
189 Number of initial real poles. See notes.
190
191 n_poles_cmplx : int, optional
192 Number of initial complex conjugate poles. See notes.
193
194 init_pole_spacing : str, optional
195 Type of initial pole spacing across the frequency interval of the S-matrix. Either *linear* (`'lin'`),
196 *logarithmic* (`'log'`), or `custom`. In case of `custom`, the initial poles must be stored in :attr:`poles`
197 as a NumPy array before calling this method. They will be overwritten by the final poles. The
198 initialization parameters `n_poles_real` and `n_poles_cmplx` will be ignored in case of `'custom'`.
199
200 parameter_type : str, optional
201 Representation type of the frequency responses to be fitted. Either *scattering* (`'s'` or `'S'`),
202 *impedance* (`'z'` or `'Z'`) or *admittance* (`'y'` or `'Y'`). It's recommended to perform the fit on the
203 original S parameters. Otherwise, scikit-rf will convert the responses from S to Z or Y, which might work
204 for the fit but can cause other issues.
205
206 fit_constant : bool, optional
207 Include a constant term **d** in the fit.
208
209 fit_proportional : bool, optional
210 Include a proportional term **e** in the fit.
211
212 Returns
213 -------
214 None
215 No return value.
216
217 Notes
218 -----
219 The required number of real or complex conjugate starting poles depends on the behaviour of the frequency
220 responses. To fit a smooth response such as a low-pass characteristic, 1-3 real poles and no complex conjugate
221 poles is usually sufficient. If resonances or other types of peaks are present in some or all of the responses,
222 a similar number of complex conjugate poles is required. Be careful not to use too many poles, as excessive
223 poles will not only increase the computation workload during the fitting and the subsequent use of the model,
224 but they can also introduce unwanted resonances at frequencies well outside the fit interval.
225
226 See Also
227 --------
228 auto_fit : Automatic vector fitting routine with pole adding and skimming.
229 """
230
231 timer_start = timer()
232
233 # use normalized frequencies during the iterations (seems to be more stable during least-squares fit)
234 norm = np.average(self.network.f)
235 # norm = np.exp(np.mean(np.log(self.network.f)))
236 freqs_norm = np.array(self.network.f) / norm
237
238 # get initial poles
239 poles = self._init_poles(freqs_norm, n_poles_real, n_poles_cmplx, init_pole_spacing)
240
241 # check and normalize custom poles
242 if poles is None:
243 if self.poles is not None and len(self.poles) > 0:
244 poles = self.poles / norm
245 else:
246 raise ValueError('Initial poles must be provided in `self.poles` when calling with '
247 '`init_pole_spacing == \'custom\'`.')
248
249 # save initial poles (un-normalize first)
250 initial_poles = poles * norm
251 max_singular = 1
252
253 logger.info('### Starting pole relocation process.\n')
254
255 # select network representation type
256 if parameter_type.lower() == 's':
257 nw_responses = self.network.s
258 elif parameter_type.lower() == 'z':
259 nw_responses = self.network.z
260 elif parameter_type.lower() == 'y':
261 nw_responses = self.network.y
262 else:
263 warnings.warn('Invalid choice of matrix parameter type (S, Z, or Y); proceeding with scattering '
264 'representation.', UserWarning, stacklevel=2)
265 nw_responses = self.network.s
266
267 # stack frequency responses as a single vector
268 # stacking order (row-major):
269 # s11, s12, s13, ..., s21, s22, s23, ...
270 freq_responses = []
271 for i in range(self.network.nports):
272 for j in range(self.network.nports):
273 freq_responses.append(nw_responses[:, i, j])
274 freq_responses = np.array(freq_responses)
275
276 # responses will be weighted according to their norm;
277 # alternative: equal weights with weight_response = 1.0
278 # or anti-proportional weights with weight_response = 1 / np.linalg.norm(freq_response)
279 weights_responses = np.linalg.norm(freq_responses, axis=1)
280 #weights_responses = np.ones(self.network.nports ** 2)
281 #weights_responses = 10 / np.exp(np.mean(np.log(np.abs(freq_responses)), axis=1))
282
283 # ITERATIVE FITTING OF POLES to the provided frequency responses
284 # initial set of poles will be replaced with new poles after every iteration
285 iterations = self.max_iterations
286 self.d_res_history = []
287 self.delta_max_history = []
288 self.history_cond_A = []
289 self.history_rank_deficiency = []
290 converged = False
291
292 # POLE RELOCATION LOOP
293 while iterations > 0:
294 logger.info(f'Iteration {self.max_iterations - iterations + 1}')
295
296 poles, d_res, cond, rank_deficiency, residuals, singular_vals = self._pole_relocation(
297 poles, freqs_norm, freq_responses, weights_responses, fit_constant, fit_proportional)
298
299 logger.info(f'Condition number of coefficient matrix is {int(cond)}')
300 self.history_cond_A.append(cond)
301
302 self.history_rank_deficiency.append(rank_deficiency)
303 logger.info(f'Rank deficiency is {rank_deficiency}.')
304
305 self.d_res_history.append(d_res)
306 logger.info(f'd_res = {d_res}')
307
308 # calculate relative changes in the singular values; stop iteration loop once poles have converged
309 new_max_singular = np.amax(singular_vals)
310 delta_max = np.abs(1 - new_max_singular / max_singular)
311 self.delta_max_history.append(delta_max)
312 logger.info(f'Max. relative change in residues = {delta_max}\n')
313 max_singular = new_max_singular
314
315 stop = False
316 if delta_max < self.max_tol:
317 if converged:
318 # is really converged, finish
319 logger.info(f'Pole relocation process converged after {self.max_iterations - iterations + 1} '
320 'iterations.')
321 stop = True
322 else:
323 # might be converged, but do one last run to be sure
324 converged = True
325 else:
326 if converged:
327 # is not really converged, continue
328 converged = False
329
330 iterations -= 1
331
332 if iterations == 0:
333 # loop ran into iterations limit; trying to assess the issue
334 max_cond = np.amax(self.history_cond_A)
335 max_deficiency = np.amax(self.history_rank_deficiency)
336 if max_cond > 1e10:
337 hint_illcond = ('\nHint: the linear system was ill-conditioned (max. condition number was '
338 f'{max_cond}).')
339 else:
340 hint_illcond = ''
341 if max_deficiency < 0:
342 hint_rank = ('\nHint: the coefficient matrix was rank-deficient (max. rank deficiency was '
343 f'{max_deficiency}).')
344 else:
345 hint_rank = ''
346 if converged and stop is False:
347 warnings.warn('Vector Fitting: The pole relocation process barely converged to tolerance. '
348 f'It took the max. number of iterations (N_max = {self.max_iterations}). '
349 'The results might not have converged properly.'
350 + hint_illcond + hint_rank, RuntimeWarning, stacklevel=2)
351 else:
352 warnings.warn('Vector Fitting: The pole relocation process stopped after reaching the '
353 f'maximum number of iterations (N_max = {self.max_iterations}). '
354 'The results did not converge properly.'
355 + hint_illcond + hint_rank, RuntimeWarning, stacklevel=2)
356
357 if stop:
358 iterations = 0
359
360 # ITERATIONS DONE
361 logger.info('Initial poles before relocation:')
362 logger.info(initial_poles)
363
364 logger.info('Final poles:')
365 logger.info(poles * norm)
366
367 logger.info('\n### Starting residues calculation process.\n')
368
369 # finally, solve for the residues with the previously calculated poles
370 residues, constant_coeff, proportional_coeff, residuals, rank, singular_vals = self._fit_residues(
371 poles, freqs_norm, freq_responses, fit_constant, fit_proportional)
372
373 # save poles, residues, d, e in actual frequencies (un-normalized)
374 self.poles = poles * norm
375 self.residues = np.array(residues) * norm
376 self.constant_coeff = np.array(constant_coeff)
377 self.proportional_coeff = np.array(proportional_coeff) / norm
378
379 timer_stop = timer()
380 self.wall_clock_time = timer_stop - timer_start
381
382 logger.info(f'\n### Vector fitting finished in {self.wall_clock_time} seconds.\n')
383
384 # raise a warning if the fitted Network is passive but the fit is not (only without proportional_coeff):
385 if self.network.is_passive() and not fit_proportional:
386 if not self.is_passive():
387 warnings.warn('The fitted network is passive, but the vector fit is not passive. Consider running '
388 '`passivity_enforce()` to enforce passivity before using this model.',
389 UserWarning, stacklevel=2)
390
391 def auto_fit(self, n_poles_init_real: int = 3, n_poles_init_cmplx: int = 3, n_poles_add: int = 3,
392 model_order_max: int = 100, iters_start: int = 3, iters_inter: int = 3, iters_final: int = 5,
393 target_error: float = 1e-2, alpha: float = 0.03, gamma: float = 0.03, nu_samples: float = 1.0,
394 parameter_type: str = 's') -> (np.ndarray, np.ndarray):
395 """
396 Automatic fitting routine implementing the "vector fitting with adding and skimming" algorithm as proposed in
397 [#Grivet-Talocia]_. This algorithm is able to provide high quality macromodels with automatic model order
398 optimization, while improving both the rate of convergence and the fit quality in case of noisy data.
399 The resulting model parameters will be stored in the class variables :attr:`poles`, :attr:`residues`,
400 :attr:`proportional_coeff` and :attr:`constant_coeff`.
401
402 Parameters
403 ----------
404 n_poles_init_real: int, optional
405 Number of real poles in the initial model.
406
407 n_poles_init_cmplx: int, optional
408 Number of complex conjugate poles in the initial model.
409
410 n_poles_add: int, optional
411 Number of new poles allowed to be added in each refinement iteration, if possible. This controls how fast
412 the model order is allowed to grow. Unnecessary poles will have to be skimmed and removed later. This
413 parameter has a strong effect on the convergence.
414
415 model_order_max: int, optional
416 Maximum model order as calculated with :math:`N_{real} + 2 N_{complex}`. This parameter provides a stopping
417 criterion in case the refinement process is not converging.
418
419 iters_start: int, optional
420 Number of initial iterations for pole relocations as in regular vector fitting.
421
422 iters_inter: int, optional
423 Number of intermediate iterations for pole relocations during each iteration of the refinement process.
424
425 iters_final: int, optional
426 Number of final iterations for pole relocations after the refinement process.
427
428 target_error: float, optional
429 Target for the model error to be reached during the refinement process. The actual achievable error is
430 bound by the noise in the data. If specified with a number greater than the noise floor, this parameter
431 provides another stopping criterion for the refinement process. It therefore affects both the convergence,
432 the final error, and the final model order (number of poles used in the model).
433
434 alpha: float, optional
435 Threshold for the error decay to stop the refinement loop in case of error stagnation. This parameter
436 provides another stopping criterion for cases where the model already has enough poles but the target error
437 still cannot be reached because of excess noise (target error too small for noise level in the data).
438
439 gamma: float, optional
440 Threshold for the detection of spurious poles.
441
442 nu_samples: float, optional
443 Required and enforced (relative) spacing in terms of frequency samples between existing poles and
444 relocated or added poles. The number can be a float, it does not have to be an integer.
445
446 parameter_type: str, optional
447 Representation type of the frequency responses to be fitted. Either *scattering* (`'s'` or `'S'`),
448 *impedance* (`'z'` or `'Z'`) or *admittance* (`'y'` or `'Y'`). It's recommended to perform the fit on the
449 original S parameters. Otherwise, scikit-rf will convert the responses from S to Z or Y, which might work
450 for the fit but can cause other issues.
451
452 Returns
453 -------
454 None
455 No return value.
456
457 See Also
458 --------
459 vector_fit : Regular vector fitting routine.
460
461 References
462 ----------
463 .. [#Grivet-Talocia] S. Grivet-Talocia and M. Bandinu, "Improving the convergence of vector fitting for
464 equivalent circuit extraction from noisy frequency responses," in IEEE Transactions on Electromagnetic
465 Compatibility, vol. 48, no. 1, pp. 104-120, Feb. 2006, DOI: https://doi.org/10.1109/TEMC.2006.870814
466 """
467
468 self.d_res_history = []
469 self.delta_max_history = []
470 self.history_cond_A = []
471 self.history_rank_deficiency = []
472 max_singular = 1
473 error_peak_history = []
474 model_order_history = []
475
476 timer_start = timer()
477
478 # use normalized frequencies during the iterations (seems to be more stable during least-squares fit)
479 norm = np.average(self.network.f)
480 # norm = np.exp(np.mean(np.log(self.network.f)))
481 freqs_norm = np.array(self.network.f) / norm
482 omega_norm = 2 * np.pi * freqs_norm
483 nu = (omega_norm[1] - omega_norm[0]) * nu_samples
484
485 # get initial poles
486 poles = self._init_poles(freqs_norm, n_poles_init_real, n_poles_init_cmplx, 'lin')
487
488 logger.info('### Starting pole relocation process.\n')
489
490 # select network representation type
491 if parameter_type.lower() == 's':
492 nw_responses = self.network.s
493 fit_constant = True
494 fit_proportional = False
495 elif parameter_type.lower() == 'z':
496 nw_responses = self.network.z
497 fit_constant = True
498 fit_proportional = True
499 elif parameter_type.lower() == 'y':
500 nw_responses = self.network.y
501 fit_constant = True
502 fit_proportional = True
503 else:
504 warnings.warn('Invalid choice of matrix parameter type (S, Z, or Y); proceeding with scattering '
505 'representation.', UserWarning, stacklevel=2)
506 nw_responses = self.network.s
507 fit_constant = True
508 fit_proportional = False
509
510 # stack frequency responses as a single vector
511 # stacking order (row-major):
512 # s11, s12, s13, ..., s21, s22, s23, ...
513 freq_responses = []
514 for i in range(self.network.nports):
515 for j in range(self.network.nports):
516 freq_responses.append(nw_responses[:, i, j])
517 freq_responses = np.array(freq_responses)
518
519 # responses will be weighted according to their norm;
520 # alternative: equal weights with weight_response = 1.0
521 # or anti-proportional weights with weight_response = 1 / np.linalg.norm(freq_response)
522 weights_responses = np.linalg.norm(freq_responses, axis=1)
523 # weights_responses = np.ones(self.network.nports ** 2)
524 # weights_responses = 10 / np.exp(np.mean(np.log(np.abs(freq_responses)), axis=1))
525
526 # INITIAL POLE RELOCATION FOR i_start ITERATIONS
527 for _ in range(iters_start):
528 poles, d_res, cond, rank_deficiency, residuals, singular_vals = self._pole_relocation(
529 poles, freqs_norm, freq_responses, weights_responses, fit_constant, fit_proportional)
530
531 self.d_res_history.append(d_res)
532
533 logger.info(f'Condition number of coefficient matrix is {int(cond)}')
534 self.history_cond_A.append(cond)
535
536 self.history_rank_deficiency.append(rank_deficiency)
537 logger.info(f'Rank deficiency is {rank_deficiency}.')
538
539 new_max_singular = np.amax(singular_vals)
540 delta_max = np.abs(1 - new_max_singular / max_singular)
541 self.delta_max_history.append(delta_max)
542 logger.info(f'Max. relative change in residues = {delta_max}\n')
543 max_singular = new_max_singular
544
545 # RESIDUE FITTING FOR ERROR COMPUTATION
546 residues, constant_coeff, proportional_coeff, residuals, rank, singular_vals = self._fit_residues(
547 poles, freqs_norm, freq_responses, fit_constant, fit_proportional, enforce_dc=False)
548 delta = self._get_delta(poles, residues, constant_coeff, proportional_coeff, freqs_norm, freq_responses,
549 weights_responses)
550 error_peak = np.max(delta)
551 error_peak_history.append(error_peak)
552
553 model_order = self.get_model_order(poles)
554 model_order_history.append(model_order)
555
556 delta_eps = 10 * alpha
557
558 # POLE SKIMMING AND ADDING LOOP
559 while error_peak > target_error and model_order < model_order_max and delta_eps > alpha:
560
561 # SKIMMING OF SPURIOUS POLES
562 spurious = self.get_spurious(poles, residues, gamma=gamma)
563 n_skim = np.sum(spurious)
564 poles = poles[~spurious]
565
566 # REPLACING SPURIOUS POLE AND ADDING NEW POLES
567 idx_freqs_start, idx_freqs_stop, idx_freqs_max, delta_mean_bands = self._find_error_bands(freqs_norm, delta)
568
569 n_bands = len(idx_freqs_max)
570 if n_bands < n_skim:
571 n_add = n_bands
572 elif n_bands < n_skim + n_poles_add:
573 n_add = n_bands
574 else:
575 n_add = n_skim + n_poles_add
576
577 for i in range(n_add):
578 omega_add = omega_norm[idx_freqs_max[i]]
579 pole_add = (-0.01 + 1j) * omega_add
580
581 # compute distance to neighbouring poles
582 abs_poles_existing = np.abs(poles) - pole_add.imag # (equation 16)
583 #abs_poles_existing = np.abs(poles - pole_add) # (equation 17)
584
585 # avoid forbidden bands (too close to neighbour)
586 if np.min(abs_poles_existing) < nu or pole_add.imag < nu:
587 # decide shift direction (towards higher or lower frequencies)
588 if idx_freqs_max[i] > 0:
589 delta_below = delta[idx_freqs_max[i] - 1]
590 else:
591 delta_below = 0
592 if idx_freqs_max[i] < len(omega_norm) - 1:
593 delta_above = delta[idx_freqs_max[i] + 1]
594 else:
595 delta_above = 0
596
597 if delta_above > delta_below:
598 # shift to higher frequencies
599 pole_add += 1j * nu
600 else:
601 # shift to lower frequencies
602 pole_add -= 1j * nu
603
604 poles = np.append(poles, [pole_add])
605
606 # INTERMEDIATE POLE RELOCATION FOR i_inter ITERATIONS
607 for _ in range(iters_inter):
608 poles, d_res, cond, rank_deficiency, residuals, singular_vals = self._pole_relocation(
609 poles, freqs_norm, freq_responses, weights_responses, fit_constant, fit_proportional)
610
611 self.d_res_history.append(d_res)
612
613 logger.info(f'Condition number of coefficient matrix is {int(cond)}')
614 self.history_cond_A.append(cond)
615
616 self.history_rank_deficiency.append(rank_deficiency)
617 logger.info(f'Rank deficiency is {rank_deficiency}.')
618
619 new_max_singular = np.amax(singular_vals)
620 delta_max = np.abs(1 - new_max_singular / max_singular)
621 self.delta_max_history.append(delta_max)
622 logger.info(f'Max. relative change in residues = {delta_max}\n')
623 max_singular = new_max_singular
624
625 # RESIDUE FITTING FOR ERROR COMPUTATION
626 residues, constant_coeff, proportional_coeff, residuals, rank, singular_vals = self._fit_residues(
627 poles, freqs_norm, freq_responses, fit_constant, fit_proportional, enforce_dc=False)
628 delta = self._get_delta(poles, residues, constant_coeff, proportional_coeff, freqs_norm, freq_responses,
629 weights_responses)
630 error_peak_history.append(np.max(delta))
631
632 m = 3
633 if len(error_peak_history) > m:
634 delta_eps = np.mean(np.abs(np.diff(error_peak_history[-1-m:-1])))
635 else:
636 delta_eps = 1
637
638 model_order = self.get_model_order(poles)
639 model_order_history.append(model_order)
640
641 # SKIMMING OF SPURIOUS POLES
642 spurious = self.get_spurious(poles, residues, gamma=gamma)
643 poles = poles[~spurious]
644
645 # FINAL POLE RELOCATION FOR i_final ITERATIONS
646 for _ in range(iters_final):
647 poles, d_res, cond, rank_deficiency, residuals, singular_vals = self._pole_relocation(
648 poles, freqs_norm, freq_responses, weights_responses, fit_constant, fit_proportional)
649
650 self.d_res_history.append(d_res)
651
652 logger.info(f'Condition number of coefficient matrix is {int(cond)}')
653 self.history_cond_A.append(cond)
654
655 self.history_rank_deficiency.append(rank_deficiency)
656 logger.info(f'Rank deficiency is {rank_deficiency}.')
657
658 new_max_singular = np.amax(singular_vals)
659 delta_max = np.abs(1 - new_max_singular / max_singular)
660 self.delta_max_history.append(delta_max)
661 logger.info(f'Max. relative change in residues = {delta_max}\n')
662 max_singular = new_max_singular
663
664 # FINAL RESIDUE FITTING
665 residues, constant_coeff, proportional_coeff, residuals, rank, singular_vals = self._fit_residues(
666 poles, freqs_norm, freq_responses, fit_constant, fit_proportional, enforce_dc=True)
667
668 # save poles, residues, d, e in actual frequencies (un-normalized)
669 self.poles = poles * norm
670 self.residues = np.array(residues) * norm
671 self.constant_coeff = np.array(constant_coeff)
672 self.proportional_coeff = np.array(proportional_coeff) / norm
673
674 timer_stop = timer()
675 self.wall_clock_time = timer_stop - timer_start
676
677 @staticmethod
678 def _init_poles(freqs: list, n_poles_real: int, n_poles_cmplx: int, init_pole_spacing: str):
679 # create initial poles and space them across the frequencies in the provided Touchstone file
680
681 fmin = np.amin(freqs)
682 fmax = np.amax(freqs)
683
684 # poles cannot be at f=0; hence, f_min for starting pole must be greater than 0
685 if fmin == 0.0:
686 # random choice: use 1/1000 of first non-zero frequency
687 fmin = freqs[1] / 1000
688
689 init_pole_spacing = init_pole_spacing.lower()
690 if init_pole_spacing == 'log':
691 pole_freqs_real = np.geomspace(fmin, fmax, n_poles_real)
692 pole_freqs_cmplx = np.geomspace(fmin, fmax, n_poles_cmplx)
693 elif init_pole_spacing == 'lin':
694 pole_freqs_real = np.linspace(fmin, fmax, n_poles_real)
695 pole_freqs_cmplx = np.linspace(fmin, fmax, n_poles_cmplx)
696 elif init_pole_spacing == 'custom':
697 pole_freqs_real = None
698 pole_freqs_cmplx = None
699 else:
700 warnings.warn('Invalid choice of initial pole spacing; proceeding with linear spacing.',
701 UserWarning, stacklevel=2)
702 pole_freqs_real = np.linspace(fmin, fmax, n_poles_real)
703 pole_freqs_cmplx = np.linspace(fmin, fmax, n_poles_cmplx)
704
705 if pole_freqs_real is not None and pole_freqs_cmplx is not None:
706 # init poles array of correct length
707 poles = np.zeros(n_poles_real + n_poles_cmplx, dtype=complex)
708
709 # add real poles
710 for i, f in enumerate(pole_freqs_real):
711 omega = 2 * np.pi * f
712 poles[i] = -1 * omega
713
714 # add complex-conjugate poles (store only positive imaginary parts)
715 i_offset = len(pole_freqs_real)
716 for i, f in enumerate(pole_freqs_cmplx):
717 omega = 2 * np.pi * f
718 poles[i_offset + i] = (-0.01 + 1j) * omega
719
720 return poles
721
722 else:
723 return None
724
725 @staticmethod
726 def _pole_relocation(poles, freqs, freq_responses, weights_responses, fit_constant, fit_proportional):
727 n_responses, n_freqs = np.shape(freq_responses)
728 n_samples = n_responses * n_freqs
729 omega = 2 * np.pi * freqs
730 s = 1j * omega
731
732 # weight of extra equation to avoid trivial solution
733 weight_extra = np.linalg.norm(weights_responses[:, None] * freq_responses) / n_samples
734
735 # weights w are applied directly to the samples, which get squared during least-squares fitting; hence sqrt(w)
736 weights_responses = np.sqrt(weights_responses)
737 weight_extra = np.sqrt(weight_extra)
738
739 # count number of rows and columns in final coefficient matrix to solve for (c_res, d_res)
740 # (ratio #real/#complex poles might change during iterations)
741
742 # We need two columns for complex poles and one column for real poles in A matrix.
743 # This number equals the model order.
744 n_cols_unused = VectorFitting.get_model_order(poles)
745
746 n_cols_used = n_cols_unused
747 n_cols_used += 1
748 idx_constant = []
749 idx_proportional = []
750 if fit_constant:
751 idx_constant = [n_cols_unused]
752 n_cols_unused += 1
753 if fit_proportional:
754 idx_proportional = [n_cols_unused]
755 n_cols_unused += 1
756
757 real_mask = poles.imag == 0
758 # list of indices in 'poles' with real values
759 idx_poles_real = np.nonzero(real_mask)[0]
760 # list of indices in 'poles' with complex values
761 idx_poles_complex = np.nonzero(~real_mask)[0]
762
763 # positions (columns) of coefficients for real and complex-conjugate terms in the rows of A determine the
764 # respective positions of the calculated residues in the results vector.
765 # to have them ordered properly for the subsequent assembly of the test matrix H for eigenvalue extraction,
766 # place real poles first, then complex-conjugate poles with their respective real and imaginary parts:
767 # [r1', r2', ..., (r3', r3''), (r4', r4''), ...]
768 n_real = len(idx_poles_real)
769 n_cmplx = len(idx_poles_complex)
770 idx_res_real = np.arange(n_real)
771 idx_res_complex_re = n_real + 2 * np.arange(n_cmplx)
772 idx_res_complex_im = idx_res_complex_re + 1
773
774 # complex coefficient matrix of shape [N_responses, N_freqs, n_cols_unused + n_cols_used]
775 # layout of each row:
776 # [pole1, pole2, ..., (constant), (proportional), pole1, pole2, ..., constant]
777 A = np.empty((n_responses, n_freqs, n_cols_unused + n_cols_used), dtype=complex)
778
779 # calculate coefficients for real and complex residues in the solution vector
780 #
781 # real pole-residue term (r = r', p = p'):
782 # fractional term is r' / (s - p')
783 # coefficient for r' is 1 / (s - p')
784 coeff_real = 1 / (s[:, None] - poles[None, idx_poles_real])
785
786 # complex-conjugate pole-residue pair (r = r' + j r'', p = p' + j p''):
787 # fractional term is r / (s - p) + conj(r) / (s - conj(p))
788 # = [1 / (s - p) + 1 / (s - conj(p))] * r' + [1j / (s - p) - 1j / (s - conj(p))] * r''
789 # coefficient for r' is 1 / (s - p) + 1 / (s - conj(p))
790 # coefficient for r'' is 1j / (s - p) - 1j / (s - conj(p))
791 coeff_complex_re = (1 / (s[:, None] - poles[None, idx_poles_complex]) +
792 1 / (s[:, None] - np.conj(poles[None, idx_poles_complex])))
793 coeff_complex_im = (1j / (s[:, None] - poles[None, idx_poles_complex]) -
794 1j / (s[:, None] - np.conj(poles[None, idx_poles_complex])))
795
796 # part 1: first sum of rational functions (variable c)
797 A[:, :, idx_res_real] = coeff_real
798 A[:, :, idx_res_complex_re] = coeff_complex_re
799 A[:, :, idx_res_complex_im] = coeff_complex_im
800
801 # part 2: constant (variable d) and proportional term (variable e)
802 A[:, :, idx_constant] = 1
803 A[:, :, idx_proportional] = s[:, None]
804
805 # part 3: second sum of rational functions multiplied with frequency response (variable c_res)
806 A[:, :, n_cols_unused + idx_res_real] = -1 * freq_responses[:, :, None] * coeff_real
807 A[:, :, n_cols_unused + idx_res_complex_re] = -1 * freq_responses[:, :, None] * coeff_complex_re
808 A[:, :, n_cols_unused + idx_res_complex_im] = -1 * freq_responses[:, :, None] * coeff_complex_im
809
810 # part 4: constant (variable d_res)
811 A[:, :, -1] = -1 * freq_responses
812
813 A_ri = np.hstack((A.real, A.imag))
814
815 # calculation of matrix sizes after QR decomposition:
816 # stacked coefficient matrix (A.real, A.imag) has shape (L, M, N)
817 # with
818 # L = n_responses = n_ports ** 2
819 # M = 2 * n_freqs (because of hstack with 2x n_freqs)
820 # N = n_cols_unused + n_cols_used
821 # then
822 # R has shape (L, K, N) with K = min(M, N)
823 dim_m = 2 * n_freqs
824 dim_n = n_cols_unused + n_cols_used
825 dim_k = min(dim_m, dim_n)
826
827 # QR decomposition
828 # R = np.linalg.qr(A_ri, 'r')
829
830 # direct QR of stacked matrices for linalg.qr() only works with numpy>=1.22.0
831 # workaround for old numpy:
832 R = np.empty((n_responses, dim_k, dim_n))
833 for i in range(n_responses):
834 R[i] = np.linalg.qr(A_ri[i], mode='r')
835
836 # only R22 is required to solve for c_res and d_res
837 # R12 and R22 can have a different number of rows, depending on K
838 if dim_k == dim_m:
839 # K = M
840 n_rows_r12 = n_freqs
841 n_rows_r22 = n_freqs
842 else:
843 # K = N
844 n_rows_r12 = n_cols_unused
845 n_rows_r22 = n_cols_used
846 R22 = R[:, n_rows_r12:, n_cols_unused:]
847
848 # weighting
849 R22 = weights_responses[:, None, None] * R22
850
851 # assemble compressed coefficient matrix A_fast by row-stacking individual upper triangular matrices R22
852 dim0 = n_responses * n_rows_r22 + 1
853
854 A_fast = np.empty((dim0, n_cols_used))
855 A_fast[:-1, :] = R22.reshape((dim0 - 1, n_cols_used))
856
857 # extra equation to avoid trivial solution
858 A_fast[-1, idx_res_real] = np.sum(coeff_real.real, axis=0)
859 A_fast[-1, idx_res_complex_re] = np.sum(coeff_complex_re.real, axis=0)
860 A_fast[-1, idx_res_complex_im] = np.sum(coeff_complex_im.real, axis=0)
861 A_fast[-1, -1] = n_freqs
862
863 # weighting
864 A_fast[-1, :] = weight_extra * A_fast[-1, :]
865
866 scaling = 1 / np.linalg.norm(A_fast, axis=0)
867 A_fast = scaling * A_fast
868
869 # right hand side vector (weighted)
870 b = np.zeros(dim0)
871 b[-1] = weight_extra * n_samples
872
873 # check condition of the linear system
874 cond = np.linalg.cond(A_fast)
875 full_rank = np.min(A_fast.shape)
876
877 # solve least squares for real parts
878 x, residuals, rank, singular_vals = np.linalg.lstsq(A_fast, b, rcond=None)
879
880 x = scaling * x
881
882 # rank deficiency
883 rank_deficiency = full_rank - rank
884
885 # assemble individual result vectors from single LS result x
886 c_res = x[:-1]
887 d_res = x[-1]
888
889 # check if d_res is suited for zeros calculation
890 tol_res = 1e-8
891 if np.abs(d_res) < tol_res:
892 # d_res is too small, discard solution and proceed the |d_res| = tol_res
893 logger.info(f'Replacing d_res solution as it was too small ({d_res}).')
894 d_res = tol_res * (d_res / np.abs(d_res))
895
896 # build test matrix H, which will hold the new poles as eigenvalues
897 H = np.zeros((len(c_res), len(c_res)))
898
899 poles_real = poles[np.nonzero(real_mask)]
900 poles_cplx = poles[np.nonzero(~real_mask)]
901
902 H[idx_res_real, idx_res_real] = poles_real.real
903 H[idx_res_real] -= c_res / d_res
904
905 H[idx_res_complex_re, idx_res_complex_re] = poles_cplx.real
906 H[idx_res_complex_re, idx_res_complex_im] = poles_cplx.imag
907 H[idx_res_complex_im, idx_res_complex_re] = -1 * poles_cplx.imag
908 H[idx_res_complex_im, idx_res_complex_im] = poles_cplx.real
909 H[idx_res_complex_re] -= 2 * c_res / d_res
910
911 poles_new = np.linalg.eigvals(H)
912
913 # replace poles for next iteration
914 # complex poles need to come in complex conjugate pairs; append only the positive part
915 poles = poles_new[np.nonzero(poles_new.imag >= 0)]
916
917 # flip real part of unstable poles (real part needs to be negative for stability)
918 poles.real = -1 * np.abs(poles.real)
919
920 return poles, d_res, cond, rank_deficiency, residuals, singular_vals
921
922 @staticmethod
923 def _fit_residues(poles, freqs, freq_responses, fit_constant, fit_proportional, enforce_dc=True):
924 n_responses, n_freqs = np.shape(freq_responses)
925 omega = 2 * np.pi * freqs
926 s = 1j * omega
927
928 # We need two columns for complex poles and one column for real poles in A matrix.
929 # This number equals the model order.
930 n_cols = VectorFitting.get_model_order(poles)
931
932 idx_constant = []
933 idx_proportional = []
934 if fit_constant:
935 idx_constant = [n_cols]
936 n_cols += 1
937 if fit_proportional:
938 idx_proportional = [n_cols]
939 n_cols += 1
940
941 # list of indices in 'poles' with real and with complex values
942 real_mask = poles.imag == 0
943 idx_poles_real = np.nonzero(real_mask)[0]
944 idx_poles_complex = np.nonzero(~real_mask)[0]
945
946 # find and save indices of real and complex poles in the poles list
947 i = 0
948 idx_res_real = []
949 idx_res_complex_re = []
950 idx_res_complex_im = []
951 for pole in poles:
952 if pole.imag == 0:
953 idx_res_real.append(i)
954 i += 1
955 else:
956 idx_res_complex_re.append(i)
957 idx_res_complex_im.append(i + 1)
958 i += 2
959
960 # complex coefficient matrix of shape [N_freqs, n_cols]
961 # layout of each row:
962 # [pole1, pole2, ..., (constant), (proportional)]
963 A = np.empty((n_freqs, n_cols), dtype=complex)
964
965 # calculate coefficients for real and complex residues in the solution vector
966 #
967 # real pole-residue term (r = r', p = p'):
968 # fractional term is r' / (s - p')
969 # coefficient for r' is 1 / (s - p')
970 coeff_real = 1 / (s[:, None] - poles[None, idx_poles_real])
971
972 # complex-conjugate pole-residue pair (r = r' + j r'', p = p' + j p''):
973 # fractional term is r / (s - p) + conj(r) / (s - conj(p))
974 # = [1 / (s - p) + 1 / (s - conj(p))] * r' + [1j / (s - p) - 1j / (s - conj(p))] * r''
975 # coefficient for r' is 1 / (s - p) + 1 / (s - conj(p))
976 # coefficient for r'' is 1j / (s - p) - 1j / (s - conj(p))
977 coeff_complex_re = (1 / (s[:, None] - poles[None, idx_poles_complex]) +
978 1 / (s[:, None] - np.conj(poles[None, idx_poles_complex])))
979 coeff_complex_im = (1j / (s[:, None] - poles[None, idx_poles_complex]) -
980 1j / (s[:, None] - np.conj(poles[None, idx_poles_complex])))
981
982 # part 1: first sum of rational functions (variable c)
983 A[:, idx_res_real] = coeff_real
984 A[:, idx_res_complex_re] = coeff_complex_re
985 A[:, idx_res_complex_im] = coeff_complex_im
986
987 # part 2: constant (variable d) and proportional term (variable e)
988 A[:, idx_constant] = 1
989 A[:, idx_proportional] = s[:, None]
990
991 scaling = 1 / np.linalg.norm(A, axis=0)
992 A = scaling * A
993
994 # DC POINT ENFORCEMENT
995 if enforce_dc and freqs[0] == 0.0:
996 # data contains the dc point; enforce dc point via linear equality constraint:
997 # 1: remove one variable from the solution vector (constant term, if possible).
998 # 2: solve remaining linear system (without data at dc) with regular least-squares, as usual. the size of
999 # the solution vector, the coefficient matrix, and the right-hand side are reduced by 1
1000 # 3: calculate the removed variable (constant term) with the data from the dc point
1001 #
1002 # linear system: A * x = b
1003 # solution vector x contains the unknown residues
1004 # right-hand side b contains the frequency response to be fitted, sorted by ascending frequency (dc first)
1005 # coefficient matrix A and vector b are split: A = [[A11, A12], [A21, A22]], b = [[b1], [b2]]
1006 # [A11, A12] is the first row used later for dc enforcement
1007 # A21 is a column vector, which is not required anymore
1008 # A22 is the rest of the matrix for usual least-squares fitting
1009
1010 # indexing mask of constrained variable in the columns of matrix A
1011 mask_idx_constrained = np.zeros(n_cols, dtype=bool)
1012 if fit_constant:
1013 # use constant term for constrained
1014 mask_idx_constrained[idx_constant] = True
1015 else:
1016 # constant term not present; arbitrarily use first residue instead
1017 mask_idx_constrained[0] = True
1018
1019 A22 = A[1:, ~mask_idx_constrained]
1020 b2 = freq_responses[:, 1:]
1021
1022 A22_ri = np.vstack((A22.real, A22.imag))
1023 b22_ri = np.hstack((b2.real, b2.imag))
1024
1025 logger.info(f'Condition number of coefficient matrix = {int(np.linalg.cond(A22_ri))}')
1026
1027 # solve least-squares and obtain results as stack of real part vector and imaginary part vector
1028 x2, residuals, rank, singular_vals = np.linalg.lstsq(A22_ri, b22_ri.T, rcond=None)
1029
1030 # solve for x1 using the first row (the dc row):
1031 b1 = freq_responses[:, 0]
1032 A11 = A[0, mask_idx_constrained]
1033 A12 = A[0, ~mask_idx_constrained]
1034 x1 = np.real(1 / A11 * (b1 - np.dot(A12, x2)))
1035
1036 # reassemble x from x1 and x2
1037 x = np.empty((n_cols, n_responses))
1038 x[mask_idx_constrained, :] = x1
1039 x[~mask_idx_constrained, :] = x2
1040 else:
1041 # dc point not included; use and solve the entire linear system with least-squares
1042 A_ri = np.vstack((A.real, A.imag))
1043 b_ri = np.hstack((freq_responses.real, freq_responses.imag))
1044
1045 logger.info(f'Condition number of coefficient matrix = {int(np.linalg.cond(A_ri))}')
1046
1047 # solve least-squares and obtain results as stack of real part vector and imaginary part vector
1048 x, residuals, rank, singular_vals = np.linalg.lstsq(A_ri, b_ri.T, rcond=None)
1049
1050 x = scaling[:, None] * x
1051
1052 # extract residues from solution vector and align them with poles to get matching pole-residue pairs
1053 residues = np.empty((len(freq_responses), len(poles)), dtype=complex)
1054 residues[:, idx_poles_real] = np.transpose(x[idx_res_real])
1055 residues[:, idx_poles_complex] = np.transpose(x[idx_res_complex_re] + 1j * x[idx_res_complex_im])
1056
1057 # extract constant and proportional coefficient, if available
1058 if fit_constant:
1059 constant_coeff = x[idx_constant][0]
1060 else:
1061 constant_coeff = np.zeros(n_responses)
1062
1063 if fit_proportional:
1064 proportional_coeff = x[idx_proportional][0]
1065 else:
1066 proportional_coeff = np.zeros(n_responses)
1067
1068 return residues, constant_coeff, proportional_coeff, residuals, rank, singular_vals
1069
1070 @staticmethod
1071 def _get_delta(poles, residues, constant_coeff, proportional_coeff, freqs, freq_responses, weights_responses):
1072 s = 2j * np.pi * freqs
1073 model = proportional_coeff[:, None] * s + constant_coeff[:, None]
1074 for i, pole in enumerate(poles):
1075 if np.imag(pole) == 0.0:
1076 # real pole
1077 model += residues[:, i, None] / (s - pole)
1078 else:
1079 # complex conjugate pole
1080 model += (residues[:, i, None] / (s - pole) +
1081 np.conjugate(residues[:, i, None]) / (s - np.conjugate(pole)))
1082
1083 # compute weighted error and return global maximum at each frequency across all individual responses
1084 delta = np.abs(model - freq_responses) * weights_responses[:, None]
1085
1086 return np.max(delta, axis=0)
1087
1088 @staticmethod
1089 def _find_error_bands(freqs, delta):
1090 # compute error bands (maximal fit deviation)
1091 delta_mean = np.mean(delta)
1092 error = delta - delta_mean
1093
1094 # find limits of error bands
1095 idx_limits = np.nonzero(np.diff(error > 0))[0]
1096 idx_limits_filtered = idx_limits[np.diff(idx_limits, prepend=0) > 2]
1097
1098 freqs_bands = np.split(freqs, idx_limits_filtered)
1099 error_bands = np.split(error, idx_limits_filtered)
1100 n_bands = len(freqs_bands)
1101
1102 idx_freqs_start = []
1103 idx_freqs_stop = []
1104 idx_freqs_max = []
1105 delta_mean_bands = []
1106 for i_band in range(n_bands):
1107 band_error_mean = np.mean(error_bands[i_band])
1108 if band_error_mean > 0:
1109 # band with excess error;
1110 # find frequency index of error maximum inside this band
1111 i_band_max_error = np.argmax(error_bands[i_band])
1112 i_start = np.nonzero(freqs == freqs_bands[i_band][0])[0][0]
1113 i_stop = np.nonzero(freqs == freqs_bands[i_band][-1])[0][0]
1114 i_max = np.nonzero(freqs == freqs_bands[i_band][i_band_max_error])[0][0]
1115 idx_freqs_start.append(i_start)
1116 idx_freqs_stop.append(i_stop)
1117 idx_freqs_max.append(i_max)
1118 delta_mean_bands.append(np.mean(delta[i_start:i_stop]))
1119
1120 idx_freqs_start = np.array(idx_freqs_start)
1121 idx_freqs_stop = np.array(idx_freqs_stop)
1122 idx_freqs_max = np.array(idx_freqs_max)
1123 delta_mean_bands = np.array(delta_mean_bands)
1124
1125 i_sort = np.flip(np.argsort(delta_mean_bands))
1126
1127 return idx_freqs_start[i_sort], idx_freqs_stop[i_sort], idx_freqs_max[i_sort], delta_mean_bands[i_sort]
1128
1129 def get_rms_error(self, i=-1, j=-1, parameter_type: str = 's'):
1130 r"""
1131 Returns the root-mean-square (rms) error magnitude of the fit, i.e.
1132 :math:`\sqrt{ \mathrm{mean}(|S - S_\mathrm{fit} |^2) }`,
1133 either for an individual response :math:`S_{i+1,j+1}` or for larger slices of the network.
1134
1135 Parameters
1136 ----------
1137 i : int, optional
1138 Row indices of the responses to be evaluated. Either a single row selected by an integer
1139 :math:`i \in [0, N_\mathrm{ports}-1]`, or multiple rows selected by a list of integers, or all rows
1140 selected by :math:`i = -1` (*default*).
1141
1142 j : int, optional
1143 Column indices of the responses to be evaluated. Either a single column selected by an integer
1144 :math:`j \in [0, N_\mathrm{ports}-1]`, or multiple columns selected by a list of integers, or all columns
1145 selected by :math:`j = -1` (*default*).
1146
1147 parameter_type: str, optional
1148 Representation type of the fitted frequency responses. Either *scattering* (:attr:`s` or :attr:`S`),
1149 *impedance* (:attr:`z` or :attr:`Z`) or *admittance* (:attr:`y` or :attr:`Y`).
1150
1151 Returns
1152 -------
1153 rms_error : ndarray
1154 The rms error magnitude between the vector fitted model and the original network data.
1155
1156 Raises
1157 ------
1158 ValueError
1159 If the specified parameter representation type is not :attr:`s`, :attr:`z`, nor :attr:`y`.
1160 """
1161
1162 if i == -1:
1163 list_i = range(self.network.nports)
1164 elif isinstance(i, int):
1165 list_i = [i]
1166 else:
1167 list_i = i
1168
1169 if j == -1:
1170 list_j = range(self.network.nports)
1171 elif isinstance(j, int):
1172 list_j = [j]
1173 else:
1174 list_j = j
1175
1176 if parameter_type.lower() == 's':
1177 nw_responses = self.network.s
1178 elif parameter_type.lower() == 'z':
1179 nw_responses = self.network.z
1180 elif parameter_type.lower() == 'y':
1181 nw_responses = self.network.y
1182 else:
1183 raise ValueError(f'Invalid parameter type `{parameter_type}`. Valid options: `s`, `z`, or `y`')
1184
1185 error_mean_squared = 0
1186 for i in list_i:
1187 for j in list_j:
1188 nw_ij = nw_responses[:, i, j]
1189 fit_ij = self.get_model_response(i, j, self.network.f)
1190 error_mean_squared += np.mean(np.square(np.abs(nw_ij - fit_ij)))
1191
1192 return np.sqrt(error_mean_squared)
1193
1194 def _get_ABCDE(self) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
1195 """
1196 Private method.
1197 Returns the real-valued system matrices of the state-space representation of the current rational model, as
1198 defined in [#]_.
1199
1200 Returns
1201 -------
1202 A : ndarray
1203 State-space matrix A holding the poles on the diagonal as real values with imaginary parts on the sub-
1204 diagonal
1205 B : ndarray
1206 State-space matrix B holding coefficients (1, 2, or 0), depending on the respective type of pole in A
1207 C : ndarray
1208 State-space matrix C holding the residues
1209 D : ndarray
1210 State-space matrix D holding the constants
1211 E : ndarray
1212 State-space matrix E holding the proportional coefficients (usually 0 in case of fitted S-parameters)
1213
1214 Raises
1215 ------
1216 ValueError
1217 If the model parameters have not been initialized (by running :func:`vector_fit()` or :func:`read_npz()`).
1218
1219 References
1220 ----------
1221 .. [#] B. Gustavsen and A. Semlyen, "Fast Passivity Assessment for S-Parameter Rational Models Via a Half-Size
1222 Test Matrix," in IEEE Transactions on Microwave Theory and Techniques, vol. 56, no. 12, pp. 2701-2708,
1223 Dec. 2008, DOI: 10.1109/TMTT.2008.2007319.
1224 """
1225
1226 # initial checks
1227 if self.poles is None:
1228 raise ValueError('self.poles = None; nothing to do. You need to run vector_fit() first.')
1229 if self.residues is None:
1230 raise ValueError('self.residues = None; nothing to do. You need to run vector_fit() first.')
1231 if self.proportional_coeff is None:
1232 raise ValueError('self.proportional_coeff = None; nothing to do. You need to run vector_fit() first.')
1233 if self.constant_coeff is None:
1234 raise ValueError('self.constant_coeff = None; nothing to do. You need to run vector_fit() first.')
1235
1236 # assemble real-valued state-space matrices A, B, C, D, E from fitted complex-valued pole-residue model
1237
1238 # determine size of the matrix system
1239 n_ports = int(np.sqrt(len(self.constant_coeff)))
1240 n_poles_real = 0
1241 n_poles_cplx = 0
1242 for pole in self.poles:
1243 if np.imag(pole) == 0.0:
1244 n_poles_real += 1
1245 else:
1246 n_poles_cplx += 1
1247 n_matrix = (n_poles_real + 2 * n_poles_cplx) * n_ports
1248
1249 # state-space matrix A holds the poles on the diagonal as real values with imaginary parts on the sub-diagonal
1250 # state-space matrix B holds coefficients (1, 2, or 0), depending on the respective type of pole in A
1251 # assemble A = [[poles_real, 0, 0],
1252 # [0, real(poles_cplx), imag(poles_cplx],
1253 # [0, -imag(poles_cplx), real(poles_cplx]]
1254 A = np.identity(n_matrix)
1255 B = np.zeros(shape=(n_matrix, n_ports))
1256 i_A = 0 # index on diagonal of A
1257 for j in range(n_ports):
1258 for pole in self.poles:
1259 if np.imag(pole) == 0.0:
1260 # adding a real pole
1261 A[i_A, i_A] = np.real(pole)
1262 B[i_A, j] = 1
1263 i_A += 1
1264 else:
1265 # adding a complex-conjugate pole
1266 A[i_A, i_A] = np.real(pole)
1267 A[i_A, i_A + 1] = np.imag(pole)
1268 A[i_A + 1, i_A] = -1 * np.imag(pole)
1269 A[i_A + 1, i_A + 1] = np.real(pole)
1270 B[i_A, j] = 2
1271 i_A += 2
1272
1273 # state-space matrix C holds the residues
1274 # assemble C = [[R1.11, R1.12, R1.13, ...], [R2.11, R2.12, R2.13, ...], ...]
1275 C = np.zeros(shape=(n_ports, n_matrix))
1276 for i in range(n_ports):
1277 for j in range(n_ports):
1278 # i: row index
1279 # j: column index
1280 i_response = i * n_ports + j
1281
1282 j_residues = 0
1283 for zero in self.residues[i_response]:
1284 if np.imag(zero) == 0.0:
1285 C[i, j * (n_poles_real + 2 * n_poles_cplx) + j_residues] = np.real(zero)
1286 j_residues += 1
1287 else:
1288 C[i, j * (n_poles_real + 2 * n_poles_cplx) + j_residues] = np.real(zero)
1289 C[i, j * (n_poles_real + 2 * n_poles_cplx) + j_residues + 1] = np.imag(zero)
1290 j_residues += 2
1291
1292 # state-space matrix D holds the constants
1293 # assemble D = [[d11, d12, ...], [d21, d22, ...], ...]
1294 D = np.zeros(shape=(n_ports, n_ports))
1295 for i in range(n_ports):
1296 for j in range(n_ports):
1297 # i: row index
1298 # j: column index
1299 i_response = i * n_ports + j
1300 D[i, j] = self.constant_coeff[i_response]
1301
1302 # state-space matrix E holds the proportional coefficients (usually 0 in case of fitted S-parameters)
1303 # assemble E = [[e11, e12, ...], [e21, e22, ...], ...]
1304 E = np.zeros(shape=(n_ports, n_ports))
1305 for i in range(n_ports):
1306 for j in range(n_ports):
1307 # i: row index
1308 # j: column index
1309 i_response = i * n_ports + j
1310 E[i, j] = self.proportional_coeff[i_response]
1311
1312 return A, B, C, D, E
1313
1314 @staticmethod
1315 def _get_s_from_ABCDE(freqs: np.ndarray,
1316 A: np.ndarray, B: np.ndarray, C: np.ndarray, D: np.ndarray, E: np.ndarray) -> np.ndarray:
1317 """
1318 Private method.
1319 Returns the S-matrix of the vector fitted model calculated from the real-valued system matrices of the state-
1320 space representation, as provided by `_get_ABCDE()`.
1321
1322 Parameters
1323 ----------
1324 freqs : ndarray
1325 Frequencies (in Hz) at which to calculate the S-matrices.
1326 A : ndarray
1327 B : ndarray
1328 C : ndarray
1329 D : ndarray
1330 E : ndarray
1331
1332 Returns
1333 -------
1334 ndarray
1335 Complex-valued S-matrices (fxNxN) calculated at frequencies `freqs`.
1336 """
1337
1338 dim_A = np.shape(A)[0]
1339 stsp_poles = np.linalg.inv(2j * np.pi * freqs[:, None, None] * np.identity(dim_A)[None, :, :] - A[None, :, :])
1340 stsp_S = np.matmul(np.matmul(C, stsp_poles), B)
1341 stsp_S += D + 2j * np.pi * freqs[:, None, None] * E
1342 return stsp_S
1343
1344 def passivity_test(self, parameter_type: str = 's') -> np.ndarray:
1345 """
1346 Evaluates the passivity of reciprocal vector fitted models by means of a half-size test matrix [#]_. Any
1347 existing frequency bands of passivity violations will be returned as a sorted list.
1348
1349 Parameters
1350 ----------
1351 parameter_type: str, optional
1352 Representation type of the fitted frequency responses. Either *scattering* (:attr:`s` or :attr:`S`),
1353 *impedance* (:attr:`z` or :attr:`Z`) or *admittance* (:attr:`y` or :attr:`Y`). Currently, only scattering
1354 parameters are supported for passivity evaluation.
1355
1356 Raises
1357 ------
1358 NotImplementedError
1359 If the function is called for `parameter_type` different than `S` (scattering).
1360
1361 ValueError
1362 If the function is used with a model containing nonzero proportional coefficients.
1363
1364 Returns
1365 -------
1366 violation_bands : ndarray
1367 NumPy array with frequency bands of passivity violation:
1368 `[[f_start_1, f_stop_1], [f_start_2, f_stop_2], ...]`.
1369
1370 See Also
1371 --------
1372 is_passive : Query the model passivity as a boolean value.
1373 passivity_enforce : Enforces the passivity of the vector fitted model, if required.
1374
1375 Examples
1376 --------
1377 Load and fit the `Network`, then evaluate the model passivity:
1378
1379 >>> nw_3port = skrf.Network('my3port.s3p')
1380 >>> vf = skrf.VectorFitting(nw_3port)
1381 >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4)
1382 >>> violations = vf.passivity_test()
1383
1384 References
1385 ----------
1386 .. [#] B. Gustavsen and A. Semlyen, "Fast Passivity Assessment for S-Parameter Rational Models Via a Half-Size
1387 Test Matrix," in IEEE Transactions on Microwave Theory and Techniques, vol. 56, no. 12, pp. 2701-2708,
1388 Dec. 2008, DOI: 10.1109/TMTT.2008.2007319.
1389 """
1390
1391 if parameter_type.lower() != 's':
1392 raise NotImplementedError('Passivity testing is currently only supported for scattering (S) parameters.')
1393 if parameter_type.lower() == 's' and len(np.flatnonzero(self.proportional_coeff)) > 0:
1394 raise ValueError('Passivity testing of scattering parameters with nonzero proportional coefficients does '
1395 'not make any sense; you need to run vector_fit() with option `fit_proportional=False` '
1396 'first.')
1397
1398 # # the network needs to be reciprocal for this passivity test method to work: S = transpose(S)
1399 # if not np.allclose(self.residues, np.transpose(self.residues)) or \
1400 # not np.allclose(self.constant_coeff, np.transpose(self.constant_coeff)) or \
1401 # not np.allclose(self.proportional_coeff, np.transpose(self.proportional_coeff)):
1402 # logger.error('Passivity testing with unsymmetrical model parameters is not supported. '
1403 # 'The model needs to be reciprocal.')
1404 # return
1405
1406 # get state-space matrices
1407 A, B, C, D, E = self._get_ABCDE()
1408 n_ports = np.shape(D)[0]
1409
1410 # build half-size test matrix P from state-space matrices A, B, C, D
1411 inv_neg = np.linalg.inv(D - np.identity(n_ports))
1412 inv_pos = np.linalg.inv(D + np.identity(n_ports))
1413 prod_neg = np.matmul(np.matmul(B, inv_neg), C)
1414 prod_pos = np.matmul(np.matmul(B, inv_pos), C)
1415 P = np.matmul(A - prod_neg, A - prod_pos)
1416
1417 # extract eigenvalues of P
1418 P_eigs = np.linalg.eigvals(P)
1419
1420 # purely imaginary square roots of eigenvalues identify frequencies (2*pi*f) of borders of passivity violations
1421 freqs_violation = []
1422 for sqrt_eigenval in np.sqrt(P_eigs, dtype=complex):
1423 if np.real(sqrt_eigenval) == 0.0:
1424 freqs_violation.append(np.imag(sqrt_eigenval) / 2 / np.pi)
1425
1426 # include dc (0) unless it's already included
1427 if len(np.nonzero(np.array(freqs_violation) == 0.0)[0]) == 0:
1428 freqs_violation.append(0.0)
1429
1430 # sort the output from lower to higher frequencies
1431 freqs_violation = np.sort(freqs_violation)
1432
1433 # identify frequency bands of passivity violations
1434
1435 # sweep the bands between crossover frequencies and identify bands of passivity violations
1436 violation_bands = []
1437 for i, freq in enumerate(freqs_violation):
1438 if i == len(freqs_violation) - 1:
1439 # last band stops always at infinity
1440 f_start = freq
1441 f_stop = np.inf
1442 f_center = 1.1 * f_start # 1.1 is chosen arbitrarily to have any frequency for evaluation
1443 else:
1444 # intermediate band between this frequency and the previous one
1445 f_start = freq
1446 f_stop = freqs_violation[i + 1]
1447 f_center = 0.5 * (f_start + f_stop)
1448
1449 # calculate singular values at the center frequency between crossover frequencies to identify violations
1450 s_center = self._get_s_from_ABCDE(np.array([f_center]), A, B, C, D, E)
1451 sigma = np.linalg.svd(s_center[0], compute_uv=False)
1452 passive = True
1453 for singval in sigma:
1454 if singval > 1:
1455 # passivity violation in this band
1456 passive = False
1457 if not passive:
1458 # add this band to the list of passivity violations
1459 if violation_bands is None:
1460 violation_bands = [[f_start, f_stop]]
1461 else:
1462 violation_bands.append([f_start, f_stop])
1463
1464 return np.array(violation_bands)
1465
1466 def is_passive(self, parameter_type: str = 's') -> bool:
1467 """
1468 Returns the passivity status of the model as a boolean value.
1469
1470 Parameters
1471 ----------
1472 parameter_type : str, optional
1473 Representation type of the fitted frequency responses. Either *scattering* (:attr:`s` or :attr:`S`),
1474 *impedance* (:attr:`z` or :attr:`Z`) or *admittance* (:attr:`y` or :attr:`Y`). Currently, only scattering
1475 parameters are supported for passivity evaluation.
1476
1477 Returns
1478 -------
1479 passivity : bool
1480 :attr:`True` if model is passive, else :attr:`False`.
1481
1482 See Also
1483 --------
1484 passivity_test : Verbose passivity evaluation routine.
1485 passivity_enforce : Enforces the passivity of the vector fitted model, if required.
1486
1487 Examples
1488 --------
1489 Load and fit the `Network`, then check whether or not the model is passive:
1490
1491 >>> nw_3port = skrf.Network('my3port.s3p')
1492 >>> vf = skrf.VectorFitting(nw_3port)
1493 >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4)
1494 >>> vf.is_passive() # returns True or False
1495 """
1496
1497 viol_bands = self.passivity_test(parameter_type)
1498 if len(viol_bands) == 0:
1499 return True
1500 else:
1501 return False
1502
1503 def passivity_enforce(self, n_samples: int = 200, f_max: float = None, parameter_type: str = 's',
1504 preserve_dc: bool = True) -> None:
1505 """
1506 Enforces the passivity of the vector fitted model, if required. This is an implementation of the methods
1507 presented in [#]_ and [#]_ using singular value perturbation. To preserve the dc point in the model during
1508 passivity enforcement, only the residues are perturbed, not the constant term.
1509
1510 Parameters
1511 ----------
1512 n_samples : int, optional
1513 Number of linearly spaced frequency samples at which passivity will be evaluated and enforced.
1514 (Default: 200). If there are very narrow frequency bands of passivity violations, a sufficiently large
1515 number of frequency samples is required.
1516
1517 f_max : float or None, optional
1518 Highest frequency of interest for the passivity enforcement (in Hz, not rad/s). This limit usually
1519 equals the highest sample frequency of the fitted Network. If None, the highest frequency in
1520 :attr:`self.network` is used, which must not be None is this case. If `f_max` is not None, it overrides the
1521 highest frequency in :attr:`self.network`.
1522
1523 parameter_type : str, optional
1524 Representation type of the fitted frequency responses. Either *scattering* (:attr:`s` or :attr:`S`),
1525 *impedance* (:attr:`z` or :attr:`Z`) or *admittance* (:attr:`y` or :attr:`Y`). Currently, only scattering
1526 parameters are supported for passivity evaluation.
1527
1528 preserve_dc : bool, optional
1529 Enables dc point preservation during passivity enforcement. This only works if the fitted model is already
1530 passive at the dc point, which is not always the case. If it is not passive, dc point preservation is
1531 disabled and passivity is also enforced on the dc point.
1532
1533 Returns
1534 -------
1535 None
1536
1537 Raises
1538 ------
1539 NotImplementedError
1540 If the function is called for `parameter_type` different than `S` (scattering).
1541
1542 ValueError
1543 If the function is used with a model containing nonzero proportional coefficients. Or if both `f_max` and
1544 :attr:`self.network` are None.
1545
1546 See Also
1547 --------
1548 is_passive : Returns the passivity status of the model as a boolean value.
1549 passivity_test : Verbose passivity evaluation routine.
1550 plot_passivation : Convergence plot for passivity enforcement iterations.
1551
1552 Examples
1553 --------
1554 Load and fit the `Network`, then enforce the passivity of the model:
1555
1556 >>> nw_3port = skrf.Network('my3port.s3p')
1557 >>> vf = skrf.VectorFitting(nw_3port)
1558 >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4)
1559 >>> vf.passivity_enforce() # won't do anything if model is already passive
1560
1561 References
1562 ----------
1563 .. [#] T. Dhaene, D. Deschrijver and N. Stevens, "Efficient Algorithm for Passivity Enforcement of S-Parameter-
1564 Based Macromodels," in IEEE Transactions on Microwave Theory and Techniques, vol. 57, no. 2, pp. 415-420,
1565 Feb. 2009, DOI: 10.1109/TMTT.2008.2011201
1566
1567 .. [#] D. Deschrijver and T. Dhaene, "DC-Preserving Passivity Enforcement for S-Parameter Based Macromodels,"
1568 in IEEE Transactions on Microwave Theory and Techniques, vol. 58, no. 4, pp. 923-928, April 2010,
1569 DOI: 10.1109/TMTT.2010.2042556
1570 """
1571
1572 if parameter_type.lower() != 's':
1573 raise NotImplementedError('Passivity testing is currently only supported for scattering (S) parameters.')
1574 if parameter_type.lower() == 's' and len(np.flatnonzero(self.proportional_coeff)) > 0:
1575 raise ValueError('Passivity testing of scattering parameters with nonzero proportional coefficients does '
1576 'not make any sense; you need to run vector_fit() with option `fit_proportional=False` '
1577 'first.')
1578
1579 # always run passivity test first; this will write 'self.violation_bands'
1580 if self.is_passive():
1581 # model is already passive; do nothing and return
1582 logger.info('Passivity enforcement: The model is already passive. Nothing to do.')
1583 return
1584
1585 # check dc passivity and find the highest relevant frequency; either
1586 # 1) the highest frequency of passivity violation (f_viol_max)
1587 # or
1588 # 2) the highest fitting frequency (f_samples_max)
1589 violation_bands = self.passivity_test()
1590 f_viol_min = violation_bands[0, 0]
1591 f_viol_max = violation_bands[-1, 1]
1592
1593 # check passivity at the dc point; 1) in the model, 2) in the original data, if available
1594 if preserve_dc and f_viol_min == 0.0:
1595 # cannot preserve a non-passive dc point during passivity enforcement
1596 preserve_dc = False
1597 hint = ''
1598
1599 if self.network is not None:
1600 if self.network.f[0] == 0.0 and not self.network.is_passive():
1601 hint = '\nHint: The dc point in the original network data is already non-passive.'
1602
1603 warnings.warn('Passivity enforcement: The dc point in the model is not passive. Cannot '
1604 f'preserve the dc point during passivity enforcement. {hint}', UserWarning, stacklevel=2)
1605
1606 if f_max is None:
1607 if self.network is None:
1608 raise RuntimeError('Both `self.network` and parameter `f_max` are None. One of them is required to '
1609 'specify the frequency band of interest for the passivity enforcement.')
1610 else:
1611 f_samples_max = self.network.f[-1]
1612 else:
1613 f_samples_max = f_max
1614
1615 # deal with unbounded violation interval (f_viol_max == np.inf)
1616 if np.isinf(f_viol_max):
1617 f_viol_max = 1.5 * violation_bands[-1, 0]
1618 warnings.warn(
1619 'Passivity enforcement: The passivity violations of this model are unbounded. '
1620 'Passivity enforcement might still work, but consider re-fitting with a lower number of poles '
1621 'and/or without the constants (`fit_constant=False`) if the results are not satisfactory.',
1622 UserWarning, stacklevel=2)
1623
1624 # the frequency band for the passivity evaluation is from dc to 20% above the highest relevant frequency
1625 if f_viol_max < f_samples_max:
1626 f_eval_max = 1.2 * f_samples_max
1627 else:
1628 f_eval_max = 1.2 * f_viol_max
1629
1630 # let's not automatically adjust n_samples. The calculated number can
1631 # be huge (>100k). Combined with a high number of poles in the model, this can bust the memory.
1632 freqs_eval = np.linspace(0, f_eval_max, n_samples)
1633
1634 # get model state-space matrices
1635 A, B, C_t, D, E = self._get_ABCDE()
1636 dim_A = np.shape(A)[0]
1637
1638 # ASYMPTOTIC PASSIVITY ENFORCEMENT
1639
1640 # check if constant term has been fitted (not zero)
1641 # a model without the constant term is always asymptotically passive
1642 if len(np.nonzero(D)[0]) != 0:
1643 # D was fitted;
1644 # asymptotic passivity needs to be checked and enforced, if violated.
1645 # for dc preservation, the asymptotic passivity violations in D are compensated using C
1646 # D is not touched, because it contains the dc point ( lim s --> {inf S(s)} = D)
1647 u, sigma, vh = np.linalg.svd(D, compute_uv=True)
1648
1649 # find and perturb singular values that cause passivity violations
1650 # sigma_viol = sigma * upsilon - psi with
1651 # upsilon[sigma > delta] = 1
1652 # upsilon[sigma <= delta] = 0
1653 # psi[sigma > delta] = delta
1654 # psi[sigma <= delta] = 0
1655 # (implemented below in a more compact form)
1656 delta = 1
1657 idx_viol = np.nonzero(sigma > delta)
1658 sigma_viol = np.zeros_like(sigma)
1659 sigma_viol[idx_viol] = sigma[idx_viol] - delta
1660
1661 # calculate S_viol from perturbed sigma and previous U and Vh
1662 S_viol = np.dot(u * sigma_viol, vh)
1663
1664 # find new set of residues C_viol by solving underdetermined least-squares problem
1665 # S_viol = C_viol * B
1666 #
1667 # mind the transpose of the system to compensate for the exchanged order of matrix multiplication:
1668 # S_viol = C_viol * B <==> transpose(S_viol) = transpose(B) * transpose(C_viol)
1669 C_viol, residuals, rank, singular_vals = np.linalg.lstsq(np.vstack((B.T.real, B.T.imag)),
1670 np.vstack((S_viol.T.real, S_viol.T.imag)),
1671 rcond=None)
1672 C_t -= C_viol.T
1673
1674 # UNIFORM PASSIVITY ENFORCEMENT
1675
1676 # preparing coefficient matrix; can be reused in every iteration
1677 # S(s_eval) = D_t + s_eval * C_t * inv(s_eval * I - A) * B
1678 # = D_t + s_eval * C_t * A_freq * B
1679 # with
1680 # A_freq = inv(s_eval * I - A)
1681 # s_eval = j * omega_eval = 2j * pi * freqs_eval
1682 A_freq = np.linalg.inv(2j * np.pi * freqs_eval[:, None, None] * np.identity(dim_A)[None, :, :] - A[None, :, :])
1683
1684 # construct coefficient matrix for least-squares residue fitting (C_viol)
1685 coeffs = np.matmul(A_freq, B)
1686
1687 C_viol = np.empty_like(C_t)
1688 n_ports = np.shape(C_viol)[0]
1689 model_order = self.get_model_order(self.poles)
1690
1691 # predefined tolerance parameter (users should not need to change this)
1692 delta_threshold = 0.999
1693 sigma_max = 1.1 # just to enter iteration loop for the first time
1694
1695 # iterative compensation of passivity violations
1696 t = 0
1697 self.history_max_sigma = []
1698 while t < self.max_iterations and sigma_max > 1.0:
1699 logger.info(f'Passivity enforcement; Iteration {t + 1}')
1700
1701 # calculate S-matrix of the model at freqs_eval (shape fxNxN)
1702 #S_eval = self._get_s_from_ABCDE(freqs_eval, A, B, C_t, D, E)
1703 S_eval = D + np.matmul(C_t, coeffs) # much faster!
1704
1705 # singular value decomposition,
1706 # shape(u) = (n_samples, n_ports, n_ports)
1707 # shape(sigma) = (n_samples, n_ports)
1708 # shape(vh) = (n_samples, n_ports, n_ports)
1709 u, sigma, vh = np.linalg.svd(S_eval)
1710
1711 # keep track of the greatest singular value in every iteration step
1712 sigma_max = np.amax(sigma)
1713 self.history_max_sigma.append(sigma_max)
1714
1715 if sigma_max > delta_threshold:
1716 delta = delta_threshold
1717 else:
1718 delta = sigma_max
1719
1720 # find and perturb singular values that cause passivity violations
1721 # sigma_viol = sigma * upsilon - psi with
1722 # upsilon[sigma > delta] = 1
1723 # upsilon[sigma <= delta] = 0
1724 # psi[sigma > delta] = delta
1725 # psi[sigma <= delta] = 0
1726 # (implemented below in a more compact form)
1727 idx_viol = np.nonzero(sigma > delta)
1728 sigma_viol = np.zeros_like(sigma)
1729 sigma_viol[idx_viol] = sigma[idx_viol] - delta
1730
1731 S_viol = np.matmul(u * sigma_viol[:, None, :], vh)
1732
1733 # stack frequency responses as a single vector
1734 # stacking order (row-major):
1735 # s11, s12, s13, ..., s21, s22, s23, ...
1736 S_viol_stacked = []
1737 for i in range(n_ports):
1738 for j in range(n_ports):
1739 S_viol_stacked.append(S_viol[:, i, j])
1740 S_viol_stacked = np.array(S_viol_stacked)
1741
1742 # The existing method _fit_residues() can be use here to fit the violation residues. Enabling `fit_constant`
1743 # in combination with `enforce_dc` removes the dc rows from the linear system and enforces the dc solution
1744 # on the constant term. In case of dc preservation during passivity enforcement, we can ignore that constant
1745 # term entirely and only use the violation residues.
1746 # If dc preservation is disabled, we could also perturb the constant term. This is not currently done. In
1747 # this new method, we always only perturb the residues. Disabling `fit_constant` and `preserve_dc` in this
1748 # case will solve for the residues without the constant term in the linear system.
1749 C_viol_stacked, D_viol_stacked, E_viol_stacked, residuals, rank, singular_vals = self._fit_residues(
1750 self.poles, freqs_eval, S_viol_stacked, fit_constant=preserve_dc, fit_proportional=False,
1751 enforce_dc=preserve_dc)
1752
1753 # reshape C_viol into state-space format: [[R1.11, R2.11, R3.11, ..., R1.1N, R2.1N, R3.1N, ...],
1754 # [R1.21, R2.21, R3.21, ..., R1.2N, R3.2N, R3.2N, ...],
1755 # ...
1756 # [R1.N1, R2.N1, R3.N1, ..., R1.NN, R3.NN, R3.NN, ...]]
1757 for i_port in range(n_ports):
1758 for j_port in range(n_ports):
1759 j_residues = 0
1760 for residue in C_viol_stacked[i_port * n_ports + j_port]:
1761 if np.imag(residue) == 0.0:
1762 C_viol[i_port, j_port * model_order + j_residues] = np.real(residue)
1763 j_residues += 1
1764 else:
1765 C_viol[i_port, j_port * model_order + j_residues] = np.real(residue)
1766 C_viol[i_port, j_port * model_order + j_residues + 1] = np.imag(residue)
1767 j_residues += 2
1768
1769 # perturb residues by subtracting respective row and column in C_t
1770 C_t = C_t - C_viol
1771
1772 t += 1
1773
1774 # PASSIVATION PROCESS DONE; model is either passive or max. number of iterations have been exceeded
1775 if t == self.max_iterations:
1776 warnings.warn('Passivity enforcement: Aborting after the max. number of iterations has been '
1777 'exceeded.', RuntimeWarning, stacklevel=2)
1778
1779 # save/update model parameters (perturbed residues)
1780 self.history_max_sigma = np.array(self.history_max_sigma)
1781
1782 n_ports = np.shape(D)[0]
1783 for i in range(n_ports):
1784 k = 0 # column index in C_t
1785 for j in range(n_ports):
1786 i_response = i * n_ports + j
1787 z = 0 # column index self.residues
1788 for pole in self.poles:
1789 if np.imag(pole) == 0.0:
1790 # real pole --> real residue
1791 self.residues[i_response, z] = C_t[i, k]
1792 k += 1
1793 else:
1794 # complex-conjugate pole --> complex-conjugate residue
1795 self.residues[i_response, z] = C_t[i, k] + 1j * C_t[i, k + 1]
1796 k += 2
1797 z += 1
1798
1799 # run final passivity test to make sure passivation was successful
1800 violation_bands = self.passivity_test()
1801 if len(violation_bands) > 0:
1802 # trying to determine the required number of evaluation samples based on the bandwidth and separation
1803 # distance of the violation bands
1804 violation_band_separation = np.diff(violation_bands.flat)
1805 min_spacing_nonzero = np.amin(violation_band_separation[violation_band_separation != 0.0])
1806
1807 # we should need an absolute minimum of 1 sample in each violating frequency band.
1808 # in practice, the frequency spacing should preferably be much more dense.
1809 # let's recommend 2 samples per violation band.
1810 n_samples_required = int(f_eval_max / min_spacing_nonzero * 2)
1811
1812 if n_samples_required > n_samples:
1813 hint = f'Consider trying again with n_samples > {n_samples_required}.'
1814 else:
1815 hint = ''
1816
1817 warnings.warn('Passivity enforcement was not successful.\nModel is still non-passive in these '
1818 f'frequency bands: {violation_bands}.\nTry running this routine again with a larger number of'
1819 f' samples (parameter `n_samples`). This run was using n_samples = {n_samples}. {hint}',
1820 RuntimeWarning, stacklevel=2)
1821
1822 def write_npz(self, path: str) -> None:
1823 """
1824 Writes the model parameters in :attr:`poles`, :attr:`residues`,
1825 :attr:`proportional_coeff` and :attr:`constant_coeff` to a labeled NumPy .npz file.
1826
1827 Parameters
1828 ----------
1829 path : str
1830 Target path without filename for the export. The filename will be added automatically based on the network
1831 name in :attr:`network`
1832
1833 Returns
1834 -------
1835 None
1836
1837 See Also
1838 --------
1839 read_npz : Reads all model parameters from a .npz file
1840
1841 Examples
1842 --------
1843 Load and fit the `Network`, then export the model parameters to a .npz file:
1844
1845 >>> nw_3port = skrf.Network('my3port.s3p')
1846 >>> vf = skrf.VectorFitting(nw_3port)
1847 >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4)
1848 >>> vf.write_npz('./data/')
1849
1850 The filename depends on the network name stored in `nw_3port.name` and will have the prefix `coefficients_`, for
1851 example `coefficients_my3port.npz`. The coefficients can then be read using NumPy's load() function:
1852
1853 >>> coeffs = numpy.load('./data/coefficients_my3port.npz')
1854 >>> poles = coeffs['poles']
1855 >>> residues = coeffs['residues']
1856 >>> prop_coeffs = coeffs['proportionals']
1857 >>> constants = coeffs['constants']
1858
1859 Alternatively, the coefficients can be read directly into a new instance of `VectorFitting`, see
1860 :func:`read_npz`.
1861 """
1862
1863 if self.poles is None:
1864 warnings.warn('Nothing to export; Poles have not been fitted.', RuntimeWarning, stacklevel=2)
1865 return
1866 if self.residues is None:
1867 warnings.warn('Nothing to export; Residues have not been fitted.', RuntimeWarning, stacklevel=2)
1868 return
1869 if self.proportional_coeff is None:
1870 warnings.warn('Nothing to export; Proportional coefficients have not been fitted.', RuntimeWarning,
1871 stacklevel=2)
1872 return
1873 if self.constant_coeff is None:
1874 warnings.warn('Nothing to export; Constants have not been fitted.', RuntimeWarning, stacklevel=2)
1875 return
1876
1877 filename = self.network.name
1878
1879 logger.info(f'Exporting results as compressed NumPy array to {path}')
1880 np.savez_compressed(os.path.join(path, f'coefficients_{filename}'),
1881 poles=self.poles, residues=self.residues, proportionals=self.proportional_coeff,
1882 constants=self.constant_coeff)
1883
1884 def read_npz(self, file: str) -> None:
1885 """
1886 Reads all model parameters :attr:`poles`, :attr:`residues`, :attr:`proportional_coeff` and
1887 :attr:`constant_coeff` from a labeled NumPy .npz file.
1888
1889 Parameters
1890 ----------
1891 file : str
1892 NumPy .npz file containing the parameters. See notes.
1893
1894 Returns
1895 -------
1896 None
1897
1898 Raises
1899 ------
1900 ValueError
1901 If the shapes of the coefficient arrays in the provided file are not compatible.
1902
1903 Notes
1904 -----
1905 The .npz file needs to include the model parameters as individual NumPy arrays (ndarray) labeled '*poles*',
1906 '*residues*', '*proportionals*' and '*constants*'. The shapes of those arrays need to match the network
1907 properties in :class:`network` (correct number of ports). Preferably, the .npz file was created by
1908 :func:`write_npz`.
1909
1910 See Also
1911 --------
1912 write_npz : Writes all model parameters to a .npz file
1913
1914 Examples
1915 --------
1916 Create an empty `VectorFitting` instance (with or without the fitted `Network`) and load the model parameters:
1917
1918 >>> vf = skrf.VectorFitting(None)
1919 >>> vf.read_npz('./data/coefficients_my3port.npz')
1920
1921 This can be useful to analyze or process a previous vector fit instead of fitting it again, which sometimes
1922 takes a long time. For example, the model passivity can be evaluated and enforced:
1923
1924 >>> vf.passivity_enforce()
1925 """
1926
1927 with np.load(file) as data:
1928 poles = data['poles']
1929
1930 # legacy support for exported residues
1931 if 'zeros' in data:
1932 # old .npz file from deprecated write_npz() with residues called 'zeros'
1933 residues = data['zeros']
1934 else:
1935 # new .npz file from current write_npz()
1936 residues = data['residues']
1937
1938 proportional_coeff = data['proportionals']
1939 constant_coeff = data['constants']
1940
1941 n_ports = int(np.sqrt(len(constant_coeff)))
1942 n_resp = n_ports ** 2
1943 if np.shape(residues)[0] == np.shape(proportional_coeff)[0] == np.shape(constant_coeff)[0] == n_resp:
1944 self.poles = poles
1945 self.residues = residues
1946 self.proportional_coeff = proportional_coeff
1947 self.constant_coeff = constant_coeff
1948 else:
1949 raise ValueError('The shapes of the provided parameters are not compatible. The coefficient file needs '
1950 'to contain NumPy arrays labeled `poles`, `residues`, `proportionals`, and '
1951 '`constants`. Their shapes must match the number of network ports and the number of '
1952 'frequencies.')
1953
1954 def get_model_response(self, i: int, j: int, freqs: Any = None) -> np.ndarray:
1955 """
1956 Returns one of the frequency responses :math:`H_{i+1,j+1}` of the fitted model :math:`H`.
1957
1958 Parameters
1959 ----------
1960 i : int
1961 Row index of the response in the response matrix.
1962
1963 j : int
1964 Column index of the response in the response matrix.
1965
1966 freqs : list of float or ndarray or None, optional
1967 List of frequencies for the response plot. If None, the sample frequencies of the fitted network in
1968 :attr:`network` are used.
1969
1970 Returns
1971 -------
1972 response : ndarray
1973 Model response :math:`H_{i+1,j+1}` at the frequencies specified in `freqs` (complex-valued Numpy array).
1974
1975 Examples
1976 --------
1977 Get fitted S11 at 101 frequencies from 0 Hz to 10 GHz:
1978
1979 >>> import skrf
1980 >>> vf = skrf.VectorFitting(skrf.data.ring_slot)
1981 >>> vf.vector_fit(3, 0)
1982 >>> s11_fit = vf.get_model_response(0, 0, numpy.linspace(0, 10e9, 101))
1983 """
1984
1985 if self.poles is None:
1986 warnings.warn('Returning a zero-vector; Poles have not been fitted.',
1987 RuntimeWarning, stacklevel=2)
1988 return np.zeros_like(freqs)
1989 if self.residues is None:
1990 warnings.warn('Returning a zero-vector; Residues have not been fitted.',
1991 RuntimeWarning, stacklevel=2)
1992 return np.zeros_like(freqs)
1993 if self.proportional_coeff is None:
1994 warnings.warn('Returning a zero-vector; Proportional coefficients have not been fitted.',
1995 RuntimeWarning, stacklevel=2)
1996 return np.zeros_like(freqs)
1997 if self.constant_coeff is None:
1998 warnings.warn('Returning a zero-vector; Constants have not been fitted.',
1999 RuntimeWarning, stacklevel=2)
2000 return np.zeros_like(freqs)
2001 if freqs is None:
2002 freqs = np.linspace(np.amin(self.network.f), np.amax(self.network.f), 1000)
2003
2004 s = 2j * np.pi * np.array(freqs)
2005 n_ports = int(np.sqrt(len(self.constant_coeff)))
2006 i_response = i * n_ports + j
2007 residues = self.residues[i_response]
2008
2009 resp = self.proportional_coeff[i_response] * s + self.constant_coeff[i_response]
2010 for i, pole in enumerate(self.poles):
2011 if np.imag(pole) == 0.0:
2012 # real pole
2013 resp += residues[i] / (s - pole)
2014 else:
2015 # complex conjugate pole
2016 resp += residues[i] / (s - pole) + np.conjugate(residues[i]) / (s - np.conjugate(pole))
2017 return resp
2018
2019 @axes_kwarg
2020 def plot(self, component: str, i: int = -1, j: int = -1, freqs: Any = None,
2021 parameter: str = 's', *, ax: Axes = None) -> Axes:
2022 """
2023 Plots the specified component of the parameter :math:`H_{i+1,j+1}` in the fit, where :math:`H` is
2024 either the scattering (:math:`S`), the impedance (:math:`Z`), or the admittance (:math:`H`) response specified
2025 in `parameter`.
2026
2027 Parameters
2028 ----------
2029 component : str
2030 The component to be plotted. Must be one of the following items:
2031 ['db', 'mag', 'deg', 'deg_unwrap', 're', 'im'].
2032 `db` for magnitude in decibels,
2033 `mag` for magnitude in linear scale,
2034 `deg` for phase in degrees (wrapped),
2035 `deg_unwrap` for phase in degrees (unwrapped/continuous),
2036 `re` for real part in linear scale,
2037 `im` for imaginary part in linear scale.
2038
2039 i : int, optional
2040 Row index of the response. `-1` to plot all rows.
2041
2042 j : int, optional
2043 Column index of the response. `-1` to plot all columns.
2044
2045 freqs : list of float or ndarray or None, optional
2046 List of frequencies for the response plot. If None, the sample frequencies of the fitted network in
2047 :attr:`network` are used. This only works if :attr:`network` is not `None`.
2048
2049 parameter : str, optional
2050 The network representation to be used. This is only relevant for the plot of the original sampled response
2051 in :attr:`network` that is used for comparison with the fit. Must be one of the following items unless
2052 :attr:`network` is `None`: ['s', 'z', 'y'] for *scattering* (default), *impedance*, or *admittance*.
2053
2054 ax : :class:`matplotlib.Axes` object or None
2055 matplotlib axes to draw on. If None, the current axes is fetched with :func:`gca()`.
2056
2057 Returns
2058 -------
2059 :class:`matplotlib.Axes`
2060 matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current
2061 figure.
2062
2063 Raises
2064 ------
2065 ValueError
2066 If the `freqs` parameter is not specified while the Network in :attr:`network` is `None`.
2067 Also if `component` and/or `parameter` are not valid.
2068 """
2069
2070 components = ['db', 'mag', 'deg', 'deg_unwrap', 're', 'im']
2071 if component.lower() in components:
2072 if self.residues is None or self.poles is None:
2073 raise RuntimeError('Poles and/or residues have not been fitted. Cannot plot the model response.')
2074
2075 n_ports = int(np.sqrt(np.shape(self.residues)[0]))
2076
2077 if i == -1:
2078 list_i = range(n_ports)
2079 elif isinstance(i, int):
2080 list_i = [i]
2081 else:
2082 list_i = i
2083
2084 if j == -1:
2085 list_j = range(n_ports)
2086 elif isinstance(j, int):
2087 list_j = [j]
2088 else:
2089 list_j = j
2090
2091 if self.network is not None:
2092 # plot the original network response at each sample frequency (scatter plot)
2093 if parameter.lower() == 's':
2094 responses = self.network.s
2095 elif parameter.lower() == 'z':
2096 responses = self.network.z
2097 elif parameter.lower() == 'y':
2098 responses = self.network.y
2099 else:
2100 raise ValueError('The network parameter type is not valid, must be `s`, `z`, or `y`, '
2101 f'got `{parameter}`.')
2102
2103 i_samples = 0
2104 for i in list_i:
2105 for j in list_j:
2106 if i_samples == 0:
2107 label = 'Samples'
2108 else:
2109 label = '_nolegend_'
2110 i_samples += 1
2111
2112 y_vals = None
2113 if component.lower() == 'db':
2114 y_vals = 20 * np.log10(np.abs(responses[:, i, j]))
2115 elif component.lower() == 'mag':
2116 y_vals = np.abs(responses[:, i, j])
2117 elif component.lower() == 'deg':
2118 y_vals = np.rad2deg(np.angle(responses[:, i, j]))
2119 elif component.lower() == 'deg_unwrap':
2120 y_vals = np.rad2deg(np.unwrap(np.angle(responses[:, i, j])))
2121 elif component.lower() == 're':
2122 y_vals = np.real(responses[:, i, j])
2123 elif component.lower() == 'im':
2124 y_vals = np.imag(responses[:, i, j])
2125
2126 ax.scatter(self.network.f, y_vals, color='r', label=label)
2127
2128 if freqs is None:
2129 # get frequency array from the network
2130 freqs = self.network.f
2131
2132 if freqs is None:
2133 raise ValueError(
2134 'Neither `freqs` nor `self.network` is specified. Cannot plot model response without any '
2135 'frequency information.')
2136
2137 # plot the fitted responses
2138 y_label = ''
2139 i_fit = 0
2140 for i in list_i:
2141 for j in list_j:
2142 if i_fit == 0:
2143 label = 'Fit'
2144 else:
2145 label = '_nolegend_'
2146 i_fit += 1
2147
2148 y_model = self.get_model_response(i, j, freqs)
2149 y_vals = None
2150 if component.lower() == 'db':
2151 y_vals = 20 * np.log10(np.abs(y_model))
2152 y_label = 'Magnitude (dB)'
2153 elif component.lower() == 'mag':
2154 y_vals = np.abs(y_model)
2155 y_label = 'Magnitude'
2156 elif component.lower() == 'deg':
2157 y_vals = np.rad2deg(np.angle(y_model))
2158 y_label = 'Phase (Degrees)'
2159 elif component.lower() == 'deg_unwrap':
2160 y_vals = np.rad2deg(np.unwrap(np.angle(y_model)))
2161 y_label = 'Phase (Degrees)'
2162 elif component.lower() == 're':
2163 y_vals = np.real(y_model)
2164 y_label = 'Real Part'
2165 elif component.lower() == 'im':
2166 y_vals = np.imag(y_model)
2167 y_label = 'Imaginary Part'
2168
2169 ax.plot(freqs, y_vals, color='k', label=label)
2170
2171 ax.set_xlabel('Frequency (Hz)')
2172 ax.set_ylabel(y_label)
2173 ax.legend(loc='best')
2174
2175 # only print title if a single response is shown
2176 if i_fit == 1:
2177 ax.set_title(f'Response i={i}, j={j}')
2178
2179 return ax
2180 else:
2181 raise ValueError(f'The specified component ("{component}") is not valid. Must be in {components}.')
2182
2183 def plot_s_db(self, *args, **kwargs) -> Axes:
2184 """
2185 Plots the magnitude in dB of the scattering parameter response(s) in the fit.
2186
2187 Parameters
2188 ----------
2189 *args : any, optional
2190 Additional arguments to be passed to :func:`plot`.
2191
2192 **kwargs : dict, optional
2193 Additional keyword arguments to be passed to :func:`plot`.
2194
2195 Returns
2196 -------
2197 :class:`matplotlib.Axes`
2198 matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current
2199 figure.
2200
2201 Notes
2202 -----
2203 This simply calls ``plot('db', *args, **kwargs)``.
2204 """
2205
2206 return self.plot('db', *args, **kwargs)
2207
2208 def plot_s_mag(self, *args, **kwargs) -> Axes:
2209 """
2210 Plots the magnitude in linear scale of the scattering parameter response(s) in the fit.
2211
2212 Parameters
2213 ----------
2214 *args : any, optional
2215 Additional arguments to be passed to :func:`plot`.
2216
2217 **kwargs : dict, optional
2218 Additional keyword arguments to be passed to :func:`plot`.
2219
2220 Returns
2221 -------
2222 :class:`matplotlib.Axes`
2223 matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current
2224 figure.
2225
2226 Notes
2227 -----
2228 This simply calls ``plot('mag', *args, **kwargs)``.
2229 """
2230
2231 return self.plot('mag', *args, **kwargs)
2232
2233 def plot_s_deg(self, *args, **kwargs) -> Axes:
2234 """
2235 Plots the phase in degrees of the scattering parameter response(s) in the fit.
2236
2237 Parameters
2238 ----------
2239 *args : any, optional
2240 Additional arguments to be passed to :func:`plot`.
2241
2242 **kwargs : dict, optional
2243 Additional keyword arguments to be passed to :func:`plot`.
2244
2245 Returns
2246 -------
2247 :class:`matplotlib.Axes`
2248 matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current
2249 figure.
2250
2251 Notes
2252 -----
2253 This simply calls ``plot('deg', *args, **kwargs)``.
2254 """
2255
2256 return self.plot('deg', *args, **kwargs)
2257
2258 def plot_s_deg_unwrap(self, *args, **kwargs) -> Axes:
2259 """
2260 Plots the unwrapped phase in degrees of the scattering parameter response(s) in the fit.
2261
2262 Parameters
2263 ----------
2264 *args : any, optional
2265 Additional arguments to be passed to :func:`plot`.
2266
2267 **kwargs : dict, optional
2268 Additional keyword arguments to be passed to :func:`plot`.
2269
2270 Returns
2271 -------
2272 :class:`matplotlib.Axes`
2273 matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current
2274 figure.
2275
2276 Notes
2277 -----
2278 This simply calls ``plot('deg_unwrap', *args, **kwargs)``.
2279 """
2280
2281 return self.plot('deg_unwrap', *args, **kwargs)
2282
2283 def plot_s_re(self, *args, **kwargs) -> Axes:
2284 """
2285 Plots the real part of the scattering parameter response(s) in the fit.
2286
2287 Parameters
2288 ----------
2289 *args : any, optional
2290 Additional arguments to be passed to :func:`plot`.
2291
2292 **kwargs : dict, optional
2293 Additional keyword arguments to be passed to :func:`plot`.
2294
2295 Returns
2296 -------
2297 :class:`matplotlib.Axes`
2298 matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current
2299 figure.
2300
2301 Notes
2302 -----
2303 This simply calls ``plot('re', *args, **kwargs)``.
2304 """
2305
2306 return self.plot('re', *args, **kwargs)
2307
2308 def plot_s_im(self, *args, **kwargs) -> Axes:
2309 """
2310 Plots the imaginary part of the scattering parameter response(s) in the fit.
2311
2312 Parameters
2313 ----------
2314 *args : any, optional
2315 Additional arguments to be passed to :func:`plot`.
2316
2317 **kwargs : dict, optional
2318 Additional keyword arguments to be passed to :func:`plot`.
2319
2320 Returns
2321 -------
2322 :class:`matplotlib.Axes`
2323 matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current
2324 figure.
2325
2326 Notes
2327 -----
2328 This simply calls ``plot('im', *args, **kwargs)``.
2329 """
2330
2331 return self.plot('im', *args, **kwargs)
2332
2333 @axes_kwarg
2334 def plot_s_singular(self, freqs: Any = None, *, ax: Axes = None) -> Axes:
2335 """
2336 Plots the singular values of the vector fitted S-matrix in linear scale.
2337
2338 Parameters
2339 ----------
2340 freqs : list of float or ndarray or None, optional
2341 List of frequencies for the response plot. If None, the sample frequencies of the fitted network in
2342 :attr:`network` are used. This only works if :attr:`network` is not `None`.
2343
2344 ax : :class:`matplotlib.Axes` object or None
2345 matplotlib axes to draw on. If None, the current axes is fetched with :func:`gca()`.
2346
2347 Returns
2348 -------
2349 :class:`matplotlib.Axes`
2350 matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current
2351 figure.
2352
2353 Raises
2354 ------
2355 ValueError
2356 If the `freqs` parameter is not specified while the Network in :attr:`network` is `None`.
2357 """
2358
2359 if freqs is None:
2360 if self.network is None:
2361 raise ValueError(
2362 'Neither `freqs` nor `self.network` is specified. Cannot plot model response without any '
2363 'frequency information.')
2364 else:
2365 freqs = self.network.f
2366
2367 # get system matrices of state-space representation
2368 A, B, C, D, E = self._get_ABCDE()
2369
2370 n_ports = np.shape(D)[0]
2371
2372 # calculate and save singular values for each frequency
2373 u, sigma, vh = np.linalg.svd(self._get_s_from_ABCDE(freqs, A, B, C, D, E))
2374
2375 # plot the frequency response of each singular value
2376 for n in range(n_ports):
2377 ax.plot(freqs, sigma[:, n], label=fr'$\sigma_{n + 1}$')
2378 ax.set_xlabel('Frequency (Hz)')
2379 ax.set_ylabel('Magnitude')
2380 ax.legend(loc='best')
2381 return ax
2382
2383 @axes_kwarg
2384 def plot_convergence(self, ax: Axes = None) -> Axes:
2385 """
2386 Plots the history of the model residue parameter **d_res** during the iterative pole relocation process of the
2387 vector fitting, which should eventually converge to a fixed value. Additionally, the relative change of the
2388 maximum singular value of the coefficient matrix **A** are plotted, which serve as a convergence indicator.
2389
2390 Parameters
2391 ----------
2392 ax : :class:`matplotlib.Axes` object or None
2393 matplotlib axes to draw on. If None, the current axes is fetched with :func:`gca()`.
2394
2395 Returns
2396 -------
2397 :class:`matplotlib.Axes`
2398 matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current
2399 figure.
2400 """
2401
2402 ax.semilogy(np.arange(len(self.delta_max_history)) + 1, self.delta_max_history, color='darkblue')
2403 ax.set_xlabel('Iteration step')
2404 ax.set_ylabel('Max. relative change', color='darkblue')
2405 ax2 = ax.twinx()
2406 ax2.plot(np.arange(len(self.d_res_history)) + 1, self.d_res_history, color='orangered')
2407 ax2.set_ylabel('Residue', color='orangered')
2408 return ax
2409
2410 @axes_kwarg
2411 def plot_passivation(self, ax: Axes = None) -> Axes:
2412 """
2413 Plots the history of the greatest singular value during the iterative passivity enforcement process, which
2414 should eventually converge to a value slightly lower than 1.0 or stop after reaching the maximum number of
2415 iterations specified in the class variable :attr:`max_iterations`.
2416
2417 Parameters
2418 ----------
2419 ax : :class:`matplotlib.Axes` object or None
2420 matplotlib axes to draw on. If None, the current axes is fetched with :func:`gca()`.
2421
2422 Returns
2423 -------
2424 :class:`matplotlib.Axes`
2425 matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current
2426 figure.
2427 """
2428
2429 ax.plot(np.arange(len(self.history_max_sigma)) + 1, self.history_max_sigma)
2430 ax.set_xlabel('Iteration step')
2431 ax.set_ylabel('Max. singular value')
2432 return ax
2433
2434 def write_spice_subcircuit_s(self, file: str, fitted_model_name: str = "s_equivalent",
2435 create_reference_pins: bool = False) -> None:
2436 """
2437 Creates an equivalent N-port subcircuit based on its vector fitted scattering (S) parameter responses
2438 in spice simulator netlist syntax (compatible with LTspice, ngspice, Xyce, ...). The circuit synthesis is based
2439 on a direct implementation of the state-space representation of the vector fitted model [#vf-book]_.
2440
2441 Parameters
2442 ----------
2443 file : str
2444 Path and filename including file extension (usually .sp) for the subcircuit file.
2445
2446 fitted_model_name: str
2447 Name of the resulting subcircuit, default "s_equivalent"
2448
2449 create_reference_pins: bool
2450 If set to True, the synthesized subcircuit will have N pin-pairs:
2451 p1 p1_ref p2 p2_ref ... pN pN_ref
2452
2453 If set to False, the synthesized subcircuit will have N pins
2454 p1 p2 ... pN
2455 In this case, the reference nodes will be internally connected
2456 to the global ground net 0.
2457
2458 The default is False
2459
2460 Returns
2461 -------
2462 None
2463
2464 Examples
2465 --------
2466 Load and fit the `Network`, then export the equivalent subcircuit:
2467
2468 >>> nw_3port = skrf.Network('my3port.s3p')
2469 >>> vf = skrf.VectorFitting(nw_3port)
2470 >>> vf.auto_fit()
2471 >>> vf.write_spice_subcircuit_s('/my3port_model.sp')
2472
2473 References
2474 ----------
2475 .. [#vf-book] S. Grivet-Talocia and B. Gustavsen, "Passive Macromodeling", Wiley, 2016,
2476 doi: https://doi.org/10.1002/9781119140931
2477
2478 """
2479
2480 if np.any(self.proportional_coeff):
2481 build_e = True
2482 else:
2483 build_e = False
2484
2485 with open(file, 'w') as f:
2486 # write title line
2487 f.write('* EQUIVALENT CIRCUIT FOR VECTOR FITTED S-MATRIX\n')
2488 f.write('* Created using scikit-rf vectorFitting.py\n')
2489 f.write('*\n')
2490
2491 # Create subcircuit pin string and reference nodes
2492 if create_reference_pins:
2493 str_input_nodes = " ".join(map(lambda x: f'p{x + 1} p{x + 1}_ref', range(self.network.nports)))
2494 else:
2495 str_input_nodes = " ".join(map(lambda x: f'p{x + 1}', range(self.network.nports)))
2496
2497 f.write(f'.SUBCKT {fitted_model_name} {str_input_nodes}\n')
2498
2499 for i in range(self.network.nports):
2500 f.write('*\n')
2501 f.write(f'* Port network for port {i + 1}\n')
2502
2503 if create_reference_pins:
2504 node_ref_i = f'p{i + 1}_ref'
2505 else:
2506 node_ref_i = '0'
2507
2508 # reference impedance (real, i.e. resistance) of port i
2509 z0_i = np.real(self.network.z0[0, i])
2510
2511 # transfer gain of the controlled current sources representing the incident power wave a_i at port i
2512 #
2513 # the gain values result from the definition of the incident power wave:
2514 # a_i = 1 / 2 / sqrt(Z0_i) * (V_i + Z0_i * I_i) = 1 / 2 / sqrt(Z0_i) * V_i + sqrt(Z0_i) / 2 * I_i
2515 gain_vccs_a_i = 1 / 2 / np.sqrt(z0_i)
2516 gain_cccs_a_i = np.sqrt(z0_i) / 2
2517
2518 # transfer gain of the controlled current source representing the reflected power wave b_i at port i
2519 #
2520 # the gain values result from the definition of the reflected power wave:
2521 # b_i = 1 / 2 / sqrt(Z0_i) * (V_i - Z0_i * I_i)
2522 #
2523 # depending on the circuit topology used for the equivalent port network, this can be implemented
2524 # with either controlled current and/or controlled voltage sources. in case of the Norton current
2525 # source used in this implementation, the reflected power wave relates to the source current as:
2526 # b_i = sqrt(Z0_i) / 2 * I_b_i <==> I_b_i = 2 / sqrt(Z0_i) * b_i
2527 gain_b_i = 2 / np.sqrt(z0_i)
2528
2529 # dummy voltage source (v = 0) for port current sensing (I_i)
2530 f.write(f'V{i + 1} p{i + 1} s{i + 1} 0\n')
2531
2532 # adding port reference resistor Ri = Z0_i
2533 f.write(f'R{i + 1} s{i + 1} {node_ref_i} {z0_i}\n')
2534
2535 # transfer of states and inputs from port j to input/output network of port i
2536 for j in range(self.network.nports):
2537 if create_reference_pins:
2538 node_ref_j = f'p{j + 1}_ref'
2539 else:
2540 node_ref_j = '0'
2541
2542 # reference impedance (real, i.e. resistance) of port i
2543 z0_j = np.real(self.network.z0[0, j])
2544
2545 # Stacking order in VectorFitting class variables:
2546 # s11, s12, s13, ..., s21, s22, s23, ...
2547 idx_S_i_j = i * self.network.nports + j
2548
2549 # VCCS and CCCS adding their currents to represent the incident wave a_j
2550 gain_vccs_a_j = 1 / 2 / np.sqrt(z0_j)
2551 gain_cccs_a_j = np.sqrt(z0_j) / 2
2552
2553 d = self.constant_coeff[idx_S_i_j]
2554 e = self.proportional_coeff[idx_S_i_j]
2555
2556 if d != 0.0:
2557 # avoid zero-valued coefficients (in case of fit_constant=False)
2558
2559 # input a_j is scaled by constant term d_i_j and by current gain for b_i
2560 g_ij = gain_b_i * d * gain_vccs_a_j
2561 f_ij = gain_b_i * d * gain_cccs_a_j
2562 f.write(f'Gd{i + 1}_{j + 1} {node_ref_i} s{i + 1} p{j + 1} {node_ref_j} {g_ij}\n')
2563 f.write(f'Fd{i + 1}_{j + 1} {node_ref_i} s{i + 1} V{j + 1} {f_ij}\n')
2564
2565 if build_e and e != 0.0:
2566 # avoid zero-valued coefficients (in case of fit_proportional=False)
2567 # proportional coefficients require an extra node for the differentiation using an inductor
2568 # [Y(s) ~ s * E * U(s)]
2569
2570 # differentiated input a_j is scaled by proportional term e_i_j and by current gain for b_i
2571 g_ij = gain_b_i * e
2572 f.write(f'Ge{i + 1}_{j + 1} {node_ref_i} s{i + 1} e{j + 1} 0 {g_ij}\n')
2573
2574 # each residue rk_i_j at port i is multiplied by its respective state signal xk_j
2575 for k in range(len(self.poles)):
2576 pole = self.poles[k]
2577 residue = self.residues[idx_S_i_j, k]
2578 g_re = gain_b_i * np.real(residue)
2579 g_im = gain_b_i * np.imag(residue)
2580
2581 if np.imag(pole) == 0.0:
2582 # Real pole/residue pair; represented by one state
2583 xkj = f'x{k + 1}_a{j + 1}'
2584 f.write(f'Gr{k + 1}_{i + 1}_{j + 1} {node_ref_i} s{i + 1} {xkj} 0 {g_re}\n')
2585 else:
2586 # Complex-conjugate pole/residue pair; represented by two states
2587 # real part at x_{k + 1}_re_{j + 1}
2588 # imaginary part at x_{k + 1}_im_{j + 1}
2589 xk_re_j = f'x{k + 1}_re_a{j + 1}'
2590 xk_im_j = f'x{k + 1}_im_a{j + 1}'
2591 f.write(f'Gr{k + 1}_re_{i + 1}_{j + 1} {node_ref_i} s{i + 1} {xk_re_j} 0 {g_re}\n')
2592 f.write(f'Gr{k + 1}_im_{i + 1}_{j + 1} {node_ref_i} s{i + 1} {xk_im_j} 0 {g_im}\n')
2593
2594 # create state networks driven by this port i (input variable u = a_i)
2595 f.write('*\n')
2596 f.write(f'* State networks driven by port {i + 1}\n')
2597 for k in range(len(self.poles)):
2598 pole = self.poles[k]
2599 pole_re = np.real(pole)
2600 pole_im = np.imag(pole)
2601
2602 # Transfer of input (a_i) to state networks (node xk_i) using VCCS and CCCS
2603 if pole_im == 0.0:
2604 # Real pole; represented by one state, input a_i is scaled by b = 1
2605 xki = f'x{k + 1}_a{i + 1}'
2606 f.write(f'Cx{k + 1}_a{i + 1} {xki} 0 1.0\n') # 1F capacitor makes math easy
2607 f.write(f'Gx{k + 1}_a{i + 1} 0 {xki} p{i + 1} {node_ref_i} {1 * gain_vccs_a_i}\n')
2608 f.write(f'Fx{k + 1}_a{i + 1} 0 {xki} V{i + 1} {1 * gain_cccs_a_i}\n')
2609 f.write(f'Rp{k + 1}_a{i + 1} 0 {xki} {-1 / pole_re}\n')
2610 else:
2611 # Complex pole of a conjugate pair; represented by two states
2612 # real part at x_{k + 1}_re_{i + 1}, input a_i is scaled by b = 2
2613 xk_re_i = f'x{k + 1}_re_a{i + 1}'
2614 xk_im_i = f'x{k + 1}_im_a{i + 1}'
2615 f.write(f'Cx{k + 1}_re_a{i + 1} {xk_re_i} 0 1.0\n') # 1F capacitor makes math easy
2616 f.write(
2617 f'Gx{k + 1}_re_a{i + 1} 0 {xk_re_i} p{i + 1} {node_ref_i} {2 * gain_vccs_a_i}\n')
2618 f.write(f'Fx{k + 1}_re_a{i + 1} 0 {xk_re_i} V{i + 1} {2 * gain_cccs_a_i}\n')
2619 f.write(f'Rp{k + 1}_re_re_a{i + 1} 0 {xk_re_i} {-1 / pole_re}\n')
2620 f.write(f'Gp{k + 1}_re_im_a{i + 1} 0 {xk_re_i} {xk_im_i} 0 {pole_im}\n')
2621
2622 # imaginary part at x_{k + 1}_im_{i + 1}, input a_i is inactive (b = 0)
2623 f.write(f'Cx{k + 1}_im_a{i + 1} {xk_im_i} 0 1.0\n') # 1F capacitor makes math easy
2624 f.write(f'Gp{k + 1}_im_re_a{i + 1} 0 {xk_im_i} {xk_re_i} 0 {-1 * pole_im}\n')
2625 f.write(f'Rp{k + 1}_im_im_a{i + 1} 0 {xk_im_i} {-1 / pole_re}\n')
2626
2627 # create differentiation network for this port i (input variable u = a_i)
2628 if build_e:
2629 f.write('*\n')
2630 f.write(f'* Network with derivative of input a_{i + 1} for proportional term\n')
2631 # voltage on node 'e{i + 1}' to gnd (0) represents time-derivative of input a_i for terms e_j_i
2632 f.write(f'Le{i + 1} e{i + 1} 0 1.0\n') # 1H inductor makes math easy
2633 f.write(f'Ge{i + 1} 0 e{i + 1} p{i + 1} {node_ref_i} {gain_vccs_a_i}\n')
2634 f.write(f'Fe{i + 1} 0 e{i + 1} V{i + 1} {gain_cccs_a_i}\n')
2635
2636 f.write(f'.ENDS {fitted_model_name}\n')