Debian Codegraph @

skrf/calibration/calibration.py

raw symbols SCIP
1 """
2 .. module:: skrf.calibration.calibration
3
4 ================================================================
5 calibration (:mod:`skrf.calibration.calibration`)
6 ================================================================
7
8
9 This module provides objects for VNA calibration. Specific algorithms
10 inherit from the common base class :class:`Calibration`.
11
12 Base Class
13 ----------
14
15 .. autosummary::
16 :toctree: generated/
17
18 Calibration
19
20 One-port
21 --------
22
23 .. autosummary::
24 :toctree: generated/
25
26 OnePort
27 SDDL
28 SDDLWeikle
29 PHN
30
31 Two-port
32 --------
33
34 .. autosummary::
35 :toctree: generated/
36
37 TwelveTerm
38 SOLT
39 EightTerm
40 UnknownThru
41 LRM
42 LRRM
43 MRC
44 TRL
45 MultilineTRL
46 NISTMultilineTRL
47 TUGMultilineTRL
48 SixteenTerm
49 LMR16
50 Normalization
51
52 Multi-port
53 --------
54
55 .. autosummary::
56 :toctree: generated/
57
58 MultiportCal
59 MultiportSOLT
60
61 Three Receiver (1.5 port)
62 -------------------------
63
64 .. autosummary::
65 :toctree: generated/
66
67 TwoPortOnePath
68 EnhancedResponse
69
70 Switch Terms
71 ------------
72
73 .. autosummary::
74 :toctree: generated/
75
76 compute_switch_terms
77
78 Generic Methods
79 ---------------
80 .. autosummary::
81 :toctree: generated/
82
83 ideal_coefs_12term
84 terminate
85 terminate_nport
86 unterminate
87 determine_line
88 determine_reflect
89 convert_12term_2_8term
90 convert_8term_2_12term
91 align_measured_ideals
92 two_port_error_vector_2_Ts
93 error_dict_2_network
94
95 PNA interaction
96 ---------------
97 .. autosummary::
98 :toctree: generated/
99
100 convert_skrfcoefs_2_pna
101 convert_pnacoefs_2_skrf
102
103 """
104
105 from __future__ import annotations
106
107 import json
108 import warnings
109 from collections import OrderedDict, defaultdict
110 from copy import copy
111 from itertools import combinations
112 from numbers import Number
113 from textwrap import dedent
114 from typing import Literal
115 from warnings import warn
116
117 import numpy as np
118 from numpy import angle, einsum, exp, imag, invert, linalg, ones, poly1d, real, sqrt, zeros
119 from numpy.linalg import det
120 from scipy.optimize import least_squares
121
122 from .. import __version__ as skrf__version__
123 from .. import util
124 from ..io.touchstone import read_zipped_touchstones
125 from ..mathFunctions import ALMOST_ZERO, cross_ratio, find_closest, find_correct_sign, rand_c, sqrt_phase_unwrap
126 from ..network import (
127 Network,
128 average,
129 connect,
130 renormalize_s,
131 s2t,
132 s2z,
133 subnetwork,
134 t2s,
135 two_port_reflect,
136 z2s,
137 zipfile,
138 )
139 from ..networkSet import NetworkSet
140
141 ComplexArray = np.typing.NDArray[complex]
142
143 global coefs_list_12term
144 coefs_list_12term =[
145 'forward directivity',
146 'forward source match',
147 'forward reflection tracking',
148 'forward transmission tracking',
149 'forward load match',
150 'forward isolation',
151 'reverse directivity',
152 'reverse load match',
153 'reverse reflection tracking',
154 'reverse transmission tracking',
155 'reverse source match',
156 'reverse isolation'
157 ]
158
159 global coefs_list_8term
160 """
161 There are various notations used for this same model. Given that all
162 measurements have been unterminated properly the error box model holds
163 and the following equalities hold:
164
165 k = e10/e23 # in s-param
166 k = alpha/beta # in mark's notation
167 beta/alpha *1/Err = 1/(e10e32) # marks -> rytting notation
168 """
169 coefs_list_8term = [
170 'forward directivity',
171 'forward source match',
172 'forward reflection tracking',
173 'reverse directivity',
174 'reverse source match',
175 'reverse reflection tracking',
176 'forward switch term',
177 'reverse switch term',
178 'k',
179 'forward isolation',
180 'reverse isolation'
181 ]
182
183 global coefs_list_3term
184 coefs_list_3term = [
185 'directivity',
186 'source match',
187 'reflection tracking',
188 ]
189
190
191 class Calibration:
192 """
193 Base class for all Calibration objects.
194
195 This class implements the common mechanisms for all calibration
196 algorithms. Specific calibration algorithms should inherit this
197 class and override the methods:
198 * :func:`Calibration.run`
199 * :func:`Calibration.apply_cal`
200 * :func:`Calibration.embed` (optional)
201
202
203 The family of properties prefixed `coefs` and
204 `coefs..ntwks` returns error coefficients. If the property coefs
205 is accessed and empty, then :func:`Calibration.run` is called.
206
207 """
208
209 family = ''
210 def __init__(self, measured, ideals, sloppy_input=False,
211 is_reciprocal=True,name=None, self_calibration=False,*args, **kwargs):
212 r"""
213 Calibration initializer.
214
215 Notes
216 -----
217 About the order of supplied standards,
218
219 If the measured and ideals parameters are lists of Networks and
220 `sloppy_input=False`, then their elements must align. However,
221 if the measured and ideals are dictionaries, or
222 `sloppy_input=True`, then we will try to align them for you
223 based on the names of the networks (see `func:`align_measured_ideals`).
224
225 You do not want to use this `sloppy_input` feature if the
226 calibration depends on the standard order (like TRL).
227
228 Parameters
229 ----------
230 measured : list/dict of :class:`~skrf.network.Network` objects
231 Raw measurements of the calibration standards. The order
232 must align with the `ideals` parameter ( or use `sloppy_input`)
233
234 ideals : list/dict of :class:`~skrf.network.Network` objects
235 Predicted ideal response of the calibration standards.
236 The order must align with `ideals` list ( or use `sloppy_input`)
237
238 sloppy_input : Boolean.
239 Allows ideals and measured lists to be 'aligned' based on
240 the network names.
241
242 is_reciprocal : Boolean
243 enables the reciprocity assumption on the calculation of the
244 error_network, which is only relevant for one-port
245 calibrations.
246
247 name: string
248 the name of this calibration instance, like 'waveguide cal'
249 this is just for convenience [None].
250
251 self_calibration: Boolean
252 True if there are less ideals than measurements.
253 Used in self-calibration such as LMR, LRRM, where some of the
254 standards can be unknown.
255
256 \*args, \*\*kwargs : key-word arguments
257 stored in self.kwargs, which may be used by sub-classes
258 most likely in `run`.
259
260
261 """
262 # allow them to pass di
263 # lets make an ideal flush thru for them :
264 if hasattr(measured, 'keys'):
265 measured = measured.values()
266 if not sloppy_input:
267 warn('dictionary passed, sloppy_input automatically activated', stacklevel=2)
268 sloppy_input = True
269
270 if hasattr(ideals, 'keys'):
271 ideals = ideals.values()
272 if not sloppy_input:
273 warn('dictionary passed, sloppy_input automatically activated', stacklevel=2)
274 sloppy_input = True
275
276 # fill measured and ideals with copied lists of input
277 self.measured = [ntwk.copy() for ntwk in measured]
278 self.ideals = [ntwk.copy() for ntwk in ideals]
279
280 self.sloppy_input=sloppy_input
281 if sloppy_input:
282 self.measured, self.ideals = \
283 align_measured_ideals(self.measured, self.ideals)
284
285 self.self_calibration = self_calibration
286 if not self_calibration and len(self.measured) != len(self.ideals):
287 raise(IndexError(dedent(
288 """
289 The length of measured and ideals lists are different.
290 Number of ideals must equal the number of measured.
291 If you are using `sloppy_input` ensure the names are uniquely alignable.
292 """
293 )))
294
295 # ensure all the measured Networks' frequency's are the same
296 for measure in self.measured:
297 if self.measured[0].frequency != measure.frequency:
298 raise(ValueError("Measured Networks don't have matching frequencies."))
299 if np.any(self.measured[0].z0 != measure.z0):
300 raise(ValueError("Measured Networks don't have matching z0."))
301 if len(self.measured) > 0:
302 if np.any(self.measured[0].z0 != self.measured[0].z0[0,0]):
303 warn("Non-constant z0 in measurements. Expect trouble", stacklevel=2)
304 # ensure that all ideals have same frequency of the measured
305 # if not, then attempt to interpolate
306 for k in list(range(len(self.ideals))):
307 if self.ideals[k].frequency != self.measured[0].frequency:
308 print(dedent(
309 f"""Warning: Frequency information doesn't match on ideals[{k}],
310 attempting to interpolate the ideal[{k}] Network .."""))
311 try:
312 # try to resample our ideals network to match
313 # the measurement frequency
314 self.ideals[k].interpolate_self(\
315 self.measured[0].frequency)
316 print('Success')
317
318 except Exception as err:
319 raise(IndexError(f'Failed to interpolate. Check frequency of ideals[{k}].')) from err
320 if np.any(self.ideals[k].z0 != self.measured[0].z0):
321 raise ValueError("Measured and ideals z0 are different.")
322
323 # passed to calibration algorithm in run()
324 self.kwargs = kwargs
325 self.name = name
326 self.is_reciprocal = is_reciprocal
327
328 # initialized internal properties to None
329 self._residual_ntwks = None
330 self._caled_ntwks =None
331 self._caled_ntwk_sets = None
332
333 def __str__(self):
334 if self.name is None:
335 name = ''
336 else:
337 name = self.name
338
339 if 'fromcoefs' in self.family.lower():
340 output = f"{self.family} Calibration: '{name}', {self.frequency}"
341 else:
342 output = f"{self.family} Calibration: '{name}', {self.frequency}, {len(self.measured)}-standards"
343 return output
344
345 def __repr__(self):
346 return self.__str__()
347
348 def run(self):
349 """
350 Run the calibration algorithm.
351 """
352 raise NotImplementedError('The Subclass must implement this')
353
354 def apply_cal(self, ntwk):
355 """
356 Apply correction to a Network.
357 """
358 raise NotImplementedError('The Subclass must implement this')
359
360 def apply_cal_to_list(self, ntwk_list):
361 """
362 Apply correction to list or dict of Networks.
363 """
364 if hasattr(ntwk_list, 'keys'):
365 return {k: self.apply_cal(nw) for k, nw in ntwk_list.items()}
366 else:
367 return [self.apply_cal(k) for k in ntwk_list]
368
369 def apply_cal_to_all_in_dir(self, *args, **kwargs):
370 """
371 Apply correction to all touchstone files in a given directory.
372
373 See `skrf.io.general.read_all_networks`.
374 """
375
376 from ..io.general import read_all_networks
377 ntwkDict = read_all_networks(*args, **kwargs)
378 return self.apply_cal_to_list(ntwkDict)
379
380 def apply_cal_to_network_set(self, ntwk_set):
381 """
382 Apply correction to a NetworkSet.
383 """
384 cal_ns = NetworkSet([self.apply_cal(ntwk) for ntwk in ntwk_set])
385 if hasattr(ntwk_set, 'name'):
386 cal_ns.name = ntwk_set.name
387 return cal_ns
388
389 def embed(self,ntwk):
390 """
391 Embed an ideal response in the estimated error network[s]
392 """
393 raise NotImplementedError('The Subclass must implement this')
394
395 def pop(self,std=-1):
396 """
397 Remove and return tuple of (ideal, measured) at index.
398
399 Parameters
400 ----------
401 std : int or str
402 the integer of calibration standard to remove, or the name
403 of the ideal or measured calibration standard to remove.
404
405 Returns
406 -------
407 ideal,measured : tuple of skrf.Networks
408 the ideal and measured networks which were popped out of the
409 calibration
410
411 """
412
413 if isinstance(std, str):
414 for idx,ideal in enumerate(self.ideals):
415 if std == ideal.name:
416 std = idx
417
418 if isinstance(std, str):
419 for idx,measured in enumerate(self.measured):
420 if std == measured.name:
421 std = idx
422
423 if isinstance(std, str):
424 raise (ValueError(f'standard {std} not found in ideals'))
425
426 return (self.ideals.pop(std), self.measured.pop(std))
427
428 def remove_and_cal(self, std):
429 """
430 Remove a cal standard and correct it, returning correct and ideal.
431
432 This requires requires overdetermination. Useful in
433 troubleshooting a calibration in which one standard is junk, but
434 you dont know which.
435
436 Parameters
437 ----------
438 std : int or str
439 the integer of calibration standard to remove, or the name
440 of the ideal or measured calibration standard to remove.
441
442 Returns
443 -------
444 ideal,corrected : tuple of skrf.Networks
445 the ideal and corrected networks which were removed out of the
446 calibration
447
448 """
449 measured, ideals = copy(self.measured), copy(self.ideals)
450 i,m = self.pop(std)
451 self.run()
452 c = self.apply_cal(m)
453 self.measured = measured
454 self.ideals = ideals
455 self.run()
456 return c,i
457
458
459
460
461
462 @classmethod
463 def from_coefs_ntwks(cls, coefs_ntwks, **kwargs):
464 """
465 Create a calibration from its error coefficients.
466
467 Parameters
468 ----------
469 coefs_ntwks : dict of Networks objects
470 error coefficients for the calibration
471
472 See Also
473 --------
474 Calibration.from_coefs
475 """
476 # assigning this measured network is a hack so that
477 # * `calibration.frequency` property evaluates correctly
478 # * TRL.__init__() will not throw an error
479 if not hasattr(coefs_ntwks,'keys'):
480 # maybe they passed a list? lets try and make a dict from it
481 coefs_ntwks = NetworkSet(coefs_ntwks).to_dict()
482
483 coefs = NetworkSet(coefs_ntwks).to_s_dict()
484
485 frequency = list(coefs_ntwks.values())[0].frequency
486
487 cal= cls.from_coefs(frequency=frequency, coefs=coefs, **kwargs)
488 return cal
489
490 @classmethod
491 def from_coefs(cls, frequency, coefs, **kwargs):
492 """
493 Create a calibration from its error coefficients.
494
495 Parameters
496 ----------
497 frequency : :class:`~skrf.frequency.Frequency`
498 frequency info, (duh)
499 coefs : dict of numpy arrays
500 error coefficients for the calibration
501
502 See Also
503 --------
504 Calibration.from_coefs_ntwks
505
506 """
507 # assigning this measured network is a hack so that
508 # * `calibration.frequency` property evaluates correctly
509 # * TRL.__init__() will not throw an error
510 n = Network(frequency = frequency,
511 s = rand_c(frequency.npoints,2,2))
512 measured = [n,n,n]
513
514 if 'forward switch term' in coefs:
515 switch_terms = (Network(frequency = frequency,
516 s=coefs['forward switch term']),
517 Network(frequency = frequency,
518 s=coefs['reverse switch term']))
519 kwargs['switch_terms'] = switch_terms
520
521
522 cal = cls(measured, measured, **kwargs)
523 cal.coefs = coefs
524 cal.family += '(fromCoefs)'
525 return cal
526
527 @property
528 def frequency(self):
529 """
530 :class:`~skrf.frequency.Frequency` object of the calibration.
531 """
532 return self.measured[0].frequency.copy()
533
534 @property
535 def nstandards(self):
536 """
537 Number of ideal/measurement pairs in calibration.
538 """
539 if len(self.ideals) != len(self.measured):
540 warn("number of ideals and measured don't agree", stacklevel=2)
541 return len(self.ideals)
542
543 @property
544 def coefs(self):
545 """
546 Dictionary or error coefficients in form of numpy arrays.
547
548 The keys of this will be different depending on the
549 Calibration Model. This dictionary should be populated
550 when the `run()` function is called.
551
552 Notes
553 -----
554 when setting this, property, the numpy arrays are flattened.
555 this makes accessing the coefs more concise in the code.
556
557 See Also
558 --------
559 coefs_3term
560 coefs_8term
561 coefs_12term
562 coefs_ntwks
563 """
564 try:
565 return self._coefs
566 except(AttributeError):
567 self.run()
568 return self._coefs
569
570 @coefs.setter
571 def coefs(self,d):
572 """
573 """
574 for k in d:
575 d[k] = d[k].flatten()
576 self._coefs = d
577
578 def update_coefs(self, d):
579 """
580 Update current dict of error coefficients.
581 """
582 for k in d:
583 d[k] = d[k].flatten()
584
585 self._coefs.update(d)
586
587 @property
588 def output_from_run(self):
589 """
590 Return any output from the :func:`run`.
591
592 This just returns what's in _output_from_run, and calls
593 :func:`run` if that attribute is non-existent.
594 finally, returns None if run() is called, and nothing is in
595 _output_from_run.
596 """
597 try:
598 return self._output_from_run
599 except(AttributeError):
600 # maybe i haven't run yet
601 self.run()
602 try:
603 return self._output_from_run
604 except(AttributeError):
605 # i did run and there is no output_from_run
606 return None
607
608 @property
609 def coefs_ntwks(self):
610 """
611 Dictionary of error coefficients in form of Network objects.
612
613 See Also
614 --------
615 coefs_3term_ntwks
616 coefs_12term_ntwks
617 coefs_8term_ntwks
618 """
619 ns = NetworkSet.from_s_dict(d=self.coefs,
620 frequency=self.frequency)
621 return ns.to_dict()
622
623 @property
624 def coefs_3term(self):
625 """
626 Dictionary of error coefficients for One-port Error model.
627
628 Contains the keys:
629 * directivity
630 * source match
631 * reflection tracking'
632 """
633 return {k: self.coefs.get(k) for k in [\
634 'directivity',
635 'source match',
636 'reflection tracking',
637 ]}
638
639 @property
640 def coefs_3term_ntwks(self):
641 """
642 Dictionary of error coefficients in form of Network objects.
643 """
644 ns = NetworkSet.from_s_dict(d=self.coefs_3term,
645 frequency=self.frequency)
646 return ns.to_dict()
647
648 @property
649 def normalized_directivity(self):
650 """
651 Directivity normalized to the reflection tracking.
652 """
653 try:
654 return self.coefs_ntwks['directivity']/\
655 self.coefs_ntwks['reflection tracking']
656 except Exception:
657 pass
658 try:
659 out = {}
660 for direction in ['forward','reverse']:
661 out[direction + ' normalized directivity'] =\
662 self.coefs_ntwks[direction + ' directivity']/\
663 self.coefs_ntwks[direction + ' reflection tracking']
664 return out
665 except Exception as err:
666 raise ValueError('cant find error coefs') from err
667
668
669 @property
670 def coefs_8term(self):
671 """
672 Dictionary of error coefficients for 8-term (Error-box) Model.
673
674 Contains the keys:
675 * forward directivity
676 * forward source match
677 * forward reflection tracking
678 * reverse directivity
679 * reverse source match
680 * reverse reflection tracking
681 * forward switch term
682 * reverse switch term
683 * k
684 * forward isolation
685 * reverse isolation
686
687 Notes
688 -----
689 If this calibration uses the 12-term model, then
690 :func:`convert_12term_2_8term` is called. See [1]_
691
692 References
693 ----------
694
695 .. [1] "Formulations of the Basic Vector Network Analyzer Error
696 Model including Switch Terms" by Roger B. Marks
697
698
699 """
700
701 d = self.coefs
702 if all([k in d.keys() for k in coefs_list_3term]):
703 raise ValueError("Can't convert one port error terms to two port error terms")
704
705 # Check if we have all 12-term keys and convert to 8-term if we do.
706 if all([k in d.keys() for k in coefs_list_12term]):
707 return convert_12term_2_8term(d)
708
709 return d
710
711 @property
712 def coefs_8term_ntwks(self):
713 """
714 Dictionary of error coefficients in form of Network objects.
715 """
716 ns = NetworkSet.from_s_dict(d=self.coefs_8term,
717 frequency=self.frequency)
718 return ns.to_dict()
719
720 @property
721 def coefs_12term(self):
722 """
723 Dictionary of error coefficients for 12-term Model.
724
725 Contains the keys:
726 * forward directivity
727 * forward source match
728 * forward reflection tracking
729 * forward transmission tracking
730 * forward load match
731 * forward isolation
732 * reverse directivity
733 * reverse load match
734 * reverse reflection tracking
735 * reverse transmission tracking
736 * reverse source match
737 * reverse isolation
738
739 Notes
740 -----
741 If this calibration uses the 8-term model, then
742 :func:`convert_8term_2_12term` is called. See [1]_
743
744
745 References
746 ----------
747
748 .. [1] "Formulations of the Basic Vector Network Analyzer Error
749 Model including Switch Terms" by Roger B. Marks
750
751
752 """
753 d = self.coefs
754 if all([k in d.keys() for k in coefs_list_3term]):
755 raise ValueError("Can't convert one port error terms to two port error terms")
756
757 # Check if we have all 12-term keys and return the coefs if we do
758 if all([k in d.keys() for k in coefs_list_12term]):
759 return d
760
761 return convert_8term_2_12term(d)
762
763 @property
764 def coefs_12term_ntwks(self):
765 """
766 Dictionary or error coefficients in form of Network objects.
767 """
768 ns = NetworkSet.from_s_dict(d=self.coefs_12term,
769 frequency=self.frequency)
770 return ns.to_dict()
771
772 @property
773 def verify_12term(self):
774 """
775 """
776
777 Edf = self.coefs_12term['forward directivity']
778 Esf = self.coefs_12term['forward source match']
779 Erf = self.coefs_12term['forward reflection tracking']
780 Etf = self.coefs_12term['forward transmission tracking']
781 Elf = self.coefs_12term['forward load match']
782
783 Edr = self.coefs_12term['reverse directivity']
784 Elr = self.coefs_12term['reverse load match']
785 Err = self.coefs_12term['reverse reflection tracking']
786 Etr = self.coefs_12term['reverse transmission tracking']
787 Esr = self.coefs_12term['reverse source match']
788
789 return Etf*Etr - (Err + Edr*(Elf - Esr))*(Erf + Edf *(Elr - Esf))
790
791 @property
792 def verify_12term_ntwk(self):
793 return Network(s= self.verify_12term, frequency = self.frequency)
794
795 @property
796 def residual_ntwks(self):
797 """
798 Dictionary of residual Networks.
799
800 These residuals are complex differences between the ideal
801 standards and their corresponding corrected measurements.
802
803 """
804 return [caled - ideal for (ideal, caled) in zip(self.ideals, self.caled_ntwks)]
805
806
807 @property
808 def residual_ntwk_sets(self):
809 """
810 Returns a NetworkSet for each `residual_ntwk`, grouped by their names.
811 """
812
813 residual_sets={}
814 std_names = list(set([k.name for k in self.ideals]))
815 for std_name in std_names:
816 residual_sets[std_name] = NetworkSet(
817 [k for k in self.residual_ntwks if k.name.startswith(std_name)])
818 return residual_sets
819
820 @property
821 def caled_ntwks(self):
822 """
823 List of the corrected calibration standards.
824 """
825 return self.apply_cal_to_list(self.measured)
826
827
828 @property
829 def caled_ntwk_sets(self):
830 """
831 Return a NetworkSet for each `caled_ntwk`, grouped by their names.
832 """
833
834 caled_sets={}
835 std_names = list(set([k.name for k in self.ideals ]))
836 for std_name in std_names:
837 caled_sets[std_name] = NetworkSet(
838 [k for k in self.caled_ntwks if k.name.startswith(std_name)])
839 return caled_sets
840
841 @property
842 def biased_error(self) -> NetworkSet:
843 """
844 Estimate of biased error for overdetermined calibration with
845 multiple connections of each standard.
846
847 Returns
848 -------
849 biased_error : skrf.Network
850 Network with s_mag is proportional to the biased error
851
852 Notes
853 -----
854 Mathematically, this is
855
856 .. math::
857
858 mean_s(|mean_c(r)|)
859
860 Where:
861
862 * r: complex residual errors
863 * mean_c: complex mean taken across connection
864 * mean_s: complex mean taken across standard
865
866 See Also
867 --------
868 biased_error
869 unbiased_error
870 total_error
871
872 """
873 rns = self.residual_ntwk_sets
874 out = NetworkSet([rns[k].mean_s for k in rns]).mean_s_mag
875 out.name = 'Biased Error'
876 return out
877
878 @property
879 def unbiased_error(self) -> NetworkSet:
880 """
881 Estimate of unbiased error for overdetermined calibration with
882 multiple connections of each standard.
883
884 Returns
885 -------
886 unbiased_error : skrf.Network
887 Network with s_mag is proportional to the unbiased error
888
889 Notes
890 -----
891 Mathematically, this is
892
893 mean_s(std_c(r))
894
895 where:
896 * r : complex residual errors
897 * std_c : standard deviation taken across connections
898 * mean_s : complex mean taken across standards
899
900 See Also
901 --------
902 biased_error
903 unbiased_error
904 total_error
905 """
906 rns = self.residual_ntwk_sets
907 out = NetworkSet([rns[k].std_s for k in rns]).mean_s_mag
908 out.name = 'Unbiased Error'
909 return out
910
911 @property
912 def total_error(self) -> NetworkSet:
913 """
914 Estimate of total error for overdetermined calibration with
915 multiple connections of each standard.This is the combined
916 effects of both biased and un-biased errors.
917
918 Returns
919 -------
920 total_error : skrf.Network
921 Network with s_mag is proportional to the total error
922
923 Notes
924 -----
925 Mathematically, this is
926
927 std_cs(r)
928
929 where:
930 * r : complex residual errors
931 * std_cs : standard deviation taken across connections and standards
932
933 See Also
934 --------
935 biased_error
936 unbiased_error
937 total_error
938 """
939 out = NetworkSet(self.residual_ntwks).mean_s_mag
940 out.name = 'Total Error'
941 return out
942
943 @property
944 def error_ntwk(self):
945 """
946 The calculated error Network or Network[s].
947
948 This will return a single two-port network for a one-port cal.
949 For a 2-port calibration this will return networks
950 for forward and reverse excitation. However, these are not
951 sufficient to use for embedding, see the :func:`embed` function
952 for that.
953
954 """
955 return error_dict_2_network(
956 self.coefs,
957 frequency = self.frequency,
958 is_reciprocal= self.is_reciprocal)
959
960 def write(self, file=None, *args, **kwargs):
961 r"""
962 Write the Calibration to disk using :func:`~skrf.io.general.write`.
963
964
965 Parameters
966 ----------
967 file : str or file-object
968 filename or a file-object. If left as None then the
969 filename will be set to Calibration.name, if its not None.
970 If both are None, ValueError is raised.
971 \*args, \*\*kwargs : arguments and keyword arguments
972 passed through to :func:`~skrf.io.general.write`
973
974 Notes
975 -----
976 If the self.name is not None and file is can left as None
977 and the resultant file will have the `.ntwk` extension appended
978 to the filename.
979
980 Examples
981 --------
982 >>> cal.name = 'my_cal'
983 >>> cal.write()
984
985 See Also
986 --------
987 skrf.io.general.write
988 skrf.io.general.read
989
990 """
991 # this import is delayed until here because of a circular dependency
992 from ..io.general import write
993
994 if file is None:
995 if self.name is None:
996 raise (ValueError('No filename given. You must provide a filename, or set the name attribute'))
997 file = self.name
998
999 write(file,self, *args, **kwargs)
1000
1001 @util.axes_kwarg
1002 def plot_calibration_errors(self, *args, ax: util.Axes = None, **kwargs):
1003 """
1004 Plot biased, unbiased and total error in dB scaled.
1005
1006 See Also
1007 --------
1008 biased_error
1009 unbiased_error
1010 total_error
1011 """
1012
1013
1014 port_list = self.biased_error.port_tuples
1015 for m,n in port_list:
1016 ax.set_title(f"S{self.biased_error.ntwk_set[0]._fmt_trace_name(m,n)}")
1017 self.unbiased_error.plot_s_db(m,n,**kwargs)
1018 self.biased_error.plot_s_db(m,n,**kwargs)
1019 self.total_error.plot_s_db(m,n,**kwargs)
1020 ax.set_ylim(-100,0)
1021
1022
1023 def plot_caled_ntwks(self, attr: str = 's_smith', show_legend: bool = False, **kwargs):
1024 r"""
1025 Plot corrected calibration standards.
1026
1027 Given that the calibration is overdetermined, this may be used
1028 as a heuristic verification of calibration quality.
1029
1030 Parameters
1031 ----------
1032 attr : str
1033 Network property to plot, ie 's_db', 's_smith', etc.
1034 Default is 's_smith'
1035 show_legend : bool, optional
1036 draw a legend or not. Default is False.
1037 \*\*kwargs : kwargs
1038 passed to the plot method of Network
1039 """
1040 ns = NetworkSet(self.caled_ntwks)
1041 fig, axes = util.subplots(figsize=(8,8))
1042
1043 kwargs.update({'show_legend':show_legend})
1044
1045 for ax ,(m, n) in zip(axes, ns[0].port_tuples):
1046 ax.set_title(f"S{ns.ntwk_set[0]._fmt_trace_name(m, n)}")
1047 ns.__getattribute__('plot_'+attr)(m, n, **kwargs)
1048
1049 fig.tight_layout()
1050
1051
1052 def plot_residuals(self, attr: str = 's_db', **kwargs):
1053 r"""
1054 Plot residual networks.
1055
1056 Given that the calibration is overdetermined, this may be used
1057 as a metric of the calibration's *goodness of fit*
1058
1059 Parameters
1060 ----------
1061 attr : str, optional.
1062 Network property to plot, ie 's_db', 's_smith', etc.
1063 Default is 's_db'
1064 \*\*kwargs : kwargs
1065 passed to the plot method of Network
1066
1067 See Also
1068 --------
1069 Calibration.residual_networks
1070 """
1071
1072 NetworkSet(self.residual_ntwks).__getattribute__('plot_'+attr)(**kwargs)
1073
1074
1075
1076 class OnePort(Calibration):
1077 r"""
1078 Standard algorithm for a one port calibration.
1079
1080 Solves the linear set of equations:
1081
1082
1083 .. math::
1084 e_{11}\mathbf{i_1m_1}-\Delta e\,\mathbf{i_1}+e_{00}=\mathbf{m_1}
1085
1086 e_{11}\mathbf{i_2m_2}-\Delta e\,\mathbf{i_2}+e_{00}=\mathbf{m_2}
1087
1088 e_{11}\mathbf{i_3m_3}-\Delta e\,\mathbf{i_3}+e_{00}=\mathbf{m_3}
1089
1090 ...
1091
1092 Where **m**'s and **i**'s are the measured and ideal reflection coefficients,
1093 respectively.
1094
1095 See :func:`__init__` for the correct parameters order. If more than three
1096 standards are supplied, then a least square algorithm is applied.
1097
1098 See [1]_ and [2]_
1099
1100 References
1101 ----------
1102
1103 .. [1] http://na.tm.agilent.com/vnahelp/tip20.html
1104
1105 .. [2] Bauer, R.F., Jr.; Penfield, Paul, "De-Embedding and Unterminating,"
1106 Microwave Theory and Techniques, IEEE Transactions on , vol.22, no.3, pp.282,288, Mar 1974
1107 doi: 10.1109/TMTT.1974.1128212
1108 URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1128212&isnumber=25001
1109
1110 """
1111
1112 family = 'OnePort'
1113 def __init__(self, measured, ideals,*args, **kwargs):
1114 """
1115 One Port initializer.
1116
1117 If more than three standards are supplied then a least square
1118 algorithm is applied.
1119
1120 Notes
1121 -----
1122 See func:`Calibration.__init__` for details about
1123 automatic standards alignment (aka `sloppy_input`)
1124
1125
1126 Parameters
1127 ----------
1128 measured : list/dict of :class:`~skrf.network.Network` objects
1129 Raw measurements of the calibration standards. The order
1130 must align with the `ideals` parameter ( or use `sloppy_input`)
1131
1132 ideals : list/dict of :class:`~skrf.network.Network` objects
1133 Predicted ideal response of the calibration standards.
1134 The order must align with `ideals` list ( or use `sloppy_input`)
1135
1136 args, kwargs :
1137 passed to func:`Calibration.__init__`
1138
1139 Notes
1140 -----
1141 This uses numpy.linalg.lstsq() for least squares calculation
1142
1143 See Also
1144 --------
1145 Calibration.__init__
1146 """
1147 Calibration.__init__(self, measured, ideals,
1148 *args, **kwargs)
1149
1150 def _check_input(self):
1151 if not all([n.number_of_ports==1 for n in self.ideals]):
1152 raise ValueError(f'ideals for {self.family} should be 1-port Networks')
1153 if not all([n.number_of_ports==1 for n in self.measured]):
1154 raise ValueError(f'measured networks for {self.family} should be 1-port Networks')
1155
1156 def run(self):
1157 """ Run the calibration algorithm.
1158 """
1159 numStds = self.nstandards
1160 numCoefs=3
1161
1162 mList = [self.measured[k].s.reshape((-1,1)) for k in range(numStds)]
1163 iList = [self.ideals[k].s.reshape((-1,1)) for k in range(numStds)]
1164
1165 self._check_input()
1166
1167 # ASSERT: mList and aList are now kx1x1 matrices, where k in frequency
1168 fLength = len(mList[0])
1169
1170 #initialize outputs
1171 abc = np.zeros((fLength,numCoefs),dtype=complex)
1172 residuals = np.zeros((fLength,\
1173 np.sign(numStds-numCoefs)),dtype=complex)
1174 parameter_variance = np.zeros((fLength, 3,3),dtype=complex)
1175 measurement_variance = np.zeros((fLength, 1),dtype=complex)
1176 # loop through frequencies and form m, a vectors and
1177 # the matrix M. where M = i1, 1, i1*m1
1178 # i2, 1, i2*m2
1179 # ...etc
1180 for f in list(range(fLength)):
1181 #create m, i, and 1 vectors
1182 one = np.ones(shape=(numStds,1))
1183 m = np.array([ mList[k][f] for k in range(numStds)]).reshape(-1,1)# m-vector at f
1184 i = np.array([ iList[k][f] for k in range(numStds)]).reshape(-1,1)# i-vector at f
1185
1186 # construct the matrix
1187 Q = np.hstack([i, one, i*m])
1188 # calculate least squares
1189 abcTmp, residualsTmp = np.linalg.lstsq(Q,m,rcond=None)[0:2]
1190 if numStds > 3:
1191 measurement_variance[f,:]= residualsTmp/(numStds-numCoefs)
1192 parameter_variance[f,:] = \
1193 abs(measurement_variance[f,:])*\
1194 np.linalg.inv(np.dot(Q.T,Q))
1195
1196
1197 abc[f,:] = abcTmp.flatten()
1198 try:
1199 residuals[f,:] = residualsTmp
1200 except ValueError as err:
1201 raise(ValueError('matrix has singular values. ensure standards are far enough away on smith chart'))\
1202 from err
1203
1204 # convert the abc vector to standard error coefficients
1205 a,b,c = abc[:,0], abc[:,1],abc[:,2]
1206 e01e10 = a+b*c
1207 e00 = b
1208 e11 = c
1209 self._coefs = {\
1210 'directivity':e00,\
1211 'reflection tracking':e01e10, \
1212 'source match':e11\
1213 }
1214
1215
1216 # output is a dictionary of information
1217 self._output_from_run = {
1218 'residuals':residuals,
1219 'parameter variance':parameter_variance
1220 }
1221
1222 return None
1223
1224 def apply_cal(self, ntwk):
1225 er_ntwk = Network(frequency = self.frequency, name=ntwk.name)
1226 tracking = self.coefs['reflection tracking']
1227 s12 = np.sqrt(tracking)
1228 s21 = s12
1229
1230 s11 = self.coefs['directivity']
1231 s22 = self.coefs['source match']
1232 er_ntwk.s = np.array([[s11, s12],[s21,s22]]).transpose(2,0,1)
1233 return er_ntwk.inv**ntwk
1234
1235 def embed(self,ntwk):
1236 embedded = self.error_ntwk ** ntwk
1237 embedded.name = ntwk.name
1238 return embedded
1239
1240
1241 class SDDLWeikle(OnePort):
1242 """
1243 Short-Delay-Delay-Load (Oneport Calibration), Liu-Weikle formulation.
1244
1245 One-port self-calibration, which contains a known short, a known
1246 mismatched load, and two partially-unknown delay shorts.
1247 The short can be an offset short with known phase, or a zero-length
1248 (flush) short. The load can have an arbitrary impedance, as long
1249 as it's reflective (not perfectly matched) and known exactly. This
1250 is especially useful when an ideal load is impractical to fabricate.
1251 The delay shorts have unity reflection magnitudes, but unknown phases
1252 (unknown electrical lengths).
1253
1254 See :func:`__init__` for the correct parameters order.
1255
1256 This class uses the Liu-Weikle formulation,
1257 which requires a mismatched load (i.e. non-zero reflection coefficient).
1258 Calibration fails if the load is perfectly matched. In the paper, a
1259 fully-known radiating open is used as the load standard.
1260
1261 It was originally designed for waveguide calibration with resistance to
1262 flange misalignment by Liu-Weikle [1]_, which was itself a modification
1263 of the earlier Sigg-Simon SDDM calibration [2]_. In Sigg-Simon's SDDM,
1264 the load must be matched, while Liu-Weikle SDDL only allows a mismatched
1265 load.
1266
1267 .. note::
1268 This algorithm is bandwidth-limited due to phase wrapping,
1269 conceptually similar to TRL's bandwidth limit. Some over-determined
1270 multi-line variants allow wideband calibration, but this is not
1271 implemented in scikit-rf. If a wideband calibration is required (common
1272 for coaxial systems), it's necessary to manually split measurements to
1273 multiple subbands and calibrate each band separately.
1274
1275 Band edges may suffer from increased errors. It's recommended to test
1276 line lengths experimentally via simulations first. Choosing an optimal
1277 selection of line lengths that covers the widest bandwidth is a
1278 non-trivial optimization problem, with several proposed solutions [3]_.
1279
1280 References
1281 ----------
1282 .. [1] Z. Liu and R. M. Weikle, "A reflectometer calibration method resistant to waveguide flange misalignment,"
1283 Microwave Theory and Techniques, IEEE Transactions on, vol. 54, no. 6, pp. 2447-2452, Jun. 2006.
1284
1285 .. [2] W. Sigg and J. Simon, "Reflectometer calibration using load, short and offset shorts with
1286 unknown phase," Electronics Letters, vol. 27, no. 18, pp. 1650–1651, 1991.
1287
1288 .. [3] A. Lewandowski, W. Wiatr, L. J. Opalski and R. Biedrzycki, "Accuracy and Bandwidth Optimization of the
1289 Over-Determined Offset-Short Reflectometer Calibration," in IEEE Transactions on Microwave Theory and
1290 Techniques, vol. 63, no. 3, pp. 1076-1089, March 2015, doi: 10.1109/TMTT.2015.2396496.
1291 """
1292
1293 family = 'SDDL'
1294 def __init__(self, measured, ideals, *args, **kwargs):
1295 """
1296 Short-Delay-Delay-Load initializer.
1297
1298 Measured and ideal networks must be in the order:
1299
1300 * short
1301 * delay short1
1302 * delay short2
1303 * load
1304
1305 Parameters
1306 ----------
1307 measured : list/dict of :class:`~skrf.network.Network` objects
1308 Raw measurements of the calibration standards. The order
1309 must align with the `ideals` parameter ( or use `sloppy_input`)
1310
1311 ideals : list/dict of :class:`~skrf.network.Network` objects
1312 Predicted ideal response of the calibration standards.
1313 The order must align with `ideals` list ( or use sloppy_input
1314
1315 args, kwargs :
1316 passed to func:`Calibration.__init__`
1317
1318 See Also
1319 --------
1320 Calibration.__init__
1321
1322 """
1323 if (len(measured) != 4) or (len(ideals)) != 4:
1324 raise IndexError('Incorrect number of standards.')
1325 Calibration.__init__(self, measured = measured,
1326 ideals =ideals, **kwargs)
1327
1328 def run(self):
1329 self._check_input()
1330
1331 #measured reflection coefficients
1332 w_s = self.measured[0].s.flatten() # short
1333 w_1 = self.measured[1].s.flatten() # delay short 1
1334 w_2 = self.measured[2].s.flatten() # delay short 2
1335 w_l = self.measured[3].s.flatten() # load
1336
1337 # ideal response of reflection coefficients
1338 G_l = self.ideals[3].s.flatten() # gamma_load
1339 # handle singularities
1340 G_l[G_l ==0] = ALMOST_ZERO
1341
1342
1343 w_1p = w_1 - w_s # between (9) and (10)
1344 w_2p = w_2 - w_s
1345 w_lp = w_l - w_s
1346
1347
1348 ## NOTE: the published equation has an incorrect sign on this argument
1349 ## perhaps because they assume arg to measure clockwise angle??
1350 alpha = exp(1j*2*angle(1./w_2p - 1./w_1p)) # (17)
1351
1352 p = alpha/( 1./w_1p - alpha/w_1p.conj() - (1.+G_l)/(G_l*w_lp )) # (22)
1353 q = p/(alpha* G_l) #(23) (put in terms of p)
1354
1355 Bp_re = -1*((1 + (imag(p+q)/real(q-p)) * (imag(q-p)/real(p+q)))/\
1356 (1 + (imag(p+q)/real(q-p))**2)) * real(p+q) # (25)
1357
1358 Bp_im = imag(q+p)/real(q-p) * Bp_re #(24)
1359 Bp = Bp_re + Bp_im*1j
1360
1361 B = Bp + w_s #(10)
1362 C = Bp * (1./w_1p - alpha/w_1p.conj()) + alpha * Bp/Bp.conj() #(20)
1363 A = B - w_s + w_s*C #(6)
1364
1365 # convert the abc vector to standard error coefficients
1366 e00 = B
1367 e11 = -C
1368 e01e10 = A + e00*e11
1369
1370 self._coefs = {\
1371 'directivity':e00,\
1372 'reflection tracking':e01e10, \
1373 'source match':e11\
1374 }
1375
1376 class SDDL(OnePort):
1377 """
1378 Short-Delay-Delay-Load (Oneport Calibration), formulation by Arsenovic
1379 et, al.
1380
1381 One-port self-calibration, which contains a known short, a known
1382 arbitrary-impedance load, and two partially-unknown delay shorts.
1383 The short can be an offset short with known phase, or a zero-length
1384 (flush) short. The load can be perfectly matched or an arbitrary impedance
1385 standard, as long as it's known exactly. This is especially useful when
1386 an ideal load is impractical to fabricate. The delay shorts have unity
1387 reflection magnitudes, but unknown phases (unknown electrical lengths).
1388
1389 See :func:`__init__` for the correct parameters order.
1390
1391 This class uses the Arsenovic et, al. formulation [1]_, which allows
1392 either a mismatched or a matched load as the calibration standard.
1393 It's a generalization of both Sigg-Simon's original SDDM [2]_ and
1394 Liu-Weikle's modified SDDL methods [3]_, which are limited to matching
1395 or reflective loads only. The latter was originally designed for waveguide
1396 calibration with resistance to flange misalignment.
1397
1398 .. note::
1399 This algorithm is bandwidth-limited due to phase wrapping,
1400 conceptually similar to TRL's bandwidth limit. Some over-determined
1401 multi-line variants allow wideband calibration, but this is not
1402 implemented in scikit-rf. If a wideband calibration is required (common
1403 for coaxial systems), it's necessary to manually split measurements to
1404 multiple subbands and calibrate each band separately.
1405
1406 Band edges may suffer from increased errors. It's recommended to test
1407 line lengths experimentally via simulations first. Choosing an optimal
1408 selection of line lengths that covers the widest bandwidth is a
1409 non-trivial optimization problem, with several proposed solutions [4]_.
1410
1411 References
1412 ----------
1413 .. [1] A. Arsenovic, R. M. Weikle, and J. L. Hesler, “Reflectometer calibration with a pair of partially known
1414 standards,” European Microwave Conference, pp. 327–330, Dec. 2015, doi: 10.1109/EUMC.2015.7345766.
1415
1416 .. [2] Z. Liu and R. M. Weikle, "A reflectometer calibration method resistant to waveguide flange misalignment,"
1417 Microwave Theory and Techniques, IEEE Transactions on, vol. 54, no. 6, pp. 2447-2452, Jun. 2006.
1418
1419 .. [3] W. Sigg and J. Simon, "Reflectometer calibration using load, short and offset shorts with
1420 unknown phase," Electronics Letters, vol. 27, no. 18, pp. 1650–1651, 1991.
1421
1422 .. [4] A. Lewandowski, W. Wiatr, L. J. Opalski and R. Biedrzycki, "Accuracy and Bandwidth Optimization of the
1423 Over-Determined Offset-Short Reflectometer Calibration," in IEEE Transactions on Microwave Theory and
1424 Techniques, vol. 63, no. 3, pp. 1076-1089, March 2015, doi: 10.1109/TMTT.2015.2396496.
1425 """
1426
1427 family = 'SDDL'
1428 def __init__(self, measured, ideals, *args, **kwargs):
1429 """
1430 Short-Delay-Delay-Load initializer.
1431
1432 Measured and ideal networks must be in the order:
1433
1434 [ Short, Delay short1, Delay short2, Load]
1435
1436 The ideal delay shorts can be set to `None`, as they are
1437 determined during the calibration.
1438
1439 Parameters
1440 ----------
1441 measured : list/dict of :class:`~skrf.network.Network` objects
1442 Raw measurements of the calibration standards. The order
1443 must align with the `ideals` parameter ( or use `sloppy_input`)
1444
1445 ideals : list/dict of :class:`~skrf.network.Network` objects
1446 Predicted ideal response of the calibration standards.
1447 The order must align with `ideals` list ( or use sloppy_input
1448
1449 args, kwargs :
1450 passed to func:`Calibration.__init__`
1451
1452 See Also
1453 --------
1454 Calibration.__init__
1455
1456 """
1457 # if they pass None for the ideal responses for delay shorts
1458 # then we will copy the short standard in their place. this is
1459 # only to avoid throwing an error when initializing the cal, the
1460 # values are not used.
1461 if ideals[1] is None:
1462 ideals[1] = ideals[0].copy()
1463 if ideals[2] is None:
1464 ideals[2] = ideals[0].copy()
1465
1466 if (len(measured) != 4) or (len(ideals)) != 4:
1467 raise IndexError('Incorrect number of standards.')
1468 Calibration.__init__(self, measured = measured,
1469 ideals =ideals, **kwargs)
1470
1471
1472 def run(self):
1473 self._check_input()
1474
1475 #measured impedances
1476 d = s2z(self.measured[0].s,1) # short
1477 a = s2z(self.measured[1].s,1) # delay short 1
1478 b = s2z(self.measured[2].s,1) # delay short 2
1479 c = s2z(self.measured[3].s,1) # load
1480 l = s2z(self.ideals[-1].s,1) # ideal def of load
1481 cr_alpha = cross_ratio(b,a,c,d)
1482 cr_beta = cross_ratio(a,b,c,d)
1483
1484 alpha = imag(cr_alpha)/real(cr_alpha/l)
1485 beta = imag(cr_beta)/real(cr_beta/l)
1486
1487 self.ideals[1].s = z2s(alpha*1j,1)
1488 self.ideals[2].s = z2s(beta*1j,1)
1489
1490 OnePort.run(self)
1491
1492
1493 class PHN(OnePort):
1494 """
1495 Pair of Half Knowns (Oneport Calibration).
1496
1497 One-port self-calibration, which contains two fully-known arbitrary
1498 impedance standards, and two partially-known standards (such as open
1499 or short circuits with unknown phase). See :func:`__init__` for the
1500 correct parameters order.
1501
1502 This is a generalization of the SDDL calibration algorithm, see [1]_.
1503
1504 .. important::
1505 Unfortunately, due to a square-root sign ambiguity in the solution of a
1506 quadratic equation, this algorithm can be unstable. While it has proven to
1507 be reliable in rectangular waveguide calibration scenarios, it often fails
1508 for arbitrary-impedance standards with random reflection coefficients. This
1509 is a major drawback in the current solution, but the authors believe this
1510 problem may be overcome analytically by future research.
1511
1512 References
1513 ----------
1514 .. [1] A. Arsenovic, R. M. Weikle, and J. L. Hesler, “Reflectometer calibration with a pair of partially known
1515 standards,” European Microwave Conference, pp. 327–330, Dec. 2015, doi: 10.1109/EUMC.2015.7345766.
1516 """
1517
1518 family = 'PHN'
1519 def __init__(self, measured, ideals, *args, **kwargs):
1520 """
1521 Half-Half-Full-Full initializer.
1522
1523 Measured and ideal networks must be in the order:
1524
1525 [Half-Known 1, Half-Known 2, Fully-Known 1, Fully-Known 2]
1526
1527 The phases of half-known standards can be set to an approximate
1528 value, as they are determined during the calibration.
1529
1530 Parameters
1531 ----------
1532 measured : list/dict of :class:`~skrf.network.Network` objects
1533 Raw measurements of the calibration standards. The order
1534 must align with the `ideals` parameter.
1535
1536 ideals : list/dict of :class:`~skrf.network.Network` objects
1537 Predicted ideal response of the calibration standards.
1538 The order must align with `ideals` list.
1539
1540 args, kwargs :
1541 passed to func:`Calibration.__init__`
1542
1543 See Also
1544 --------
1545 Calibration.__init__
1546 """
1547 if (len(measured) != 4) or (len(ideals)) != 4:
1548 raise IndexError('Incorrect number of standards.')
1549
1550 Calibration.__init__(self, measured = measured,
1551 ideals =ideals, **kwargs)
1552
1553
1554 def run(self):
1555 self._check_input()
1556
1557 # ideals (in impedance)
1558 a = s2z(self.ideals[0].s,1).flatten() # half known
1559 b = s2z(self.ideals[1].s,1).flatten() # half known
1560 c = s2z(self.ideals[2].s,1).flatten() # fully known
1561 d = s2z(self.ideals[3].s,1).flatten() # fully known
1562
1563 # measured (in impedances)
1564 a_ = s2z(self.measured[0].s,1).flatten() # half known
1565 b_ = s2z(self.measured[1].s,1).flatten() # half known
1566 c_ = s2z(self.measured[2].s,1).flatten() # fully known
1567 d_ = s2z(self.measured[3].s,1).flatten() # fully known
1568
1569 z = cross_ratio(a_,b_,c_,d_)
1570
1571 # intermediate variables
1572 e = c-d-c*z
1573 f = d-c-d*z
1574 g = c*d*z
1575
1576 A = -real(f*z.conj())
1577 B = 1j*imag( f*e.conj() + g.conj()*z)
1578 C = real( g*e.conj())
1579
1580 npts = len(A)
1581 b1,b2 = zeros(npts, dtype=complex), zeros(npts, dtype=complex)
1582
1583 for k in range(npts):
1584 p = poly1d([A[k],B[k],C[k]])
1585 b1[k],b2[k] = p.r
1586
1587 a1 = -(f*b1 + g)/(z*b1 + e)
1588 a2 = -(f*b2 + g)/(z*b2 + e)
1589
1590 # temporarily translate into s-parameters so make the root-choice
1591 # choosing a root in impedance doesn't generally work for typical
1592 # calibration standards
1593 b1_s = z2s(b1.reshape(-1,1,1),1)
1594 b2_s = z2s(b2.reshape(-1,1,1),1)
1595 a1_s = z2s(a1.reshape(-1,1,1),1)
1596 a2_s = z2s(a2.reshape(-1,1,1),1)
1597
1598 b_guess = z2s(b.reshape(-1,1,1),1)
1599 a_guess = z2s(a.reshape(-1,1,1),1)
1600
1601 distance1 = abs(a1_s - a_guess) + abs(b1_s - b_guess)
1602 distance2 = abs(a2_s - a_guess) + abs(b2_s - b_guess)
1603
1604
1605 b_found = np.where(distance1<distance2, b1, b2)
1606 a_found = np.where(distance1<distance2, a1, a2)
1607
1608
1609 self.ideals[0].s = z2s(a_found.reshape(-1,1,1),1)
1610 self.ideals[1].s = z2s(b_found.reshape(-1,1,1),1)
1611
1612 OnePort.run(self)
1613
1614
1615 ## Two Ports
1616
1617 class TwelveTerm(Calibration):
1618 """
1619 12-term, full two-port calibration.
1620
1621 `TwelveTerm` is the traditional, fully determined, two-port calibration
1622 originally developed in [1]_.
1623
1624 `TwelveTerm` can accept any number of reflect and transmissive standards,
1625 as well as arbitrary (non-flush) transmissive standards.
1626
1627 * If more than 3 reflect standards are provided, a least-squares
1628 solution is implemented for the one-port stage of the calibration.
1629 * If more than 1 transmissive standard is given the `load match`,
1630 and `transmission tracking` terms are calculated multiple times
1631 and averaged.
1632
1633 References
1634 ------------
1635 .. [1] "Calibration Process of Automatic Network Analyzer Systems" by Stig Rehnmark
1636
1637 """
1638
1639 family = 'TwelveTerm'
1640 def __init__(self, measured, ideals, n_thrus=None, trans_thres=-40,
1641 *args, **kwargs):
1642 """
1643 TwelveTerm initializer.
1644
1645 Use the `n_thrus` argument to explicitly define the number of
1646 transmissive standards. Otherwise, if `n_thrus=None`, then we
1647 will try and guess which are transmissive, by comparing the mean
1648 :math:`|s21|` and :math:`|s12|` responses (in dB) to `trans_thres`.
1649
1650 Notes
1651 ------
1652 See func:`Calibration.__init__` for details about automatic
1653 standards alignment (aka `sloppy_input`).
1654
1655 Parameters
1656 -------------
1657 measured : list/dict of :class:`~skrf.network.Network` objects
1658 Raw measurements of the calibration standards. The order
1659 must align with the `ideals` parameter ( or use `sloppy_input`)
1660
1661 ideals : list/dict of :class:`~skrf.network.Network` objects
1662 Predicted ideal response of the calibration standards.
1663 The order must align with `ideals` list ( or use sloppy_input
1664
1665 n_thrus : int
1666 Number of transmissive standards. If None, we will try and
1667 guess for you by comparing measure transmission to trans_thres,
1668
1669 trans_thres: float
1670 The minimum transmission magnitude (in dB) that is
1671 the threshold for categorizing a transmissive standard.
1672 Compared to the measured s21,s12 meaned over frequency
1673 Only use if n_thrus=None.
1674
1675 isolation : :class:`~skrf.network.Network` object
1676 Measurement with loads on both ports with a perfect isolation
1677 between the ports. Used for determining the isolation error terms.
1678 If no measurement is given leakage is assumed to be zero.
1679
1680 Loads don't need to be same as the one used as a match standard or
1681 even have similar reflection coefficients. Reflects can be also used,
1682 but accuracy might not be as good.
1683
1684 See Also
1685 -----------
1686 Calibration.__init__
1687
1688 """
1689
1690 kwargs.update({'measured':measured,
1691 'ideals':ideals})
1692
1693 # note: this will enable sloppy_input and align stds if necessary
1694 Calibration.__init__(self, *args, **kwargs)
1695
1696 # if they didn't tell us the number of thrus, then lets
1697 # heuristically determine it
1698 trans_thres_mag = 10 ** (trans_thres / 20)
1699
1700 if n_thrus is None:
1701 warn('n_thrus is None, guessing which stds are transmissive', stacklevel=2)
1702 n_thrus=0
1703 for k in self.ideals:
1704 mean_trans = NetworkSet([k.s21, k.s12]).mean_s_mag
1705 trans_mag = np.mean(mean_trans.s_mag.flatten())
1706 # this number is arbitrary but reasonable
1707 if trans_mag > trans_thres_mag:
1708 n_thrus +=1
1709
1710
1711 if n_thrus ==0:
1712 raise ValueError(
1713 'couldnt find a transmissive standard. check your data, or explicitly use `n_thrus` argument'
1714 )
1715 self.n_thrus = n_thrus
1716
1717 # if they didntly give explicit order, lets try and put the
1718 # more transmissive standards last, by sorted measured/ideals
1719 # based on mean s21
1720 if self.sloppy_input:
1721 trans = [np.mean(k.s21.s_mag) for k in self.ideals]
1722 # see http://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list
1723 # get order of indices of sorted means s21
1724 order = [x for (y,x) in sorted(zip(trans, range(len(trans))),\
1725 key=lambda pair: pair[0])]
1726 self.measured = [self.measured[k] for k in order]
1727 self.ideals = [self.ideals[k] for k in order]
1728
1729 def run(self):
1730 """
1731 """
1732 n_thrus = self.n_thrus
1733 p1_m = [k.s11 for k in self.measured[:-n_thrus]]
1734 p2_m = [k.s22 for k in self.measured[:-n_thrus]]
1735 p1_i = [k.s11 for k in self.ideals[:-n_thrus]]
1736 p2_i = [k.s22 for k in self.ideals[:-n_thrus]]
1737 thrus = self.measured[-n_thrus:]
1738 ideal_thrus = self.ideals[-n_thrus:]
1739
1740 # create one port calibration for reflective standards
1741 port1_cal = OnePort(measured = p1_m, ideals = p1_i)
1742 port2_cal = OnePort(measured = p2_m, ideals = p2_i)
1743
1744 # cal coefficient dictionaries
1745 p1_coefs = dict(port1_cal.coefs)
1746 p2_coefs = dict(port2_cal.coefs)
1747
1748 if self.kwargs.get('isolation',None) is not None:
1749 p1_coefs['isolation'] = self.kwargs['isolation'].s21.s.flatten()
1750 p2_coefs['isolation'] = self.kwargs['isolation'].s12.s.flatten()
1751 else:
1752 p1_coefs['isolation'] = np.zeros(len(self.frequency), dtype=complex)
1753 p2_coefs['isolation'] = np.zeros(len(self.frequency), dtype=complex)
1754
1755
1756 # loop thru thrus, and calculate error terms for each one
1757 # load match and transmission tracking for ports 1 and 2
1758 lm1, lm2,tt1, tt2 = [],[],[],[]
1759 for thru, thru_i in zip(thrus, ideal_thrus):
1760 lm1.append(thru_i.inv**port1_cal.apply_cal(thru.s11))
1761 lm2.append(thru_i.flipped().inv**port2_cal.apply_cal(thru.s22))
1762
1763 # forward transmission tracking
1764 g = lm1[-1].s
1765 d = p1_coefs['source match'].reshape(-1,1,1)
1766 e,f,b,h = thru_i.s11.s, thru_i.s22.s,thru_i.s21.s,thru_i.s12.s
1767 m = thru.s21.s - p1_coefs['isolation'].reshape(-1,1,1)
1768
1769 ac = m*1./b * (1 - (d*e + f*g + b*g*h*d) + (d*e*f*g) )
1770 tt1.append(ac[:])
1771
1772 # reverse transmission tracking
1773 thru.flip(),thru_i.flip() # flip thrus to keep same ports as above
1774 g = lm2[-1].s
1775 d = p2_coefs['source match'].reshape(-1,1,1)
1776
1777 e,f,b,h = thru_i.s11.s, thru_i.s22.s,thru_i.s21.s,thru_i.s12.s
1778 m = thru.s21.s - p2_coefs['isolation'].reshape(-1,1,1)
1779
1780 ac = m*1./b * (1 - (d*e+f*g+b*g*h*d) + d*e*f*g)
1781 tt2.append(ac[:])
1782
1783 thru.flip(), thru_i.flip() # flip em back
1784
1785 p1_coefs['transmission tracking'] = np.mean(np.array(tt1),axis=0).flatten()
1786 p2_coefs['transmission tracking'] = np.mean(np.array(tt2),axis=0).flatten()
1787 p1_coefs['load match'] = NetworkSet(lm1).mean_s.s.flatten()
1788 p2_coefs['load match'] = NetworkSet(lm2).mean_s.s.flatten()
1789
1790
1791 # update coefs
1792 coefs = {}
1793
1794 coefs.update({f'forward {k}': p1_coefs[k] for k in p1_coefs})
1795 coefs.update({f'reverse {k}': p2_coefs[k] for k in p2_coefs})
1796 eight_term_coefs = convert_12term_2_8term(coefs)
1797
1798 coefs.update({l: eight_term_coefs[l] for l in \
1799 ['forward switch term','reverse switch term','k'] })
1800 self._coefs = coefs
1801
1802 def apply_cal(self,ntwk):
1803 """
1804 """
1805 caled = ntwk.copy()
1806
1807 s11 = ntwk.s[:,0,0]
1808 s12 = ntwk.s[:,0,1]
1809 s21 = ntwk.s[:,1,0]
1810 s22 = ntwk.s[:,1,1]
1811
1812 Edf = self.coefs['forward directivity']
1813 Esf = self.coefs['forward source match']
1814 Erf = self.coefs['forward reflection tracking']
1815 Etf = self.coefs['forward transmission tracking']
1816 Elf = self.coefs['forward load match']
1817 Eif = self.coefs.get('forward isolation',0)
1818
1819 Edr = self.coefs['reverse directivity']
1820 Elr = self.coefs['reverse load match']
1821 Err = self.coefs['reverse reflection tracking']
1822 Etr = self.coefs['reverse transmission tracking']
1823 Esr = self.coefs['reverse source match']
1824 Eir = self.coefs.get('reverse isolation',0)
1825
1826
1827 D = (1+(s11-Edf)/(Erf)*Esf)*(1+(s22-Edr)/(Err)*Esr) -\
1828 ((s21-Eif)/(Etf))*((s12-Eir)/(Etr))*Elf*Elr
1829
1830
1831 caled.s[:,0,0] = \
1832 (((s11-Edf)/(Erf))*(1+(s22-Edr)/(Err)*Esr)-\
1833 Elf*((s21-Eif)/(Etf))*(s12-Eir)/(Etr)) /D
1834
1835 caled.s[:,1,1] = \
1836 (((s22-Edr)/(Err))*(1+(s11-Edf)/(Erf)*Esf)-\
1837 Elr*((s21-Eif)/(Etf))*(s12-Eir)/(Etr)) /D
1838
1839 caled.s[:,1,0] = \
1840 ( ((s21 -Eif)/(Etf))*(1+((s22-Edr)/(Err))*(Esr-Elf)) )/D
1841
1842 caled.s[:,0,1] = \
1843 ( ((s12 -Eir)/(Etr))*(1+((s11-Edf)/(Erf))*(Esf-Elr)) )/D
1844
1845 return caled
1846
1847 def embed(self, ntwk):
1848 measured = ntwk.copy()
1849
1850 s11 = ntwk.s[:,0,0]
1851 s12 = ntwk.s[:,0,1]
1852 s21 = ntwk.s[:,1,0]
1853 s22 = ntwk.s[:,1,1]
1854 det = s11*s22 - s12*s21
1855
1856 Edf = self.coefs['forward directivity']
1857 Esf = self.coefs['forward source match']
1858 Erf = self.coefs['forward reflection tracking']
1859 Etf = self.coefs['forward transmission tracking']
1860 Elf = self.coefs['forward load match']
1861 Eif = self.coefs.get('forward isolation',0)
1862
1863 Edr = self.coefs['reverse directivity']
1864 Elr = self.coefs['reverse load match']
1865 Err = self.coefs['reverse reflection tracking']
1866 Etr = self.coefs['reverse transmission tracking']
1867 Esr = self.coefs['reverse source match']
1868 Eir = self.coefs.get('reverse isolation',0)
1869
1870
1871 measured = ntwk.copy()
1872
1873 D1 = (1 - Esf*s11 - Elf*s22 + Esf*Elf*det)
1874 D2 = (1 - Elr*s11 - Esr*s22 + Esr*Elr*det)
1875
1876 measured.s[:,0,0] = Edf + Erf * (s11 - Elf*det)/D1
1877 measured.s[:,1,0] = Eif + Etf * s21/D1
1878 measured.s[:,1,1] = Edr + Err * (s22 - Elr*det)/D2
1879 measured.s[:,0,1] = Eir + Etr * s12/D2
1880
1881 return measured
1882
1883
1884 class SOLT(TwelveTerm):
1885 """
1886 Short-Open-Load-Thru, Full two-port calibration.
1887
1888 SOLT is the traditional, fully determined, two-port calibration
1889 originally developed in [1]_.
1890 Although the acronym SOLT implies the use of 4 standards, skrf's
1891 algorithm can accept any number of reflect standards, If
1892 more than 3 reflect standards are provided a least-squares solution
1893 is implemented for the one-port stage of the calibration.
1894
1895 Redundant thru measurements can also be used, through the `n_thrus`
1896 parameter. See :func:`__init__`
1897
1898 References
1899 ------------
1900 .. [1] W. Kruppa and K. F. Sodomsky, "An Explicit Solution for the Scattering Parameters of a Linear Two-Port
1901 Measured with an Imperfect Test Set (Correspondence)," IEEE Transactions on Microwave Theory and Techniques,
1902 vol. 19, no. 1, pp. 122-123, Jan. 1971.
1903
1904
1905 See Also
1906 ---------
1907 TwelveTerm
1908
1909 """
1910 family = 'SOLT'
1911 def __init__(self, measured, ideals, n_thrus=1, *args, **kwargs):
1912 """
1913 SOLT initializer.
1914
1915 If you aren't using `sloppy_input`, then the order of the
1916 standards must align.
1917
1918 If `n_thrus!=None`, then the thru standard[s] must be last in
1919 the list. The `n_thrus` argument can be used to allow multiple
1920 measurements of the thru standard.
1921
1922 If the ideal element for the thru is set to None, a flush thru
1923 is assumed.
1924
1925 Notes
1926 -----
1927 See func:`Calibration.__init__` for details about automatic
1928 standards alignment (aka `sloppy_input`).
1929
1930 Parameters
1931 ----------
1932 measured : list/dict of :class:`~skrf.network.Network` objects
1933 Raw measurements of the calibration standards. The order
1934 must align with the `ideals` parameter ( or use `sloppy_input`)
1935
1936 ideals : list/dict of :class:`~skrf.network.Network` objects
1937 Predicted ideal response of the calibration standards.
1938 The order must align with `ideals` list ( or use `sloppy_input`)
1939 The thru standard can be None
1940
1941 n_thrus : int
1942 number of thru measurements
1943
1944 isolation : :class:`~skrf.network.Network` object
1945 Measurement with loads on both ports. Used for determining the
1946 isolation error terms. If no measurement is given isolation is
1947 assumed to be zero.
1948
1949
1950 See Also
1951 --------
1952 TwelveTerm.__init__
1953 """
1954
1955 # see if they passed a None for the thru, and if so lets
1956 # make an ideal flush thru for them
1957 for k in range(-n_thrus,len(ideals)):
1958 if ideals[k] is None:
1959 if (n_thrus is None) or (hasattr(ideals, 'keys')) or \
1960 (hasattr(measured, 'keys')):
1961 raise ValueError(dedent(
1962 """Can't use sloppy_input and have the ideal thru be None.
1963 Measured and ideals must be lists, or dont use None for the thru ideal."""))
1964
1965 ideal_thru = measured[0].copy()
1966 ideal_thru.s[:,0,0] = 0
1967 ideal_thru.s[:,1,1] = 0
1968 ideal_thru.s[:,1,0] = 1
1969 ideal_thru.s[:,0,1] = 1
1970 ideals[k] = ideal_thru
1971
1972 kwargs.update({'measured':measured,
1973 'ideals':ideals,
1974 'n_thrus':n_thrus})
1975
1976 TwelveTerm.__init__(self,*args, **kwargs)
1977
1978
1979 class TwoPortOnePath(TwelveTerm):
1980 """
1981 Two Port One Path Calibration (aka poor man's TwelveTerm).
1982
1983 Provides full error correction on a switchless three receiver
1984 system, i.e. you can only measure the waves a1,b1,and b2.
1985 Given this architecture, the DUT must be flipped and measured
1986 twice to be fully corrected.
1987
1988 To allow for this, the `apply_cal` method takes a tuple of
1989 measurements in the order (forward,reverse), and creates a composite
1990 measurement that is correctable.
1991
1992 """
1993 family = 'TwoPortOnePath'
1994
1995 def __init__(self, measured, ideals, n_thrus=None, source_port=1,
1996 *args, **kwargs):
1997 """
1998 Two Port One Path Calibration initializer.
1999
2000 Use the `n_thrus` argument to explicitly define the number of
2001 transmissive standards. Otherwise, if `n_thrus=None`, then we
2002 will try and guess which are transmissive, by comparing the mean
2003 :math: `|s21|` and :math: `|s12|` responses (in dB) to `trans_thres`.
2004
2005 Notes
2006 -----
2007 See func:`Calibration.__init__` for details about automatic
2008 standards alignment (aka `sloppy_input`).
2009
2010 Parameters
2011 ----------
2012 measured : list/dict of :class:`~skrf.network.Network` objects
2013 Raw measurements of the calibration standards. The order
2014 must align with the `ideals` parameter ( or use `sloppy_input`)
2015
2016 ideals : list/dict of :class:`~skrf.network.Network` objects
2017 Predicted ideal response of the calibration standards.
2018 The order must align with `ideals` list ( or use sloppy_input
2019
2020 n_thrus : int
2021 number of thru measurements
2022
2023 source_port : [1,2]
2024 The port on which the source is active. should be 1 or 2
2025
2026
2027
2028 See Also
2029 --------
2030 TwelveTerm.__init__
2031 """
2032
2033 if source_port not in [1, 2]:
2034 raise ValueError("Invalid source_port value. Expected 1 or 2.")
2035
2036 self.sp = source_port-1
2037 self.rp = 1 if self.sp == 0 else 0
2038 # Make S12 = S21 and S22 = S11 for numerical reasons
2039 measured_sym = [m.copy() for m in measured]
2040 for m in measured_sym:
2041 m.s[:,self.sp, self.rp] = m.s[:,self.rp, self.sp]
2042 m.s[:,self.rp, self.rp] = m.s[:,self.sp, self.sp]
2043
2044 kwargs.update({'measured':measured_sym,
2045 'ideals':ideals,
2046 'n_thrus':n_thrus})
2047 TwelveTerm.__init__(self,*args, **kwargs)
2048
2049
2050 def run(self):
2051 """
2052 """
2053
2054 # run a full twelve term then just copy all forward error terms
2055 # over reverse error terms
2056 TwelveTerm.run(self)
2057
2058
2059 out_coefs = self.coefs.copy()
2060
2061 if self.sp ==0:
2062 forward = 'forward'
2063 reverse = 'reverse'
2064 elif self.sp ==1:
2065 forward = 'reverse'
2066 reverse = 'forward'
2067 else:
2068 raise ValueError('source_port is out of range. should be 1 or 2.')
2069 for k in self.coefs:
2070 if k.startswith(forward):
2071 k_out = k.replace(forward,reverse)
2072 out_coefs[k_out] = self.coefs[k]
2073
2074 eight_term_coefs = convert_12term_2_8term(out_coefs)
2075 out_coefs.update({l: eight_term_coefs[l] for l in \
2076 ['forward switch term','reverse switch term','k'] })
2077 self._coefs = out_coefs
2078
2079 def apply_cal(self, ntwk_tuple):
2080 """
2081 apply the calibration to a measurement.
2082
2083 Notes
2084 -----
2085 Full correction is possible given you have measured your DUT
2086 in both orientations. Meaning, you have measured the device,
2087 then physically flipped the device and made a second measurement.
2088
2089 This tuple of 2-port Networks is what is meant by
2090 (forward,reverse), in the docstring below
2091
2092 If you pass a single 2-port Network, then the measurement will
2093 only be partially corrected using what is known as the
2094 `EnhancedResponse` calibration.
2095
2096 Parameters
2097 ----------
2098 network_tuple: tuple, or Network
2099 tuple of 2-port Networks in order (forward, reverse) OR
2100 a single 2-port Network.
2101
2102
2103
2104 """
2105 if isinstance(ntwk_tuple,tuple) or isinstance(ntwk_tuple,list):
2106 f,r = ntwk_tuple[0].copy(), ntwk_tuple[1].copy()
2107 sp,rp = self.sp,self.rp
2108 ntwk = f.copy()
2109 ntwk.s[:,sp,sp] = f.s[:,sp,sp]
2110 ntwk.s[:,rp,sp] = f.s[:,rp,sp]
2111 ntwk.s[:,rp,rp] = r.s[:,sp,sp]
2112 ntwk.s[:,sp,rp] = r.s[:,rp,sp]
2113
2114 out = TwelveTerm.apply_cal(self, ntwk)
2115 return out
2116
2117 else:
2118 warnings.warn('only gave a single measurement orientation, error correction is partial without a tuple',
2119 stacklevel=2)
2120 ntwk = ntwk_tuple.copy()
2121 sp,rp = self.sp,self.rp
2122
2123 ntwk.s[:,rp,rp] = 0
2124 ntwk.s[:,sp,rp] = 0
2125 out = TwelveTerm.apply_cal(self, ntwk)
2126 out.s[:,rp,rp] = 0
2127 out.s[:,sp,rp] = 0
2128
2129 return out
2130
2131 class EnhancedResponse(TwoPortOnePath):
2132 """
2133 Enhanced Response Partial Calibration.
2134
2135 Why are you using this?
2136 For full error you correction, you can measure the DUT in both
2137 orientations and instead use TwoPortOnePath
2138
2139 Accuracy of correct measurements will rely on having a good match
2140 at the passive side of the DUT.
2141
2142 For code-structuring reasons, this is a dummy placeholder class.
2143 Its just TwoPortOnePath, which defaults to enhancedresponse correction
2144 when you apply the calibration to a single network, and not a tuple
2145 of networks.
2146 """
2147 family = 'EnhancedResponse'
2148
2149
2150 class EightTerm(Calibration):
2151 """
2152 General EightTerm (aka Error-box) Two-port calibration.
2153
2154 This is basically an extension of the one-port algorithm to two-port
2155 measurements, A least squares estimator is used to determine the
2156 error coefficients. No self-calibration takes place.
2157 The concept is presented in [1]_ , but implementation follows that
2158 of [2]_ .
2159
2160 See :func:`__init__`
2161
2162 Notes
2163 -----
2164 An important detail of implementing the error-box
2165 model is that the internal switch must be correctly accounted for.
2166 This is done through the measurement of :term:`switch terms`.
2167
2168
2169 References
2170 ----------
2171
2172 .. [1] Speciale, R.A.; , "A Generalization of the TSD Network-Analyzer Calibration Procedure,
2173 Covering n-Port Scattering-Parameter Measurements, Affected by Leakage Errors,"
2174 Microwave Theory and Techniques, IEEE Transactions on,
2175 vol.25, no.12, pp. 1100- 1115, Dec 1977.
2176 URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1129282&isnumber=25047
2177
2178 .. [2] Rytting, D. (1996) Network Analyzer Error Models and Calibration Methods.
2179 RF 8: Microwave Measurements for Wireless Applications (ARFTG/NIST Short Course Notes)
2180
2181 """
2182
2183 family = 'EightTerm'
2184 def __init__(self, measured, ideals, switch_terms=None,
2185 isolation=None, ut_hook=None,*args, **kwargs):
2186 """
2187 EightTerm Initializer.
2188
2189 Notes
2190 -----
2191 See func:`Calibration.__init__` for details about automatic
2192 standards alignment (aka `sloppy_input`).
2193
2194 Parameters
2195 ----------
2196 measured : list/dict of :class:`~skrf.network.Network` objects
2197 Raw measurements of the calibration standards. The order
2198 must align with the `ideals` parameter
2199
2200 ideals : list/dict of :class:`~skrf.network.Network` objects
2201 Predicted ideal response of the calibration standards.
2202 The order must align with `ideals` list
2203
2204 switch_terms : tuple of :class:`~skrf.network.Network` objects
2205 the pair of switch terms in the order (forward, reverse)
2206
2207 isolation : :class:`~skrf.network.Network` object
2208 Measurement with loads on both ports with a perfect isolation
2209 between the ports. Used for determining the isolation error terms.
2210 If no measurement is given leakage is assumed to be zero.
2211
2212 Loads don't need to be same as the one used as a match standard or
2213 even have similar reflection coefficients. Reflects can be also used,
2214 but accuracy might not be as good.
2215
2216 """
2217
2218 self.switch_terms = switch_terms
2219 if switch_terms is None:
2220 warn('No switch terms provided', stacklevel=2)
2221
2222 if isolation is None:
2223 self.isolation = measured[0].copy()
2224 self.isolation.s[:,:,:] = 0
2225 else:
2226 self.isolation = isolation.copy()
2227 #Zero port matching so that networks can be simply subtracted
2228 self.isolation.s[:,0,0] = 0
2229 self.isolation.s[:,1,1] = 0
2230
2231 self.ut_hook=ut_hook
2232
2233 Calibration.__init__(self,
2234 measured = measured,
2235 ideals = ideals,
2236 **kwargs)
2237
2238
2239 def unterminate(self,ntwk):
2240 """
2241 Unterminates switch terms from a raw measurement.
2242
2243 See Also
2244 --------
2245 calibration.unterminate
2246 """
2247 if self.ut_hook is not None:
2248 return self.ut_hook(self,ntwk)
2249
2250 if self.switch_terms is not None:
2251 gamma_f, gamma_r = self.switch_terms
2252 return unterminate(ntwk, gamma_f, gamma_r)
2253
2254 else:
2255 return ntwk
2256
2257
2258
2259 def terminate(self, ntwk):
2260 """
2261 Terminate a network with switch terms.
2262
2263 See Also
2264 --------
2265 calibration.terminate
2266 """
2267 if self.switch_terms is not None:
2268 gamma_f, gamma_r = self.switch_terms
2269 return terminate(ntwk, gamma_f, gamma_r)
2270 else:
2271 return ntwk
2272
2273 @property
2274 def measured_unisolated(self):
2275 return [k-self.isolation for k in self.measured]
2276
2277 @property
2278 def measured_unterminated(self):
2279 return [self.unterminate(k) for k in self.measured_unisolated]
2280
2281 def run(self):
2282 numStds = self.nstandards
2283 numCoefs = 7
2284
2285
2286 mList = [k.s for k in self.measured_unterminated]
2287 iList = [k.s for k in self.ideals]
2288
2289 fLength = len(mList[0])
2290 #initialize outputs
2291 error_vector = np.zeros(shape=(fLength,numCoefs),dtype=complex)
2292 residuals = np.zeros(shape=(fLength,4*numStds-numCoefs),dtype=complex)
2293 Q = np.zeros((numStds*4, 7),dtype=complex)
2294 M = np.zeros((numStds*4, 1),dtype=complex)
2295 # loop through frequencies and form m, a vectors and
2296 # the matrix M. where M = e00 + S11i
2297 # i2, 1, i2*m2
2298 # ...etc
2299 for f in list(range(fLength)):
2300 # loop through standards and fill matrix
2301 for k in list(range(numStds)):
2302 m,i = mList[k][f,:,:],iList[k][f,:,:] # 2x2 s-matrices
2303 Q[k*4:k*4+4,:] = np.array([\
2304 [ 1, i[0,0]*m[0,0], -i[0,0], 0, i[1,0]*m[0,1], 0, 0 ],\
2305 [ 0, i[0,1]*m[0,0], -i[0,1], 0, i[1,1]*m[0,1], 0, -m[0,1] ],\
2306 [ 0, i[0,0]*m[1,0], 0, 0, i[1,0]*m[1,1], -i[1,0], 0 ],\
2307 [ 0, i[0,1]*m[1,0], 0, 1, i[1,1]*m[1,1], -i[1,1], -m[1,1] ],\
2308 ])
2309 #pdb.set_trace()
2310 M[k*4:k*4+4,:] = np.array([\
2311 [ m[0,0]],\
2312 [ 0 ],\
2313 [ m[1,0]],\
2314 [ 0 ],\
2315 ])
2316
2317 # calculate least squares
2318 error_vector_at_f, residuals_at_f = np.linalg.lstsq(Q,M,rcond=None)[0:2]
2319 #if len (residualsTmp )==0:
2320 # raise ValueError( 'matrix has singular values, check standards')
2321
2322
2323 error_vector[f,:] = error_vector_at_f.flatten()
2324 residuals[f,:] = residuals_at_f
2325
2326 e = error_vector
2327 # put the error vector into human readable dictionary
2328 self._coefs = {\
2329 'forward directivity':e[:,0],
2330 'forward source match':e[:,1],
2331 'forward reflection tracking':(e[:,0]*e[:,1])-e[:,2],
2332 'reverse directivity':e[:,3]/e[:,6],
2333 'reverse source match':e[:,4]/e[:,6],
2334 'reverse reflection tracking':(e[:,4]/e[:,6])*(e[:,3]/e[:,6])- (e[:,5]/e[:,6]),
2335 'k':e[:,6],
2336 }
2337
2338 self._coefs['forward isolation'] = self.isolation.s[:,1,0].flatten()
2339 self._coefs['reverse isolation'] = self.isolation.s[:,0,1].flatten()
2340
2341 if self.switch_terms is not None:
2342 self._coefs.update({
2343 'forward switch term': self.switch_terms[0].s.flatten(),
2344 'reverse switch term': self.switch_terms[1].s.flatten(),
2345 })
2346 else:
2347 self._coefs.update({
2348 'forward switch term': np.zeros(fLength, dtype=complex),
2349 'reverse switch term': np.zeros(fLength, dtype=complex),
2350 })
2351 # output is a dictionary of information
2352 self._output_from_run = {
2353 'error vector':e,
2354 'residuals':residuals
2355 }
2356
2357 return None
2358
2359 def apply_cal(self, ntwk):
2360 """Applies the calibration to the input network.
2361 Inverse of `embed`.
2362
2363 Parameters
2364 ----------
2365 ntwk : :class:`~skrf.network.Network`
2366 Uncalibrated input network.
2367
2368 Returns
2369 -------
2370 caled : :class:`~skrf.network.Network`
2371 Calibrated network.
2372 """
2373 caled = ntwk.copy()
2374
2375 T1,T2,T3,T4 = self.T_matrices
2376
2377 caled.s[:,1,0] -= self.coefs['forward isolation']
2378 caled.s[:,0,1] -= self.coefs['reverse isolation']
2379
2380 caled = self.unterminate(caled)
2381 caled.s = linalg.inv(-caled.s @ T3 + T1) @ (caled.s @ T4 - T2)
2382
2383 return caled
2384
2385 def embed(self, ntwk):
2386 """Applies the error boxes to the calibrated input network.
2387 Inverse of `apply_cal`.
2388
2389 Parameters
2390 ----------
2391 ntwk : :class:`~skrf.network.Network`
2392 Calibrated input network.
2393
2394 Returns
2395 -------
2396 embedded : :class:`~skrf.network.Network`
2397 Network with error boxes applied.
2398 """
2399 embedded = ntwk.copy()
2400
2401 T1,T2,T3,T4 = self.T_matrices
2402
2403 embedded.s = (T1 @ ntwk.s + T2) @ linalg.inv(T3 @ ntwk.s + T4)
2404 embedded = self.terminate(embedded)
2405
2406 embedded.s[:,1,0] += self.coefs['forward isolation']
2407 embedded.s[:,0,1] += self.coefs['reverse isolation']
2408
2409 return embedded
2410
2411
2412 @property
2413 def T_matrices(self):
2414 """
2415 Intermediate matrices used for embedding and de-embedding.
2416
2417 Returns
2418 -------
2419 T1,T2,T3,T4 : numpy ndarray
2420
2421 """
2422 ec = self.coefs
2423 npoints = len(ec['k'])
2424 one = np.ones(npoints,dtype=complex)
2425 zero = np.zeros(npoints,dtype=complex)
2426
2427 Edf = self.coefs['forward directivity']
2428 Esf = self.coefs['forward source match']
2429 Erf = self.coefs['forward reflection tracking']
2430 Edr = self.coefs['reverse directivity']
2431 Esr = self.coefs['reverse source match']
2432 Err = self.coefs['reverse reflection tracking']
2433 k = self.coefs['k']
2434
2435 detX = Edf*Esf-Erf
2436 detY = Edr*Esr-Err
2437
2438 T1 = np.array([
2439 [ -detX, zero ],
2440 [ zero, -k*detY ]
2441 ]).transpose(2,0,1)
2442 T2 = np.array([
2443 [ Edf, zero ],
2444 [ zero, k*Edr ]
2445 ]).transpose(2,0,1)
2446 T3 = np.array([
2447 [ -Esf, zero ],
2448 [ zero, -k*Esr ]
2449 ]).transpose(2,0,1)
2450 T4 = np.array([
2451 [ one, zero ],
2452 [ zero, k ]
2453 ]).transpose(2,0,1)
2454
2455 return T1,T2,T3,T4
2456
2457
2458 def renormalize(self, z0_old, z0_new, powerwave=False):
2459 """Renormalizes the calibration error boxes to a new reference impedance.
2460
2461 Useful for example after doing a TRL calibration with non-50 ohm
2462 transmission lines. After the TRL calibration reference impedance is the
2463 line characteristic impedance. If the transmission line characteristic
2464 impedance is known this function can be used to renormalize the
2465 reference impedance to 50 ohms or any other impedance.
2466 """
2467 ec = self.coefs
2468 npoints = len(ec['k'])
2469 one = np.ones(npoints,dtype=complex)
2470
2471 Edf = self.coefs['forward directivity']
2472 Esf = self.coefs['forward source match']
2473 Erf = self.coefs['forward reflection tracking']
2474 Edr = self.coefs['reverse directivity']
2475 Esr = self.coefs['reverse source match']
2476 Err = self.coefs['reverse reflection tracking']
2477 k = self.coefs['k']
2478
2479 S1 = np.array([
2480 [ Edf, Erf/k ],
2481 [ k, Esf ]
2482 ]).transpose(2,0,1)
2483
2484 S2 = np.array([
2485 [ Edr, one ],
2486 [ Err, Esr ]
2487 ]).transpose(2,0,1)
2488
2489 #Port impedances before renormalization.
2490 #Only the DUT side (port 2) is renormalized.
2491 #VNA side (port 1) stays unchanged.
2492 z = np.zeros((len(k),2), dtype=complex)
2493 z[:,0] = z0_new
2494 z[:,1] = z0_old
2495
2496 if powerwave:
2497 S1 = renormalize_s(S1, z, z0_new, s_def='power')
2498 S2 = renormalize_s(S2, z, z0_new, s_def='power')
2499 else:
2500 S1 = renormalize_s(S1, z, z0_new, s_def='traveling')
2501 S2 = renormalize_s(S2, z, z0_new, s_def='traveling')
2502
2503 self.coefs['forward directivity'] = S1[:,0,0]
2504 self.coefs['forward source match'] = S1[:,1,1]
2505 self.coefs['forward reflection tracking'] = S1[:,0,1]*S1[:,1,0]
2506 self.coefs['reverse directivity'] = S2[:,0,0]
2507 self.coefs['reverse source match'] = S2[:,1,1]
2508 self.coefs['reverse reflection tracking'] = S2[:,1,0]*S2[:,0,1]
2509 self.coefs['k'] = S1[:,1,0]/S2[:,0,1]
2510
2511 return None
2512
2513
2514 class TRL(EightTerm):
2515 """
2516 Thru-Reflect-Line (also called LRL for Line-Reflect-Line).
2517
2518 A Similar self-calibration algorithm as developed by Engen and
2519 Hoer [1]_, more closely following into a more matrix form in [2]_.
2520
2521 Reference impedance of the calibration is characteristic impedance of the
2522 transmission lines. If the characteristic impedance is known, reference
2523 impedance can be renormalized using `EightTerm.renormalize` function.
2524
2525 See Also
2526 --------
2527 determine_line function which actually determines the line s-parameters
2528
2529
2530
2531 References
2532 ----------
2533 .. [1] G. F. Engen and C. A. Hoer, "Thru-Reflect-Line: An Improved Technique for Calibrating the Dual
2534 Six-Port Automatic Network Analyzer,"
2535 IEEE Transactions on Microwave Theory and Techniques, vol. 27, no. 12, pp. 987-993, 1979.
2536
2537 .. [2] H.-J. Eul and B. Schiek, "A generalized theory and new calibration procedures for network analyzer
2538 self-calibration,"
2539 IEEE Transactions on Microwave Theory and Techniques, vol. 39, no. 4, pp. 724-731, 1991.
2540
2541
2542 """
2543 family = 'TRL'
2544 def __init__(self, measured, ideals=None, estimate_line=False,
2545 n_reflects=1,solve_reflect=True, *args,**kwargs):
2546 r"""
2547 Initialize a TRL calibration.
2548
2549 Note that the order of `measured` and `ideals` is strict.
2550 It must be [Thru, Reflect, Line]. A multiline algorithms is
2551 used if more than one line is passed. A multi-reflect algorithm
2552 is used if multiple reflects are passed, see `n_reflects` argument.
2553
2554 All of the `ideals` can be individually set to `None`, or the entire
2555 list set to `None` (`ideals=None`). For each ideal set to `None`,
2556 the following assumptions are made:
2557
2558 * thru : flush thru
2559 * reflect : flush shorts
2560 * line : an approximately 90deg matched line (can be lossy)
2561
2562 The reflect ideals can also be given as a +-1.
2563
2564 If thru is non-zero length, the calibration is done with zero length
2565 thru and the ideal thru length is subtracted from the ideal lines. The
2566 resulting calibration reference plane is at the center of the thru.
2567 Ideal reflect standard reference plane is at the center of the thru even
2568 if the ideal thru length is non-zero.
2569
2570 Note you can also use the `estimate_line` option to
2571 automatically estimate the initial guess for the line length
2572 from measurements . This is sensible
2573 if you have no idea what the line length is, but your **error
2574 networks** are well matched (E_ij >>E_ii).
2575
2576
2577 Notes
2578 -----
2579 This implementation inherits from :class:`EightTerm`. dont
2580 forget to pass switch_terms.
2581
2582
2583 Parameters
2584 ----------
2585 measured : list of :class:`~skrf.network.Network`
2586 must be in order [Thru, Reflect[s], Line[s]]. if the number
2587 of reflects is >1 then use `n_reflects` argument.
2588
2589 ideals : list of :class:`~skrf.network.Network`, [+1,-1] , None
2590 must be in order [Thru, Reflect, Line]. Each element in the
2591 list may be None, or equivalently, the list may be None.
2592 Also the reflects can be simply given as +1 or -1.
2593
2594 estimate_line : bool
2595 should we estimates the length of the line standard from
2596 raw measurements, if not we assume its about 90 deg.
2597
2598 solve_reflect : bool
2599 Solve for the reflect or not.
2600
2601 n_reflects : 1
2602 number of reflective standards
2603
2604 \*args, \*\*kwargs : passed to EightTerm.__init__
2605 dont forget the `switch_terms` argument is important
2606
2607 Examples
2608 --------
2609
2610 >>> thru = rf.Network('thru.s2p')
2611 >>> reflect = rf.Network('reflect.s2p')
2612 >>> line = rf.Network('line.s2p')
2613
2614 Ideals is None, so we assume it's close to a flush short:
2615
2616 >>> trl = TRL(measured=[thru,reflect,line], ideals=None)
2617
2618 Reflect is given as close to a flush short:
2619
2620 >>> trl = TRL(measured=[thru,reflect,line], ideals=[None,-1,None])
2621
2622 Reflect is given as close to a flush open:
2623
2624 >>> trl = TRL(measured=[thru,reflect,line], ideals=[None,+1,None])
2625
2626 See Also
2627 --------
2628 determine_line
2629 determine_reflect
2630 NISTMultilineTRL
2631 TUGMultilineTRL
2632
2633 """
2634 #warn('Value of Reflect is not solved for yet.')
2635
2636 self.n_stds = n_stds = len(measured)
2637 self.n_reflects = n_reflects
2638 self.estimate_line = estimate_line
2639 self.solve_reflect = solve_reflect
2640
2641 ## generate ideals, given various inputs
2642
2643 if ideals is None:
2644 ideals = [None]*len(measured)
2645
2646 if ideals[0] is None:
2647 # lets make an ideal flush thru for them
2648 ideal_thru = measured[0].copy()
2649 ideal_thru.s[:,0,0] = 0
2650 ideal_thru.s[:,1,1] = 0
2651 ideal_thru.s[:,1,0] = 1
2652 ideal_thru.s[:,0,1] = 1
2653 ideals[0] = ideal_thru
2654
2655 orig_ideal_thru = None
2656
2657 if np.any(ideals[0].s[:,1,0] != 1) or np.any(ideals[0].s[:,0,1] != 1):
2658 orig_ideal_thru = ideals[0]
2659 ideals[0] = ideals[0].copy()
2660 ideals[0].s[:,0,0] = 0
2661 ideals[0].s[:,1,1] = 0
2662 ideals[0].s[:,0,1] = 1
2663 ideals[0].s[:,1,0] = 1
2664
2665 for k in range(1,n_reflects+1):
2666 if ideals[k] is None:
2667 # default assume they are using flushshorts
2668 ideals[k] = -1
2669
2670 if isinstance(ideals[k], Number):
2671 ideal_reflect = measured[k].copy()
2672 ideal_reflect.s[:,0,0] = ideals[k]
2673 ideal_reflect.s[:,1,1] = ideals[k]
2674 ideal_reflect.s[:,1,0] = 0
2675 ideal_reflect.s[:,0,1] = 0
2676 ideals[k] = ideal_reflect
2677
2678
2679 for k in range(n_reflects+1,n_stds):
2680 if ideals[k] is None:
2681 # lets make an 90deg line for them
2682 ideal_line = measured[k].copy()
2683 ideal_line.s[:,0,0] = 0
2684 ideal_line.s[:,1,1] = 0
2685 ideal_line.s[:,1,0] = -1j
2686 ideal_line.s[:,0,1] = -1j
2687 ideals[k] = ideal_line
2688
2689 if orig_ideal_thru is not None:
2690 ideals[k] = ideals[k].copy()
2691 # De-embed original thru
2692 ideals[k].s[:,0,1] /= orig_ideal_thru.s[:,0,1]
2693 ideals[k].s[:,1,0] /= orig_ideal_thru.s[:,1,0]
2694
2695
2696 EightTerm.__init__(self,
2697 measured = measured,
2698 ideals = ideals,
2699 **kwargs)
2700
2701 def run(self):
2702 m_ut = self.measured_unterminated
2703 n_reflects = self.n_reflects
2704 n_stds = self.n_stds
2705 estimate_line = self.estimate_line
2706 solve_reflect = self.solve_reflect
2707 ideals = self.ideals
2708
2709 ## Solve for the line[s]
2710 for k in range(n_reflects+1,n_stds):
2711 if estimate_line:
2712 # setting line_approx to None causes determine_line() to
2713 # estimate the line length from raw measurements
2714 line_approx = None
2715 else:
2716 line_approx = ideals[k]
2717
2718 self.ideals[k] = determine_line(m_ut[0], m_ut[k], line_approx) # find line
2719
2720 ## Solve for the reflect[s]
2721 if solve_reflect:
2722 for k in range(1,n_reflects+1):
2723 # solve for reflect using the last line if they pass >1
2724 r = determine_reflect(m_ut[0],m_ut[k],m_ut[-1],reflect_approx=ideals[k], line_approx=self.ideals[-1])
2725 self.ideals[k] = two_port_reflect(r,r)
2726
2727 return EightTerm.run(self)
2728
2729 MultilineTRL = TRL
2730
2731 class NISTMultilineTRL(EightTerm):
2732 """
2733 NIST Multiline TRL calibration.
2734
2735 Multiline TRL can use multiple lines to extend bandwidth and accuracy of the
2736 calibration. Different line measurements are combined in a way that minimizes
2737 the error in calibration.
2738
2739 Calibration reference plane is at the edges of the lines.
2740
2741 At every frequency point there should be at least one line pair that has phase
2742 difference that is not 0 degrees or a multiple of 180 degrees otherwise
2743 calibration equations are singular and accuracy is very poor.
2744
2745 By default the reference impedance of the calibration is the characteristic
2746 impedance of the transmission lines. If the characteristic impedance is
2747 known reference impedance can be renormalized by giving `z0_ref` and
2748 `z0_line`. Alternatively if capacitance/length of the transmission line is
2749 given with `c0` argument, characteristic impedance can be solved assuming
2750 that conductance/length is zero.
2751
2752 Algorithm is the one published in [0]_, but implementation is based on [1]_.
2753
2754 References
2755 ----------
2756 .. [0] D. C. DeGroot, J. A. Jargon and R. B. Marks, "Multiline TRL revealed,"
2757 60th ARFTG Conference Digest, Fall 2002., Washington, DC, USA, 2002, pp. 131-155.
2758
2759 .. [1] K. Yau "On the metrology of nanoscale Silicon transistors above 100 GHz"
2760 Ph.D. dissertation, Dept. Elec. Eng. and Comp. Eng., University of Toronto, Toronto, Canada, 2011.
2761
2762 """
2763
2764 family = 'TRL'
2765 def __init__(self, measured, Grefls, l,
2766 er_est=1, refl_offset=None, ref_plane=0,
2767 gamma_root_choice='auto', k_method='multical', c0=None,
2768 z0_ref=50, z0_line=None, *args, **kwargs):
2769 r"""
2770 NISTMultilineTRL initializer.
2771
2772 Note that the order of `measured` is strict.
2773 It must be [Thru, Reflects, Lines]. Multiple reflects can
2774 also be used.
2775
2776 Notes
2777 -------
2778 This implementation inherits from :class:`EightTerm`. Don't
2779 forget to pass switch_terms.
2780
2781
2782 Parameters
2783 --------------
2784 measured : list of :class:`~skrf.network.Network`
2785 must be in order [Thru, Reflects, Lines]
2786
2787 Grefls : complex or list of complex
2788 Estimated reflection coefficients of reflect standards.
2789 Usually -1 for short or +1 for open.
2790
2791 l : list of float
2792 Lengths of through and lines. If through is non-zero length its
2793 length is subtracted from the line lengths for the calibration and
2794 afterwards the calibration reference planes are shifted back by half
2795 thru on both ports using the solved propagation constant.
2796
2797 er_est : complex
2798 Estimated effective permittivity of the lines.
2799 Imaginary part is the loss at 1 GHz.
2800 Negative imaginary part indicates losses.
2801
2802 refl_offset : float or list of float
2803 Estimated offsets of the reflect standards from the reference plane
2804 at the end of the lines.
2805 Negative length is towards the VNA. Units are in meters.
2806
2807 ref_plane : float or list of float
2808 Reference plane shift after the calibration.
2809 Negative length is towards the VNA. Units are in meters.
2810
2811 Different shifts can be given to different ports by giving a two element list.
2812 First element is shift of port 1 and second is shift of port 2.
2813
2814 gamma_root_choice : string
2815 Method to use for choosing the correct eigenvalue for propagation
2816 constant.
2817
2818 'estimate' : Choose the root that is closer to the estimated propagation
2819 constant. Best choice when data is of good quality. To improve the
2820 performance in phatological cases it's possible to give estimate
2821 of the propagation constant as a keyword argument with 'gamma_est'.
2822
2823 'real' : Force the real part of the gamma to be positive corresponding
2824 to a lossy line. Imaginary part can be negative.
2825 This is the suggested method when lines have moderate loss and the
2826 measurement noise is low. This is the default method.
2827
2828 'auto' : Use heuristics to choose the eigenvalue.
2829
2830 'imag' : Force the imaginary part of the gamma to be positive,
2831 corresponding to a positive length line. Real part can be positive.
2832 May choose incorrectly when the line is long due to phase wrapping.
2833
2834 k_method : string
2835 Method to use for determining the 'k' error coefficient.
2836 Currently valid choices are 'marks' or 'multical'.
2837 The default method is 'multical'.
2838
2839 c0 : None, float or list of float
2840 Capacitance/length of the transmission line in units F/m used for
2841 reference impedance renormalization.
2842
2843 Characteristic impedance of the transmission lines can be determined
2844 from the solved propagation constant if capacitance per length is known.
2845 After the characteristic impedance is solved reference impedance of
2846 the calibration is changed to `z0_ref`.
2847 Solved characteristic impedance can be accessed with `cal.z0`.
2848
2849 Assumes TEM mode and conductance/length to be zero.
2850
2851 If `c0` == `z0_line` is None, the characteristic impedance is not renormalized.
2852 In this case reference impedance of the calibration is characteristic
2853 impedance of the transmission lines.
2854
2855 z0_ref : None, complex or list of complex
2856 New reference impedance for the characteristic impedance renormalizarion.
2857
2858 No effect if `c0` is None and `z0_line` is None.
2859
2860 If `z0_ref` is None, no renormalization is done.
2861
2862 z0_line : None, complex or list of complex
2863 Characteristic impedance of the transmission lines. Used for reference
2864 impedance renormalization.
2865
2866 If `z0` == `z0_line` is None, the characteristic impedance is not renormalized.
2867 In this case reference impedance of the calibration is characteristic
2868 impedance of the transmission lines.
2869
2870 \*args, \*\*kwargs : passed to EightTerm.__init__
2871 dont forget the `switch_terms` argument is important
2872
2873 See Also
2874 --------
2875 TUGMultilineTRL
2876
2877 """
2878 self.refl_offset = refl_offset
2879
2880 if np.isscalar(ref_plane):
2881 ref_plane = [ref_plane, ref_plane]
2882 self.ref_plane = ref_plane
2883 self.er_est = er_est
2884 self.l = [float(v) for v in l] # cast to float, see gh-895
2885 self.Grefls = Grefls
2886 self.gamma_root_choice = gamma_root_choice
2887 self.k_method = k_method
2888 self.z0_ref = z0_ref
2889 self.c0 = c0
2890 self.z0_line = z0_line
2891
2892 fpoints = len(measured[0].frequency)
2893 if np.isscalar(self.z0_ref):
2894 self.z0_ref = [self.z0_ref] * fpoints
2895 if np.isscalar(self.z0_line):
2896 self.z0_line = [self.z0_line] * fpoints
2897 if np.isscalar(self.c0):
2898 self.c0 = [self.c0] * fpoints
2899
2900 if np.isscalar(self.Grefls):
2901 # assume a single reflect
2902 self.Grefls = [self.Grefls]
2903
2904 n_reflects = len(self.Grefls)
2905
2906 if self.refl_offset is None:
2907 self.refl_offset = [0] * len(self.Grefls)
2908
2909 if np.isscalar(self.refl_offset):
2910 self.refl_offset = [self.refl_offset] * n_reflects
2911
2912 if len(measured) != len(self.Grefls) + len(l):
2913 raise ValueError(dedent(
2914 f"""Amount of measurements {len(measured)} doesn't match amount of line lengths {len(l)}
2915 and reflection coefficients {len(self.Grefls)}"""))
2916
2917 #Not used, but needed for Calibration class init
2918 ideals = measured
2919
2920 #EightTerm applies the switch correction
2921 EightTerm.__init__(self,
2922 measured = measured,
2923 ideals = ideals,
2924 self_calibration=True,
2925 **kwargs)
2926
2927 m_sw = [k for k in self.measured_unterminated]
2928
2929
2930 self.measured_reflects = m_sw[1:1+n_reflects]
2931 self.measured_lines = [m_sw[0]]
2932 self.measured_lines.extend(m_sw[1+n_reflects:])
2933
2934 self.ref_plane[0] -= l[0]/2
2935 self.ref_plane[1] -= l[0]/2
2936 self.refl_offset = [r - l[0]/2 for r in self.refl_offset]
2937
2938 # The first line is thru
2939 self.l = [i - self.l[0] for i in self.l]
2940
2941 if len(l) != len(self.measured_lines):
2942 raise ValueError("Different amount of lines and line lengths found")
2943
2944 def run(self):
2945 c = 299792458.0
2946 pi = np.pi
2947
2948 inv = linalg.inv
2949 exp = np.exp
2950 log = np.log
2951 abs = np.abs
2952
2953 gamma_est_user = self.kwargs.get('gamma_est', None)
2954
2955 measured_reflects = self.measured_reflects
2956 measured_lines = self.measured_lines
2957 measured_lines_t = list(map(lambda x: s2t(x.s), self.measured_lines))
2958 l = self.l
2959 er_est = self.er_est
2960
2961 freqs = measured_lines[0].f
2962 fpoints = len(freqs)
2963 lines = len(l)
2964 gamma = np.zeros(fpoints, dtype=complex)
2965 z0 = np.zeros(fpoints, dtype=complex)
2966
2967 gamma_est = (1j*2*pi*freqs[0]/c)*np.sqrt(er_est.real + 1j*er_est.imag/(freqs[0]*1e-9))
2968
2969 line_c = np.zeros(fpoints, dtype=int)
2970 er_eff = np.zeros(fpoints, dtype=complex)
2971
2972 Tmat1 = np.ones(shape=(fpoints, 2, 2), dtype=complex)
2973 Tmat2 = np.ones(shape=(fpoints, 2, 2), dtype=complex)
2974
2975 Smat1 = np.ones(shape=(fpoints, 2, 2), dtype=complex)
2976 Smat2 = np.ones(shape=(fpoints, 2, 2), dtype=complex)
2977
2978 e = np.zeros(shape=(fpoints, 7), dtype=complex)
2979 nstd = np.zeros(shape=(fpoints), dtype=float)
2980
2981 def t2s_single(t):
2982 return t2s(t[np.newaxis,:,:])[0]
2983
2984 def s2t_single(s):
2985 return s2t(s[np.newaxis,:,:])[0]
2986
2987 def root_choice(Mij, dl, gamma_est):
2988 e_val = linalg.eigvals(Mij)
2989 Da = [0,0]
2990 Db = [0,0]
2991 ga = [0,0]
2992 gb = [0,0]
2993 for i in [0,1]:
2994 if i == 0:
2995 eij1 = e_val[0]
2996 eij2 = e_val[1]
2997 else:
2998 eij1 = e_val[1]
2999 eij2 = e_val[0]
3000 ea = (eij1 + 1/eij2)/2
3001 periods = np.round(((gamma_est*dl).imag - (-log(ea)).imag)/(2*pi))
3002 ga[i] = (-log(ea) + 1j*2*pi*periods)/dl
3003 Da[i] = abs(ga[i]*dl - gamma_est*dl)/abs(gamma_est*dl)
3004
3005 eb = (eij2 + 1/eij1)/2
3006 periods = np.round(-((gamma_est*dl).imag + (-log(eb)).imag)/(2*pi))
3007 gb[i] = (-log(eb) + 1j*2*pi*periods)/dl
3008 Db[i] = abs(gb[i]*dl + gamma_est*dl)/abs(-gamma_est*dl)
3009 if Da[0] + Db[0] < 0.1*(Da[1] + Db[1]):
3010 return e_val
3011 if Da[1] + Db[1] < 0.1*(Da[0] + Db[0]):
3012 return e_val[::-1]
3013 if np.sign((ga[0]).real) != np.sign((gb[0]).real):
3014 if Da[0] + Db[0] < Da[1] + Db[1]:
3015 return e_val
3016 else:
3017 return e_val[::-1]
3018 else:
3019 if abs((ga[0]-gb[0]).real) < 0.1*abs((ga[1] + gb[1]).real) \
3020 and abs(ga[0].real/ga[0].imag) > 0.001 \
3021 and ga[0].real > 0:
3022 if Da[0] + Db[0] < 0.2:
3023 return e_val
3024 else:
3025 return e_val[::-1]
3026 else:
3027 if Da[0] + Db[0] < Da[1] + Db[1]:
3028 return e_val
3029 else:
3030 return e_val[::-1]
3031 #Unreachable
3032 return e_val
3033
3034 V_inv = np.eye(lines-1, dtype=complex) \
3035 - (1.0/lines)*np.ones(shape=(lines-1, lines-1), dtype=complex)
3036
3037 b1_vec = np.zeros(lines-1, dtype=complex)
3038 b2_vec = np.zeros(lines-1, dtype=complex)
3039 CoA1_vec = np.zeros(lines-1, dtype=complex)
3040 CoA2_vec = np.zeros(lines-1, dtype=complex)
3041
3042 b1_vec2 = np.zeros(lines-1, dtype=complex)
3043 b2_vec2 = np.zeros(lines-1, dtype=complex)
3044 CoA1_vec2 = np.zeros(lines-1, dtype=complex)
3045 CoA2_vec2 = np.zeros(lines-1, dtype=complex)
3046
3047 if self.z0_line is not None and self.c0 is not None:
3048 raise ValueError('Only one of c0 or z0_line can be given.')
3049
3050 for m in range(fpoints):
3051 min_phi_eff = pi*np.ones(lines)
3052 #Find the best common line to use
3053 for n in range(lines):
3054 for k in range(lines):
3055 if n == k:
3056 continue
3057 dl = l[k] - l[n]
3058 pd = abs(exp(-gamma_est*dl) - exp(gamma_est*dl))/2
3059 if -1 <= pd <= 1:
3060 phi_eff = np.arcsin( pd )
3061 else:
3062 phi_eff = np.pi/2
3063 min_phi_eff[n] = min(min_phi_eff[n], phi_eff)
3064 #Common line is selected to be one with the largest phase difference
3065 line_c[m] = np.argmax(min_phi_eff)
3066
3067 #Pre-calculate inverse T-matrix of the common line
3068 inv_line_c = inv(measured_lines_t[line_c[m]][m])
3069
3070 #Propagation constant extraction
3071 #Compute eigenvalues of each line pair
3072
3073 g_dl = np.zeros(lines-1, dtype=complex)
3074 dl_vec = np.zeros(lines-1, dtype=complex)
3075 k = 0
3076
3077 for n in range(lines):
3078 #Skip the common line
3079 if n == line_c[m]:
3080 continue
3081 dl = l[n] - l[line_c[m]]
3082 Mij = (measured_lines_t[n][m]).dot(inv_line_c)
3083
3084 if 'estimate' in self.gamma_root_choice:
3085 #Choose the correct root later
3086 e_val = linalg.eigvals(Mij)
3087 else:
3088 #Choose the correct root using heuristics
3089 e_val = root_choice(Mij, dl, gamma_est)
3090
3091 g_dl1 = -log(0.5*(e_val[0] + 1.0/e_val[1]))
3092 g_dl2 = -log(0.5*(e_val[1] + 1.0/e_val[0]))
3093
3094 g_dl[k] = g_dl1
3095
3096 if 'real' in self.gamma_root_choice and (g_dl1/dl).real < 0:
3097 #Choose root that has bigger real part (more lossier)
3098 g_dl[k] = g_dl2
3099
3100 if 'imag' in self.gamma_root_choice and (g_dl1/dl).imag < 0:
3101 #Choose root that has larger imaginary part
3102 #Only works for short lines
3103 g_dl[k] = g_dl2
3104
3105 if 'estimate' in self.gamma_root_choice:
3106 #Choose root that is closer to the estimate
3107 if gamma_est_user is not None:
3108 g_est = gamma_est_user[m]
3109 else:
3110 #Use estimate from earlier iterations
3111 g_est = gamma_est
3112 periods1 = np.round( ((gamma_est*dl).imag - g_dl1.imag)/(2*pi))
3113 periods2 = np.round( ((gamma_est*dl).imag - g_dl2.imag)/(2*pi))
3114 g_dl1 += 1j*2*pi*periods1
3115 g_dl2 += 1j*2*pi*periods2
3116
3117 if abs(g_dl1 - g_est*dl) < abs(g_dl2 - g_est*dl):
3118 g_dl[k] = g_dl1
3119 else:
3120 g_dl[k] = g_dl2
3121 else:
3122 periods = np.round(((gamma_est*dl).imag - (g_dl[k].imag))/(2*pi))
3123 g_dl[k] += 1j*2*pi*periods
3124 dl_vec[k] = dl
3125 k = k + 1
3126
3127 gamma[m] = (dl_vec.transpose().dot(V_inv).dot(g_dl))/(dl_vec.transpose().dot(V_inv).dot(dl_vec))
3128
3129 if m != fpoints-1:
3130 gamma_est = gamma[m].real + 1j*gamma[m].imag*freqs[m+1]/freqs[m]
3131 er_eff[m] = -(gamma[m]/(2*pi*freqs[m]/c))**2
3132
3133 root1 = []
3134 root2 = []
3135
3136 d1 = [0,0]
3137 d2 = [0,0]
3138
3139 S_thru = measured_lines[0].s[m]
3140
3141 p = 0
3142
3143 for n in range(lines):
3144 if n == line_c[m]:
3145 continue
3146 #Port 1
3147 T = measured_lines_t[n][m].dot(inv_line_c)
3148 T = measured_lines[n].s[m,1,0]*measured_lines[line_c[m]].s[m,0,1]*T
3149 e_val = linalg.eigvals(T)
3150
3151 B1 = np.array([\
3152 [T[0,1]/(e_val[0]-T[0,0]), T[0,1]/(e_val[1]-T[0,0])],
3153 [(e_val[0]-T[1,1])/T[1,0], (e_val[1]-T[1,1])/T[1,0]]])
3154 CoA1 = np.array([\
3155 [T[1,0]/(e_val[1]-T[1,1]), T[1,0]/(e_val[0]-T[1,1])],
3156 [(e_val[1]-T[0,0])/T[0,1], (e_val[0]-T[0,0])/T[0,1]]])
3157 B_est1 = T[0,1]/(exp(gamma[m]*(l[n]-l[line_c[m]]) - T[0,0]))
3158 CoA_est1 = T[1,0]/(exp(-gamma[m]*(l[n]-l[line_c[m]]) - T[1,1]))
3159 dB1 = abs(B1 - B_est1)/abs(B_est1)
3160 dCoA1 = abs(CoA1 - CoA_est1)/abs(CoA_est1)
3161
3162 if abs(B1[0,1] - B_est1) < abs(B1[1,1] - B_est1):
3163 b1_vec[p] = B1[0,1]
3164 b1_vec2[p] = B1[0,0]
3165 root1.append([0,1])
3166 else:
3167 b1_vec[p] = B1[1,1]
3168 b1_vec2[p] = B1[1,0]
3169 root1.append([1,1])
3170
3171 if abs(CoA1[0,1] - CoA_est1) < abs(CoA1[1,1] - CoA_est1):
3172 CoA1_vec[p] = CoA1[0,1]
3173 CoA1_vec2[p] = CoA1[0,0]
3174 else:
3175 CoA1_vec[p] = CoA1[1,1]
3176 CoA1_vec2[p] = CoA1[1,0]
3177
3178 d1[0] += np.sum(dB1[:,root1[-1][1]]) + np.sum(dCoA1[:,root1[-1][1]])
3179 d1[1] += np.sum(dB1[:,int(not root1[-1][1])]) + np.sum(dCoA1[:,int(not root1[-1][1])])
3180
3181 #Port 2
3182 k = np.array([[0,1],[1,0]], dtype=complex)
3183
3184 T = s2t_single(k.dot(measured_lines[n].s[m]).dot(k)).dot(\
3185 inv(s2t_single(k.dot(measured_lines[line_c[m]].s[m]).dot(k))))
3186 T = measured_lines[n].s[m][0,1]*measured_lines[line_c[m]].s[m][1,0]*T
3187 e_val = linalg.eigvals(T)
3188
3189 B2 = np.array([\
3190 [T[0,1]/(e_val[0]-T[0,0]), T[0,1]/(e_val[1]-T[0,0])],
3191 [(e_val[0]-T[1,1])/T[1,0], (e_val[1]-T[1,1])/T[1,0]]])
3192 CoA2 = np.array([\
3193 [T[1,0]/(e_val[1]-T[1,1]), T[1,0]/(e_val[0]-T[1,1])],
3194 [(e_val[1]-T[0,0])/T[0,1], (e_val[0]-T[0,0])/T[0,1]]])
3195 B_est2 = T[0,1]/(exp(gamma[m]*(l[n]-l[line_c[m]]) - T[0,0]))
3196 CoA_est2 = T[1,0]/(exp(-gamma[m]*(l[n]-l[line_c[m]]) - T[1,1]))
3197 dB2 = abs(B2 - B_est2)/abs(B_est2)
3198 dCoA2 = abs(CoA2 - CoA_est2)/abs(CoA_est2)
3199
3200 if abs(B2[0,1] - B_est2) < abs(B2[1,1] - B_est2):
3201 b2_vec[p] = B2[0,1]
3202 b2_vec2[p] = B2[0,0]
3203 root2.append([0,1])
3204 else:
3205 b2_vec[p] = B2[1,1]
3206 b2_vec2[p] = B2[1,0]
3207 root2.append([1,1])
3208
3209 if abs(CoA2[0,1] - CoA_est2) < abs(CoA2[1,1] - CoA_est2):
3210 CoA2_vec[p] = CoA2[0,1]
3211 CoA2_vec2[p] = CoA2[0,0]
3212 else:
3213 CoA2_vec[p] = CoA2[1,1]
3214 CoA2_vec2[p] = CoA2[1,0]
3215
3216 d2[0] += np.sum(dB2[:,root2[-1][1]]) + np.sum(dCoA2[:,root2[-1][1]])
3217 d2[1] += np.sum(dB2[:,int(not root2[-1][1])]) + np.sum(dCoA2[:,int(not root2[-1][1])])
3218
3219 p += 1
3220
3221 Vb = np.zeros(shape=(lines-1,lines-1), dtype=complex)
3222 Vc = np.zeros(shape=(lines-1,lines-1), dtype=complex)
3223 #Fill in upper triangular matrix
3224 l_not_common = [i for i in l if i != l[line_c[m]]]
3225 for b in range(len(l_not_common)):
3226 for a in range(b+1):
3227 if a == b: #Diagonal
3228 len_l = l_not_common[a]
3229 exp_factor = exp(-gamma[m]*(len_l - l[line_c[m]]))
3230 Vb[a,b] = abs(exp_factor)**2 + 1/abs(exp_factor)**2 + \
3231 2*( abs(exp(-gamma[m]*len_l))*\
3232 abs(exp(-gamma[m]*l[line_c[m]])) )**2
3233 n = abs(exp_factor - 1/exp_factor)**2
3234 Vb[a,b] /= n
3235
3236 Vc[a,b] = abs(exp_factor)**2 + 1/(abs(exp_factor))**2 + \
3237 2/( abs(exp(-gamma[m]*l[line_c[m]]))*\
3238 abs(exp(-gamma[m]*len_l)) )**2
3239 Vc[a,b] /= n
3240 elif a < b:
3241 len_a = l_not_common[a]
3242 len_b = l_not_common[b]
3243 exp_factor = exp(-gamma[m]*(len_a -l[line_c[m]]))
3244 exp_factor2 = exp(-gamma[m]*(len_b -l[line_c[m]]))
3245 Vb[a,b] = exp_factor*exp_factor2.conjugate() + \
3246 (abs(exp(-gamma[m]*l[line_c[m]])))**2 * \
3247 exp(-gamma[m]*len_a)*(exp(-gamma[m]*len_b)).conjugate()
3248 n = (exp_factor - 1/exp_factor)* \
3249 (exp_factor2-1/exp_factor2).conjugate()
3250 Vb[a,b] /= n
3251 Vb[b,a] = Vb[a,b].conjugate()
3252
3253 Vc[a,b] = 1/(exp_factor*exp_factor2.conjugate()) + \
3254 1/( (abs(exp(-gamma[m]*l[line_c[m]])))**2 * \
3255 exp(-gamma[m]*len_a)*(exp(-gamma[m]*len_b)).conjugate() )
3256 Vc[a,b] /= n
3257 Vc[b,a] = Vc[a,b].conjugate()
3258
3259 def solve_A(B1, B2, CoA1, CoA2, S_thru, m):
3260 #Determine A using unknown reflect
3261 Ap = B1*B2 - B1*S_thru[1,1] - B2*S_thru[0,0] + linalg.det(S_thru)
3262 Ap = -Ap/(1 - CoA1*S_thru[0,0] - CoA2*S_thru[1,1] + CoA1*CoA2*linalg.det(S_thru))
3263
3264 A1_vals = np.zeros(len(measured_reflects), dtype=complex)
3265 A2_vals = np.zeros(len(measured_reflects), dtype=complex)
3266
3267 for n in range(len(measured_reflects)):
3268 S_r = measured_reflects[n].s[m]
3269
3270 S_r11 = S_r[0,0]
3271 S_r22 = S_r[1,1]
3272
3273 Arr = (S_r11 - B1)/(1 - S_r11*CoA1)* \
3274 (1 - S_r22*CoA2)/(S_r22 - B2)
3275 Gr_est = self.Grefls[n]*exp(-2*gamma[m]*(self.refl_offset[n] - l[0]/2.))
3276 G_trial = (S_r11 - B1)/(np.sqrt(Ap*Arr)*(1 - S_r11*CoA1))
3277 if abs( Gr_est/abs(Gr_est) - G_trial/abs(G_trial) ) > np.sqrt(2):
3278 A1_vals[n] = -np.sqrt(Ap*Arr)
3279 else:
3280 A1_vals[n] = np.sqrt(Ap*Arr)
3281 A2_vals[n] = A1_vals[n]/Arr
3282
3283 A1 = np.mean(A1_vals)
3284 A2 = np.mean(A2_vals)
3285 return A1, A2
3286
3287 inv_Vb = inv(Vb)
3288 inv_Vc = inv(Vc)
3289 sum_inv_Vb = np.sum(inv_Vb)
3290 sum_inv_Vc = np.sum(inv_Vc)
3291 values = []
3292 #List possible root choices for B and CoA
3293 for i in [(0,0), (0,1), (1,0), (1,1)]:
3294 if i[0] == 0:
3295 b1 = b1_vec
3296 coa1 = CoA1_vec
3297 else:
3298 b1 = b1_vec2
3299 coa1 = CoA1_vec2
3300
3301 if i[1] == 0:
3302 b2 = b2_vec
3303 coa2 = CoA2_vec
3304 else:
3305 b2 = b2_vec2
3306 coa2 = CoA2_vec2
3307
3308 B1 = np.sum(inv_Vb.dot(b1))/sum_inv_Vb
3309 B2 = np.sum(inv_Vb.dot(b2))/sum_inv_Vb
3310 CoA1 = np.sum(inv_Vc.dot(coa1))/sum_inv_Vc
3311 CoA2 = np.sum(inv_Vc.dot(coa2))/sum_inv_Vc
3312
3313 denom = 1 - CoA1*S_thru[0,0] - CoA2*S_thru[1,1] + CoA1*CoA2*\
3314 (S_thru[0,0]*S_thru[1,1] - S_thru[0,1]*S_thru[1,0])
3315
3316 values.append( (abs(denom), B1, B2, CoA1, CoA2) )
3317
3318 if abs(values[0][0]) > 1e-9 and d1[1]/d1[0] > 10 and d2[1]/d2[0] > 10:
3319 #Estimate seems to be correct
3320 B1, B2, CoA1, CoA2 = values[0][1:]
3321 A1, A2 = solve_A(B1, B2, CoA1, CoA2, S_thru, m)
3322 else:
3323 #Estimation is incorrect or the accuracy is bad
3324 #Choose the root that minimizes error to measurements
3325 best_error = None
3326 best_values = []
3327 for v in values:
3328 if abs(v[0]) < 1e-9:
3329 continue
3330 B1, B2, CoA1, CoA2 = v[1:]
3331 A1, A2 = solve_A(B1, B2, CoA1, CoA2, S_thru, m)
3332 C1 = CoA1*A1
3333 C2 = CoA2*A2
3334 R = S_thru[0,1]*(1 - C1*C2)/(A1 - B1*C1)
3335
3336 T1 = R*np.array([[A1, B1],[C1, 1]])
3337 g = np.array([[0,1],[1,0]])
3338 T2 = np.array([[A2, B2],[C2, 1]])
3339
3340 error = 0
3341 for n in range(lines):
3342 meas = measured_lines[n].s[m]
3343 ideal = np.array([[exp(-gamma[m]*l[n]), 0],[0,exp(gamma[m]*l[n])]])
3344 embedded = t2s_single(T1.dot(ideal).dot(g.dot(inv(T2).dot(g))))
3345
3346 error += np.sum(abs(embedded - meas))
3347 if best_error is None or error < best_error:
3348 best_error = error
3349 best_values = v
3350 if best_error is None:
3351 # All roots are numerically badly behaved, just choose the
3352 # original estimate
3353 B1, B2, CoA1, CoA2 = values[0][1:]
3354 else:
3355 B1, B2, CoA1, CoA2 = best_values[1:]
3356 A1, A2 = solve_A(B1, B2, CoA1, CoA2, S_thru, m)
3357
3358 sigmab = np.sqrt(1/(np.sum(inv_Vb).real))
3359 sigmac = np.sqrt(1/(np.sum(inv_Vc).real))
3360
3361 nstd[m] = (sigmab + sigmac)/2
3362
3363 C1 = CoA1*A1
3364 C2 = CoA2*A2
3365
3366 #Determine R1, R2
3367 if self.k_method == 'marks':
3368 p1_len_est = self.kwargs.get('p1_len_est', 0)
3369 p2_len_est = self.kwargs.get('p2_len_est', 0)
3370
3371 z0_phase = np.angle( np.sqrt(er_eff[m]) )
3372 Qox = ( 1 - 1j*z0_phase)
3373 Qoy = ( 1 - 1j*z0_phase)
3374
3375 R1R2 = (S_thru[1,0]*(1 - C1*C2))**-1
3376 gam = A2 - B2*C2
3377 de = (A1-B1*C1)*(R1R2*(A2-B2*C2))**2
3378 beta_sqr = (abs(de)**2 + abs(gam)**2)/\
3379 (de.conjugate()*Qox + de.conjugate()*Qoy)
3380 s21y = np.sqrt( beta_sqr )
3381 R2 = ((A2 -B2*C2)/s21y)**-1
3382
3383 R2_est = exp(gamma[m]*p2_len_est)
3384 if abs( R2_est/abs(R2_est) -R2/abs(R2) ) > np.sqrt(2):
3385 R2 = -R2
3386 R1 = R1R2/R2
3387 R1_est = exp(gamma[m]*p1_len_est)
3388
3389 if abs( R1_est/abs(R1_est) - R1/abs(R1) ) > np.sqrt(2):
3390 warn('Inconsistencies detected', stacklevel=2)
3391 elif self.k_method == 'multical':
3392 denom = 1 - CoA1*S_thru[0,0] - CoA2*S_thru[1,1] + CoA1*CoA2*\
3393 (S_thru[0,0]*S_thru[1,1] - S_thru[0,1]*S_thru[1,0])
3394 R1 = S_thru[0,1]/denom
3395 R2 = S_thru[1,0]/denom
3396 else:
3397 raise ValueError(f'Unknown k_method: {self.k_method}')
3398
3399 #Reference plane shift
3400 if np.any(self.ref_plane):
3401 shift1 = exp(-2*gamma[m]*self.ref_plane[0])
3402 shift2 = exp(-2*gamma[m]*self.ref_plane[1])
3403 A1 *= shift1
3404 A2 *= shift2
3405 C1 *= shift1
3406 C2 *= shift2
3407 R1 *= shift1
3408 R2 *= shift2
3409
3410 if self.c0 is not None:
3411 #Estimate the line characteristic impedance
3412 #using known capacitance/length
3413 z0[m] = gamma[m]/(1j*2*np.pi*freqs[m]*self.c0[m])
3414 else:
3415 #Set the known line characteristic impedance
3416 if self.z0_line is not None:
3417 z0[m] = self.z0_line[m]
3418 else:
3419 z0[m] = self.z0_ref[m]
3420
3421 #Error matrices
3422 Tmat1[m,:,:] = R1*np.array([[A1, B1],[C1, 1]])
3423 Tmat2[m,:,:] = R2*np.array([[A2, B2],[C2, 1]])
3424
3425 Smat1[m,:,:] = t2s_single(Tmat1[m,:,:])
3426 Smat2[m,:,:] = t2s_single(Tmat2[m,:,:])
3427
3428 #Convert the error coefficients to
3429 #definitions used by the EightTerm class.
3430 dx = linalg.det(Smat1[m,:,:])
3431 dy = linalg.det(Smat2[m,:,:])
3432
3433 if self.k_method == 'marks':
3434 k = Smat1[m,1,0]/Smat2[m,0,1]
3435 else:
3436 k = dx*dy*Smat1[m,1,0]/(Smat2[m,0,1]*Smat2[m,1,0])
3437
3438 #Error coefficients
3439 e[m] = [Smat1[m,0,0],
3440 Smat1[m,1,1],
3441 dx,
3442 Smat2[m,0,0],
3443 Smat2[m,1,1],
3444 dy,
3445 k]
3446
3447 self._z0 = z0
3448 self._gamma = gamma
3449 self._er_eff = er_eff
3450 self._nstd = nstd
3451 self._coefs = {\
3452 'forward directivity':e[:,0],
3453 'forward source match':e[:,1],
3454 'forward reflection tracking':e[:,0]*e[:,1]-e[:,2],
3455 'reverse directivity':e[:,3],
3456 'reverse source match':e[:,4],
3457 'reverse reflection tracking':e[:,4]*e[:,3]- e[:,5],
3458 'k':e[:,6],
3459 }
3460
3461 self._coefs['forward isolation'] = self.isolation.s[:,1,0].flatten()
3462 self._coefs['reverse isolation'] = self.isolation.s[:,0,1].flatten()
3463
3464 if self.switch_terms is not None:
3465 self._coefs.update({
3466 'forward switch term': self.switch_terms[0].s.flatten(),
3467 'reverse switch term': self.switch_terms[1].s.flatten(),
3468 })
3469 else:
3470 self._coefs.update({
3471 'forward switch term': np.zeros(fpoints, dtype=complex),
3472 'reverse switch term': np.zeros(fpoints, dtype=complex),
3473 })
3474 # output is a dictionary of information
3475 self._output_from_run = {
3476 'error vector':e
3477 }
3478
3479 #Reference impedance renormalization
3480 if self.z0_ref is not None and np.any(z0 != self.z0_ref):
3481 powerwave = self.kwargs.get('powerwave', False)
3482 self.renormalize(z0, self.z0_ref, powerwave=powerwave)
3483
3484 @classmethod
3485 def from_coefs(cls, frequency, coefs, **kwargs):
3486 """
3487 Create a calibration from its error coefficients.
3488
3489 Parameters
3490 ----------
3491 frequency : :class:`~skrf.frequency.Frequency`
3492 frequency info, (duh)
3493 coefs : dict of numpy arrays
3494 error coefficients for the calibration
3495
3496 See Also
3497 --------
3498 Calibration.from_coefs_ntwks
3499
3500 """
3501 # assigning this measured network is a hack so that
3502 # * `calibration.frequency` property evaluates correctly
3503 # * __init__() will not throw an error
3504 n = Network(frequency = frequency,
3505 s = rand_c(frequency.npoints,2,2))
3506 measured = [n,n,n]
3507
3508 if 'forward switch term' in coefs:
3509 switch_terms = (Network(frequency = frequency,
3510 s=coefs['forward switch term']),
3511 Network(frequency = frequency,
3512 s=coefs['reverse switch term']))
3513 kwargs['switch_terms'] = switch_terms
3514
3515
3516 #Fill the required __init__ fields with garbage
3517 #and assign the coefficients manually
3518 cal = cls(measured, [-1], [0,1], **kwargs)
3519 cal.coefs = coefs
3520 cal.family += '(fromCoefs)'
3521 return cal
3522
3523 @property
3524 def gamma(self):
3525 """
3526 Propagation constant of the solved line.
3527
3528 """
3529 try:
3530 return self._gamma
3531 except(AttributeError):
3532 self.run()
3533 return self._gamma
3534
3535 @property
3536 def er_eff(self):
3537 r"""
3538 Effective permittivity of the solved line.
3539
3540 Defined in terms of the propagation constant:
3541
3542 .. math::
3543 \gamma = \alpha + j \beta = \frac{2\pi f}{c} \sqrt{\epsilon_{r,eff}}
3544 """
3545 try:
3546 return self._er_eff
3547 except(AttributeError):
3548 self.run()
3549 return self._er_eff
3550
3551 @property
3552 def z0(self):
3553 """
3554 Solved characteristic impedance of the transmission lines.
3555
3556 This is only solved if C0 parameter (Capacitance/length in units F/m) is given.
3557
3558 Solved Z0 assumes that conductance/length is zero and line supports TEM mode.
3559 """
3560 try:
3561 return self._z0
3562 except(AttributeError):
3563 self.run()
3564 return self._z0
3565
3566 @property
3567 def nstd(self):
3568 """
3569 Normalized standard deviation of the calibration error.
3570
3571 Normalization is done such that 90 degree long single line gives
3572 a standard deviation of 1.
3573 """
3574 try:
3575 return self._nstd
3576 except(AttributeError):
3577 self.run()
3578 return self._nstd
3579
3580 def save_calibration(self, filename):
3581 """
3582 save calibration as an archive containing the standards, parameters and calibration results
3583
3584 Parameters
3585 ----------
3586 filename : str
3587 the path of the zip archive to save
3588
3589 """
3590 parameters = OrderedDict()
3591 parameters["file type"] = "skrf calibration"
3592 parameters["calibration class"] = self.__class__.__name__
3593 parameters["skrf version"] = skrf__version__
3594
3595 parameters["measured"] = ntwk_names = [ntwk.name for ntwk in self.measured]
3596 for i, name in enumerate(ntwk_names):
3597 ntwk_names[i] = util.unique_name(name, ntwk_names, i)
3598 parameters["ideals"] = None
3599
3600 if self.switch_terms:
3601 fswitch, rswitch = self.switch_terms # type: Network
3602 fswitch.name = "forward switch terms"
3603 rswitch.name = "reverse switch terms"
3604 parameters["switch terms"] = fswitch.name, rswitch.name
3605 else:
3606 parameters["switch terms"] = None
3607
3608 parameters["kwargs"] = {
3609 "Grefls": self.Grefls,
3610 "l": self.l,
3611 "er_est": self.er_est,
3612 "refl_offset": self.refl_offset,
3613 "ref_plane": self.ref_plane,
3614 "gamma_root_choice": self.gamma_root_choice,
3615 "k_method": self.k_method
3616 }
3617
3618 with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
3619 archive.writestr("parameters.json", json.dumps(parameters, indent=2))
3620 if self.switch_terms:
3621 fswitch.write_touchstone(dir="switch terms", to_archive=archive)
3622 rswitch.write_touchstone(dir="switch terms", to_archive=archive)
3623 for i, ntwk in enumerate(self.measured): # type: int, Network
3624 ntwk.write_touchstone(ntwk_names[i] + ".s2p", dir="measured", to_archive=archive)
3625 for ntwk in self.coefs_ntwks.values():
3626 ntwk.write_touchstone(dir="coefs", to_archive=archive)
3627 gamma_ntwk = Network(f=self.measured[0].f, s=self.gamma, z0=50., comments="propagation constant")
3628 gamma_ntwk.write_touchstone("gamma.s1p", to_archive=archive)
3629
3630 @classmethod
3631 def load_calibration_archive(cls, filename):
3632 with zipfile.ZipFile(filename) as archive:
3633 parameters = json.loads(archive.open("parameters.json").read().decode("ascii"))
3634 measured_dict = read_zipped_touchstones(archive, "measured")
3635 switch_terms_dict = read_zipped_touchstones(archive, "switch terms")
3636 coefs_dict = read_zipped_touchstones(archive, "coefs") # not used currently
3637 gamma_ntwk = Network.zipped_touchstone("gamma.s1p", archive)
3638
3639 measured = list()
3640 for name in parameters["measured"]:
3641 measured.append(measured_dict[name])
3642
3643 if parameters["switch terms"] is None:
3644 switch_terms = None
3645 else:
3646 switch_terms = [
3647 switch_terms_dict[parameters["switch terms"][0]],
3648 switch_terms_dict[parameters["switch terms"][1]]
3649 ]
3650
3651 kwargs = parameters["kwargs"]
3652
3653 cal = cls(measured, switch_terms=switch_terms, **kwargs)
3654 cal.coefs = NetworkSet(coefs_dict).to_s_dict()
3655 cal._gamma = gamma_ntwk.s.flatten()
3656
3657 return cal
3658
3659 class TUGMultilineTRL(EightTerm):
3660 """
3661 TUG Multiline TRL calibration.
3662
3663 An improved multiline TRL calibration procedure that generalizes the calibration process
3664 by solving a single 4x4 weighted eigenvalue problem.
3665
3666 The overall algorithm is based on [1]_, but the weighting matrix calculation is based on [2]_.
3667 You can read the mathematical details online at [3]_.
3668
3669 The calibration reference plane is at the edges of the first line.
3670 By default, the reference impedance of the calibration is the characteristic impedance
3671 of the transmission lines. If the characteristic impedance is known,
3672 the reference impedance can be renormalized afterwards by running the method `renormalize()`.
3673
3674 Examples
3675 --------
3676
3677 >>> line1 = rf.Network('line1.s2p')
3678 >>> line2 = rf.Network('line2.s2p')
3679 >>> line3 = rf.Network('line3.s2p')
3680 >>> short = rf.Network('short.s2p')
3681 >>> dut = rf.Network('dut.s2p')
3682
3683 Normal multiline TRL calibration:
3684
3685 >>> cal = rf.TUGMultilineTRL(line_meas=[line1,line2,line3], line_lengths=[0, 1e-3, 5e-3], er_est=4-.0j,
3686 >>> reflect_meas=short, reflect_est=-1, reflect_offset=0)
3687 >>> dut_cal = cal.apply_cal(dut)
3688
3689 Case of not using reflect measurements:
3690
3691 >>> cal = rf.TUGMultilineTRL(line_meas=[line1,line2,line3], line_lengths=[0, 1e-3, 5e-3], er_est=4-.0j)
3692 >>> dut_cal = cal.apply_cal(dut) # only S21 and S12 are correct
3693
3694 References
3695 ----------
3696 .. [1] Z. Hatab, M. Gadringer and W. Bösch, "Improving The Reliability of The Multiline TRL Calibration Algorithm,"
3697 2022 98th ARFTG Microwave Measurement Conference (ARFTG), Las Vegas, NV, USA, 2022, pp. 1-5,
3698 doi: https://doi.org/10.1109/ARFTG52954.2022.9844064
3699
3700 .. [2] Z. Hatab, M. Gadringer and W. Bösch, "Propagation of Linear Uncertainties Through Multiline
3701 Thru-Reflect-Line Calibration," in IEEE Transactions on Instrumentation and Measurement,
3702 vol. 72, pp. 1-9, 2023, doi: https://doi.org/10.1109/TIM.2023.3296123
3703
3704 .. [3] https://ziadhatab.github.io/posts/multiline-trl-calibration/
3705
3706 See Also
3707 --------
3708 NISTMultilineTRL
3709 """
3710
3711 family = 'TRL'
3712 def __init__(self, line_meas, line_lengths, er_est=1-.0j,
3713 reflect_meas=None, reflect_est=None, reflect_offset=0, ref_plane=0,
3714 *args, **kwargs):
3715 r"""
3716 TUGMultilineTRL initializer.
3717
3718 The order of the lines in `line_meas` and `line_lengths` should be the same.
3719 Also, the first line is defined as thru. If non-zero, the calibration plane is
3720 shifted by half of its length using the extracted propagation constant.
3721
3722 You can perform calibration without reflect measurements, but this will only provide you with the
3723 propagation constant and relative effective permittivity. Without reflect measurements, you can
3724 accurately calibrate S21 and S12 of a DUT. However, calibrating S11 and S22 requires a symmetric
3725 reflect as part of the calibration process.
3726
3727 Notes
3728 -------
3729 This implementation inherits from :class:`EightTerm`. Don't
3730 forget to pass switch_terms.
3731
3732 Parameters
3733 --------------
3734 line_meas : list of two-port :class:`~skrf.network.Network`
3735 measurement of the lines. First line is defined as thru.
3736
3737 line_lengths : list of float
3738 Lengths of the lines. If thru is non-zero length, the calibration plane is
3739 shifted by half of its length using the solved propagation constant.
3740 Units are in meters.
3741
3742 er_est : complex
3743 Estimated permittivity of the lines at first frequency point of the measurement.
3744 Negative imaginary part indicates losses.
3745
3746 reflect_meas : a two-port :class:`~skrf.network.Network` or a list of two-port :class:`~skrf.network.Network`
3747 measurement of symmetric reflect.
3748 Multiple symmetric reflect can be passed in a list, which is used to compute to average solution of the
3749 error terms.
3750
3751 reflect_est : complex or list of complex
3752 Estimated reflection coefficients of reflect standards at first frequency point of the measurement.
3753 Usually -1 for short or +1 for open.
3754
3755 reflect_offset : float or list of float
3756 Offset of the reflect standards from the reference plane.
3757 Units are in meters.
3758
3759 ref_plane : float or list of float
3760 Reference plane shift after the calibration.
3761 Negative length is towards the VNA. Units are in meters.
3762
3763 Different shifts can be given to different ports by giving a two element list.
3764 First element is shift of port 1 and second is shift of port 2.
3765
3766 \*args, \*\*kwargs : passed to EightTerm.__init__
3767 dont forget the `switch_terms` argument is important
3768
3769 """
3770
3771 self.line_meas = line_meas
3772 self.line_lengths = line_lengths
3773 self.er_est = er_est*(1+0j) # make complex
3774 if len(self.line_lengths) != len(self.line_meas):
3775 raise ValueError("Different amount of measured lines and line lengths found.")
3776
3777 if len(self.line_lengths) < 2:
3778 raise ValueError("Less than two lines have been found.")
3779
3780 self.freq = self.line_meas[0].frequency
3781 s_nan = np.array([ np.eye(2)*np.nan for f in self.freq.f])
3782
3783 self.reflect_meas = (
3784 [Network(s=s_nan, frequency=self.freq)]
3785 if reflect_meas is None
3786 else (reflect_meas if isinstance(reflect_meas, list) else [reflect_meas])
3787 )
3788 self.reflect_est = np.atleast_1d(reflect_est)
3789 self.reflect_offset = np.atleast_1d(reflect_offset)*np.ones(len(self.reflect_est))
3790
3791 if len(self.reflect_meas) != len(self.reflect_est):
3792 raise ValueError("Different amount of measured reflects and estimated reflects found.")
3793
3794 # EightTerm applies the switch correction
3795 measured = self.line_meas if reflect_meas is None else self.line_meas + self.reflect_meas
3796 EightTerm.__init__(self,
3797 measured = measured,
3798 ideals = measured, # not actually used. Just to initiate the class
3799 self_calibration=True,
3800 **kwargs)
3801
3802 n_lines = len(self.line_lengths)
3803 # switch term corrected
3804 self.line_meas = self.measured_unterminated[:n_lines]
3805 self.reflect_meas = self.reflect_meas if reflect_meas is None else self.measured_unterminated[n_lines:]
3806
3807 self.ref_plane = np.atleast_1d(ref_plane)*np.ones(2)
3808
3809 def run(self):
3810 # Constants
3811 c0 = 299792458 # speed of light in vacuum (m/s)
3812 Q = np.array([[0,0,0,1], [0,-1,0,0], [0,0,-1,0], [1,0,0,0]])
3813 P = np.array([[1,0,0,0], [0, 0,1,0], [0,1, 0,0], [0,0,0,1]])
3814
3815 # Functions used throughout the calibration
3816 def gamma2ereff(x, f):
3817 return -(c0 / 2 / np.pi / f * x) ** 2
3818 def ereff2gamma(x, f):
3819 return 2 * np.pi * f / c0 * np.sqrt(-x)
3820
3821 def s2t_single(S, pseudo=False):
3822 T = S.copy()
3823 T[0,0] = -(S[0,0]*S[1,1]-S[0,1]*S[1,0])
3824 T[0,1] = S[0,0]
3825 T[1,0] = -S[1,1]
3826 T[1,1] = 1
3827 return T if pseudo else T/S[1,0]
3828
3829 def t2s_single(T, pseudo=False):
3830 S = T.copy()
3831 S[0,0] = T[0,1]
3832 S[0,1] = T[0,0]*T[1,1]-T[0,1]*T[1,0]
3833 S[1,0] = 1
3834 S[1,1] = -T[1,0]
3835 return S if pseudo else S/T[1,1]
3836
3837 def compute_G_with_takagi(A):
3838 '''
3839 Implementation of Takagi decomposition to compute the matrix G used to determine the weighting matrix.
3840 Takagi decomposition is based on the paper below:
3841 Alexander M. Chebotarev, Alexander E. Teretenkov,
3842 "Singular value decomposition for the Takagi factorization of symmetric matrices,"
3843 Applied Mathematics and Computation, Volume 234, 2014, Pages 380-384, https://doi.org/10.1016/j.amc.2014.01.170.
3844 '''
3845 u,s,vh = np.linalg.svd(A)
3846 u,s,vh = u[:,:2],s[:2],vh[:2,:] # low-rank truncated (Eckart-Young theorem)
3847 phi = np.sqrt( s*np.diag(vh@u.conj()) )
3848 G = u@np.diag(phi)
3849 # this is the eigenvalue of the weighted eigenvalue problem (1/2 squared Frobenius norm of W)
3850 lambd = s[0]*s[1]
3851 return G, lambd
3852
3853 def WLS(x,y,w=1):
3854 # Weighted least-squares for a single parameter estimation
3855 x = x*(1+0j) # force x to be complex type
3856 return (x.conj().dot(w).dot(y))/(x.conj().dot(w).dot(x))
3857
3858 def Vgl(N):
3859 # inverse covariance matrix for propagation constant computation
3860 return np.eye(N-1, dtype=complex) - (1/N)*np.ones(shape=(N-1, N-1), dtype=complex)
3861
3862 def compute_gamma(X_inv, M, lengths, gamma_est, inx=0):
3863 # gamma = alpha + 1j*beta is determined through linear weighted least-squares
3864 # with inx you can choose the reference line. doesn't make any difference.
3865 lengths = lengths - lengths[inx]
3866 EX = (X_inv@M)[[0,-1],:] # extract z and y columns
3867 EX = np.diag(1/EX[:,inx])@EX # normalize to a reference line based on index `inx` (can be any)
3868 del_inx = np.arange(len(lengths)) != inx # get rid of the reference line
3869
3870 # solve for alpha
3871 l = -2*lengths[del_inx]
3872 gamma_l = np.log(EX[0,:]/EX[-1,:])[del_inx]
3873 alpha = WLS(l, gamma_l.real, Vgl(len(l)+1))
3874
3875 # solve for beta
3876 l = -lengths[del_inx]
3877 gamma_l = np.log((EX[0,:] + 1/EX[-1,:])/2)[del_inx]
3878 n = np.round( (gamma_l - gamma_est*l).imag/np.pi/2 )
3879 gamma_l = gamma_l - 1j*2*np.pi*n # unwrap
3880 beta = WLS(l, gamma_l.imag, Vgl(len(l)+1))
3881 return alpha + 1j*beta
3882
3883 def solve_quadratic(v1, v2, inx, x_est):
3884 # This is related to solving the normalized error terms using nullspace approach.
3885 # The variable `inx` allowes to reuse the function to shuffel the coefficient to get other error terms.
3886 v12,v13 = v1[inx]
3887 v22,v23 = v2[inx]
3888 mask = np.ones(v1.shape, bool)
3889 mask[inx] = False
3890 v11,v14 = v1[mask]
3891 v21,v24 = v2[mask]
3892 if abs(v12) > abs(v22): # to avoid dividing by small numbers
3893 k2 = -v11*v22*v24/v12 + v11*v14*v22**2/v12**2 + v21*v24 - v14*v21*v22/v12
3894 k1 = v11*v24/v12 - 2*v11*v14*v22/v12**2 - v23 + v13*v22/v12 + v14*v21/v12
3895 k0 = v11*v14/v12**2 - v13/v12
3896 c2 = np.roots([k2,k1,k0])*np.ones(2)
3897 c1 = (1 - c2*v22)/v12
3898 else:
3899 k2 = -v11*v12*v24/v22 + v11*v14 + v12**2*v21*v24/v22**2 - v12*v14*v21/v22
3900 k1 = v11*v24/v22 - 2*v12*v21*v24/v22**2 + v12*v23/v22 - v13 + v14*v21/v22
3901 k0 = v21*v24/v22**2 - v23/v22
3902 c1 = np.roots([k2,k1,k0])*np.ones(2)
3903 c2 = (1 - c1*v12)/v22
3904 x = np.array( [v1*x + v2*y for x,y in zip(c1,c2)] ) # 2 solutions
3905 mininx = np.argmin( abs(x - x_est).sum(axis=1) )
3906 return x[mininx]
3907
3908 line_meas_S = np.array([x.s for x in self.line_meas]) # get the S-parameters
3909 reflect_meas_S = np.array([x.s for x in self.reflect_meas]) # get the S-parameters
3910 lengths = np.atleast_1d( self.line_lengths ) # make numpy array
3911 er_est = self.er_est
3912 reflect_est = self.reflect_est
3913 reflect_offset = self.reflect_offset
3914
3915 fpoints = len(self.freq.f)
3916 Xs = np.zeros(shape=(fpoints, 4, 4), dtype=complex) # to store the combined error boxes (6 error terms)
3917 ks = np.zeros(shape=(fpoints,), dtype=complex) # to store the 7th transmission error terms
3918 er_effs = np.zeros(shape=(fpoints,), dtype=complex)
3919 gammas = np.zeros(shape=(fpoints,), dtype=complex)
3920 lambds = np.zeros(shape=(fpoints,), dtype=float) # to store the eigenvalue of the weighted eigendecomposition
3921
3922 # compute the calibration at each frequency point
3923 for m, f in enumerate(self.freq.f):
3924 # measurements
3925 Mi = np.array([s2t_single(x) for x in line_meas_S[:,m,:,:]]) # convert to T-parameters
3926 M = np.array([x.flatten('F') for x in Mi]).T
3927 Dinv = np.diag([1/np.linalg.det(x) for x in Mi])
3928
3929 ## Compute W via Takagi decomposition (also the eigenvalue lambda)
3930 G, lambd = compute_G_with_takagi(Dinv@M.T@P@Q@M)
3931 W = (G@np.array([[0,1j],[-1j,0]])@G.T).conj()
3932
3933 gamma_est = ereff2gamma(er_est, f)
3934 gamma_est = abs(gamma_est.real) + 1j*abs(gamma_est.imag) # this to avoid sign inconsistencies
3935
3936 z_est = np.exp(-gamma_est*lengths)
3937 y_est = 1/z_est
3938 W_est = (np.outer(y_est,z_est) - np.outer(z_est,y_est)).conj()
3939 W = -W if abs(W-W_est).sum() > abs(W+W_est).sum() else W # resolve the sign ambiguity
3940
3941 ## weighted eigenvalue problem
3942 F = M@W@Dinv@M.T@P@Q
3943 eigval, eigvec = np.linalg.eig(F+lambd*np.eye(4))
3944 inx = np.argsort(abs(eigval))
3945 v1 = eigvec[:,inx[0]]
3946 v2 = eigvec[:,inx[1]]
3947 v3 = eigvec[:,inx[2]]
3948 v4 = eigvec[:,inx[3]]
3949 x1__est = v1/v1[0]
3950 x1__est[-1] = x1__est[1]*x1__est[2]
3951 x4_est = v4/v4[-1]
3952 x4_est[0] = x4_est[1]*x4_est[2]
3953 x2__est = np.array([x4_est[2], 1, x4_est[2]*x1__est[2], x1__est[2]])
3954 x3__est = np.array([x4_est[1], x4_est[1]*x1__est[1], 1, x1__est[1]])
3955
3956 # solve quadratic equation for each column
3957 x1_ = solve_quadratic(v1, v4, [0,3], x1__est) # range
3958 x2_ = solve_quadratic(v2, v3, [1,2], x2__est) # nullspace
3959 x3_ = solve_quadratic(v2, v3, [2,1], x3__est) # nullspace
3960 x4 = solve_quadratic(v1, v4, [3,0], x4_est) # range
3961
3962 # build the normalized error terms (average the answers from range and nullspaces)
3963 a12 = (x2_[0] + x4[2])/2
3964 b21 = (x3_[0] + x4[1])/2
3965 a21_a11 = (x1_[1] + x3_[3])/2
3966 b12_b11 = (x1_[2] + x2_[3])/2
3967 X_ = np.kron([[1,b21],[b12_b11,1]], [[1,a12],[a21_a11,1]]) # normalized cal coefficients
3968
3969 X_inv = np.linalg.inv(X_)
3970
3971 ## compute propagation constant
3972 gamma = compute_gamma(X_inv, M, lengths, gamma_est)
3973 er_eff = gamma2ereff(gamma, f) # new estimate of er_eff
3974 er_est = er_eff
3975
3976 ## solve a11b11 and k from thru measurement (first line in the list)
3977 ka11b11,_,_,k = X_inv@M[:,0]
3978 a11b11 = ka11b11/k
3979 # shift plane to edges of the thru standard plus defined reference plane
3980 a11b11 = a11b11*np.exp(2*gamma*(lengths[0] - self.ref_plane.sum()))
3981 k = k*np.exp(-gamma*(lengths[0] - self.ref_plane.sum()))
3982
3983 if np.isnan(reflect_meas_S[0,m,0,0]):
3984 # no reflect measurement available.
3985 a11 = np.sqrt(a11b11)
3986 b11 = a11
3987 else:
3988 # solve for a11/b11, a11 and b11 (use redundant reflect measurement, if available)
3989 reflect_est_offset = reflect_est*np.exp(-2*gamma*reflect_offset) # shift estimated reflect
3990 Mr = np.array([s2t_single(x, pseudo=True).flatten('F') for x in reflect_meas_S[:,m,:,:]]).T
3991 T = X_inv@Mr
3992 a11_b11 = -T[2,:]/T[1,:]
3993 a11 = np.sqrt(a11_b11*a11b11)
3994 b11 = a11b11/a11
3995 G_cal = (
3996 (reflect_meas_S[:,m,0,0] - a12) / (1 - reflect_meas_S[:,m,0,0]*a21_a11)/a11
3997 + (reflect_meas_S[:,m,1,1]
3998 + b21)/(1 + reflect_meas_S[:,m,1,1]*b12_b11)/b11 )/2 # average
3999 for inx,(Gcal,Gest) in enumerate(zip(G_cal, reflect_est_offset)):
4000 if abs(Gcal - Gest) > abs(Gcal + Gest):
4001 a11[inx] = -a11[inx]
4002 b11[inx] = -b11[inx]
4003 G_cal[inx] = -G_cal[inx]
4004 a11 = a11.mean()
4005 b11 = b11.mean()
4006
4007 X = X_@np.diag([a11b11, b11, a11, 1]) # build the calibration matrix (de-normalize)
4008
4009 Xs[m] = X
4010 ks[m] = k
4011 gammas[m] = gamma
4012 er_effs[m] = er_eff
4013 lambds[m] = lambd
4014
4015 self._er_eff = er_effs
4016 self._gamma = gammas
4017 self._lambd = lambds
4018
4019 e = np.zeros(shape=(len(self.freq.f), 7), dtype=complex)
4020 e[:,0] = Xs[:,2,3]
4021 e[:,1] = -Xs[:,3,2]
4022 e[:,2] = -Xs[:,2,2]
4023 e[:,3] = -Xs[:,1,3]
4024 e[:,4] = Xs[:,3,1]
4025 e[:,5] = -Xs[:,1,1]
4026 e[:,6] = 1/ks/(e[:,4]*e[:,3]-e[:,5])
4027
4028 self._coefs = {\
4029 'forward directivity':e[:,0],
4030 'forward source match':e[:,1],
4031 'forward reflection tracking':e[:,0]*e[:,1]-e[:,2],
4032 'reverse directivity':e[:,3],
4033 'reverse source match':e[:,4],
4034 'reverse reflection tracking':e[:,4]*e[:,3]-e[:,5],
4035 'k':e[:,6],
4036 }
4037 self._coefs['forward isolation'] = self.isolation.s[:,1,0].flatten()
4038 self._coefs['reverse isolation'] = self.isolation.s[:,0,1].flatten()
4039
4040 if self.switch_terms is not None:
4041 self._coefs.update({
4042 'forward switch term': self.switch_terms[0].s.flatten(),
4043 'reverse switch term': self.switch_terms[1].s.flatten(),
4044 })
4045 else:
4046 self._coefs.update({
4047 'forward switch term': np.zeros(fpoints, dtype=complex),
4048 'reverse switch term': np.zeros(fpoints, dtype=complex),
4049 })
4050 # output is a dictionary of information
4051 self._output_from_run = {
4052 'error vector':e
4053 }
4054
4055 @property
4056 def gamma(self):
4057 """
4058 Propagation constant of the solved line.
4059
4060 """
4061 try:
4062 return self._gamma
4063 except(AttributeError):
4064 self.run()
4065 return self._gamma
4066
4067 @property
4068 def er_eff(self):
4069 """
4070 Relative effective permittivity of the solved line.
4071
4072 """
4073 try:
4074 return self._er_eff
4075 except(AttributeError):
4076 self.run()
4077 return self._er_eff
4078
4079 @property
4080 def lambd(self):
4081 """
4082 Eigenvalue of the weighted eigendecomposition.
4083 The closer the eigenvalue to zero, the more sensitive the calibration to error.
4084 Similar to the normalized standard deviation of NIST multiline TRL, but reversed.
4085
4086 """
4087 try:
4088 return self._lambd
4089 except(AttributeError):
4090 self.run()
4091 return self._lambd
4092
4093
4094 class UnknownThru(EightTerm):
4095 """
4096 Two-Port Self-Calibration allowing the *thru* standard to be unknown.
4097
4098 This algorithm was originally developed in [1]_, and
4099 is based on the 8-term error model (:class:`EightTerm`). It allows
4100 the *thru* to be unknown, other than it must be reciprocal. This
4101 is useful when when a well-known thru is not realizable.
4102
4103
4104 References
4105 ----------
4106 .. [1] A. Ferrero and U. Pisani, "Two-port network analyzer calibration using an unknown `thru,`"
4107 IEEE Microwave and Guided Wave Letters, vol. 2, no. 12, pp. 505-507, 1992.
4108
4109 """
4110
4111 family = 'UnknownThru'
4112
4113 # Use standard SOL calibration to solve two 1-port error boxes
4114 # before the Thru calibration.
4115 _ONEPORT_ALGO = OnePort
4116
4117 def __init__(self, measured, ideals, *args, **kwargs):
4118 r"""
4119 UnknownThru Initializer.
4120
4121 Note that the *thru* standard must be last in both measured, and
4122 ideal lists. The ideal for the *thru* is only used to choose
4123 the sign of a square root. Thus, it only has to be have s21, s12
4124 known within :math:`\pi` phase.
4125
4126 Parameters
4127 ----------
4128 measured : list/dict of :class:`~skrf.network.Network` objects
4129 Raw measurements of the calibration standards. The order
4130 must align with the `ideals` parameter ( or use `sloppy_input`)
4131
4132 ideals : list/dict of :class:`~skrf.network.Network` objects
4133 Predicted ideal response of the calibration standards.
4134 The order must align with `ideals` list ( or use `sloppy_input`)
4135
4136 switch_terms : tuple of :class:`~skrf.network.Network` objects
4137 the pair of switch terms in the order (forward, reverse)
4138 """
4139
4140 EightTerm.__init__(self, measured = measured, ideals = ideals,
4141 **kwargs)
4142
4143
4144 def run(self):
4145 p1_m = [k.s11 for k in self.measured_unterminated[:-1]]
4146 p2_m = [k.s22 for k in self.measured_unterminated[:-1]]
4147 p1_i = [k.s11 for k in self.ideals[:-1]]
4148 p2_i = [k.s22 for k in self.ideals[:-1]]
4149
4150 thru_m = self.measured_unterminated[-1]
4151
4152 # create one port calibration for all reflective standards
4153 port1_cal = self._ONEPORT_ALGO(measured = p1_m, ideals = p1_i)
4154 port2_cal = self._ONEPORT_ALGO(measured = p2_m, ideals = p2_i)
4155
4156 # cal coefficient dictionaries
4157 p1_coefs = port1_cal.coefs.copy()
4158 p2_coefs = port2_cal.coefs.copy()
4159
4160 e_rf = port1_cal.coefs_ntwks['reflection tracking']
4161 e_rr = port2_cal.coefs_ntwks['reflection tracking']
4162
4163 # create single dictionary for all error terms
4164 coefs = {}
4165
4166 coefs['forward isolation'] = self.isolation.s[:,1,0].flatten()
4167 coefs['reverse isolation'] = self.isolation.s[:,0,1].flatten()
4168
4169 coefs.update({f'forward {k}': p1_coefs[k] for k in p1_coefs})
4170 coefs.update({f'reverse {k}': p2_coefs[k] for k in p2_coefs})
4171
4172 if self.switch_terms is not None:
4173 coefs.update({
4174 'forward switch term': self.switch_terms[0].s.flatten(),
4175 'reverse switch term': self.switch_terms[1].s.flatten(),
4176 })
4177 else:
4178 warn('No switch terms provided', stacklevel=2)
4179 coefs.update({
4180 'forward switch term': np.zeros(len(self.frequency), dtype=complex),
4181 'reverse switch term': np.zeros(len(self.frequency), dtype=complex),
4182 })
4183 self.coefs = coefs
4184
4185 # this is equivalent to sqrt(detX*detY/detM)
4186 e10e32 = np.sqrt((e_rf * e_rr * thru_m.s21 / thru_m.s12).s.flatten())
4187
4188 # We have almost all the information in self.coefs, except the last
4189 # one, self.coefs['k']. This parameter has a sign ambiguity because
4190 # e10e32 is a square root with two solutions. We need to pick the
4191 # solution with the phase angle closer to the user's approximate
4192 # definition.
4193 k_ambiguous = e10e32 / e_rr.s.flatten()
4194 self._choose_k(k_ambiguous)
4195
4196 def _choose_k(self, k_ambiguous):
4197 # square root is multi-valued
4198 k1 = k_ambiguous
4199 k2 = -1 * k_ambiguous
4200
4201 # Measured thru network (including crosstalk) and the user-provided
4202 # definition.
4203 thru_meas = self.measured[-1]
4204 thru_def = self.ideals[-1]
4205
4206 # solution of the Thru using k1
4207 self.coefs.update({'k': k1})
4208 solved_thru_k1 = self.apply_cal(thru_meas)
4209
4210 # solution of the Thru using k2
4211 self.coefs.update({'k': k2})
4212 solved_thru_k2 = self.apply_cal(thru_meas)
4213
4214 # Compare the phase angle differences of two solutions.
4215 arg_diff1 = np.abs(
4216 np.angle(solved_thru_k1.s[:,1,0] / thru_def.s[:,1,0])
4217 )
4218 arg_diff2 = np.abs(
4219 np.angle(solved_thru_k2.s[:,1,0] / thru_def.s[:,1,0])
4220 )
4221
4222 # At every frequency, pick the corresponding k value from k1 if
4223 # arg_diff1 is smaller, or vice versa.
4224 k_chosen = np.where(arg_diff1 < arg_diff2, k1, k2)
4225 self.coefs.update({'k': k_chosen})
4226
4227
4228 class LRM(EightTerm):
4229 """
4230 Line-Reflect-Match self-calibration.
4231
4232 The required calibration standards are:
4233
4234 * Line: Fully known.
4235 * Reflect: Unknown reflect, phase needs to be known within 90 degrees.
4236 * Match: Fully known.
4237
4238 Reflect and match are assumed to be identical on both ports. The measured
4239 and ideals lists must be given in LRM order.
4240
4241 Implementation is based on [1]_.
4242
4243 References
4244 ----------
4245 .. [1] Zhao, W.; Liu, S.; Wang, H.; Liu, Y.; Zhang, S.; Cheng, C.; Feng,
4246 K.; Ocket, I.; Schreurs, D.; Nauwelaers, B.; Qin, H.; Yang, X.
4247 A Unified Approach for Reformulations of LRM/LRMM/LRRM Calibration
4248 Algorithms Based on the T-Matrix Representation. Appl. Sci. 2017, 7,
4249 866.
4250 """
4251
4252 family = 'LRM'
4253
4254 def __init__(self, measured, ideals, switch_terms=None, isolation=None,
4255 *args, **kwargs):
4256 """
4257 LRM Initializer.
4258
4259 Parameters
4260 ----------
4261 measured : list of :class:`~skrf.network.Network` objects
4262 Raw measurements of the calibration standards. The order
4263 must align with the `ideals` parameter
4264
4265 ideals : list of :class:`~skrf.network.Network` objects
4266 Predicted ideal response of the calibration standards.
4267 The order must align with `measured` list
4268
4269 switch_terms : tuple of :class:`~skrf.network.Network` objects
4270 the pair of switch terms in the order (forward, reverse)
4271
4272 isolation : :class:`~skrf.network.Network` object
4273 Measurement with loads on both ports with a perfect isolation
4274 between the ports. Used for determining the isolation error terms.
4275 If no measurement is given leakage is assumed to be zero.
4276 """
4277
4278 super().__init__(
4279 measured = measured,
4280 ideals = ideals,
4281 switch_terms = switch_terms,
4282 isolation = isolation,
4283 **kwargs)
4284
4285 def run(self):
4286 mList = [k for k in self.measured_unterminated]
4287 lm = mList[0]
4288 rm = mList[1]
4289 mm = mList[2]
4290
4291 gm = self.ideals[2].s[:,0,0]
4292 if self.ideals[2].nports > 1:
4293 if any(gm != self.ideals[2].s[:,1,1]):
4294 warnings.warn('Match ideal port 1 and port 2 are different. Using port 1 match also for port 2.',
4295 stacklevel=2)
4296
4297 if self.ideals[1].nports > 1:
4298 if any(self.ideals[1].s[:,0,0] != self.ideals[1].s[:,1,1]):
4299 warnings.warn('Reflect ideal port 1 and port 2 are different. Using port 1 reflect also for port 2.',
4300 stacklevel=2)
4301
4302 inv = np.linalg.inv
4303
4304 tl = self.ideals[0].t
4305
4306 fpoints = len(mList[0])
4307
4308 r1 = rm.s[:,0,0]
4309 r2 = rm.s[:,1,1]
4310 m1 = mm.s[:,0,0]
4311 m2 = mm.s[:,1,1]
4312
4313 lm11 = lm.s[:,0,0]
4314 lm12 = lm.s[:,0,1]
4315 lm21 = lm.s[:,1,0]
4316 lm22 = lm.s[:,1,1]
4317
4318 ones = np.ones(fpoints, dtype=complex)
4319 zeros = np.zeros(fpoints, dtype=complex)
4320
4321 wlr1 = np.transpose(np.array([[ones, ones], [r1, m1]]), [2,0,1])
4322 wll1 = np.transpose(np.array([[ones, zeros], [lm11, lm12]]), [2,0,1])
4323 wll2 = np.transpose(np.array([[zeros, ones], [lm21, lm22]]), [2,0,1])
4324 wlr2 = np.transpose(np.array([[ones, ones], [r2, m2]]), [2,0,1])
4325
4326 wl = inv(wlr1) @ wll1 @ inv(wll2) @ wlr2
4327
4328 # xyz2 == (x/y)*z**2
4329 xyz2 = -np.linalg.det(tl) / np.linalg.det(wl)
4330
4331 c2 = wl[:, 0, 0]
4332 c1 = -tl[:, 1, 0] - tl[:, 0, 1]
4333 c0 = wl[:, 1, 1] * xyz2
4334
4335 z0 = -c1 + np.sqrt(c1**2 - 4*c2*c0)/(2*c2)
4336 z1 = -c1 - np.sqrt(c1**2 - 4*c2*c0)/(2*c2)
4337 zs = np.stack([z0, z1])
4338
4339 grs = np.zeros((2, fpoints), dtype=complex)
4340 xs = np.zeros((2, fpoints), dtype=complex)
4341 er = np.zeros((2, fpoints), dtype=complex)
4342
4343 for root in [0, 1]:
4344 z = zs[root]
4345 xyz = xyz2 / z
4346
4347 w11 = wl[:, 0, 0] * z
4348 w21 = wl[:, 1, 0] * z
4349 w12 = wl[:, 0, 1] * xyz
4350 w22 = wl[:, 1, 1] * xyz
4351
4352 x = w12 / (tl[:, 1, 0] + tl[:, 1, 1]*gm - w22)
4353 gr = (w11 - tl[:, 1, 0] + w21*x) / tl[:, 1, 1]
4354
4355 er[root] = np.abs(gr - self.ideals[1].s[:,0,0])
4356
4357 grs[root] = gr
4358 xs[root] = x
4359
4360 root = er[0] < er[1]
4361
4362 gr = np.where(root, grs[0], grs[1])
4363 x = np.where(root, xs[0], xs[1])
4364 z = np.where(root, zs[0], zs[1])
4365 y = x * z**2 / xyz2
4366
4367 self._solved_r = Network(s=gr, frequency=self.measured[0].frequency)
4368
4369 # Calculate error matrices
4370 t10 = np.transpose(np.array([[ones, x], [gr, gm*x]]), [2,0,1]) \
4371 @ inv(np.transpose(np.array([[ones,ones],[r1, m1]]), [2,0,1]))
4372 t23 = np.transpose((1/z)*np.array([[ones, y], [gr, gm*y]]), [2,0,1]) \
4373 @ inv(np.transpose(np.array([[ones,ones],[r2, m2]]), [2,0,1]))
4374
4375 Smat1 = t2s(t10)
4376 Smat2 = t2s(t23)
4377
4378 # Convert the error coefficients to
4379 # definitions used by the EightTerm class.
4380 dx = linalg.det(Smat1)
4381 dy = linalg.det(Smat2)
4382
4383 k = Smat1[:,0,1]/Smat2[:,0,1]
4384
4385 # Error coefficients
4386 e = [Smat1[:,0,0],
4387 Smat1[:,1,1],
4388 dx,
4389 Smat2[:,0,0],
4390 Smat2[:,1,1],
4391 dy,
4392 k]
4393
4394 self._coefs = {\
4395 'forward directivity':e[1],
4396 'forward source match':e[0],
4397 'forward reflection tracking':e[0]*e[1]-e[2],
4398 'reverse directivity':e[4],
4399 'reverse source match':e[3],
4400 'reverse reflection tracking':e[4]*e[3]- e[5],
4401 'k':e[6],
4402 }
4403
4404 self._coefs['forward isolation'] = self.isolation.s[:,1,0].flatten()
4405 self._coefs['reverse isolation'] = self.isolation.s[:,0,1].flatten()
4406
4407 if self.switch_terms is not None:
4408 self._coefs.update({
4409 'forward switch term': self.switch_terms[0].s.flatten(),
4410 'reverse switch term': self.switch_terms[1].s.flatten(),
4411 })
4412 else:
4413 self._coefs.update({
4414 'forward switch term': np.zeros(fpoints, dtype=complex),
4415 'reverse switch term': np.zeros(fpoints, dtype=complex),
4416 })
4417 # output is a dictionary of information
4418 self._output_from_run = {
4419 'error vector':e
4420 }
4421
4422 @property
4423 def solved_r(self):
4424 """
4425 Solved reflect
4426 """
4427 try:
4428 return self._solved_r
4429 except(AttributeError):
4430 self.run()
4431 return self._solved_r
4432
4433
4434 class LRRM(EightTerm):
4435 """
4436 Line-Reflect-Reflect-Match self-calibration.
4437
4438 The required calibration standards are:
4439
4440 * Line: Fully known.
4441 * Reflect: Unknown reflect, phase needs to be known within 90 degrees.
4442 * Reflect: Reflect with known absolute value of the reflection coefficient, \
4443 phase needs to be known within 90 degrees. \
4444 Different from the other reflect.
4445 * Match: Match with known resistance in series with unknown inductance.
4446
4447 Reflects are assumed to be identical on both ports. Note that the first
4448 reflect's magnitude of the reflection coefficient can be unknown, but the
4449 second reflect's magnitude of the reflection coefficient needs to be known.
4450 Match needs to be only measured on the first port, the second port of match
4451 measurement is not used during the calibration.
4452
4453 If match_fit == 'lc' then the second reflect is assumed to be a lossless
4454 capacitor. Measurements should then include low frequencies for accurate
4455 open capacitance determination. 'lc_fit_c_freq' argument can be given to
4456 specify the maximum frequency in Hz where open looks like an ideal
4457 capacitor, above this frequency open is assumed to only have known absolute
4458 value similar to 'l' fit. Default is infinity.
4459
4460 Implementation is based on papers [1]_ and [2]_. 'lc' match_fit based on
4461 [3]_.
4462
4463 References
4464 ----------
4465 .. [1] Zhao, W.; Liu, S.; Wang, H.; Liu, Y.; Zhang, S.; Cheng, C.; Feng,
4466 K.; Ocket, I.; Schreurs, D.; Nauwelaers, B.; Qin, H.; Yang, X.
4467 A Unified Approach for Reformulations of LRM/LRMM/LRRM Calibration
4468 Algorithms Based on the T-Matrix Representation. Appl. Sci. 2017, 7,
4469 866.
4470
4471 .. [2] F. Purroy and L. Pradell, "New theoretical analysis of the LRRM
4472 calibration technique for vector network analyzers," in IEEE
4473 Transactions on Instrumentation and Measurement, vol. 50, no. 5,
4474 pp. 1307-1314, Oct. 2001.
4475
4476 .. [3] S. Liu, I. Ocket, A. Lewandowski, D. Schreurs and B. Nauwelaers, "An
4477 Improved Line-Reflect-Reflect-Match Calibration With an Enhanced Load
4478 Model," in IEEE Microwave and Wireless Components Letters, vol. 27,
4479 no. 1, pp. 97-99, Jan. 2017.
4480 """
4481
4482 family = 'LRRM'
4483
4484 def __init__(self, measured, ideals, switch_terms=None, isolation=None,
4485 z0=50, match_fit='l', *args, **kwargs):
4486 """
4487 LRRM Initializer.
4488
4489 Parameters
4490 ----------
4491 measured : list of :class:`~skrf.network.Network` objects
4492 Raw measurements of the calibration standards. The order
4493 must be line, reflect, reflect, match and must align with the
4494 `ideals` parameter
4495
4496 ideals : list of :class:`~skrf.network.Network` objects
4497 Predicted ideal response of the calibration standards.
4498 The order must align with `measured` list
4499
4500 switch_terms : tuple of :class:`~skrf.network.Network` objects
4501 the pair of switch terms in the order (forward, reverse)
4502
4503 isolation : :class:`~skrf.network.Network` object
4504 Measurement with loads on both ports with a perfect isolation
4505 between the ports. Used for determining the isolation error terms.
4506 If no measurement is given leakage is assumed to be zero.
4507
4508 z0 : int
4509 Calibration reference impedance. Only affects the solved match
4510 inductance. Has no effect on the solved calibration parameters.
4511
4512 match_fit : string or None
4513 Match model. Valid choices are:
4514 'l' to fit a single inductance over all frequencies.
4515 'lc' to fit match with series inductor and parallel capacitor and
4516 assuming that the second reflect is open with unknown capacitance.
4517 'none' to not fit inductance and let it be different for each
4518 frequency point.
4519
4520 'l' or 'lc' is recommended for normal use.
4521 """
4522
4523 self.z0 = z0
4524 # TODO: Second port not implemented.
4525 self.match_port = 0
4526 # Maximum frequency to assume that open behaves like ideal capacitor when
4527 # using match_fit == 'lc'.
4528 self.lc_fit_c_freq = kwargs.get('lc_fit_c_freq', float('inf'))
4529
4530 self.match_fit = match_fit
4531 if self.match_port not in [0, 1]:
4532 raise ValueError('match_port must be either 0 or 1.')
4533
4534 super().__init__(
4535 measured = measured,
4536 ideals = ideals,
4537 switch_terms = switch_terms,
4538 isolation = isolation,
4539 **kwargs)
4540
4541 def run(self):
4542 mList = [k for k in self.measured_unterminated]
4543 lm = mList[0]
4544 r1m = mList[1]
4545 r2m = mList[2]
4546 mm = mList[3]
4547
4548 inv = np.linalg.inv
4549
4550 tl = self.ideals[0].t
4551
4552 w = 2*np.pi*self.measured[0].f
4553 fpoints = len(mList[0])
4554
4555 r11 = r1m.s[:,0,0]
4556 r12 = r1m.s[:,1,1]
4557 r21 = r2m.s[:,0,0]
4558 r22 = r2m.s[:,1,1]
4559
4560 lm11 = lm.s[:,0,0]
4561 lm12 = lm.s[:,0,1]
4562 lm21 = lm.s[:,1,0]
4563 lm22 = lm.s[:,1,1]
4564
4565 mm1 = mm.s[:,0,0]
4566
4567 thru_s21 = self.ideals[0].s[:,1,0]
4568
4569 ones = np.ones(fpoints, dtype=complex)
4570 zeros = np.zeros(fpoints, dtype=complex)
4571
4572 wlr1 = np.transpose(np.array([[ones, ones], [r11, r21]]), [2,0,1])
4573 wll1 = np.transpose(np.array([[ones, zeros], [lm11, lm12]]), [2,0,1])
4574 wll2 = np.transpose(np.array([[zeros, ones], [lm21, lm22]]), [2,0,1])
4575 wlr2 = np.transpose(np.array([[ones, ones], [r12, r22]]), [2,0,1])
4576
4577 wl = inv(wlr1) @ wll1 @ inv(wll2) @ wlr2
4578
4579 # xyz2 == (x/y)*z**2
4580 xyz2 = -np.linalg.det(tl) / np.linalg.det(wl)
4581
4582 c2 = wl[:, 0, 0]
4583 c1 = -tl[:, 1, 0] - tl[:, 0, 1]
4584 c0 = wl[:, 1, 1] * xyz2
4585
4586 z0 = (-c1 + np.sqrt(c1**2 - 4*c2*c0))/(2*c2)
4587 z1 = (-c1 - np.sqrt(c1**2 - 4*c2*c0))/(2*c2)
4588 zs = np.stack([z0, z1])
4589
4590 # wm and solve_gr equations are different if match is on the second port.
4591 assert self.match_port == 0
4592 wm_t1 = inv(np.transpose(np.array([[ones, ones],[r11, r21]]), [2,0,1]))
4593 wm_t2 = np.transpose(np.array([[ones], [mm1]]), [2,0,1])
4594 wm = wm_t1 @ wm_t2
4595 wm1 = wm[:, 0, 0]
4596 wm2 = wm[:, 1, 0]
4597
4598 def solve_gr(gm):
4599 gr1s = np.zeros((2, fpoints), dtype=complex)
4600 gr2s = np.zeros((2, fpoints), dtype=complex)
4601 xs = np.zeros((2, fpoints), dtype=complex)
4602 er = np.zeros((2, fpoints), dtype=complex)
4603 efs = np.zeros((2, 4, fpoints), dtype=complex)
4604
4605 for root in [0, 1]:
4606 z = zs[root]
4607 xyz = xyz2 / z
4608
4609 w11 = wl[:, 0, 0] * z
4610 w21 = wl[:, 1, 0] * z
4611 w12 = wl[:, 0, 1] * xyz
4612 w22 = wl[:, 1, 1] * xyz
4613
4614 e1 = (tl[:, 1, 1]**2) * wm1
4615 e0 = tl[:, 1, 1] * (tl[:, 1, 0] - w22) * wm1 + tl[:, 1, 1] * wm2 * w12
4616 f1 = tl[:, 1, 1] * (w11 - tl[:, 1, 0]) * wm1 + tl[:, 1, 1] * wm2 * w12
4617 f0 = (w11 - tl[:, 1, 0]) * (tl[:, 1, 0] - w22) * wm1 + wm1 * w21 * w12
4618
4619 gr2 = -(f0 - e0 * gm) / (f1 - e1 * gm)
4620
4621 x = w12 / (tl[:, 1, 0] + tl[:, 1, 1]*gr2 - w22)
4622 gr1 = ((w11 - tl[:, 1, 0]) * (tl[:, 1, 0] + tl[:, 1, 1] * gr2 - w22) + w21*w12) \
4623 / (tl[:, 1, 1] * (tl[:, 1, 0] + tl[:, 1, 1] * gr2 - w22))
4624
4625 egr1 = np.abs(gr1 - self.ideals[1].s[:,0,0])
4626 egr2 = np.abs(gr2 - self.ideals[2].s[:,0,0])
4627
4628 er[root] = egr1 + egr2
4629 gr1s[root] = gr1
4630 gr2s[root] = gr2
4631 efs[root, 0, :] = e1
4632 efs[root, 1, :] = e0
4633 efs[root, 2, :] = f1
4634 efs[root, 3, :] = f0
4635 xs[root] = x
4636
4637 root = er[0] < er[1]
4638
4639 gr1 = np.where(root, gr1s[0], gr1s[1])
4640 gr2 = np.where(root, gr2s[0], gr2s[1])
4641 x = np.where(root, xs[0], xs[1])
4642 z = np.where(root, zs[0], zs[1])
4643 efs = np.where(root, efs[0], efs[1])
4644 y = x * z**2 / xyz2
4645
4646 return gr1, gr2, x, y, z, efs
4647
4648 def calc_gm(R, l, c=0):
4649 """
4650 Calculates reflection coefficient of resistor R in series with inductance
4651 l in parallel with capacitor c.
4652 """
4653 return (self.z0 + R*(-1 + 1j*c*w*self.z0) - l*w*(1j + c*w*self.z0)) \
4654 /(-self.z0 + R*(-1 - 1j*c*w*self.z0) + l*w*(-1j + c*w*self.z0))
4655
4656 # First, solve reflects assuming ideal gm
4657 gmi = self.ideals[3].s[:, self.match_port, self.match_port]
4658 gr1, gr2, x, y, z, efs = solve_gr(gmi)
4659
4660 # Next solve for match inductance
4661 R = (self.z0 * (1 + gmi)/(1 - gmi)).real # Resistance of the match
4662
4663 a = 2*gr2.real + np.abs(gr2)**2 - \
4664 2*(gr2*thru_s21**(-2)).real - np.abs(gr2*thru_s21**(-2))**2
4665 b = 4*R*(gr2.imag + (gr2*thru_s21**(-2)).imag)
4666 c = 4*R**2*(np.abs(gr2)**2 - 1)
4667
4668 det = b**2 - 4*a*c
4669 if np.any(det < 0):
4670 warnings.warn('Load inductance determination failed. Calibration might be incorrect.', stacklevel=2)
4671 det[det < 0] = 0
4672 wL = [None, None]
4673 wL[0] = (-b+np.sqrt(det))/(2*a)
4674 wL[1] = (-b-np.sqrt(det))/(2*a)
4675
4676 gm_guess = [None, None]
4677 for p in [0,1]:
4678 gm_guess[p] = (R + 1j*wL[p] - self.z0)/(R + 1j*wL[p] + self.z0)
4679
4680 # Choose the root according to which one is closer to the ideal
4681 m_ideal = self.ideals[3].s[:,0,0]
4682 root = (np.abs(gm_guess[0] - m_ideal) > np.abs(gm_guess[1] - m_ideal)).astype(int)
4683
4684 # L from reactance
4685 match_l = np.choose(root, wL)/w
4686 match_c = zeros
4687
4688 # Weight L estimate by frequency
4689 l0 = np.sum(w * match_l) / np.sum(w)
4690
4691 e1 = efs[0, :]
4692 e0 = efs[1, :]
4693 f1 = efs[2, :]
4694 f0 = efs[3, :]
4695
4696 gr2_abs = np.abs(self.ideals[2].s[:,0,0])
4697
4698 if self.match_fit == 'l':
4699
4700 def min_l(l):
4701 """
4702 Calculates gr2 absolute value error as a function of
4703 the match inductance.
4704 """
4705 gm = (R + 1j*w*l - self.z0)/(R + 1j*w*l + self.z0)
4706 return gr2_abs - np.abs((f0 - e0 * gm) / (f1 - e1 * gm))
4707
4708 # Try some alternative initial guesses
4709 init_x = np.linspace(-10, 10, 10)
4710 init_l = init_x / (w[-1])
4711 init_guess = [np.mean(min_l(l)**2) for l in init_l]
4712 li = np.argmin(init_guess)
4713 best_guess = init_l[li]
4714
4715 # Choose the best guess for the least squares initial value
4716 if init_guess[li] < np.mean(min_l(l0)**2):
4717 l0 = best_guess
4718
4719 sol = least_squares(min_l, l0, method="lm", diff_step=np.sqrt(np.finfo(np.float64).resolution))
4720 match_l = sol.x * np.ones(match_l.shape)
4721 match_c = zeros
4722
4723 elif self.match_fit == 'lc':
4724
4725 if self.ideals[2].s[0,0,0].real < 0:
4726 warnings.warn("2nd reflect assumed to be open, but 2nd ideal ' \
4727 'doesn't look like open. Calibration is likely incorrect.", stacklevel=2)
4728
4729 match_c = -1/(np.choose(root, wL)*w)
4730 c0 = np.sum(w * match_c) / np.sum(w)
4731
4732 cw = w < 2 * np.pi * self.lc_fit_c_freq
4733 cw = cw.astype(float)
4734
4735 def min_lc(x):
4736 l, c = x
4737 gm = calc_gm(R, l, c)
4738 # Calculate open reflection coefficient from gm
4739 gr2 = -(f0 - e0 * gm) / (f1 - e1 * gm)
4740
4741 # Fit capacitance to gr2
4742 cgr2 = (1j*(-1 + gr2))/((1 + gr2)*w*self.z0)
4743 cgr2 = np.mean(cgr2.real)
4744 gr2_c = (1j + cgr2*w*self.z0)/(1j - cgr2*w*self.z0)
4745
4746 # Error between fitted open capacitor and calculated open
4747 # capacitance
4748 e_c = gr2_c + (f0 - e0 * gm) / (f1 - e1 * gm)
4749 e_abs = gr2_abs - np.abs((f0 - e0 * gm) / (f1 - e1 * gm))
4750 e = e_c * cw + (1 - cw) * e_abs
4751 return np.abs(e)
4752
4753 # Biggest capacitance value assuming given gm matching.
4754 worst_match = 0.4 # -7 dB
4755 max_init_c = (2*worst_match)/(np.sqrt(1 - worst_match**2)*w[-1]*self.z0)
4756
4757 # Initial reactance guess, try to find positive L, C.
4758 init_x = np.linspace(0, 20, 10)
4759 init_l = init_x / (w[-1])
4760 init_c = np.linspace(0, max_init_c, 10)
4761 init_lc = [(l, c) for l in init_l for c in init_c]
4762 if l0 > 0:
4763 init_lc.append((l0, 0))
4764 if c0 > 0:
4765 init_lc.append((0, c0))
4766 init_guess = [np.mean(min_lc(x)**2) for x in init_lc]
4767 best_guess = init_lc[np.argmin(init_guess)]
4768
4769 l0 = best_guess[0]
4770 c0 = best_guess[1]
4771
4772 sol = least_squares(min_lc, [l0, c0], method='lm')
4773 match_l = sol.x[0] * np.ones(match_l.shape)
4774 match_c = sol.x[1] * np.ones(match_l.shape)
4775
4776 elif self.match_fit == 'none' or self.match_fit is None:
4777 pass
4778 else:
4779 raise ValueError(f'Unknown match_fit {self.match_fit}')
4780
4781 gamma_m = calc_gm(R, match_l, match_c)
4782
4783 # Solve finally reflects and calibration parameters using the solved match
4784 gr1, gr2, x, y, z, _ = solve_gr(gamma_m)
4785
4786 freq = self.measured[0].frequency
4787 self._solved_l = match_l
4788 self._solved_c = match_c
4789 self._solved_m = Network(s=gamma_m, frequency=freq, name='LRRM match')
4790 self._solved_r1 = Network(s=gr1, frequency=freq, name='LRRM reflect 1')
4791 self._solved_r2 = Network(s=gr2, frequency=freq, name='LRRM reflect 2')
4792
4793 # Calculate error matrices
4794 t10 = np.transpose(np.array([[ones, x], [gr1, gr2*x]]), [2,0,1]) \
4795 @ inv(np.transpose(np.array([[ones,ones],[r11, r21]]), [2,0,1]))
4796 t23 = np.transpose((1/z)*np.array([[ones, y], [gr1, gr2*y]]), [2,0,1]) \
4797 @ inv(np.transpose(np.array([[ones,ones],[r12, r22]]), [2,0,1]))
4798
4799 Smat1 = t2s(t10)
4800 Smat2 = t2s(t23)
4801
4802 # Convert the error coefficients to
4803 # definitions used by the EightTerm class.
4804 dx = linalg.det(Smat1)
4805 dy = linalg.det(Smat2)
4806
4807 k = Smat1[:,0,1]/Smat2[:,0,1]
4808
4809 # Error coefficients
4810 e = [Smat1[:,0,0],
4811 Smat1[:,1,1],
4812 dx,
4813 Smat2[:,0,0],
4814 Smat2[:,1,1],
4815 dy,
4816 k]
4817
4818 self._coefs = {\
4819 'forward directivity':e[1],
4820 'forward source match':e[0],
4821 'forward reflection tracking':e[0]*e[1]-e[2],
4822 'reverse directivity':e[4],
4823 'reverse source match':e[3],
4824 'reverse reflection tracking':e[4]*e[3]- e[5],
4825 'k':e[6],
4826 }
4827
4828 self._coefs['forward isolation'] = self.isolation.s[:,1,0].flatten()
4829 self._coefs['reverse isolation'] = self.isolation.s[:,0,1].flatten()
4830
4831 if self.switch_terms is not None:
4832 self._coefs.update({
4833 'forward switch term': self.switch_terms[0].s.flatten(),
4834 'reverse switch term': self.switch_terms[1].s.flatten(),
4835 })
4836 else:
4837 self._coefs.update({
4838 'forward switch term': np.zeros(fpoints, dtype=complex),
4839 'reverse switch term': np.zeros(fpoints, dtype=complex),
4840 })
4841 # output is a dictionary of information
4842 self._output_from_run = {
4843 'error vector':e
4844 }
4845
4846 @property
4847 def solved_l(self):
4848 """
4849 Solved inductance of the load
4850 """
4851 try:
4852 return self._solved_l
4853 except(AttributeError):
4854 self.run()
4855 return self._solved_l
4856
4857 @property
4858 def solved_c(self):
4859 """
4860 Solved capacitance of the load.
4861 Zero if match_fit != 'lc'.
4862 """
4863 try:
4864 return self._solved_c
4865 except(AttributeError):
4866 self.run()
4867 return self._solved_c
4868
4869 @property
4870 def solved_m(self):
4871 """
4872 Solved match
4873 """
4874 try:
4875 return self._solved_m
4876 except(AttributeError):
4877 self.run()
4878 return self._solved_m
4879
4880 @property
4881 def solved_r1(self):
4882 """
4883 Solved reflect1
4884 """
4885 try:
4886 return self._solved_r1
4887 except(AttributeError):
4888 self.run()
4889 return self._solved_r1
4890
4891 @property
4892 def solved_r2(self):
4893 """
4894 Solved reflect2
4895 """
4896 try:
4897 return self._solved_r2
4898 except(AttributeError):
4899 self.run()
4900 return self._solved_r2
4901
4902
4903 class MRC(UnknownThru):
4904 """
4905 Misalignment Resistance Calibration.
4906
4907 This is an error-box based calibration that is a combination of the
4908 SDDL[1]_ and the UnknownThru[2]_, algorithms.
4909 The self-calibration aspects of these two algorithms alleviate the
4910 need to know the phase of the delay shorts, as well as the exact
4911 response of the thru. Thus the calibration is resistant to
4912 waveguide flange misalignment.
4913
4914
4915 References
4916 ----------
4917 .. [1] Z. Liu and R. M. Weikle, "A reflectometer calibration method resistant to waveguide flange misalignment,"
4918 Microwave Theory and Techniques, IEEE Transactions on, vol. 54, no. 6, pp. 2447-2452, Jun. 2006.
4919
4920 .. [2] A. Ferrero and U. Pisani, "Two-port network analyzer calibration using an unknown `thru,`"
4921 IEEE Microwave and Guided Wave Letters, vol. 2, no. 12, pp. 505-507, 1992.
4922
4923
4924 """
4925
4926 family = 'MRC'
4927
4928 # Use standard SDDL calibration to solve two 1-port error boxes
4929 # before the Thru calibration. This overrides the algorithm used
4930 # by UnknownThru.run()
4931 _ONEPORT_ALGO = SDDL
4932
4933 def __init__(self, measured, ideals, *args, **kwargs):
4934 r"""
4935 MRC Initializer
4936
4937 This calibration takes exactly 5 standards, which must be in the
4938 order:
4939
4940 [Short, DelayShort1, DelayShort1, Load, Thru]
4941
4942 The ideals for the delay shorts are not used and the ideal for
4943 the *thru* is only used to choose
4944 the sign of a square root. Thus, it only has to be have s21, s12
4945 known within :math:`\pi` phase.
4946
4947
4948 Parameters
4949 --------------
4950 measured : list/dict of :class:`~skrf.network.Network` objects
4951 Raw measurements of the calibration standards. The order
4952 must align with the `ideals` parameter
4953
4954 ideals : list/dict of :class:`~skrf.network.Network` objects
4955 Predicted ideal response of the calibration standards.
4956 The order must align with `ideals` list
4957
4958 switch_terms : tuple of :class:`~skrf.network.Network` objects
4959 the pair of switch terms in the order (forward, reverse)
4960 """
4961
4962 UnknownThru.__init__(self, measured = measured, ideals = ideals,
4963 **kwargs)
4964
4965
4966 class SixteenTerm(Calibration):
4967 """
4968 General SixteenTerm (aka Error-box) Two-port calibration.
4969
4970 16-term error model is a complete error model that can solve for leakages between
4971 the different VNA receivers.
4972
4973 There are several different combinations of calibration standards that can
4974 be used. At least five two port measurements are needed. Using through, open,
4975 short, and load standards some combinations result in singular matrix.
4976 See [1]_ for list of non-singular combinations.
4977
4978 References
4979 -----------
4980 .. [1] K. J. Silvonen, "Calibration of 16-term error model (microwave measurement),"
4981 in Electronics Letters, vol. 29, no. 17, pp. 1544-1545, 19 Aug. 1993.
4982 """
4983
4984 family = 'SixteenTerm'
4985 def __init__(self, measured, ideals, switch_terms=None,
4986 *args, **kwargs):
4987 """
4988 SixteenTerm Initializer.
4989
4990 Notes
4991 -----
4992 Switch terms are already assumed to be corrected since the ordinary
4993 correction equations are not valid if the crosstalk is significant.
4994
4995 Parameters
4996 ----------
4997 measured : list/dict of :class:`~skrf.network.Network` objects
4998 Raw measurements of the calibration standards. The order
4999 must align with the `ideals` parameter
5000
5001 ideals : list/dict of :class:`~skrf.network.Network` objects
5002 Predicted ideal response of the calibration standards.
5003 The order must align with `ideals` list
5004
5005 switch_terms : tuple of :class:`~skrf.network.Network` objects
5006 the pair of switch terms in the order (forward, reverse)
5007 """
5008
5009 self.switch_terms = switch_terms
5010 if switch_terms is None:
5011 warn('No switch terms provided', stacklevel=2)
5012
5013 Calibration.__init__(self,
5014 measured = measured,
5015 ideals = ideals,
5016 **kwargs)
5017
5018 def unterminate(self,ntwk):
5019 """
5020 Unterminate switch terms from a raw measurement.
5021
5022 See Also
5023 --------
5024 calibration.unterminate
5025 """
5026 if self.switch_terms is not None:
5027 gamma_f, gamma_r = self.switch_terms
5028 return unterminate(ntwk, gamma_f, gamma_r)
5029
5030 else:
5031 return ntwk
5032
5033 def terminate(self, ntwk):
5034 """
5035 Terminate a network with switch terms.
5036
5037 See Also
5038 --------
5039 calibration.terminate
5040 """
5041 if self.switch_terms is not None:
5042 gamma_f, gamma_r = self.switch_terms
5043 return terminate(ntwk, gamma_f, gamma_r)
5044 else:
5045 return ntwk
5046
5047
5048 @property
5049 def measured_unterminated(self):
5050 return [self.unterminate(k) for k in self.measured]
5051
5052 def run(self):
5053 numStds = self.nstandards
5054 numCoefs = 15
5055
5056 mList = [k.s for k in self.measured_unterminated]
5057 iList = [k.s for k in self.ideals]
5058
5059 fLength = len(mList[0])
5060 #initialize outputs
5061 error_vector = np.zeros(shape=(fLength,numCoefs),dtype=complex)
5062 residuals = np.zeros(shape=(fLength,4*numStds-numCoefs),dtype=complex)
5063 Q = np.zeros((numStds*4, 15),dtype=complex)
5064 M = np.zeros((numStds*4, 1),dtype=complex)
5065 # loop through frequencies and form m, a vectors and
5066 # the matrix M.
5067 #i[j,k] = Actual S-parameters
5068 #m[j,k] = Measured S-parameters
5069 #t15 is normalized to one
5070 for f in list(range(fLength)):
5071 # loop through standards and fill matrix
5072 for k in list(range(numStds)):
5073 m,i = mList[k][f,:,:],iList[k][f,:,:] # 2x2 s-matrices
5074 Q[k*4:k*4+4,:] = np.array([
5075 [ i[0,0], i[1,0], 0 , 0 , 1, 0, 0, 0, -m[0,0]*i[0,0], -m[0,0]*i[1,0], -m[0,1]*i[0,0], -m[0,1]*i[1,0], -m[0,0] , 0 , -m[0,1] ], # noqa: E501
5076 [ i[0,1], i[1,1], 0 , 0 , 0, 1, 0, 0, -m[0,0]*i[0,1], -m[0,0]*i[1,1], -m[0,1]*i[0,1], -m[0,1]*i[1,1], 0 , -m[0,0] , 0 ], # noqa: E501
5077 [ 0 , 0 , i[0,0], i[1,0], 0, 0, 1, 0, -m[1,0]*i[0,0], -m[1,0]*i[1,0], -m[1,1]*i[0,0], -m[1,1]*i[1,0], -m[1,0] , 0 , -m[1,1] ], # noqa: E501
5078 [ 0 , 0 , i[0,1], i[1,1], 0 ,0 ,0, 1, -m[1,0]*i[0,1], -m[1,0]*i[1,1], -m[1,1]*i[0,1], -m[1,1]*i[1,1], 0 , -m[1,0] , 0 ], # noqa: E501
5079 ])
5080 #pdb.set_trace()
5081 M[k*4:k*4+4,:] = np.array([\
5082 [ 0 ],\
5083 [ m[0,1] ],\
5084 [ 0 ],\
5085 [ m[1,1] ],\
5086 ])
5087
5088 ## calculate least squares
5089 error_vector_at_f, residuals_at_f = np.linalg.lstsq(Q,M,rcond=None)[0:2]
5090 ##if len (residualsTmp )==0:
5091 ## raise ValueError( 'matrix has singular values, check standards')
5092
5093
5094 error_vector[f,:] = error_vector_at_f.flatten()
5095 residuals[f,:] = residuals_at_f
5096
5097 e = error_vector
5098
5099 #Normalize e23 = 1
5100 c = e[:,12]/(e[:,12]-e[:,13]*e[:,14])
5101 for i in range(len(e[0])):
5102 e[:,i] *= c
5103
5104 T1 = np.zeros(shape=(fLength, 2, 2), dtype=complex)
5105 T2 = np.zeros(shape=(fLength, 2, 2), dtype=complex)
5106 T3 = np.zeros(shape=(fLength, 2, 2), dtype=complex)
5107 T4 = np.zeros(shape=(fLength, 2, 2), dtype=complex)
5108
5109 T1[:,0,0] = e[:,0]
5110 T1[:,0,1] = e[:,1]
5111 T1[:,1,0] = e[:,2]
5112 T1[:,1,1] = e[:,3]
5113
5114 T2[:,0,0] = e[:,4]
5115 T2[:,0,1] = e[:,5]
5116 T2[:,1,0] = e[:,6]
5117 T2[:,1,1] = e[:,7]
5118
5119 T3[:,0,0] = e[:,8]
5120 T3[:,0,1] = e[:,9]
5121 T3[:,1,0] = e[:,10]
5122 T3[:,1,1] = e[:,11]
5123
5124 T4[:,0,0] = e[:,12]
5125 T4[:,0,1] = e[:,13]
5126 T4[:,1,0] = e[:,14]
5127 T4[:,1,1] = c
5128
5129 # put the error vector into human readable dictionary
5130 e1, e2, e3, e4 = self.E_matrices(T1, T2, T3, T4)
5131
5132
5133 self._coefs = {\
5134 'forward directivity':e1[:,0,0],
5135 'reverse directivity':e1[:,1,1],
5136 'forward source match':e4[:,0,0],
5137 'reverse source match':e4[:,1,1],
5138 'forward reflection tracking':e2[:,0,0]*e3[:,0,0],
5139 'reverse reflection tracking':e2[:,1,1],
5140 'k':e3[:,0,0],
5141 'forward isolation':e1[:,1,0],
5142 'reverse isolation':e1[:,0,1],
5143 'forward port 1 isolation':e3[:,1,0],
5144 'reverse port 1 isolation':e2[:,0,1],
5145 'forward port 2 isolation':e2[:,1,0],
5146 'reverse port 2 isolation':e3[:,0,1],
5147 'forward port isolation':e4[:,1,0],
5148 'reverse port isolation':e4[:,0,1],
5149 }
5150
5151 if self.switch_terms is not None:
5152 self._coefs.update({
5153 'forward switch term': self.switch_terms[0].s.flatten(),
5154 'reverse switch term': self.switch_terms[1].s.flatten(),
5155 })
5156 else:
5157 self._coefs.update({
5158 'forward switch term': np.zeros(fLength, dtype=complex),
5159 'reverse switch term': np.zeros(fLength, dtype=complex),
5160 })
5161
5162 # output is a dictionary of information
5163 self._output_from_run = {
5164 'error vector':e,
5165 'residuals':residuals
5166 }
5167
5168 return None
5169
5170 def apply_cal(self, ntwk):
5171 """Applies the calibration to the input network.
5172 Inverse of `embed`.
5173 Parameters
5174 ----------
5175 ntwk : :class:`~skrf.network.Network`
5176 Uncalibrated input network.
5177 Returns
5178 -------
5179 caled : :class:`~skrf.network.Network`
5180 Calibrated network.
5181 """
5182 caled = ntwk.copy()
5183
5184 T1,T2,T3,T4 = self.T_matrices
5185
5186 caled = self.unterminate(caled)
5187 caled.s = linalg.inv(-caled.s @ T3 + T1) @ (caled.s @ T4 - T2)
5188
5189 return caled
5190
5191 def embed(self, ntwk):
5192 """Applies the error boxes to the calibrated input network.
5193 Inverse of `apply_cal`.
5194 Parameters
5195 ----------
5196 ntwk : :class:`~skrf.network.Network`
5197 Calibrated input network.
5198 Returns
5199 -------
5200 embedded : :class:`~skrf.network.Network`
5201 Network with error boxes applied.
5202 """
5203 embedded = ntwk.copy()
5204
5205 T1,T2,T3,T4 = self.T_matrices
5206
5207 embedded.s = (T1 @ ntwk.s + T2) @ linalg.inv(T3 @ ntwk.s + T4)
5208 embedded = self.terminate(embedded)
5209
5210 return embedded
5211
5212 @property
5213 def T_matrices(self):
5214 """
5215 Intermediate matrices used for embedding and de-embedding.
5216
5217 Returns
5218 -------
5219 T1,T2,T3,T4 : numpy ndarray
5220
5221 """
5222 ec = self.coefs
5223 npoints = len(ec['forward directivity'])
5224
5225 e100 = ec['forward directivity']
5226 e111 = ec['reverse directivity']
5227 e400 = ec['forward source match']
5228 e411 = ec['reverse source match']
5229 e300 = ec['k']
5230 e311 = np.ones(npoints)
5231 e200 = ec['forward reflection tracking']/e300
5232 e211 = ec['reverse reflection tracking']
5233 e110 = ec['forward isolation']
5234 e101 = ec['reverse isolation']
5235 e301 = ec['reverse port 2 isolation']
5236 e310 = ec['forward port 1 isolation']
5237 e201 = ec['reverse port 1 isolation']
5238 e210 = ec['forward port 2 isolation']
5239 e401 = ec['reverse port isolation']
5240 e410 = ec['forward port isolation']
5241
5242 E1 = np.array([
5243 [ e100 , e101],
5244 [ e110 , e111]
5245 ]).transpose(2,0,1)
5246 E2 = np.array([
5247 [ e200 , e201],
5248 [ e210 , e211]
5249 ]).transpose(2,0,1)
5250 E3 = np.array([
5251 [ e300 , e301],
5252 [ e310 , e311]
5253 ]).transpose(2,0,1)
5254 E4 = np.array([
5255 [ e400 , e401],
5256 [ e410 , e411]
5257 ]).transpose(2,0,1)
5258
5259 invE3 = linalg.inv(E3)
5260 T1 = E2 - E1 @ invE3 @ E4
5261 T2 = E1 @ invE3
5262 T3 = -invE3 @ E4
5263 T4 = invE3
5264
5265 return T1, T2, T3, T4
5266
5267 def E_matrices(self, T1, T2, T3, T4):
5268 """
5269 Convert solved calibration T matrices to S-parameters.
5270
5271 Returns
5272 -------
5273 E1,E2,E3,E4 : numpy ndarray
5274 """
5275
5276 invT4 = linalg.inv(np.array(T4))
5277
5278 E1 = T2 @ invT4
5279 E2 = T1 - T2 @ invT4 @ T3
5280 E3 = invT4
5281 E4 = -invT4 @ T3
5282
5283 return E1, E2, E3, E4
5284
5285 def renormalize(self, z0_old, z0_new):
5286 """
5287 Renormalizes the calibration error boxes to a new reference impedance.
5288 """
5289
5290 Z = np.zeros((len(self.coefs['k']), 4, 4), dtype=complex)
5291 Z[:,0,0] = self.coefs['forward directivity']
5292 Z[:,1,1] = self.coefs['forward source match']
5293 Z[:,2,2] = self.coefs['reverse source match']
5294 Z[:,3,3] = self.coefs['reverse directivity']
5295 Z[:,1,0] = self.coefs['k']
5296 Z[:,0,1] = self.coefs['forward reflection tracking'] / self.coefs['k']
5297 Z[:,2,3] = 1
5298 Z[:,3,2] = self.coefs['reverse reflection tracking']
5299 Z[:,3,0] = self.coefs['forward isolation']
5300 Z[:,0,3] = self.coefs['reverse isolation']
5301 Z[:,2,1] = self.coefs['forward port isolation']
5302 Z[:,1,2] = self.coefs['reverse port isolation']
5303 Z[:,2,0] = self.coefs['forward port 1 isolation']
5304 Z[:,0,2] = self.coefs['reverse port 1 isolation']
5305 Z[:,3,1] = self.coefs['forward port 2 isolation']
5306 Z[:,1,3] = self.coefs['reverse port 2 isolation']
5307
5308 #Port impedances before renormalization.
5309 #Only the DUT side (port 2 and 3) is renormalized.
5310 #VNA side (port 1 and 4) stays unchanged.
5311 z = np.zeros((len(self.coefs['k']),4), dtype=complex)
5312 z[:,0] = z0_new
5313 z[:,1] = z0_old
5314 z[:,2] = z0_old
5315 z[:,3] = z0_new
5316
5317 Z = renormalize_s(Z, z, z0_new, s_def='traveling')
5318
5319 self.coefs['k'] = Z[:,1,0] / Z[:,2,3]
5320 self.coefs['forward directivity'] = Z[:,0,0]
5321 self.coefs['forward source match'] = Z[:,1,1]
5322 self.coefs['reverse source match'] = Z[:,2,2]
5323 self.coefs['reverse directivity'] = Z[:,3,3]
5324 self.coefs['forward reflection tracking'] = Z[:,1,0] * Z[:,0,1]
5325 self.coefs['reverse reflection tracking'] = Z[:,2,3] * Z[:,3,2]
5326 self.coefs['forward isolation'] = Z[:,3,0]
5327 self.coefs['reverse isolation'] = Z[:,0,3]
5328 self.coefs['forward port isolation'] = Z[:,2,1]
5329 self.coefs['reverse port isolation'] = Z[:,1,2]
5330 self.coefs['forward port 1 isolation'] = Z[:,2,0] / Z[:,2,3]
5331 self.coefs['reverse port 1 isolation'] = Z[:,0,2] * Z[:,2,3]
5332 self.coefs['forward port 2 isolation'] = Z[:,3,1] * Z[:,2,3]
5333 self.coefs['reverse port 2 isolation'] = Z[:,1,3] / Z[:,2,3]
5334 return None
5335
5336
5337 class LMR16(SixteenTerm):
5338 """
5339 SixteenTerm Load-Match-Reflect self-calibration.
5340
5341 16-Term self calibration for leaky VNA. Implementation is based on [1]_.
5342
5343 Needs five standards to be measured and given in this order:
5344 * Through
5345 * Match-match
5346 * Reflect-reflect
5347 * Reflect-match
5348 * Match-reflect
5349
5350 Reflect standard needs to be very reflective and same in all measurements.
5351 Matching of through and match standards is assumed to be perfect.
5352 Loss of the through is assumed to be zero, but its length can be non-zero.
5353
5354 Only reflect or through standard needs to be known and the other one will be
5355 solved during the calibration. Solved S-parameters of the standards
5356 can be accessed with LMR16.solved_through and LMR16.solved_reflect.
5357
5358 Switch termination is already assumed to be done either by the previous calibration or
5359 during the measurements. Regular switch correction equations used with
5360 EightTerm calibration can't be used if leakage is significant.
5361
5362 References
5363 ------------
5364 .. [1] K. Silvonen, "LMR 16-a self-calibration procedure for a leaky network analyzer,"
5365 in IEEE Transactions on Microwave Theory and Techniques, vol. 45, no. 7, pp. 1041-1049, Jul 1997
5366
5367 """
5368
5369 family = 'SixteenTerm'
5370 def __init__(self, measured, ideals, ideal_is_reflect=True, sign=None,
5371 switch_terms=None, *args, **kwargs):
5372 r"""
5373 LMR16 initializer.
5374
5375 Due to needing to solve a second order equation during the calibration a
5376 choice must be taken on the correct root. Sign argument, +1 or -1, can be
5377 given to make the root choice.
5378
5379 If sign argument is not given it is tried to be solved automatically by
5380 choosing the sign that makes :math:`k = \frac{t_{15}}{t_{12}}` closer to +1, which holds
5381 if test fixture is symmetric.
5382
5383 Parameters
5384 --------------
5385 measured : list/dict of :class:`~skrf.network.Network` objects
5386 Raw measurements of the calibration standards.
5387
5388 ideals : list/dict of :class:`~skrf.network.Network` objects
5389 Estimated response of the reflect or through calibration standard.
5390
5391 ideal_is_reflect : Boolean
5392 True if given ideal is reflect and False if ideal is through
5393
5394 sign : +1,-1 or None
5395 Sign to be used for the root choice.
5396 """
5397
5398 self.switch_terms = switch_terms
5399 if switch_terms is None:
5400 warn('No switch terms provided', stacklevel=2)
5401
5402 if isinstance(ideals, Network):
5403 ideals = [ideals]
5404 if len(ideals) != 1:
5405 raise ValueError("One ideal must be given: Through or reflect definition.")
5406 if not ideal_is_reflect:
5407 self.through = ideals[0].copy()
5408 self.reflect = None
5409 self._solved_through = self.through
5410 self._solved_reflect = Network(s=[0]*len(self.through.f), f=self.through.f, f_unit='Hz')
5411 else:
5412 self.through = None
5413 self.reflect = ideals[0].copy()
5414 self._solved_through = Network(s=[[[0,1],[1,0]]]*len(self.reflect.f), f=self.reflect.f, f_unit='Hz')
5415 self._solved_reflect = self.reflect
5416
5417 if len(measured) != 5:
5418 raise ValueError("5 Measurements are needed: T, M-M, R-R, R-M and M-R")
5419
5420 self.measured = measured
5421 self.sign = sign
5422
5423 Calibration.__init__(self,
5424 measured = measured,
5425 ideals = ideals,
5426 sloppy_input=False,
5427 self_calibration=True,
5428 **kwargs)
5429
5430 def run(self):
5431 mList = [k.s for k in self.measured_unterminated]
5432
5433 fLength = len(mList[0])
5434
5435 inv = linalg.inv
5436
5437 T1 = []
5438 T2 = []
5439 T3 = []
5440 T4 = []
5441
5442 auto_sign = self.sign is None
5443
5444 for f in range(fLength):
5445 ma = mList[0][f] #Through
5446 mb = mList[1][f] #Match-match
5447 mc = mList[2][f] #Reflect-reflect
5448 md = mList[3][f] #Reflect-match
5449 me = mList[4][f] #Match-reflect
5450
5451 nn = inv(me-ma).dot(mb-me)
5452 mm = (ma-mc).dot(nn)
5453 oo = mb-mc
5454 rr = inv(md-ma).dot(mb-md)
5455 pp = (ma-mc).dot(rr)
5456
5457 m = (pp[1,0] + oo[1,0])*mm[1,1] - (pp[1,1] + oo[1,1])*mm[1,0]
5458 n = oo[1,0]*pp[0,1] - oo[1,1]*pp[0,0]
5459 o = (mm[0,1]+ oo[0,1])*pp[0,0] - (mm[0,0] + oo[0,0])*pp[0,1]
5460 p = oo[0,1]*mm[1,0] - oo[0,0]*mm[1,1]
5461
5462 #One of the coefficients is normalized to one
5463 t12 = 1.0
5464
5465 auto_sign_abs = []
5466 if auto_sign:
5467 self.sign = 1
5468
5469 for sign_tries in [0,1,2]:
5470 gt = self.sign*np.sqrt(m*o/(n*p))
5471 if self.through is None:
5472 g = self.reflect.s[f][0,0]
5473 t = g/gt
5474 self._solved_through.s[f] = np.array([[0,t],[t,0]])
5475 else:
5476 t = self.through.s[f][1,0]
5477 g = gt*t
5478 self._solved_reflect.s[f] = np.array([g])
5479 t15 = -(p/o)*(pp[0,0]/mm[1,1])*gt*t12
5480 #If correct sign is not specified try to choose it based
5481 #on the fact that with correct sign t15/t12 ~= +1
5482 #Assuming that test fixtures are symmetric
5483 if auto_sign:
5484 auto_sign_abs.append(np.abs(1 - t15/t12))
5485 if sign_tries == 0:
5486 self.sign = -self.sign
5487 if sign_tries == 1:
5488 if auto_sign_abs[0] < auto_sign_abs[1]:
5489 self.sign = 1
5490 else:
5491 self.sign = -1
5492 else:
5493 break
5494
5495
5496 t13 = -pp[0,1]/pp[0,0]*t15
5497 t14 = -mm[1,0]/mm[1,1]*t12
5498
5499 #Normalize e23 = 1
5500 c = 1/(t15 - t13*t14)
5501
5502 t8 = (rr[0,0]*t12 + rr[0,1]*t14)*(1./g) - t13/t
5503 t9 = (nn[0,0]*t13 + nn[0,1]*t15)*(1./g) - t12/t
5504 t10 = (rr[1,0]*t12 + rr[1,1]*t14)*(1./g) - t15/t
5505 t11 = (nn[1,0]*t13 + nn[1,1]*t15)*(1./g) - t14/t
5506 t0 = mc[0,0]*t8 + mc[0,1]*t10 - (1./g)*(oo[0,0]*t12+oo[0,1]*t14)
5507 t1 = mc[0,0]*t9 + mc[0,1]*t11 - (1./g)*(oo[0,0]*t13+oo[0,1]*t15)
5508 t2 = mc[1,0]*t8 + mc[1,1]*t10 - (1./g)*(oo[1,0]*t12+oo[1,1]*t14)
5509 t3 = mc[1,0]*t9 + mc[1,1]*t11 - (1./g)*(oo[1,0]*t13+oo[1,1]*t15)
5510 t4 = mb[0,0]*t12 + mb[0,1]*t14
5511 t5 = mb[0,0]*t13 + mb[0,1]*t15
5512 t6 = mb[1,0]*t12 + mb[1,1]*t14
5513 t7 = mb[1,0]*t13 + mb[1,1]*t15
5514
5515 T1.append( c*np.array([[t0,t1],[t2,t3]]) )
5516 T2.append( c*np.array([[t4,t5],[t6,t7]]) )
5517 T3.append( c*np.array([[t8,t9],[t10,t11]]) )
5518 T4.append( c*np.array([[t12,t13],[t14,t15]]) )
5519
5520 T1 = np.array(T1)
5521 T2 = np.array(T2)
5522 T3 = np.array(T3)
5523 T4 = np.array(T4)
5524
5525 #Convert T-matrix to S-parameters
5526 #and put error terms in human readable form
5527 e1,e2,e3,e4 = self.E_matrices(T1, T2, T3, T4)
5528
5529 self._coefs = {\
5530 'forward directivity':e1[:,0,0],
5531 'reverse directivity':e1[:,1,1],
5532 'forward source match':e4[:,0,0],
5533 'reverse source match':e4[:,1,1],
5534 'forward reflection tracking':e2[:,0,0]*e3[:,0,0],
5535 'reverse reflection tracking':e2[:,1,1],
5536 'k':e3[:,0,0],
5537 'forward isolation':e1[:,1,0],
5538 'reverse isolation':e1[:,0,1],
5539 'forward port 1 isolation':e3[:,1,0],
5540 'reverse port 1 isolation':e2[:,0,1],
5541 'forward port 2 isolation':e2[:,1,0],
5542 'reverse port 2 isolation':e3[:,0,1],
5543 'forward port isolation':e4[:,1,0],
5544 'reverse port isolation':e4[:,0,1],
5545 }
5546
5547 if self.switch_terms is not None:
5548 self._coefs.update({
5549 'forward switch term': self.switch_terms[0].s.flatten(),
5550 'reverse switch term': self.switch_terms[1].s.flatten(),
5551 })
5552 else:
5553 self._coefs.update({
5554 'forward switch term': np.zeros(fLength, dtype=complex),
5555 'reverse switch term': np.zeros(fLength, dtype=complex),
5556 })
5557
5558
5559 return None
5560
5561 @classmethod
5562 def from_coefs(cls, frequency, coefs, **kwargs):
5563 """
5564 Create a calibration from its error coefficients.
5565
5566 Parameters
5567 ----------
5568 frequency : :class:`~skrf.frequency.Frequency`
5569 frequency info, (duh)
5570 coefs : dict of numpy arrays
5571 error coefficients for the calibration
5572
5573 See Also
5574 --------
5575 Calibration.from_coefs_ntwks
5576
5577 """
5578 n = Network(frequency = frequency,
5579 s = rand_c(frequency.npoints,2,2))
5580 measured = [n,n,n,n,n]
5581
5582 if 'forward switch term' in coefs:
5583 switch_terms = (Network(frequency = frequency,
5584 s=coefs['forward switch term']),
5585 Network(frequency = frequency,
5586 s=coefs['reverse switch term']))
5587 kwargs['switch_terms'] = switch_terms
5588
5589 cal = cls(measured, measured[0], **kwargs)
5590 cal.coefs = coefs
5591 cal.family += '(fromCoefs)'
5592 return cal
5593
5594 @property
5595 def residual_ntwks(self):
5596 """
5597 Dictionary of residual Networks.
5598
5599 These residuals are complex differences between the ideal
5600 standards and their corresponding corrected measurements.
5601
5602 """
5603 #Runs the calibration if needed
5604 caled_ntwks = self.caled_ntwks
5605
5606 r = self.solved_reflect
5607 m = Network(s=[0]*len(self.solved_reflect.f), f=self.solved_reflect.f, f_unit='Hz')
5608 mm = two_port_reflect(m, m)
5609 mr = two_port_reflect(m, r)
5610 rm = two_port_reflect(r, m)
5611 rr = two_port_reflect(r, r)
5612
5613 ideals = [self.solved_through, mm, rr, rm, mr]
5614
5615 return [caled - ideal for (ideal, caled) in zip(ideals, caled_ntwks)]
5616
5617 @property
5618 def solved_through(self):
5619 """
5620 Return the solved through or the ideal through if reflect was solved.
5621 """
5622 if not hasattr(self, '_coefs'):
5623 self.run()
5624 return self._solved_through
5625
5626 @property
5627 def solved_reflect(self):
5628 """
5629 Return the solved reflect or the ideal reflect if through was solved.
5630 """
5631 if not hasattr(self, '_coefs'):
5632 self.run()
5633 return self._solved_reflect
5634
5635
5636 class Normalization(Calibration):
5637 """
5638 Simple Thru Normalization.
5639
5640 For calibration the S parameters of the network are divided by average of
5641 the measured networks. The ideal networks are not used in the calibration.
5642 """
5643 def run(self):
5644 pass
5645 def apply_cal(self, input_ntwk):
5646 return input_ntwk/average(self.measured)
5647
5648 class MultiportCal:
5649 """
5650 Multi-port VNA calibration using two-port calibration method.
5651
5652 cal_dict should be a dictionary with key being two-tuples of port numbers,
5653 such as (0, 1), (0, 2), ...
5654
5655 For each key it should have another dictionary as value. The two required
5656 keys are 'method' that should be the two-port calibration class that is used
5657 to calibrate that two-port combination (for example SOLT, EightTerm, TRL)
5658 and 'measured' which is a list of measured Networks. Other inputs required
5659 by the two-port calibration should be given as additional keys (for example
5660 'ideals', 'switch_terms', ...).
5661
5662 There should be one common port in all measurements. For example in case of
5663 4-port calibration one possible choice would be to make three measurements
5664 between ports: 0-1, 0-2, and 0-3.
5665
5666 The list of measured networks can be given as either two-ports, in which
5667 case it's assumed that the two ports corresponds to the ports in the key, or
5668 multi-ports in which case a subnetwork is taken for calibration according to
5669 the key.
5670
5671 Example cal_dict for three port measurement::
5672
5673 {(0,1): {'method':SOLT, 'measured': [list of measured networks], 'ideals': [list of ideal networks]},
5674 (0,2): {'method':SOLT, 'measured': [list of measured networks], 'ideals': [list of ideal networks]}
5675 }
5676
5677 `isolation` is optional N-port network of all ports matched for isolation
5678 calibration. If None, no isolation calibration is performed.
5679
5680 Parameters
5681 ----------
5682 cal_dict : dictionary
5683 Dictionary of port pair keys as specified above.
5684 isolation: :class:`~skrf.network.Network` or None
5685 N-port measurement of all matched ports for isolation calibration.
5686 None to skip isolation calibration.
5687
5688 See Also
5689 --------
5690 calibration.MultiportSOLT
5691 """
5692
5693 family = 'Multiport'
5694 def __init__(self, cal_dict, isolation=None):
5695 if not isinstance(cal_dict, dict):
5696 raise ValueError("cal_dict not dictionary.")
5697 nports = None
5698 max_key_nports = 0
5699 min_key_nports = float('inf')
5700 z0 = None
5701 frequency = None
5702 for k, c in cal_dict.items():
5703 if len(k) != 2:
5704 raise ValueError(f"Invalid cal_dict key {k}. Expected tuple of length two.")
5705 if not isinstance(k[0], int) or not isinstance(k[1], int):
5706 raise ValueError("cal_dict key should be tuple of ints.")
5707 max_key_nports = max(max_key_nports, max(k[0], k[1]))
5708 min_key_nports = min(min_key_nports, min(k[0], k[1]))
5709 if not isinstance(c, dict):
5710 raise ValueError(f"cal_dict[{k}] not dictionary.")
5711 if 'method' not in c:
5712 raise ValueError(f"cal_dict[{k}] missing key 'method'.")
5713 if 'measured' not in c:
5714 raise ValueError(f"cal_dict[{k}] missing key 'measured'.")
5715 for m in c['measured']:
5716 if not isinstance(m, Network):
5717 raise ValueError(f"Expected Network in cal_dict[{k}]['measured']")
5718 if nports is None:
5719 nports = m.nports
5720 if m.nports not in [2, nports]:
5721 raise ValueError("Measurement have inconsistent number of ports.")
5722 if z0 is None:
5723 z0 = m.z0[0,0]
5724 elif m.z0[0,0] != z0:
5725 raise ValueError("Inconsistent z0 in measured.")
5726 if frequency is None:
5727 frequency = m.frequency
5728 elif m.frequency != frequency:
5729 raise ValueError("Inconsistent frequency in measured.")
5730 if "ideals" in c and z0 is not None:
5731 for n in c["ideals"]:
5732 if n.z0[0,0] != z0:
5733 raise ValueError(f"Ideals and measured z0 doesn't match. {n.z0[0,0]} and {z0}")
5734
5735 self.nports = nports = max_key_nports + 1
5736 if min_key_nports < 0:
5737 raise ValueError("Negative port number found. Minimum should be zero.")
5738 if min_key_nports != 0:
5739 raise ValueError("Missing port 0. Make sure that ports are zero-indexed.")
5740 if max_key_nports < 2:
5741 raise ValueError("Less than three ports found. Use two-port or one-port calibration directly.")
5742
5743 if isolation is not None:
5744 # Zero diagonal so that network can be simply subtracted
5745 isolation = isolation.copy()
5746 if isolation.nports != nports:
5747 raise ValueError("Isolation network should have the same number of ports as measurements.")
5748 for i in range(nports):
5749 isolation.s[:,i,i] = 0
5750 else:
5751 s = np.zeros((len(frequency), nports, nports), dtype=complex)
5752 isolation = Network(s=s, z0=z0, frequency=frequency)
5753 self.isolation = isolation
5754 self.cal_dict = cal_dict
5755 self.z0 = z0
5756 self.frequency = frequency
5757 self.cals = {}
5758
5759 def run(self):
5760 """
5761 Run the calibration algorithm.
5762 """
5763 nports = self.nports
5764 p_count = defaultdict(int)
5765 self.terminations = [None for i in range(nports)]
5766 self._coefs = [{} for i in range(nports)]
5767 for p in self.cal_dict.keys():
5768 p_count[p[0]] += 1
5769 p_count[p[1]] += 1
5770 port_multiples = sorted(p_count.values())
5771 if port_multiples[-2] != 1:
5772 # It's easy to put `k` in non-repeated ports if one port is always used.
5773 # I think this limitation could be removed if the `k` would be
5774 # solved to be consistent in repeated ports.
5775 raise ValueError("Invalid thru port combinations. One port should be common in all thru measurements.")
5776 for p in self.cal_dict.keys():
5777 c = self.cal_dict[p].copy()
5778 if 'ideals' in c:
5779 ideals = [i if i.nports == 2 else subnetwork(i, p) for i in c['ideals']]
5780 c['ideals'] = ideals
5781 c['measured'] = [m - subnetwork(self.isolation, p) if m.nports == 2 else subnetwork(m - self.isolation, p)
5782 for m in c['measured']]
5783 k_side = 0
5784 if p_count[p[0]] > p_count[p[1]]:
5785 k_side = 1
5786 method = c.pop('method')
5787 self.run_2port(method, p, k_side, **c)
5788
5789 def run_2port(self, method, p, k_side, **kwargs):
5790 r"""
5791 Call the two-port calibration algorithm and populate multi-port error
5792 coefficients for this port pair.
5793
5794 Parameters
5795 ----------
5796 method: Two-port calibration class
5797 Use to calibrate the port pair.
5798 p: tuple of int
5799 Length two tuple of port indices in the pair.
5800 k_side: int
5801 Port to put 'k' coefficient in the pair.
5802 \*\*kwargs: Keyword arguments
5803 Passed to the calibration method.
5804 """
5805 cal = method(**kwargs)
5806 cal.run()
5807 self.cals[p] = cal
5808
5809 coefs = cal.coefs_8term
5810 S1, S2 = self.coefs_to_ntwks(coefs, k_side=k_side)
5811 one = np.ones(coefs['k'].shape, dtype=complex)
5812 for c in cal.coefs_8term:
5813 if 'forward' in c:
5814 c2 = c.replace('forward ', '')
5815 if 'switch term' in c:
5816 self._coefs[p[1]][c2] = coefs[c]
5817 else:
5818 self._coefs[p[0]][c2] = coefs[c]
5819 elif 'reverse' in c:
5820 c2 = c.replace('reverse ', '')
5821 if 'switch term' in c:
5822 self._coefs[p[0]][c2] = coefs[c]
5823 else:
5824 self._coefs[p[1]][c2] = coefs[c]
5825 elif c == 'k':
5826 self._coefs[p[k_side]][c] = coefs[c]
5827 if 'k' not in self._coefs[p[not k_side]].keys():
5828 self._coefs[p[not k_side]][c] = one
5829 else:
5830 warn(f'Unknown coefficient in calibration {c}', stacklevel=2)
5831
5832 term1 = self.dut_termination(S1, coefs['reverse switch term'])
5833 term2 = self.dut_termination(S2, coefs['forward switch term'])
5834 f = self.frequency
5835 self.terminations[p[0]] = Network(s=term1, z0=self.z0, frequency=f)
5836 self.terminations[p[1]] = Network(s=term2, z0=self.z0, frequency=f)
5837
5838 @property
5839 def coefs(self):
5840 try:
5841 return self._coefs
5842 except(AttributeError):
5843 self.run()
5844 return self._coefs
5845
5846 @coefs.setter
5847 def coefs(self, d):
5848 self._coefs = d
5849
5850 def unterminate_2port(self, ntwk, p1, p2):
5851 """
5852 Unterminates switch terms from a raw measurement.
5853
5854 See Also
5855 --------
5856 calibration.unterminate
5857 """
5858 gamma_f = Network(s=self.coefs[p2]['switch term'])
5859 gamma_r = Network(s=self.coefs[p1]['switch term'])
5860 return unterminate(ntwk, gamma_f, gamma_r)
5861
5862 def terminate_2port(self, ntwk, p1, p2):
5863 """
5864 Terminate a network with switch terms.
5865
5866 See Also
5867 --------
5868 calibration.terminate
5869 """
5870 gamma_f = self.coefs[p2]['switch term']
5871 gamma_r = self.coefs[p1]['switch term']
5872 return terminate(ntwk, gamma_f, gamma_r)
5873
5874 def T_matrices(self, p1, p2):
5875 """
5876 Intermediate matrices used for embedding and de-embedding.
5877
5878 Returns
5879 -------
5880 T1,T2,T3,T4 : numpy ndarray
5881 """
5882 npoints = len(self.coefs[0]['k'])
5883 zero = np.zeros(npoints, dtype=complex)
5884
5885 Edf = self.coefs[p1]['directivity']
5886 Esf = self.coefs[p1]['source match']
5887 Erf = self.coefs[p1]['reflection tracking']
5888 Edr = self.coefs[p2]['directivity']
5889 Esr = self.coefs[p2]['source match']
5890 Err = self.coefs[p2]['reflection tracking']
5891 k1 = self.coefs[p1]['k']
5892 k2 = self.coefs[p2]['k']
5893
5894 detX = Edf*Esf-Erf
5895 detY = Edr*Esr-Err
5896
5897 T1 = np.array([
5898 [ -k1*detX, zero ],
5899 [ zero, -k2*detY ]
5900 ]).transpose(2,0,1)
5901 T2 = np.array([
5902 [ k1*Edf, zero ],
5903 [ zero, k2*Edr ]
5904 ]).transpose(2,0,1)
5905 T3 = np.array([
5906 [ -k1*Esf, zero ],
5907 [ zero, -k2*Esr ]
5908 ]).transpose(2,0,1)
5909 T4 = np.array([
5910 [ k1, zero ],
5911 [ zero, k2 ]
5912 ]).transpose(2,0,1)
5913
5914 return T1, T2, T3, T4
5915
5916 def apply_cal(self, ntwk):
5917 """
5918 Apply correction to a Network.
5919 """
5920 # A new copy of ntwk is created
5921 ntwk = ntwk - self.isolation
5922 caled = ntwk.copy()
5923 # Use traveling definition since it can renormalize to negative real part impedance.
5924 s_def = caled.s_def
5925 caled.s_def = 'traveling'
5926
5927 fpoints = len(ntwk.frequency)
5928 ports = np.arange(self.nports)
5929 port_combos = list(combinations(ports, 2))
5930 for p in port_combos:
5931 T1, T2, T3, T4 = self.T_matrices(p[0], p[1])
5932
5933 caled_2p = subnetwork(ntwk, p).copy()
5934 caled_2p.s_def = 'traveling'
5935
5936 caled_2p = self.unterminate_2port(caled_2p, p[0], p[1])
5937 caled_2p.s = linalg.inv(-caled_2p.s @ T3 + T1) @ (caled_2p.s @ T4 - T2)
5938 z = np.zeros((fpoints, 2), dtype=complex)
5939 z[:,0] = self.terminations[p[0]].z[:,0,0]
5940 z[:,1] = self.terminations[p[1]].z[:,0,0]
5941 caled_2p.renormalize(z)
5942 for ei, i in enumerate(p):
5943 for ej, j in enumerate(p):
5944 caled.s[:, i, j] = caled_2p.s[:, ei, ej]
5945
5946 for i in range(self.nports):
5947 caled.z0[:,i] = self.terminations[i].z[:,0,0]
5948 caled.renormalize(ntwk.z0, s_def=s_def)
5949
5950 return caled
5951
5952 def embed(self, ntwk):
5953 """
5954 Embed an ideal response in the estimated error network[s]
5955 """
5956 fpoints = len(self.coefs[0]['k'])
5957 nports = self.nports
5958 nout = ntwk.copy()
5959
5960 Z = np.zeros((fpoints, 2*nports, 2*nports), dtype=complex)
5961
5962 gammas = []
5963 for e, c in enumerate(self.coefs):
5964 gammas.append(Network(s=c['switch term'], frequency=nout.frequency, z0=50))
5965 Z[:, e, e] = c['directivity']
5966 Z[:, nports+e, nports+e] = c['source match']
5967 Z[:, e, nports+e] = c['reflection tracking'] * c['k'] / self.coefs[0]['k']
5968 Z[:, nports+e, e] = self.coefs[0]['k'] / c['k']
5969
5970 # Consistent internal port Z0.
5971 nout.z0 = 50
5972 Z = Network(s=Z, frequency=nout.frequency, z0=50)
5973 nout = connect(Z, nports, nout, 0, nports)
5974 nout = terminate_nport(nout, gammas)
5975 nout += self.isolation
5976 nout.z0 = ntwk.z0
5977 return nout
5978
5979 def coefs_to_ntwks(self, coefs, k_side=0):
5980 """
5981 Two-port 8-term error coefficients to Networks.
5982
5983 Parameters
5984 ----------
5985 k_side: int, 0 or 1
5986 Port to put 'k' coefficient.
5987 """
5988 npoints = len(coefs['k'])
5989 one = np.ones(npoints, dtype=complex)
5990
5991 Edf = coefs['forward directivity']
5992 Esf = coefs['forward source match']
5993 Erf = coefs['forward reflection tracking']
5994 Edr = coefs['reverse directivity']
5995 Esr = coefs['reverse source match']
5996 Err = coefs['reverse reflection tracking']
5997 k = coefs['k']
5998
5999 if k_side == 0:
6000 S1 = np.array([
6001 [ Edf, Erf/k ],
6002 [ k, Esf ]
6003 ]).transpose(2,0,1)
6004
6005 S2 = np.array([
6006 [ Edr, one ],
6007 [ Err, Esr ]
6008 ]).transpose(2,0,1)
6009 elif k_side == 1:
6010 S1 = np.array([
6011 [ Edf, Erf ],
6012 [ one, Esf ]
6013 ]).transpose(2,0,1)
6014
6015 S2 = np.array([
6016 [ Edr, one/k ],
6017 [ Err*k, Esr ]
6018 ]).transpose(2,0,1)
6019 else:
6020 raise ValueError(f"Invalid k_side {k_side}, expected 0 or 1.")
6021 return (S1, S2)
6022
6023 def dut_termination(self, S, gamma):
6024 """Impedance looking from DUT to VNA terminated with switch term."""
6025 term = S[:,1,1] + (S[:,0,1] * S[:,1,0] * gamma) / (1 - S[:,0,0] * gamma)
6026 return term
6027
6028 class MultiportSOLT(MultiportCal):
6029 """
6030 Multi-port VNA calibration using two-port calibration method with one transmissive standard for each two-port pair.
6031
6032 `method` should be a two-port calibration method such as `EightTerm`,
6033 `UnknownThru` or `SOLT`. This class calibrates a multi-port network using
6034 the given two-port calibration method.
6035
6036 There should be `Nports - 1` thru standards and the number of other
6037 standards depending on the number of standards required by the chosen
6038 calibration method. Standards should be always given thrus first. Thru
6039 standards are used to find the port connections during the calibration and
6040 all standards should be N-ports.
6041
6042 There should be one common port in all thru measurements. For
6043 example in case of 4-port calibration one possible choice would be to make
6044 three thru measurements between ports: 0-1, 0-2, and 0-3.
6045
6046 If isolation calibration is used it should be not passed as an argument to
6047 the two-port calibration and N-port isolation measurement should be instead
6048 given as an argument for this class.
6049
6050 `switch_terms` should be a list of switch terms with nth entry being the
6051 switch term an/bn with source from any other port. Note that in case of
6052 two-port this is the reversed order than what two-port calibration would
6053 require. If calibration is a 12-term calibration such as `SOLT` or
6054 `TwelveTerm` no switch terms are required.
6055
6056 `thru_pos` argument can be used to change the order of thru given to the
6057 calibration method. `auto` will try to determine it automatically from the
6058 calibration method. Other options are `first` and `last`. Other standards
6059 are given in the same order they are given to this class.
6060
6061 `cal_args` can be used to give addition arguments to the calibration method.
6062 If no arguments are given it should be None, otherwise a dictionary of
6063 arguments and values.
6064
6065 See Also
6066 --------
6067 calibration.MultiportCal
6068 Lower level multi-port calibration class. This needs to be used for TRL
6069 calibration as it has also lines between ports which doesn't fit the
6070 interface of this class.
6071 """
6072
6073 family = 'Multiport'
6074
6075 def __init__(
6076 self,
6077 method,
6078 measured: Network,
6079 ideals: list[Network],
6080 isolation=None,
6081 switch_terms=None,
6082 thru_pos: Literal["first", "last", "auto"] = "auto",
6083 cal_args: dict | None = None,
6084 ):
6085 self.ideals = ideals
6086 self.measured = measured
6087 self.nports = ideals[0].nports
6088 nports = self.nports
6089 if nports < 3:
6090 raise ValueError("Too few ports in input networks. At least 3 required.")
6091
6092 self.switch_terms = switch_terms
6093
6094 if thru_pos == 'auto':
6095 if method in [LRM, LRRM]:
6096 thru_pos = 'first'
6097 elif method in [SOLT, EightTerm, UnknownThru, MRC, TwelveTerm]:
6098 thru_pos = 'last'
6099 else:
6100 raise ValueError(
6101 "Unable to determine 'thru_pos' automatically. Set it manually to either 'first' or 'last'"
6102 )
6103 if thru_pos not in ['last', 'first']:
6104 raise ValueError("thru_pos must be either 'first' or 'last'")
6105
6106 if cal_args is None:
6107 cal_args = {}
6108
6109 for i in ideals:
6110 if i.nports != self.nports:
6111 raise ValueError("Inconsistent number of ports in ideals.")
6112
6113 if not issubclass(method, Calibration):
6114 raise ValueError("method must be Calibration subclass.")
6115 if issubclass(method, SixteenTerm):
6116 warn("SixteenTerm calibration is reduced to 8-terms.", stacklevel=2)
6117
6118 if len(ideals) < nports - 1:
6119 raise ValueError(f"Invalid number of ideals. Expected at least {nports-1} but got {len(ideals)}.")
6120
6121 self.thru_ports = []
6122 for thru in ideals[:nports-1]:
6123 nonzero = []
6124 for i in range(nports):
6125 for j in range(i+1, nports):
6126 if thru.s[-1, i, j] != 0:
6127 nonzero.append([i, j])
6128 if len(nonzero) != 1:
6129 raise ValueError("Invalid thru ideal. Thru should connect exactly two ports.")
6130
6131 self.thru_ports.append(tuple(nonzero[0]))
6132
6133 #Generate cal_dict in the format required by MultiportCal.
6134 nports = self.nports
6135 nthrus = nports - 1
6136 cal_dict = {}
6137 for e, p in enumerate(self.thru_ports):
6138 ideals = [subnetwork(self.ideals[e], p)]
6139 ideals_sol = [subnetwork(i, p) for i in self.ideals[nthrus:]]
6140 ideals.extend(ideals_sol)
6141 measured = [subnetwork(self.measured[e], p)]
6142 measured_sol = [subnetwork(i, p) for i in self.measured[nthrus:]]
6143 measured.extend(measured_sol)
6144 if self.switch_terms is None:
6145 sw_terms = None
6146 else:
6147 sw_terms = [self.switch_terms[i] for i in p][::-1]
6148 if thru_pos == 'last':
6149 ideals = ideals[1:] + [ideals[0]]
6150 measured = measured[1:] + [measured[0]]
6151 cal_dict[p] = {}
6152 cal_dict[p]['method'] = method
6153 cal_dict[p]['ideals'] = ideals
6154 cal_dict[p]['measured'] = measured
6155 if sw_terms is not None:
6156 cal_dict[p]['switch_terms'] = sw_terms
6157 for k, v in cal_args.items():
6158 cal_dict[p][k] = v
6159
6160 super().__init__(cal_dict=cal_dict, isolation=isolation)
6161
6162 ## Functions
6163
6164
6165
6166
6167
6168
6169
6170 def ideal_coefs_12term(frequency):
6171 """
6172 An ideal set of 12term calibration coefficients.
6173
6174 Produces a set of error coefficients, that would result if the
6175 error networks were matched thrus
6176 """
6177
6178 zero = zeros(len(frequency), dtype='complex')
6179 one = ones(len(frequency), dtype='complex')
6180 ideal_coefs = {}
6181 ideal_coefs.update({k:zero for k in [\
6182 'forward directivity',
6183 'forward source match',
6184 'forward load match',
6185 'reverse directivity',
6186 'reverse load match',
6187 'reverse source match',
6188 ]})
6189
6190 ideal_coefs.update({k:one for k in [\
6191 'forward reflection tracking',
6192 'forward transmission tracking',
6193 'reverse reflection tracking',
6194 'reverse transmission tracking',
6195 ]})
6196
6197 return ideal_coefs
6198
6199 def unterminate(ntwk, gamma_f, gamma_r):
6200 r"""
6201 Unterminate switch terms from a raw measurement.
6202
6203 In order to use the 8-term error model on a VNA which employs a
6204 switched source, the effects of the switch must be accounted for.
6205 This is done through `switch terms` as described in [1]_ . The
6206 two switch terms are defined as,
6207
6208 .. math ::
6209
6210 \Gamma_f = \frac{a2}{b2} ,\qquad\text{sourced by port 1}\
6211 \Gamma_r = \frac{a1}{b1} ,\qquad\text{sourced by port 2}
6212
6213 These can be measured by four-sampler VNA's by setting up
6214 user-defined traces onboard the VNA. If the VNA doesn't have
6215 4-samplers, then you can measure switch terms indirectly by using a
6216 two-tier two-port calibration. First do a SOLT, then convert
6217 the 12-term error coefs to 8-term, and pull out the switch terms.
6218
6219 Parameters
6220 ----------
6221 two_port : 2-port Network
6222 the raw measurement
6223 gamma_f : 1-port Network
6224 the measured forward switch term.
6225 gamma_f = a2/b2 sourced by port1
6226 gamma_r : 1-port Network
6227 the measured reverse switch term
6228 gamma_r = a1/b1 sourced by port2
6229
6230 Returns
6231 -------
6232 ntwk : Network object
6233
6234 References
6235 ----------
6236
6237 .. [1] "Formulations of the Basic Vector Network Analyzer Error
6238 Model including Switch Terms" by Roger B. Marks
6239 """
6240 unterminated = ntwk.copy()
6241
6242 # extract scattering matrices
6243 m, gamma_r, gamma_f = ntwk.s, gamma_r.s, gamma_f.s
6244 u = m.copy()
6245
6246 one = np.ones(ntwk.frequency.npoints)
6247
6248 d = one - m[:,0,1]*m[:,1,0]*gamma_r[:,0,0]*gamma_f[:,0,0]
6249 u[:,0,0] = (m[:,0,0] - m[:,0,1]*m[:,1,0]*gamma_f[:,0,0])/(d)
6250 u[:,0,1] = (m[:,0,1] - m[:,0,0]*m[:,0,1]*gamma_r[:,0,0])/(d)
6251 u[:,1,0] = (m[:,1,0] - m[:,1,1]*m[:,1,0]*gamma_f[:,0,0])/(d)
6252 u[:,1,1] = (m[:,1,1] - m[:,0,1]*m[:,1,0]*gamma_r[:,0,0])/(d)
6253
6254 unterminated.s = u
6255 return unterminated
6256
6257 def terminate(ntwk, gamma_f, gamma_r):
6258 """
6259 Terminate a network with switch terms.
6260
6261 see [1]_
6262
6263
6264 Parameters
6265 ----------
6266 two_port : 2-port Network
6267 an unterminated network
6268 gamma_f : 1-port Network
6269 measured forward switch term.
6270 gamma_f = a2/b2 sourced by port1
6271 gamma_r : 1-port Network
6272 measured reverse switch term
6273 gamma_r = a1/b1 sourced by port2
6274
6275 Returns
6276 -------
6277 ntwk : Network object
6278
6279 See Also
6280 --------
6281 unterminate_switch_terms
6282
6283 References
6284 ----------
6285
6286 .. [1] "Formulations of the Basic Vector Network Analyzer Error
6287 Model including Switch Terms" by Roger B. Marks
6288 """
6289
6290 m = ntwk.copy()
6291
6292 m.s[:,0,0] = ntwk.s[:,0,0] + ntwk.s[:,1,0]*ntwk.s[:,0,1]*gamma_f.s[:,0,0]/(1-ntwk.s[:,1,1]*gamma_f.s[:,0,0])
6293 m.s[:,1,1] = ntwk.s[:,1,1] + ntwk.s[:,1,0]*ntwk.s[:,0,1]*gamma_r.s[:,0,0]/(1-ntwk.s[:,0,0]*gamma_r.s[:,0,0])
6294 m.s[:,1,0] = ntwk.s[:,1,0]/(1-ntwk.s[:,1,1]*gamma_f.s[:,0,0])
6295 m.s[:,0,1] = ntwk.s[:,0,1]/(1-ntwk.s[:,0,0]*gamma_r.s[:,0,0])
6296 return m
6297
6298 def terminate_nport(ntwk, gammas):
6299 """
6300 Terminate N-port network with switch terms.
6301
6302 Note that for 2-port the order `gammas` is opposite of terminate.
6303 Correct order for 2-port is [gamma_r, gamma_f].
6304
6305 See [1]_
6306
6307
6308 Parameters
6309 ----------
6310 two_port : Network
6311 an unterminated network.
6312 gammas : list of 1-port Network
6313 measured switch term.
6314 gammas[i] = ai/bi sourced by any other port.
6315
6316 Returns
6317 -------
6318 ntwk : Network object
6319
6320 See Also
6321 --------
6322 terminate
6323
6324 References
6325 ----------
6326
6327 .. [1] "Formulations of the Basic Vector Network Analyzer Error
6328 Model including Switch Terms" by Roger B. Marks
6329 """
6330 nin = ntwk.copy()
6331 # Assign fixed z0 for connections for inner ports.
6332 nin.z0 = 50
6333 nout = ntwk.copy()
6334 nports = ntwk.nports
6335 fpoints = len(ntwk.frequency)
6336 if len(gammas) != ntwk.nports:
6337 raise ValueError("len(gammas) doesn't match the number of network ports")
6338 ones = np.ones(len(ntwk.s))
6339 for i in range(nports):
6340 term = np.zeros((fpoints, 2*nports, 2*nports), dtype=complex)
6341 for j in range(nports):
6342 if i == j:
6343 term[:,nports+j,j] = ones
6344 term[:,j,j+nports] = ones
6345 continue
6346 term[:,j,j] = gammas[j].s[:,0,0]
6347 term[:,nports+j,j] = ones
6348 net = Network(s=term, frequency=nin.frequency, z0=50)
6349 net = connect(nin, 0, net, 0, nports)
6350 for j in range(nports):
6351 nout.s[:,j,i] = net.s[:,j,i]
6352 nout.z0 = ntwk.z0
6353 return nout
6354
6355 def compute_switch_terms(ntwks):
6356 """
6357 A method for indirectly computing the switch terms of a VNA using measurements of at least three transmissive
6358 reciprocal devices. The VNA does not need to be calibrated, and more than three reciprocal devices can be used.
6359 However, the accuracy of the computed switch terms depends on the uniqueness of the measured reciprocal devices.
6360 Devices with asymmetric structure and semi-reflective properties can help ensure the conditioning of the system
6361 matrix, which solves the switch terms.
6362
6363 See [1]_ and [2]_
6364
6365 Parameters
6366 ----------
6367 ntwks : List of networks
6368 measured reciprocal devices. At least 3 required.
6369
6370 Returns
6371 -------
6372 Gammas : List of one-port networks of the switch terms.
6373 The order is [Gamma21, Gamma12]. Gamma21 is forward and Gamma12 is reverse.
6374
6375 References
6376 ----------
6377 .. [1] Z. Hatab, M. E. Gadringer, and W. Bösch, "Indirect Measurement of Switch Terms of a Vector Network Analyzer
6378 with Reciprocal Devices," 2023, e-print: https://arxiv.org/abs/2306.07066
6379
6380 .. [2] https://ziadhatab.github.io/posts/vna-switch-terms/
6381
6382 See Also
6383 --------
6384 terminate
6385 unterminate
6386
6387 """
6388 if len(ntwks) < 3:
6389 raise ValueError("At least three networks are required.")
6390
6391 fpoints = len(ntwks[0].frequency)
6392 Gamma21_fill = np.zeros(shape=(fpoints,), dtype=complex) # forward switch term
6393 Gamma12_fill = np.zeros(shape=(fpoints,), dtype=complex) # reverse switch term
6394 for inx in range(fpoints): # iterate through all frequency points
6395 # create the system matrix
6396 H = np.array([
6397 [-ntwk.s[inx,0,0]*ntwk.s[inx,0,1]/ntwk.s[inx,1,0], -ntwk.s[inx,1,1], 1, ntwk.s[inx,0,1]/ntwk.s[inx,1,0]]
6398 for ntwk in ntwks])
6399 _,_,vh = np.linalg.svd(H) # compute the SVD
6400 nullspace = vh[-1,:].conj() # get the nullspace
6401 Gamma21_fill[inx] = nullspace[1]/nullspace[2]
6402 Gamma12_fill[inx] = nullspace[0]/nullspace[3]
6403
6404 Gamma21 = Network(s=Gamma21_fill, frequency=ntwks[0].frequency, name='Gamma21')
6405 Gamma12 = Network(s=Gamma12_fill, frequency=ntwks[0].frequency, name='Gamma12')
6406
6407 return [Gamma21, Gamma12]
6408
6409 def determine_line(thru_m, line_m, line_approx=None):
6410 r"""
6411 Determine S21 of a matched line.
6412
6413 Given raw measurements of a `thru` and a matched `line` with unknown
6414 s21, this will calculate the response of the line. This works for
6415 lossy lines, and attenuators. The `line_approx`
6416 is an approximation to line, this used to choose the correct
6417 root sign. If left as `None`, it will be estimated from raw measurements,
6418 which requires your error networks to be well matched (S_ij >>S_ii).
6419
6420
6421 This is possible because two measurements can be combined to
6422 create a relationship of similar matrices, as shown below. Equating
6423 the eigenvalues between these measurements allows one to solve for S21
6424 of the line.
6425
6426 .. math::
6427
6428 M_t = X \cdot A_t \cdot Y \\
6429 M_l = X \cdot A_l \cdot Y\\
6430
6431 M_t \cdot M_{l}^{-1} = X \cdot A_t \cdot A_{l}^{-1} \cdot X^{-1}\\
6432
6433 eig(M_t \cdot M_{l}^{-1}) = eig( A_t \cdot A_{l}^{-1})\\
6434
6435 which can be solved to yield S21 of the line
6436
6437 Notes
6438 -----
6439 This relies on the 8-term error model, which requires that switch
6440 terms are accounted for. specifically, thru and line have their
6441 switch terms unterminated.
6442
6443 Parameters
6444 ----------
6445 thru_m : :class:`~skrf.network.Network`
6446 raw measurement of a flush thru
6447 line_m : :class:`~skrf.network.Network`
6448 raw measurement of a matched transmissive standard
6449 line_approx : :class:`~skrf.network.Network`
6450 approximate network the ideal line response. if None, then
6451 the response is approximated by line_approx = line/thru. This
6452 makes the assumption that the error networks have much larger
6453 transmission than reflection
6454
6455
6456 References
6457 ----------
6458
6459 """
6460
6461 npts = len(thru_m)
6462 zero = np.zeros(npts)
6463
6464 if line_approx is None:
6465 # estimate line length, by assuming error networks are well
6466 # matched
6467 line_approx_s21 = line_m.s[:,1,0] / thru_m.s[:,1,0]
6468 else:
6469 line_approx_s21 = line_approx.s[:,1,0]
6470
6471 C = thru_m.inv**line_m
6472 # the eigen values of the matrix C, are equal to s12,s12^-1)
6473 # we need to choose the correct one
6474 w,v = linalg.eig(C.t)
6475 s12_0, s12_1 = w[:,0], w[:,1]
6476 s12 = find_correct_sign(s12_0, s12_1, line_approx_s21)
6477 found_line = line_m.copy()
6478 found_line.s = np.array([[zero, s12],[s12,zero]]).transpose(2,0,1)
6479 return found_line
6480
6481
6482 def _regularize_inplace(z : ComplexArray, epsilon : float=1e-7) -> ComplexArray:
6483 """ Regularize an array inplace around zero """
6484 zero_idx = np.abs(z)<epsilon
6485 z[zero_idx] = .5*(epsilon * np.exp(np.angle(z[zero_idx])*1j)+z[zero_idx])
6486 return z
6487
6488 def determine_reflect(thru_m, reflect_m, line_m, reflect_approx=None,
6489 line_approx=None, return_all=False):
6490 """
6491 Determine reflect from a thru, reflect, line measurements.
6492
6493 This is used in the TRL algorithm, but is made modular for
6494 multi-line, multi-reflect options.
6495
6496
6497 Parameters
6498 ----------
6499 thru_m : :class:`~skrf.network.Network`
6500 raw measurement of a thru
6501 reflect_m: :class:`~skrf.network.Network`
6502 raw measurement of a reflect standard
6503 line_m : :class:`~skrf.network.Network`
6504 raw measurement of a matched transmissive standard
6505 reflect_approx : :class:`~skrf.network.Network`
6506 approximate One-port network for the reflect. if None, then
6507 we assume its a flush short (gamma=-1)
6508 return_all: bool
6509 return all possible values for reflect, one for each root-choice.
6510 useful for troubleshooting.
6511
6512 Returns
6513 -------
6514 reflect : :class:`~skrf.network.Network`
6515 a One-port network for the found reflect.
6516
6517 The equations are from "Thru-Reflect-Line: An Improved Technique for Calibrating the Dual Six-Port
6518 Automatic Network Analyzer", G.F. Engen et al., 1979
6519
6520 """
6521
6522 # regularize the parameters in case of matched thru and line. see gh-870
6523 thru_m = thru_m.copy()
6524 thru_m.s[:, 0, 0] = _regularize_inplace(thru_m.s[:, 0, 0])
6525 thru_m.s[:, 1, 1] = _regularize_inplace(thru_m.s[:, 1, 1])
6526
6527 #Call determine_line first to solve root choice of the propagation constant
6528 line = determine_line(thru_m, line_m, line_approx)
6529
6530 inv = linalg.inv
6531 rt = thru_m.t
6532 rd = line_m.t
6533
6534 # tt is equal to T from equation (24) in the paper
6535 tt = einsum('ijk,ikl -> ijl', rd, inv(rt))
6536
6537 a = tt[:,1,0]
6538 b = tt[:,1,1]-tt[:,0,0]
6539 c = -tt[:,0,1]
6540 sqrtD = sqrt(b*b-4*a*c)
6541
6542 # The variables a, b, c define a quadratic equation for which the solutions sol1 and sol2 correspond to the
6543 # ratios (r11/r21) and (r12/r22) from equations (30) and (31) in the paper
6544 # The quadratic equation has solutions sol1 = (-b-sqrt(b*b-4*a*c))/(2*a), sol2 = (-b+sqrt(b*b-4*a*c))/(2*a)
6545 # For a=0 these become degenerate. Also the consecutive equations for x1 and x2 contain singularities for a=0 or c=0
6546
6547 sol1 = (-b-sqrtD)/(2*a)
6548 sol2 = (-b+sqrtD)/(2*a)
6549
6550 # equation (32)
6551 x1 = (tt[:,1,0]*sol1 + tt[:,1,1])/(tt[:,0,1]/sol2 + tt[:,0,0])
6552 x2 = (tt[:,1,0]*sol2 + tt[:,1,1])/(tt[:,0,1]/sol1 + tt[:,0,0])
6553
6554 e2 = line.s[:,0,1]**2
6555 rootChoice = abs(x1 - e2) < abs(x2 - e2) # see gh-870
6556
6557 y = sol1*invert(rootChoice) + sol2*rootChoice
6558 x = sol1*rootChoice + sol2*invert(rootChoice)
6559 b = y
6560
6561 e = thru_m.s[:,0,0]
6562 d = -det(thru_m.s)
6563 f = -thru_m.s[:,1,1]
6564
6565 gam = (f-d/x)/(1-e/x) # equation (40)
6566 b_A = (e-b)/(d-b*f) # equation (41): beta/alpha
6567
6568 w1 = reflect_m.s[:,0,0]
6569 w2 = reflect_m.s[:,1,1]
6570
6571 # equation (45)
6572 a = sqrt(((w1-b)*(1+w2*b_A)*(d-b*f))/\
6573 ((w2+gam)*(1-w1/x)*(1-e/x)))
6574
6575 out = [(w1-b)/(a*(1-w1/x)), (w1-b)/(-a*(1-w1/x))] # equation (47)
6576
6577 if return_all:
6578 return [Network(frequency=thru_m.frequency, s = k) for k in out]
6579
6580 if reflect_approx is None:
6581 reflect_approx = reflect_m.copy()
6582 reflect_approx.s[:,0,0]=-1
6583
6584 closer = find_closest(out[0], out[1], reflect_approx.s11.s.flatten())
6585 reflect = reflect_approx.copy()
6586 reflect.s[:,0,0] = closer
6587
6588 return reflect.s11
6589
6590
6591 def convert_12term_2_8term(coefs_12term, redundant_k = False):
6592 """
6593 Convert the 12-term and 8-term error coefficients.
6594
6595
6596 Derivation of this conversion can be found in [#]_ .
6597
6598 References
6599 ----------
6600
6601 .. [#] Marks, Roger B.; , "Formulations of the Basic Vector Network Analyzer Error Model including Switch-Terms,"
6602 ARFTG Conference Digest-Fall, 50th , vol.32, no., pp.115-126, Dec. 1997.
6603 URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4119948&isnumber=4119931
6604
6605 """
6606
6607 # Nomenclature taken from Roger Marks
6608 Edf = coefs_12term['forward directivity']
6609 Esf = coefs_12term['forward source match']
6610 Erf = coefs_12term['forward reflection tracking']
6611 Etf = coefs_12term['forward transmission tracking']
6612 Elf = coefs_12term['forward load match']
6613 Eif = coefs_12term.get('forward isolation',0) # noqa: F841
6614
6615 Edr = coefs_12term['reverse directivity']
6616 Esr = coefs_12term['reverse source match']
6617 Err = coefs_12term['reverse reflection tracking']
6618 Elr = coefs_12term['reverse load match']
6619 Etr = coefs_12term['reverse transmission tracking']
6620 Eir = coefs_12term.get('reverse isolation',0) # noqa: F841
6621
6622 # these are given in eq (30) - (33) in Roger Mark's paper listed in
6623 # the docstring
6624 # NOTE: k = e10/e23 = alpha/beta
6625 # the 'k' nomenclature is from Soares Speciale
6626 gamma_f = (Elf - Esr)/(Err + Edr*(Elf - Esr))
6627 gamma_r = (Elr - Esf)/(Erf + Edf*(Elr - Esf))
6628
6629 k_first = Etf/(Err + Edr*(Elf - Esr) )
6630 k_second =1/(Etr/(Erf + Edf *(Elr - Esf)))
6631 k = (k_first + k_second)/2.
6632 coefs_8term = {}
6633 for l in ['forward directivity','forward source match',
6634 'forward reflection tracking','reverse directivity',
6635 'reverse reflection tracking','reverse source match',
6636 'forward isolation', 'reverse isolation']:
6637 coefs_8term[l] = coefs_12term[l].copy()
6638
6639 coefs_8term['forward switch term'] = gamma_f
6640 coefs_8term['reverse switch term'] = gamma_r
6641 coefs_8term['k'] = k
6642 if redundant_k:
6643 coefs_8term['k first'] = k_first
6644 coefs_8term['k second'] = k_second
6645 return coefs_8term
6646
6647 def convert_8term_2_12term(coefs_8term):
6648 """
6649 """
6650 Edf = coefs_8term['forward directivity']
6651 Esf = coefs_8term['forward source match']
6652 Erf = coefs_8term['forward reflection tracking']
6653
6654 Edr = coefs_8term['reverse directivity']
6655 Esr = coefs_8term['reverse source match']
6656 Err = coefs_8term['reverse reflection tracking']
6657
6658 gamma_f = coefs_8term['forward switch term']
6659 gamma_r = coefs_8term['reverse switch term']
6660 k = coefs_8term['k']
6661 k_first = coefs_8term.get('k first', k)
6662 k_second = coefs_8term.get('k second', k)
6663
6664 coefs_12term = {}
6665
6666 if np.allclose(gamma_f, np.zeros_like(gamma_f)):
6667 # taken from eq (40),(41) in the Roger Marks paper
6668 Elf = Esr
6669 Etf = Err * k_first
6670 else:
6671 # taken from eq (36),(38) in the Roger Marks paper
6672 Elf = Esr + (Err * gamma_f) / (1. - Edr * gamma_f)
6673 Etf = ((Elf - Esr) / gamma_f) * k_first
6674
6675 if np.allclose(gamma_r, np.zeros_like(gamma_r)):
6676 # taken from eq (43),(44) in the Roger Marks paper
6677 Elr = Esf
6678 Etr = Erf * 1. / k_second
6679 else:
6680 # taken from eq (37),(39) in the Roger Marks paper
6681 Elr = Esf + (Erf *gamma_r)/(1. - Edf * gamma_r)
6682 Etr = ((Elr - Esf )/gamma_r) * 1./k_second
6683
6684 coefs_12term['forward load match'] = Elf
6685 coefs_12term['reverse load match'] = Elr
6686 coefs_12term['forward transmission tracking'] = Etf
6687 coefs_12term['reverse transmission tracking'] = Etr
6688
6689 for l in ['forward directivity', 'forward source match',
6690 'forward reflection tracking', 'reverse directivity',
6691 'reverse reflection tracking', 'reverse source match',
6692 'forward isolation', 'reverse isolation']:
6693 coefs_12term[l] = coefs_8term[l].copy()
6694
6695 return coefs_12term
6696
6697
6698 def convert_pnacoefs_2_skrf(coefs):
6699 """
6700 Convert PNA error coefficients to skrf error coefficients.
6701
6702 Parameters
6703 ----------
6704 coefs : dict
6705 coefficients as retrieved from PNA
6706 ports : tuple
6707 port indices. in order (forward, reverse)
6708
6709 Returns
6710 -------
6711 skrf_coefs : dict
6712 same error coefficients but with keys matching skrf's convention
6713
6714 """
6715
6716 coefs_map ={'Directivity':'directivity',
6717 'SourceMatch':'source match',
6718 'ReflectionTracking':'reflection tracking',
6719 'LoadMatch':'load match',
6720 'TransmissionTracking':'transmission tracking',
6721 'CrossTalk':'isolation'}
6722
6723 skrf_coefs = {}
6724
6725 if len(coefs) ==3:
6726 for k in coefs:
6727 coef= k[:-5]
6728 coef_key = coefs_map[coef]
6729 skrf_coefs[coef_key] = coefs[k]
6730
6731 else:
6732 ports = list(set([k[-2] for k in coefs]))
6733 ports.sort(key=int)
6734 port_map ={ports[0]: 'forward',
6735 ports[1]: 'reverse'}
6736
6737 for k in coefs:
6738 coef,p1,p2 = k[:-5],k[-4],k[-2]
6739 # the source port has a different position for reflective
6740 # and transmissive standards
6741 if coef in ['Directivity','SourceMatch','ReflectionTracking']:
6742 coef_key = port_map[p1]+' '+coefs_map[coef]
6743 elif coef in ['LoadMatch','TransmissionTracking','CrossTalk']:
6744 coef_key = port_map[p2]+' '+coefs_map[coef]
6745 skrf_coefs[coef_key] = coefs[k]
6746
6747
6748
6749 return skrf_coefs
6750
6751 def convert_skrfcoefs_2_pna(coefs, ports = (1,2)):
6752 """
6753 Convert skrf error coefficients to pna error coefficients
6754
6755 Notes
6756 -----
6757 The skrf calibration terms can be found in variables
6758 * skrf.calibration.coefs_list_3term
6759 * skrf.calibration.coefs_list_12term
6760
6761
6762 Parameters
6763 ----------
6764 coefs : dict
6765 complex ndarrays for the cal coefficients as defined by skrf
6766 ports : tuple
6767 port indices. in order (forward, reverse)
6768
6769 Returns
6770 -------
6771 pna_coefs : dict
6772 same error coefficients but with keys matching skrf's convention
6773
6774
6775 """
6776 if not hasattr(ports, '__len__'):
6777 ports = ports,
6778
6779 coefs_map ={'directivity':'Directivity',
6780 'source match':'SourceMatch',
6781 'reflection tracking':'ReflectionTracking',
6782 'load match':'LoadMatch',
6783 'transmission tracking':'TransmissionTracking',
6784 'isolation':'CrossTalk'}
6785
6786 pna_coefs = {}
6787
6788 if len(coefs)==3:
6789 for k in coefs:
6790 coef_key = coefs_map[k] + '(%i,%i)'%(ports[0],ports[0])
6791 pna_coefs[coef_key] = coefs[k]
6792
6793
6794 else:
6795 port_map_trans ={'forward':ports[1],
6796 'reverse':ports[0]}
6797 port_map_refl ={'forward':ports[0],
6798 'reverse':ports[1]}
6799
6800 for k in coefs:
6801 fr = k.split(' ')[0] # remove 'forward|reverse-ness'
6802 eterm = coefs_map[k.lstrip(fr)[1:] ]
6803 # the source port has a different position for reflective
6804 # and transmissive standards
6805 if eterm in ['Directivity','SourceMatch','ReflectionTracking']:
6806 coef_key= eterm+'(%i,%i)'%(port_map_refl[fr],
6807 port_map_refl[fr])
6808
6809
6810 elif eterm in ['LoadMatch','TransmissionTracking','CrossTalk']:
6811 receiver_port = port_map_trans[fr]
6812 source_port = port_map_refl[fr]
6813 coef_key= eterm+'(%i,%i)'%(receiver_port,source_port)
6814 pna_coefs[coef_key] = coefs[k]
6815
6816
6817 return pna_coefs
6818
6819 def align_measured_ideals(measured, ideals):
6820 """
6821 Aligns two lists of networks based on the intersection of their names.
6822
6823 """
6824 measured = [ measure for measure in measured\
6825 for ideal in ideals if ideal.name in measure.name]
6826 ideals = [ ideal for measure in measured\
6827 for ideal in ideals if ideal.name in measure.name]
6828 return measured, ideals
6829
6830 def two_port_error_vector_2_Ts(error_coefficients):
6831 ec = error_coefficients
6832 npoints = len(ec['k'])
6833 one = np.ones(npoints,dtype=complex)
6834 zero = np.zeros(npoints,dtype=complex)
6835 #T_1 = np.zeros((npoints, 2,2),dtype=complex)
6836 #T_1[:,0,0],T_1[:,1,1] = -1*ec['det_X'], -1*ec['k']*ec['det_Y']
6837 #T_1[:,1,1] = -1*ec['k']*ec['det_Y']
6838
6839
6840 T1 = np.array([\
6841 [ -1*ec['det_X'], zero ],\
6842 [ zero, -1*ec['k']*ec['det_Y']]]).transpose().reshape(-1,2,2)
6843 T2 = np.array([\
6844 [ ec['e00'], zero ],\
6845 [ zero, ec['k']*ec['e33']]]).transpose().reshape(-1,2,2)
6846 T3 = np.array([\
6847 [ -1*ec['e11'], zero ],\
6848 [ zero, -1*ec['k']*ec['e22']]]).transpose().reshape(-1,2,2)
6849 T4 = np.array([\
6850 [ one, zero ],\
6851 [ zero, ec['k']]]).transpose().reshape(-1,2,2)
6852 return T1,T2,T3,T4
6853
6854 def error_dict_2_network(coefs, frequency, is_reciprocal=False, **kwargs):
6855 """
6856 Create a Network from a dictionary of standard error terms.
6857 """
6858
6859 if len (coefs.keys()) == 3:
6860 # ASSERT: we have one port data
6861 if is_reciprocal:
6862 #TODO: make this better and maybe have phase continuity
6863 # functionality
6864 tracking = coefs['reflection tracking']
6865 #s12 = np.sqrt(tracking)
6866 #s21 = np.sqrt(tracking)
6867 s12 = sqrt_phase_unwrap(tracking)
6868 s21 = sqrt_phase_unwrap(tracking)
6869
6870 else:
6871 s21 = coefs['reflection tracking']
6872 s12 = np.ones(len(s21), dtype=complex)
6873
6874 s11 = coefs['directivity']
6875 s22 = coefs['source match']
6876 return Network(
6877 frequency = frequency,
6878 s = np.array([[s11, s21],[s12,s22]]).transpose().reshape(-1,2,2),
6879 **kwargs)
6880
6881 else:
6882 p1,p2 = {},{}
6883 for k in ['source match','directivity','reflection tracking']:
6884 p1[k] = coefs['forward '+k]
6885 p2[k] = coefs['reverse '+k]
6886 forward = error_dict_2_network(p1, frequency = frequency,
6887 name='forward', is_reciprocal = is_reciprocal,**kwargs)
6888 reverse = error_dict_2_network(p2, frequency = frequency,
6889 name='reverse', is_reciprocal = is_reciprocal,**kwargs)
6890 return (forward, reverse)