Debian Codegraph @

skrf/tests/test_network.py

raw symbols SCIP
1 import io
2 import os
3 import pickle
4 import sys
5 import tempfile
6 import unittest
7 import warnings
8 import zipfile
9 from functools import partial
10 from pathlib import Path
11
12 import numpy as np
13 import pandas as pd
14 import pytest
15 from scipy import signal
16
17 import skrf as rf
18 from skrf import setup_pylab
19 from skrf.constants import S_DEF_HFSS_DEFAULT, S_DEFINITIONS
20 from skrf.frequency import Frequency, InvalidFrequencyWarning
21 from skrf.media import CPW, DefinedGammaZ0, DistributedCircuit
22 from skrf.networkSet import tuner_constellation
23
24 try:
25 from skrf.plotting import plot_contour
26 except ImportError:
27 pass
28
29 class NetworkTestCase(unittest.TestCase):
30 """
31 Network class operation test case.
32 The following is true, as tested by lihan in ADS,
33 test3 == test1 ** test2
34
35 To test for 2N-port deembeding Meas, Fix and DUT are created such as:
36 ::
37 Meas == Fix ** DUT
38 Meas Fix DUT
39 +---------+ +---------+ +---------+
40 -|0 4|- -|0 4|---|0 4|-
41 -|1 5|- = -|1 5|---|1 5|-
42 -|2 6|- -|2 6|---|2 6|-
43 -|3 7|- -|3 7|---|3 7|-
44 +---------+ +---------+ +---------+
45
46 Note:
47 -----
48 due to the complexity of inv computations, there will be an unavoidable
49 precision loss. thus Fix.inv ** Meas will show a small difference with DUT.
50 """
51 def setUp(self):
52 """
53 this also tests the ability to read touchstone files
54 without an error
55 """
56 setup_pylab()
57 self.test_dir = os.path.dirname(os.path.abspath(__file__))+'/'
58 self.ntwk1 = rf.Network(os.path.join(self.test_dir, 'ntwk1.s2p'))
59 self.ntwk2 = rf.Network(os.path.join(self.test_dir, 'ntwk2.s2p'))
60 self.ntwk3 = rf.Network(os.path.join(self.test_dir, 'ntwk3.s2p'))
61 self.freq = rf.Frequency(75,110,101,'ghz')
62 self.cpw = CPW(self.freq, w=10e-6, s=5e-6, ep_r=10.6)
63 l1 = self.cpw.line(0.20, 'm', z0=50)
64 l2 = self.cpw.line(0.07, 'm', z0=50)
65 l3 = self.cpw.line(0.47, 'm', z0=50)
66 self.l2 = l2
67 freq = Frequency(0, 9, 10, 'GHz')
68 m50 = DefinedGammaZ0(frequency = freq, z0_port = 50, z0 = 50)
69 self.o1 = m50.open()
70 self.splitter = m50.splitter(nports = 3, z0 = [10, 20, 30])
71 self.splitter.port_names = ["a", "b", "c"]
72 self.thru = rf.concat_ports([m50.thru()] * 2, port_order='second')
73 self.thru.renormalize([1, 2, 3, 4])
74 self.Fix = rf.concat_ports([l1, l1, l1, l1])
75 self.DUT = rf.concat_ports([l2, l2, l2, l2])
76 self.Meas = rf.concat_ports([l3, l3, l3, l3])
77 self.Fix2 = rf.concat_ports([l1, l1, l1, l1], port_order='first')
78 self.DUT2 = rf.concat_ports([l2, l2, l2, l2], port_order='first')
79 self.Meas2 = rf.concat_ports([l3, l3, l3, l3], port_order='first')
80 self.fet = rf.Network(os.path.join(self.test_dir, 'fet.s2p'))
81 self.rng = np.random.default_rng()
82 self.ntwk_noise = rf.Network(os.path.join(self.test_dir,'ntwk_noise.s2p'))
83
84 def test_network_copy(self):
85 n = self.ntwk1
86 n._ext_attrs['_is_circuit_port'] = True
87 n2 = n.copy()
88 self.assertEqual( n.frequency, n2.frequency)
89 self.assertNotEqual( id(n.frequency), id(n2.frequency))
90 self.assertNotEqual( id(n.frequency.f), id(n2.frequency.f))
91
92 n.frequency.f[0] = 0
93 self.assertNotEqual(n2.frequency.f[0], 0)
94
95 self.assertEqual(True, n2._ext_attrs.get('_is_circuit_port', False))
96
97 def test_two_port_reflect(self):
98 number_of_data_points = 10
99 f = rf.Frequency.from_f(np.linspace(2e6, 3e6, number_of_data_points), unit="Hz")
100 n=rf.Network(frequency=f, s=np.linspace(0.1, .8, number_of_data_points), name='test')
101 n2 = rf.two_port_reflect(n, n)
102 self.assertEqual(n2.name, n.name + '-' + n.name )
103 self.assertEqual(n2.s.shape, (number_of_data_points, 2, 2))
104 np.testing.assert_array_equal(n2.s[:, 0, 1], np.zeros(number_of_data_points))
105 np.testing.assert_array_equal(n2.s[:, 0, 0], n.s.flatten())
106
107 n2 = rf.two_port_reflect(n, n, name = 'new_name')
108 self.assertEqual(n2.name, 'new_name' )
109
110 def test_network_empty_frequency_range(self):
111 number_of_data_points = 10
112 f = rf.Frequency.from_f(np.linspace(2e6, 3e6, number_of_data_points), unit="Hz")
113 n=rf.Network(
114 frequency=f,
115 s=np.linspace(0.1, .8, number_of_data_points),
116 name='test',
117 z0=np.linspace(50, 50.1,number_of_data_points ))
118 empty_network = n[n.f < 0]
119 self.assertIn('1-Port Network', repr(empty_network))
120
121 def test_network_sequence_frequency_with_f_unit(self):
122 n=rf.Network(frequency=self.freq.f, f_unit=self.freq.unit)
123 np.allclose(n.f, self.freq.f)
124 n=rf.Network(f=self.freq.f, f_unit=self.freq.unit)
125 np.allclose(n.f, self.freq.f)
126
127 def test_timedomain(self):
128 t = self.ntwk1.s11.s_time
129 s = self.ntwk1.s11.s
130 self.assertTrue(len(t)== len(s))
131
132 def test_time_gate(self):
133 ntwk = self.ntwk1
134 gated = self.ntwk1.s11.time_gate(0,.2, t_unit='ns')
135 self.assertTrue(len(gated)== len(ntwk))
136
137 def test_time_gate_custom_window(self):
138 for window in ["hamming", ('kaiser', 6)]:
139 gated1 = self.ntwk1.s11.time_gate(0,.2, t_unit='ns', window=window, fft_window=window)
140
141 get_window = partial(signal.get_window, window)
142
143 gated2 = self.ntwk1.s11.time_gate(0,.2, t_unit='ns', window=get_window, fft_window=get_window)
144 assert gated1 == gated2
145
146 def test_time_gate_raises(self):
147 ntwk = self.ntwk1
148 with pytest.warns(DeprecationWarning, match="Time unit not passed"):
149 gated = self.ntwk1.s11.time_gate(0,.2)
150
151 self.assertTrue(len(gated)== len(ntwk))
152
153 with pytest.warns(DeprecationWarning, match="Time unit not passed"):
154 gated = self.ntwk1.s11.time_gate(0,.2, t_unit='')
155 self.assertTrue(len(gated)== len(ntwk))
156
157 def test_autogate(self):
158 l1 = self.cpw.line(0.1, 'm', z0=50)
159 l2 = self.cpw.line(0.1, 'm', z0=30)
160 l3 = self.cpw.line(0.1, 'm', z0=50)
161
162 ntwk = l1 ** l2 ** l3
163
164 # Auto gate should not raise
165 gated = ntwk.s11.time_gate()
166 self.assertTrue(len(gated)== len(ntwk))
167
168 def test_lpi(self):
169 """Test low pass impulse response against data generated with METAS VNA Tools."""
170
171 path = Path(self.test_dir) / "metas_tdr"
172
173 for fname in ["short_10ps_dc_50g", "short_10ps_dc_40g"]:
174
175 netw = rf.Network(path / f"{fname}.s1p")
176 ref = np.loadtxt(path / f"{fname}_low_pass_impulse.csv", skiprows=1, delimiter=";")
177 t, y = netw.impulse_response(window="boxcar", pad=0, squeeze=True)
178
179 np.testing.assert_allclose(ref[:,0], t * 1e12, rtol=2e-5)
180 np.testing.assert_allclose(ref[:,1], y, rtol=5e-5)
181
182 def test_lps(self):
183 """Test low pass step response against data generated with METAS VNA Tools."""
184 path = Path(self.test_dir) / "metas_tdr"
185
186 for fname in ["short_10ps_dc_50g", "short_10ps_dc_40g"]:
187 netw = rf.Network(path / f"{fname}.s1p")
188 ref = np.loadtxt(path / f"{fname}_low_pass_step.csv", skiprows=1, delimiter=";")
189 t, y = netw.step_response(window="boxcar", pad=0, squeeze=True)
190
191 np.testing.assert_allclose(ref[:, 0], t * 1e12, rtol=2e-5)
192 np.testing.assert_allclose(ref[:, 1], y, rtol=5e-5)
193
194 def test_bpi(self):
195 """Test band pass impulse response against data generated with METAS VNA Tools."""
196 path = Path(self.test_dir) / "metas_tdr"
197 for window in ["boxcar", None]:
198 # Check if window=None equals to window="boxcar"
199 for fname in ["short_10ps_dc_50g", "short_10ps_dc_40g", "short_10ps_10g_50g", "short_10ps_10g_40g"]:
200
201 netw = rf.Network(path / f"{fname}.s1p")
202 ref = np.loadtxt(path / f"{fname}_band_pass_impulse.csv", skiprows=1, delimiter=";")
203 t, y = netw.impulse_response(window=window, pad=0, squeeze=True, bandpass=True)
204
205 np.testing.assert_allclose(ref[:,0], t * 1e12, rtol=2e-5)
206 np.testing.assert_allclose(ref[:,1], np.abs(y), atol=1e-5)
207
208 def test_auto_use_bandpass(self):
209 path = Path(self.test_dir) / "metas_tdr"
210
211 for fname in ["short_10ps_dc_50g", "short_10ps_10g_50g"]:
212
213 netw = rf.Network(path / f"{fname}.s1p")
214 t, _y = netw.impulse_response(window="boxcar", pad=0, squeeze=True)
215 if netw.frequency.start == 0:
216 assert len(t) == 2 * len(netw) - 1
217 else:
218 assert len(t) == len(netw)
219
220
221
222 def test_time_transform_v2(self):
223 spb = (4, 5)
224 data_rate = 5e9
225 num_taps = (100, 101)
226 for i in range(2):
227 tps = 1. / spb[i] / data_rate
228 num_points = spb[i] * num_taps[i]
229 # Frequency terms should NOT contain Nyquist frequency if number of points is odd
230 inc_nyq = True if num_points % 2 == 0 else False
231 freq = np.linspace(0, 1. / 2 / tps, num_points // 2 + 1, endpoint=inc_nyq)
232
233 dut = self.ntwk1.copy()
234 freq_valid = freq[np.logical_and(freq >= dut.f[0], freq <= dut.f[-1])]
235 dut.interpolate_self(rf.Frequency.from_f(freq_valid, unit='hz'))
236
237 dut_dc = dut.extrapolate_to_dc()
238 t, y = dut_dc.s21.impulse_response(n=num_points)
239 self.assertEqual(len(t), num_points)
240 self.assertEqual(len(y), num_points)
241 self.assertTrue(np.isclose(t[1] - t[0], tps))
242 t, y = dut_dc.s21.step_response(n=num_points)
243 self.assertEqual(len(t), num_points)
244 self.assertEqual(len(y), num_points)
245 self.assertTrue(np.isclose(t[1] - t[0], tps))
246
247 def test_impulse_response_dirac(self):
248 """
249 Test if the impulse response of a perfect transmission line is pure Dirac
250 """
251 f_points = 10
252 freq = rf.Frequency.from_f(np.arange(f_points), unit='Hz')
253 s = np.ones(10)
254 netw = rf.Network(frequency=freq, s=s)
255
256 t, y = netw.impulse_response("boxcar", pad=0)
257
258 y_true = np.zeros_like(y)
259 y_true[t == 0] = 1
260 np.testing.assert_almost_equal(y, y_true)
261
262 def test_time_transform_nonlinear_f(self):
263 netw_nonlinear_f = rf.Network(os.path.join(self.test_dir, 'ntwk_arbitrary_frequency.s2p'))
264 with self.assertRaises(NotImplementedError):
265 netw_nonlinear_f.s11.step_response()
266
267 def test_time_transform(self):
268 with self.assertWarns(RuntimeWarning):
269 self.ntwk1.s11.step_response()
270
271 def test_time_transform_multiport(self):
272 dut_dc = self.ntwk1.extrapolate_to_dc()
273
274 y1 = np.zeros((1000, dut_dc.nports, dut_dc.nports))
275
276 for (i,j) in dut_dc.port_tuples:
277 oneport = getattr(dut_dc, f's{i+1}{j+1}')
278 t1, y1[:,i,j] = oneport.step_response(n=1000)
279
280 t2, y2 = dut_dc.step_response(n=1000)
281
282 np.testing.assert_almost_equal(t1, t2)
283 np.testing.assert_almost_equal(y1, y2)
284
285 def test_time_transform_squeeze(self):
286 dut_dc = self.ntwk1.extrapolate_to_dc()
287 assert dut_dc.s11.step_response()[1].ndim == 1
288 assert dut_dc.s11.step_response(squeeze=False)[1].ndim == 3
289 assert dut_dc.step_response()[1].ndim == 3
290 assert dut_dc.step_response(squeeze=False)[1].ndim == 3
291
292 def test_constructor_empty(self):
293 rf.Network()
294
295 def test_constructor_from_values(self):
296 rf.Network(f=[1,2],s=[1,2],z0=[1,2] )
297
298 def test_constructor_from_touchstone(self):
299 rf.Network(os.path.join(self.test_dir, 'ntwk1.s2p'))
300
301 def test_constructor_from_touchstone_special_encoding(self):
302 " Test creating Network from Touchstone file with various file encodings."
303 filename_latin1 = os.path.join(self.test_dir, '../io/tests/test_encoding_ISO-8859-1.s2p')
304 filename_utf8 = os.path.join(self.test_dir, '../io/tests/test_encoding_UTF-8-SIG.s2p')
305
306 ntwk1 = rf.Network(filename_latin1)
307 ntwk1_ = rf.Network(filename_latin1, encoding='latin_1')
308 self.assertEqual(ntwk1.comments, ntwk1_.comments)
309
310 ntwk2 = rf.Network(filename_utf8, encoding='utf_8_sig')
311 self.assertEqual(ntwk1.comments, ntwk2.comments)
312
313 def test_constructor_from_hfss_touchstone(self):
314 # HFSS can provide the port characteristic impedances in its generated touchstone file.
315 # Check if reading a HFSS touchstone file with non-50Ohm impedances
316 ntwk_hfss = rf.Network(os.path.join(self.test_dir, 'hfss_threeport_DB.s3p'))
317 self.assertFalse(np.isclose(ntwk_hfss.z0[0,0], 50))
318
319 def test_constructor_from_pathlib(self):
320 rf.Network(Path(self.test_dir) / 'ntwk1.ntwk')
321
322 def test_constructor_from_pickle(self):
323 rf.Network(os.path.join(self.test_dir, 'ntwk1.ntwk'))
324
325 def test_constructor_from_fid_touchstone(self):
326 filename= os.path.join(self.test_dir, 'ntwk1.s2p')
327 with open(filename,'rb') as fid:
328 rf.Network(fid)
329 with open(filename) as fid:
330 rf.Network(fid)
331
332 def test_constructor_from_stringio(self):
333 filename= os.path.join(self.test_dir, 'ntwk1.s2p')
334 with open(filename) as fid:
335 data = fid.read()
336 sio = io.StringIO(data)
337 sio.name = os.path.basename(filename) # hack a bug to touchstone reader
338 rf.Network(sio)
339
340 def test_constructor_from_stringio_hfss(self):
341 filename = os.path.join(self.test_dir, 'hfss_oneport.s1p')
342 with open(filename) as fid:
343 data = fid.read()
344 sio = io.StringIO(data)
345 sio.name = os.path.basename(filename) # hack a bug to touchstone reader
346 rf.Network(sio)
347
348 def test_constructor_from_stringio_name_kwawrg(self):
349 filename = os.path.join(self.test_dir, 'ntwk1.s2p')
350 with open(filename) as fid:
351 data = fid.read()
352 sio = io.StringIO(data)
353 rf.Network(sio, name=filename)
354
355 def test_different_ext(self):
356 filename= os.path.join(self.test_dir, 'ntwk1.s2p')
357 for par in ["g", "h", "s", "y", "z"]:
358 with open(filename) as fid:
359 data = fid.read()
360 sio = io.StringIO(data)
361 sio.name = f"test.{par}2p"
362 rf.Network(sio)
363
364 def test_constructor_from_parameters(self):
365 """Test creating Network from all supported parameters
366 with default z0 and specified z0.
367 """
368 random_z0 = self.rng.uniform(0.1, 1, (1, 2)) + \
369 1j*self.rng.uniform(0.1, 1, (1, 2))
370 for z0 in [None, random_z0]:
371 for param in rf.Network.PRIMARY_PROPERTIES:
372 params = self.rng.uniform(0.1, 1, (1, 2, 2)) + \
373 1j*self.rng.uniform(0.1, 1, (1, 2, 2))
374 kwargs = {param:params}
375 if z0 is not None:
376 kwargs['z0'] = z0
377 net = rf.Network(**kwargs)
378 if z0 is not None:
379 np.testing.assert_allclose(net.z0, z0)
380 np.testing.assert_allclose(getattr(net, param), params)
381
382 def test_constructor_from_parameters2(self):
383 """Test creating Network from all supported parameters
384 with default z0 and specified z0.
385 Multiple frequency points and z0 broadcasted
386 """
387 random_z0 = self.rng.uniform(0.1, 1, 2) + \
388 1j*self.rng.uniform(0.1, 1, 2)
389 for z0 in [None, random_z0]:
390 for param in rf.Network.PRIMARY_PROPERTIES:
391 params = self.rng.uniform(0.1, 1, (5, 2, 2)) + \
392 1j*self.rng.uniform(0.1, 1, (5, 2, 2))
393 kwargs = {param:params}
394 if z0 is not None:
395 kwargs['z0'] = z0
396 net = rf.Network(**kwargs)
397 if z0 is not None:
398 # Network z0 is broadcasted
399 np.testing.assert_allclose(net.z0[0,:], z0)
400 np.testing.assert_allclose(getattr(net, param), params)
401
402 def test_constructor_invalid_networks(self):
403 with pytest.raises(Exception) as e_info:
404 # z0 size doesn't match
405 rf.Network(s=np.zeros((2,2,2)), z0=[1,2,3])
406 with pytest.raises(Exception) as e_info:
407 # z0 size doesn't match, Z-parameters
408 rf.Network(z=np.zeros((2,2,2)), z0=[1,2,3])
409 with pytest.raises(Exception) as e_info:
410 # Invalid s shape, non-square matrix
411 rf.Network(s=np.zeros((2,2,1)))
412 with pytest.raises(Exception) as e_info:
413 # invalid s shape, too many dimensions
414 rf.network(s=np.zeros((1,2,2,2)))
415 with pytest.raises(Exception) as e_info:
416 # Multiple input parameters
417 rf.network(s=1, z=1)
418
419 def test_zipped_touchstone(self):
420 zippath = os.path.join(self.test_dir, 'ntwks.zip')
421 fname = 'ntwk1.s2p'
422 rf.Network.zipped_touchstone(fname, zipfile.ZipFile(zippath))
423
424 def test_open_saved_touchstone(self):
425 self.ntwk1.write_touchstone('ntwk1Saved',dir=self.test_dir)
426 ntwk1Saved = rf.Network(os.path.join(self.test_dir, 'ntwk1Saved.s2p'))
427 self.assertEqual(self.ntwk1, ntwk1Saved)
428
429 # Test that it still works with Pathlib objects
430 self.ntwk1.write_touchstone(Path('ntwk1Saved'),dir=Path(self.test_dir))
431 ntwk1Saved = rf.Network(Path(os.path.join(self.test_dir, 'ntwk1Saved.s2p')))
432 self.assertEqual(self.ntwk1, ntwk1Saved)
433
434 os.remove(os.path.join(self.test_dir, 'ntwk1Saved.s2p'))
435
436 def test_write_touchstone(self):
437 ports = 2
438 s_random = self.rng.uniform(-1, 1, (self.freq.npoints, ports, ports)) +\
439 1j * self.rng.uniform(-1, 1, (self.freq.npoints, ports, ports))
440 random_z0 = self.rng.uniform(1, 100, (self.freq.npoints, ports)) +\
441 1j * self.rng.uniform(-100, 100, (self.freq.npoints, ports))
442 ntwk = rf.Network(s=s_random, frequency=self.freq, z0=random_z0, name='test_ntwk', s_def='traveling')
443
444 # Writing a network with non-constant z0 should raise
445 with pytest.raises(ValueError) as e_info:
446 snp = ntwk.write_touchstone(return_string=True)
447
448 # Writing Touchstone and reading it back
449 snp = ntwk.write_touchstone(return_string=True, write_z0=True)
450
451 strio = io.StringIO(snp)
452 # Required for reading touchstone file
453 strio.name = f'StringIO.s{ports}p'
454 ntwk2 = rf.Network(strio)
455
456 np.testing.assert_allclose(ntwk2.s, s_random)
457 np.testing.assert_allclose(ntwk2.z0, random_z0)
458
459 # Renormalize output to 50 ohms
460 snp = ntwk.write_touchstone(return_string=True, r_ref=50)
461
462 # Network should not have been modified
463 self.assertTrue(np.all(ntwk.s == s_random))
464 self.assertTrue(np.all(ntwk.z0 == random_z0))
465
466 # Read back the written touchstone
467 strio = io.StringIO(snp)
468 strio.name = f'StringIO.s{ports}p'
469 ntwk2 = rf.Network(strio)
470
471 # Renormalize original network to match the written one
472 ntwk.renormalize(50)
473
474 np.testing.assert_allclose(ntwk.s, ntwk2.s)
475 np.testing.assert_allclose(ntwk.z0, ntwk2.z0)
476
477 ntwk.z0[0, 0] = 1
478 # Writing network with non-constant real z0 should fail without r_ref
479 with pytest.raises(ValueError) as e_info:
480 snp = ntwk.write_touchstone(return_string=True)
481 ntwk.z0[0, 0] = 50
482
483 ntwk.renormalize(50 + 1j)
484
485 # Writing complex characteristic impedance should fail
486 with pytest.raises(ValueError) as e_info:
487 snp = ntwk.write_touchstone(return_string=True)
488
489 def test_write_touchstone_noisy(self):
490 ntwk = self.ntwk_noise
491
492 # Test with and without noise data formatting
493 for use_formatting in (False, True):
494 # Read back the written touchstone
495 if use_formatting:
496 ntwkstr = ntwk.write_touchstone(
497 return_string=True,
498 format_spec_freq='{:<6.4f}',
499 format_spec_A='\t{:>6.4f}',
500 format_spec_B='\t{:>6.4f}',
501 format_spec_nf_freq='{:<6.4f}',
502 format_spec_nf_min='\t{:<6.4f}',
503 format_spec_g_opt_mag='\t{:<6.4f}',
504 format_spec_g_opt_phase='\t{:<6.4f}',
505 format_spec_rn='\t{:<6.4f}',
506 )
507 else:
508 ntwkstr = ntwk.write_touchstone(return_string=True)
509 strio = io.StringIO(ntwkstr)
510 strio.name = 'StringIO.s2p'
511 new_ntwk = rf.Network(strio)
512
513 # Only compare to original noise data, not interpolated
514 ntwk.resample(ntwk.f_noise)
515 new_ntwk.resample(new_ntwk.f_noise)
516
517 # Newly written noise properties should match the original
518 np.testing.assert_allclose(ntwk.f_noise.f_scaled, new_ntwk.f_noise.f_scaled)
519 np.testing.assert_allclose(ntwk.nfmin, new_ntwk.nfmin)
520 np.testing.assert_allclose(ntwk.nfmin_db, new_ntwk.nfmin_db)
521 np.testing.assert_allclose(ntwk.g_opt, new_ntwk.g_opt)
522 np.testing.assert_allclose(ntwk.rn, new_ntwk.rn)
523 np.testing.assert_allclose(ntwk.z0, new_ntwk.z0)
524
525 def test_pickling(self):
526 original_ntwk = self.ntwk1
527 with tempfile.NamedTemporaryFile(dir=self.test_dir, suffix='ntwk') as fid:
528 pickle.dump(original_ntwk, fid, protocol=2) # Default Python2: 0, Python3: 3
529 fid.seek(0)
530 unpickled = pickle.load(fid)
531 self.assertEqual(original_ntwk, unpickled)
532
533 def test_stitch(self):
534 tmp = self.ntwk1.copy()
535 tmp.frequency = Frequency.from_f(tmp.f + tmp.f[0], 'Hz')
536 with pytest.warns(rf.frequency.InvalidFrequencyWarning):
537 c = rf.stitch(self.ntwk1, tmp)
538
539 def test_cascade(self):
540 self.assertEqual(self.ntwk1 ** self.ntwk2, self.ntwk3)
541 self.assertEqual(self.Fix ** self.DUT ** self.Fix.flipped(), self.Meas)
542
543 def test_cascade2(self):
544 self.assertEqual(self.ntwk1 >> self.ntwk2, self.ntwk3)
545 self.assertEqual(self.Fix2 >> self.DUT2 >> self.Fix2.flipped(), self.Meas2)
546
547 def test_concat_ports(self):
548 for idx in range(4):
549 i,j = 2*idx, 2*(idx+1)
550 self.assertTrue(np.allclose(self.DUT2.s[:, i:j, i:j], self.l2.s)) # check s-parameters
551 self.assertTrue(np.allclose(self.DUT2.z0[:, i:j], self.l2.z0)) # check z0
552 self.assertTrue(np.all(self.DUT2.port_modes == np.array(['S']*8))) # check port mode
553
554 def test_connect(self):
555 self.assertEqual(rf.connect(self.ntwk1, 1, self.ntwk2, 0) , \
556 self.ntwk3)
557
558 xformer = rf.Network()
559 xformer.frequency=rf.Frequency(1, 1, 1, unit='GHz')
560 xformer.s = ((0,1),(1,0)) # connects thru
561 xformer.z0 = (50,25) # transforms 50 ohm to 25 ohm
562 c = rf.connect(xformer,0,xformer,1) # connect 50 ohm port to 25 ohm port
563 self.assertTrue(np.all(np.abs(c.s-rf.impedance_mismatch(50, 25)) < 1e-6))
564
565 def test_connect_nport_2port(self):
566 freq = rf.Frequency(1, 10, npoints=10, unit='GHz')
567
568 # create a line which can be connected to each port
569 med = rf.DefinedGammaZ0(freq)
570 line = med.line(1, unit='m')
571 line.z0 = [10, 20]
572
573 for nport_portnum in [1,2,3,4,5,6,7,8]:
574
575 # create a Nport network with port impedance i at port i
576 nport = rf.Network()
577 nport.frequency = freq
578 nport.s = np.zeros((10, nport_portnum, nport_portnum))
579 nport.z0 = np.arange(start=1, stop=nport_portnum + 1)
580
581 # Connect the line to each port and check for port impedance
582 for port in range(nport_portnum):
583 nport_line = rf.connect(nport, port, line, 0)
584 z0_expected = nport.z0
585 z0_expected[:,port] = line.z0[:,1]
586 np.testing.assert_allclose(
587 nport_line.z0,
588 z0_expected
589 )
590
591 def test_connect_no_frequency(self):
592 """ Connecting 2 networks defined without frequency returns Error
593 """
594 # try to connect two networks defined without their frequency properties
595 s = self.rng.random((10, 2, 2))
596 ntwk1 = rf.Network(s=s)
597 ntwk2 = rf.Network(s=s)
598
599 with self.assertRaises(ValueError):
600 ntwk1**ntwk2
601
602 def test_connect_complex_ports(self):
603 """ Test that connecting two networks gives the same resulting network
604 (same Z-parameters) with all s_def when using complex port impedances.
605 """
606
607 # Generate random Z-parameters for two networks
608 z1 = self.rng.uniform(1, 100, size=(1, 2, 2)) +\
609 1j*self.rng.uniform(-100, 100, size=(1, 2, 2))
610 z2 = self.rng.uniform(1, 100, size=(1, 2, 2)) +\
611 1j*self.rng.uniform(-100, 100, size=(1, 2, 2))
612
613 # Port impedances
614 z0_1 = self.rng.uniform(1, 100, size=2) +\
615 1j*self.rng.uniform(-100, 100, size=2)
616 z0_2 = self.rng.uniform(1, 100, size=2) +\
617 1j*self.rng.uniform(-100, 100, size=2)
618 z0_3 = self.rng.uniform(1, 100, size=2) +\
619 1j*self.rng.uniform(-100, 100, size=2)
620
621 # Cascade Z-parameters calculated with ABCD parameters
622 net3_z = rf.a2z(rf.z2a(z1) @ rf.z2a(z2))
623
624 for s_def in rf.S_DEFINITIONS:
625 net3_ref = rf.Network(s=[[0,0],[0,0]], f=1, z0=z0_3, s_def=s_def)
626 net3_ref.z = net3_z
627
628 net1 = rf.Network(s=[[0,0],[0,0]], f=1, z0=z0_1, s_def=s_def)
629 net2 = rf.Network(s=[[0,0],[0,0]], f=1, z0=z0_2, s_def=s_def)
630 net1.z = z1
631 net2.z = z2
632
633 # Cascade calculated with S-parameters
634 net12 = net1 ** net2
635 net12.renormalize(z0_3)
636 self.assertTrue(net12.s_def == s_def)
637 self.assertTrue(net3_ref.s_def == s_def)
638 np.testing.assert_almost_equal(net3_ref.z0, net12.z0)
639 np.testing.assert_almost_equal(net12.s, net3_ref.s)
640 np.testing.assert_almost_equal(net3_z, net3_ref.z)
641
642 def test_connect_different_s_def(self):
643 """ Test that connecting two networks gives the same resulting
644 network (same Z-parameters) with all s_def when using complex port
645 impedances.
646 """
647
648 # Generate random Z-parameters for two networks
649 z1 = self.rng.uniform(1, 100, size=(1, 2, 2)) +\
650 1j*self.rng.uniform(-100, 100, size=(1, 2, 2))
651 z2 = self.rng.uniform(1, 100, size=(1, 2, 2)) +\
652 1j*self.rng.uniform(-100, 100, size=(1, 2, 2))
653
654 # Port impedances
655 z0_1 = self.rng.uniform(1, 100, size=2) +\
656 1j*self.rng.uniform(-100, 100, size=2)
657 z0_2 = self.rng.uniform(1, 100, size=2) +\
658 1j*self.rng.uniform(-100, 100, size=2)
659 z0_3 = self.rng.uniform(1, 100, size=2) +\
660 1j*self.rng.uniform(-100, 100, size=2)
661
662 # Cascade Z-parameters calculated with ABCD parameters
663 net3_z = rf.a2z(rf.z2a(z1) @ rf.z2a(z2))
664
665 for s_def1 in rf.S_DEFINITIONS:
666 net3_ref = rf.Network(s=[[0,0],[0,0]], f=1, z0=z0_3, s_def=s_def1)
667 net3_ref.z = net3_z
668 net1 = rf.Network(s=[[0,0],[0,0]], f=1, z0=z0_1, s_def=s_def1)
669 net1.z = z1
670
671 for s_def2 in rf.S_DEFINITIONS:
672 net2 = rf.Network(s=[[0,0],[0,0]], f=1, z0=z0_2, s_def=s_def2)
673 net2.z = z2
674
675 # Cascade calculated with S-parameters
676 with warnings.catch_warnings(record=True) as w:
677 # Trigger all warnings
678 warnings.simplefilter("always")
679 net12 = net1 ** net2
680 # Check that method warns about connecting networks with
681 # different s_def.
682 if net1.s_def != net2.s_def:
683 self.assertTrue(len(w) == 1)
684 else:
685 self.assertTrue(len(w) == 0)
686 net12.renormalize(z0_3)
687 self.assertTrue(net12.s_def == s_def1)
688 self.assertTrue(net3_ref.s_def == s_def1)
689 np.testing.assert_almost_equal(net3_ref.z0, net12.z0)
690 np.testing.assert_almost_equal(net12.s, net3_ref.s)
691 np.testing.assert_almost_equal(net3_z, net3_ref.z)
692
693 def test_connect_drop_ext_attrs(self):
694 """Test that connecting a network created using the Circuit's class
695 method, which has '_ext_attr' attributes, to another standard network.
696 """
697 # Create a network with '_ext_attr' attributes
698 ntwk_tmp = self.ntwk1.copy()
699 ntwk_tmp._ext_attrs['_is_circuit_open'] = True
700
701 # Connect the network to another standard network
702 ntwk_connected = rf.connect(ntwk_tmp, 1, self.ntwk2, 0)
703 self.assertFalse(ntwk_connected._ext_attrs.get('_is_circuit_open', False))
704
705 # Connect the network to another standard network
706 ntwk_connected = rf.connect(self.ntwk2, 0, ntwk_tmp, 1)
707 self.assertFalse(ntwk_connected._ext_attrs.get('_is_circuit_open', False))
708
709 def test_connect_port_names(self):
710 """Test that connecting a network with port_names to another network
711 without port_names in case of mismatch and multiple connections gives
712 the propers port_names and port impedances.
713 """
714 ntwk1 = rf.connect(self.splitter, 1, self.thru, 0, 2)
715
716 # this keeps port_names from splitter and provides port_names for thru
717 np.testing.assert_almost_equal(ntwk1.z0[0], [10, 3, 4])
718 self.assertTrue(ntwk1.port_names == ["a", "2", "3"])
719
720 # this removes port_names from splitter
721 ntwk2 = rf.connect(self.thru, 2, self.splitter, 0, 2)
722 np.testing.assert_almost_equal(ntwk2.z0[0], [1, 2, 30])
723 self.assertTrue(ntwk2.port_names is None)
724
725 def test_interconnect_complex_ports(self):
726 """ Test that connecting two complex ports in a network
727 gives the same S-parameters with all s_def when the rest of
728 the ports are real
729 """
730 for p in range(3, 5):
731 z = self.rng.uniform(1, 100, size=(1, p, p)) +\
732 1j*self.rng.uniform(-100, 100, size=(1, p, p))
733 z0 = self.rng.uniform(1, 100, size=(1, p)) + 1j*0
734 z0[:, -2:] += 1j*self.rng.uniform(-100, 100, size=(1, 2))
735 nets = []
736 for s_def in rf.S_DEFINITIONS:
737 net = rf.Network(s=np.zeros((p,p)), f=1, z0=z0, s_def=s_def)
738 net.z = z
739 # Connect the last two complex ports together
740 rf.innerconnect(net, p - 2, 2)
741 nets.append(net)
742 for net in nets[1:]:
743 np.testing.assert_almost_equal(net.s, net[0].s)
744 self.assertTrue((net.z0 == net[0].z0).all())
745 self.assertTrue(net.s_def != net[0].s_def)
746
747 def test_parallelconnect(self):
748 # Create 2 network with 2 ports
749 ntwka = rf.Network(s=self.rng.random((1, 2, 2)), f=1, name='ntwka')
750 ntwkb = rf.Network(s=self.rng.random((1, 2, 2)), f=1, name='ntwkb')
751
752 # Connect the 2 networks together by connect
753 ntwk_cnt = rf.connect(ntwka, 1, ntwkb, 0)
754
755 # Connect the 2 networks together by parallelconnect
756 ntwk_par = rf.parallelconnect([ntwka, ntwkb], [1, 0])
757
758 # Check that the two networks are the same
759 self.assertTrue(np.allclose(ntwk_cnt.s, ntwk_par.s))
760
761 def test_parallelconnect_open(self):
762 # Create a network with 4 ports
763 s = self.rng.random((1, 4, 4))
764 ntwk = rf.Network(s=s, f=1)
765 open_port = rf.Network(s=np.ones((1, 1, 1)), f=1)
766
767 # Connect the first 2 ports together by innerconnect
768 ntwk_cnt = rf.connect(ntwk, 3, open_port, 0)
769
770 # Connect the first 2 ports together by parallelconnect
771 par_ntwk = rf.parallelconnect(ntwk, [3])
772
773 # Check that the two networks are the same
774 self.assertTrue(np.allclose(ntwk_cnt.s, par_ntwk.s))
775
776 def test_parallelconnect_inner(self):
777 # Create a network with 4 ports
778 s = self.rng.random((1, 4, 4))
779 ntwk = rf.Network(s=s, f=1, name='ntwk')
780
781 # Connect the first 2 ports together by innerconnect
782 ntwk_inter = rf.innerconnect(ntwk, 0, 1)
783
784 # Connect the first 2 ports together by parallelconnect
785 par_ntwka = rf.parallelconnect([ntwk], [[0, 1]])
786 par_ntwkb = rf.parallelconnect(ntwk, [[0, 1]])
787
788 # Check that the two networks are the same
789 self.assertTrue(np.allclose(ntwk_inter.s, par_ntwka.s))
790 self.assertTrue(np.allclose(ntwk_inter.s, par_ntwkb.s))
791
792 # Connect the last 3 ports together by circuit
793 port = rf.Circuit.Port(frequency=ntwk.frequency, name='port')
794 cnx = [
795 [(port, 0), (ntwk, 0)],
796 [(ntwk, 1), (ntwk, 2), (ntwk, 3)]
797 ]
798 ckt_ntwk = rf.Circuit(cnx, name='ckt_ntwk').network
799
800 # Connect the last 3 ports together by parallelconnect
801 par_ntwk = rf.parallelconnect(ntwk, [[1, 2, 3]])
802
803 # Check that the two networks are the same
804 self.assertTrue(np.allclose(ckt_ntwk.s, par_ntwk.s))
805
806 def test_parallelconnect_mismatch(self):
807 # Create 2 network with 2 ports
808 ntwka = rf.Network(s=self.rng.random((1, 2, 2)), f=1, name='ntwka', z0=25)
809 ntwkb = rf.Network(s=self.rng.random((1, 2, 2)), f=1, name='ntwkb', z0=75)
810
811 # Connect the 2 networks together by connect
812 ntwk_cnt = rf.connect(ntwka, 1, ntwkb, 0)
813
814 # Connect the 2 networks together by parallelconnect
815 ntwk_par = rf.parallelconnect([ntwka, ntwkb], [1, 0])
816
817 # Check that the two networks are the same
818 self.assertTrue(np.allclose(ntwk_cnt.s, ntwk_par.s))
819
820 # Create matched network in circuit
821 port1 = rf.Circuit.Port(frequency=ntwka.frequency, name='port1', z0=50)
822 port2 = rf.Circuit.Port(frequency=ntwka.frequency, name='port2', z0=50)
823
824 cnx = [
825 [(port1, 0), (ntwka, 0)],
826 [(ntwka, 1), (ntwkb, 0)],
827 [(ntwkb, 1), (port2, 0)]
828 ]
829 ntwk_ckt = rf.Circuit(cnx, name='ckt_ntwk').network
830
831 # Check that the two networks are not equal
832 self.assertFalse(np.allclose(ntwk_ckt.s, ntwk_par.s))
833
834 # Renormalize matched network to match circuit
835 ntwk_par.renormalize(ntwk_ckt.z0)
836
837 # Check that the two networks are the same
838 self.assertTrue(np.allclose(ntwk_ckt.s, ntwk_par.s))
839
840
841 def test_innerconnect_with_T(self):
842 # Create 3 network with 2 ports
843 ntwka = rf.Network(s=self.rng.random((1, 2, 2)), f=1, name='ntwka')
844 ntwkb = rf.Network(s=self.rng.random((1, 2, 2)), f=1, name='ntwkb')
845 ntwkc = rf.Network(s=self.rng.random((1, 2, 2)), f=1, name='ntwkc')
846
847 # Connect the 3 networks together by tee
848 media = rf.media.DefinedGammaZ0(frequency=ntwka.frequency)
849 tee_ntwk = media.tee()
850 tee_ntwk = rf.connect(tee_ntwk, 0, ntwka, 1)
851 tee_ntwk = rf.connect(tee_ntwk, 1, ntwkb, 1)
852 tee_ntwk = rf.connect(tee_ntwk, 2, ntwkc, 1)
853
854 # Connect the 3 networks together by circuit
855 port1 = rf.Circuit.Port(frequency=ntwka.frequency, name='port1')
856 port2 = rf.Circuit.Port(frequency=ntwkb.frequency, name='port2')
857 port3 = rf.Circuit.Port(frequency=ntwkc.frequency, name='port3')
858
859 cnxs = [
860 [(port1, 0), (ntwka, 0)],
861 [(port2, 0), (ntwkb, 0)],
862 [(port3, 0), (ntwkc, 0)],
863 [(ntwka, 1), (ntwkb, 1), (ntwkc, 1)]
864 ]
865 ckt_ntwk = rf.Circuit(cnxs, name='ckt_ntwk').network
866
867 # Connect the 3 networks together by parallelconnect
868 ntwk_par = rf.parallelconnect([ntwka, ntwkb, ntwkc], [1, 1, 1])
869
870 # Check that the two networks are the same
871 self.assertTrue(np.allclose(ntwk_par.s, tee_ntwk.s))
872 self.assertTrue(np.allclose(ntwk_par.s, ckt_ntwk.s))
873
874 def test_innerconnect_with_singular_case(self):
875 # Schematic of the test circuit:
876 # +------+ +------+ +------------+ +------------+
877 # -|0 | | 1|- p1-|T1(0) T2(1)|-p3 p1-|T1(0) T2(1)|-p2
878 # | 2|----|0 | => | | => +--|T1(1) T2(2)|--+
879 # -|1 | | 2|- p2-|T1(1) T2(2)|-p4 | +------------+ |
880 # +------+ +------+ +------------+ +------------------+
881 # T1 T2 Temp Thru
882
883 # Create media and Tees
884 media = rf.media.DefinedGammaZ0()
885 T1, T2 = media.tee(name='T1'), media.tee(name='T2')
886
887 # Connect the T1 and T2 together
888 temp = rf.connect(T1, 2, T2, 0)
889
890 # Check the s-parameters of the temporary Network
891 self.assertTrue(np.allclose(temp.s, np.array([ [ [-0.5, 0.5, 0.5, 0.5],
892 [ 0.5, -0.5, 0.5, 0.5],
893 [ 0.5, 0.5, -0.5, 0.5],
894 [ 0.5, 0.5, 0.5, -0.5], ]
895 for _ in range(media.frequency.npoints) ]
896 ,dtype=complex)))
897
898 # Innerconnect the temp to ntw and compares with the expected result
899 with self.assertWarns(RuntimeWarning):
900 ntw = rf.innerconnect(temp, 1, 3)
901
902 self.assertTrue(np.allclose(ntw.s, media.thru().s))
903
904 def test_max_stable_gain(self):
905 # Check whether the maximum stable gain agrees with that derived from Y-parameters
906 y12 = self.fet.y[:, 0, 1]
907 y21 = self.fet.y[:, 1, 0]
908 # Maximum stable gain derived from Y-parameters
909 gms_y = np.abs(y21) / np.abs(y12)
910 self.assertTrue(
911 np.all(
912 np.abs(self.fet.max_stable_gain - gms_y) < 1e-6
913 )
914 )
915
916 # Check whether a runtime warning is raised when zero division occurs
917 net = rf.Network(f=[1], s=[[0, 0],[0, 0]], z0=50)
918 with pytest.raises(RuntimeWarning):
919 net.max_stable_gain
920
921 # Check whether an error is raised when the network is not 2 port.
922 net = rf.Network(f=[1], s=np.eye(3), z0=50)
923 with pytest.raises(ValueError):
924 net.max_stable_gain
925
926 def test_max_gain(self):
927 # Check whether the max gain agrees with that calculated with ADS
928 maxgain_ads = np.loadtxt(os.path.join(self.test_dir, 'maxgain_ads.csv'), encoding='utf-8', delimiter=',')
929 self.assertTrue(
930 np.all(
931 np.abs(10 * np.log10(self.fet.max_gain) - maxgain_ads[:,1]) < 1e-6
932 )
933 )
934
935 # Check whether a runtime warning is raised when zero division occurs
936 net = rf.Network(f=[1], s=[[0, 0],[0, 0]], z0=50)
937 with pytest.raises(RuntimeWarning):
938 net.max_gain
939
940 # Check whether an error is raised when the network is not 2 port.
941 net = rf.Network(f=[1], s=np.eye(3), z0=50)
942 with pytest.raises(ValueError):
943 net.max_gain
944
945 def test_unilateral_gain(self):
946 # Check whether the unilateral gain agrees with that derived from Y-parameters
947 y11 = self.fet.y[:, 0, 0]
948 y12 = self.fet.y[:, 0, 1]
949 y21 = self.fet.y[:, 1, 0]
950 y22 = self.fet.y[:, 1, 1]
951 # Unilateral gain derived from Y-parameters
952 U_y = (np.abs(y21 - y12) ** 2) \
953 / (4 * (np.real(y11) * np.real(y22) - np.real(y12) * np.real(y21)))
954 self.assertTrue(
955 np.all(
956 np.abs(self.fet.unilateral_gain - U_y) < 1e-6
957 )
958 )
959
960 # Check whether a runtime warning is raised when zero division occurs
961 net = rf.Network(f=[1], s=[[0, 0],[0, 0]], z0=50)
962 with pytest.raises(RuntimeWarning):
963 net.unilateral_gain
964
965 # Check whether an error is raised when the network is not 2 port.
966 net = rf.Network(f=[1], s=np.eye(3), z0=50)
967 with pytest.raises(ValueError):
968 net.unilateral_gain
969
970 def test_delay(self):
971 ntwk1_delayed = self.ntwk1.delay(1,'ns',port=0)
972 self.assertTrue(
973 np.all(
974 self.ntwk1.group_delay[:,:,:]
975 -ntwk1_delayed.group_delay[:,:,:]
976 -np.array(
977 [[-1.e-09+0.j, -5.e-10+0.j],
978 [-5.e-10+0.j, 0.e+00+0.j]]
979 ) < 1e-9
980 )
981 )
982 ntwk2_delayed = self.ntwk2.delay(1,'ps',port=1)
983 self.assertTrue(
984 np.all(
985 self.ntwk2.group_delay[:,:,:]
986 -ntwk2_delayed.group_delay[:,:,:]
987 -np.array(
988 [[ 0.e+00+0.j, -5.e-13+0.j],
989 [-5.e-13+0.j, -1.e-12+0.j]]
990 ) < 1e-9
991 )
992 )
993
994 def test_connect_multiports(self):
995 a = rf.Network()
996 a.frequency = rf.Frequency(1, 1, 1, unit='GHz')
997 a.s = np.arange(16).reshape(4,4)
998 a.z0 = np.arange(4) + 1 # Z0 should never be zero
999
1000 b = rf.Network()
1001 b.frequency = rf.Frequency(1, 1, 1, unit='GHz')
1002 b.s = np.arange(16).reshape(4,4)
1003 b.z0 = np.arange(4)+10
1004
1005 c=rf.connect(a,2,b,0,2)
1006 self.assertTrue((c.z0==[1,2,12,13]).all())
1007
1008 d=rf.connect(a,0,b,0,3)
1009 self.assertTrue((d.z0==[4,13]).all())
1010
1011 @pytest.mark.skip(reason="not supporting this function currently ")
1012 def test_connect_fast(self):
1013 self.assertEqual(rf.connect_fast(self.ntwk1, 1, self.ntwk2, 0) , \
1014 self.ntwk3)
1015
1016 xformer = rf.Network()
1017 xformer.frequency = rf.Frequency(1, 1, 1, unit='GHz')
1018 xformer.s = ((0,1),(1,0)) # connects thru
1019 xformer.z0 = (50,25) # transforms 50 ohm to 25 ohm
1020 c = rf.connect_fast(xformer,0,xformer,1) # connect 50 ohm port to 25 ohm port
1021 self.assertTrue(np.all(np.abs(c.s-rf.impedance_mismatch(50, 25)) < 1e-6))
1022
1023 def test_flip(self):
1024 self.assertEqual(rf.connect(self.ntwk1, 1, self.ntwk2, 0) , \
1025 self.ntwk3)
1026
1027 gain = rf.Network()
1028 gain.frequency = rf.Frequency(1, 1, 1, unit='GHz')
1029 gain.s = ((0,2),(0.5,0)) # connects thru with gain of 2.0
1030 gain.z0 = (37,82)
1031 flipped = gain.copy()
1032 flipped.flip()
1033 c = rf.connect(gain,1,flipped,0)
1034 self.assertTrue(np.all(np.abs(c.s - np.array([[0,1],[1,0]])) < 1e-6))
1035
1036 def test_renumber(self):
1037 ntwk = self.ntwk1
1038 from_ports_num = [0,1]
1039 to_ports_num = [1,0]
1040 from_ports_name = ["A", "B"]
1041 to_ports_name = ["B", "A"]
1042
1043 ntwk.port_names = from_ports_name
1044 ntwk_renum = ntwk.renumbered(from_ports_num, to_ports_num)
1045
1046 assert to_ports_name == ntwk_renum.port_names
1047
1048 def test_de_embed_by_inv(self):
1049 self.assertEqual(self.ntwk1.inv ** self.ntwk3, self.ntwk2)
1050 self.assertEqual(self.ntwk3 ** self.ntwk2.inv, self.ntwk1)
1051 self.assertEqual(self.Fix.inv ** self.Meas ** self.Fix.flipped().inv,
1052 self.DUT)
1053
1054 def test_de_embed_port_impedance(self):
1055 ntw = self.ntwk1.copy()
1056 ntw.renormalize((25, 75))
1057 ntw_inv = ntw.inv
1058 self.assertTrue(np.allclose(ntw_inv.z0, (75, 25)))
1059 rst = ntw_inv ** self.ntwk3
1060 rst.renormalize(50)
1061 self.assertEqual(rst, self.ntwk2)
1062
1063 @pytest.mark.skipif("matplotlib" not in sys.modules, reason="Requires matplotlib in sys.modules.")
1064 def test_plot_one_port_db(self):
1065 self.ntwk1.plot_s_db(0,0)
1066
1067 @pytest.mark.skipif("matplotlib" not in sys.modules, reason="Requires matplotlib in sys.modules.")
1068 def test_plot_one_port_deg(self):
1069 self.ntwk1.plot_s_deg(0,0)
1070
1071 @pytest.mark.skipif("matplotlib" not in sys.modules, reason="Requires matplotlib in sys.modules.")
1072 def test_plot_one_port_smith(self):
1073 self.ntwk1.plot_s_smith(0,0)
1074
1075 @pytest.mark.skipif("matplotlib" not in sys.modules, reason="Requires matplotlib in sys.modules.")
1076 def test_plot_two_port_db(self):
1077 self.ntwk1.plot_s_db()
1078
1079 @pytest.mark.skipif("matplotlib" not in sys.modules, reason="Requires matplotlib in sys.modules.")
1080 def test_plot_two_port_deg(self):
1081 self.ntwk1.plot_s_deg()
1082
1083 @pytest.mark.skipif("matplotlib" not in sys.modules, reason="Requires matplotlib in sys.modules.")
1084 def test_plot_two_port_smith(self):
1085 self.ntwk1.plot_s_smith()
1086
1087 @pytest.mark.skipif("matplotlib" not in sys.modules, reason="Requires matplotlib in sys.modules.")
1088 def test_plot_z_responses_singularities(self):
1089 with np.errstate(divide='raise'):
1090 self.o1.plot_z_time_impulse(window = None)
1091
1092 def test_zy_singularities(self):
1093 networks = [
1094 rf.N(f=[1], s=[1], z0=[50]),
1095 rf.N(f=[1], s=[-1], z0=[50]),
1096 rf.N(f=[1], s=[[0, 1], [1, 0]], z0=[50]),
1097 rf.N(f=[1], s=[[1, 0], [0, 1]], z0=50),
1098 rf.N(f=[1], s=[[-1, 0], [0, -1]], z0=50),
1099 rf.N(f=[1], s=[[0.5, 0.5], [0.5, 0.5]], z0=[50]),
1100 rf.N(f=[1], s=[[-0.5, -0.5], [-0.5, -0.5]], z0=[50]),
1101 ]
1102 # These conversion can be very inaccurate since results are very close
1103 # to singular.
1104 # Test that they are close with loose accuracy tolerance.
1105 for net in networks:
1106 for s_def in rf.S_DEFINITIONS:
1107 np.testing.assert_allclose(
1108 rf.z2s(rf.s2z(net.s, net.z0, s_def=s_def), net.z0, s_def=s_def), net.s, atol=1e-3
1109 )
1110 np.testing.assert_allclose(
1111 rf.y2s(rf.s2y(net.s, net.z0, s_def=s_def), net.z0, s_def=s_def), net.s, atol=1e-3
1112 )
1113
1114 def test_conversions(self):
1115 #Converting to other format and back to S-parameters should return the original network
1116 s_random = self.rng.uniform(-10, 10, (self.freq.npoints, 2, 2)) +\
1117 1j * self.rng.uniform(-10, 10, (self.freq.npoints, 2, 2))
1118 ntwk_random = rf.Network(s=s_random, frequency=self.freq)
1119 for test_z0 in (50, 10, 90+10j, 4-100j):
1120 for test_ntwk in (self.ntwk1, self.ntwk2, self.ntwk3, ntwk_random):
1121 ntwk = rf.Network(s=test_ntwk.s, f=test_ntwk.f, z0=test_z0)
1122 np.testing.assert_allclose(rf.a2s(rf.s2a(ntwk.s, test_z0), test_z0), ntwk.s)
1123 np.testing.assert_allclose(rf.z2s(rf.s2z(ntwk.s, test_z0), test_z0), ntwk.s)
1124 np.testing.assert_allclose(rf.y2s(rf.s2y(ntwk.s, test_z0), test_z0), ntwk.s)
1125 np.testing.assert_allclose(rf.h2s(rf.s2h(ntwk.s, test_z0), test_z0), ntwk.s)
1126 np.testing.assert_allclose(rf.t2s(rf.s2t(ntwk.s)), ntwk.s)
1127 np.testing.assert_allclose(rf.t2s(rf.s2t(self.Fix.s)), self.Fix.s)
1128
1129 def test_multiport_conversions(self):
1130 #Converting to other format and back to S-parameters should return the original network
1131 for ports in range(3, 6):
1132 s_random = self.rng.uniform(-10, 10, (self.freq.npoints, ports, ports)) +\
1133 1j * self.rng.uniform(-10, 10, (self.freq.npoints, ports, ports))
1134 test_ntwk = rf.Network(s=s_random, frequency=self.freq)
1135 random_z0 = self.rng.uniform(1, 100, (self.freq.npoints, ports)) +\
1136 1j * self.rng.uniform(-100, 100, (self.freq.npoints, ports))
1137 for test_z0 in (50, random_z0):
1138 for s_def in rf.S_DEFINITIONS:
1139 ntwk = rf.Network(s=test_ntwk.s, f=test_ntwk.f, z0=test_z0, s_def=s_def)
1140 np.testing.assert_allclose(
1141 rf.z2s(rf.s2z(ntwk.s, test_z0, s_def=s_def), test_z0, s_def=s_def), ntwk.s
1142 )
1143 np.testing.assert_allclose(
1144 rf.y2s(rf.s2y(ntwk.s, test_z0, s_def=s_def), test_z0, s_def=s_def), ntwk.s
1145 )
1146
1147 def test_y_z_compatability(self):
1148 # Test that np.linalg.inv(Z) == Y
1149 fpoints = 3
1150 for p in range(2, 6):
1151 s = self.rng.uniform(-1, 1, (fpoints, p, p)) + 1j * self.rng.uniform(-1, 1, (fpoints, p, p))
1152 random_z0 = self.rng.uniform(1, 100, (fpoints, p)) + 1j * self.rng.uniform(-100, 100, (fpoints, p))
1153 for test_z0 in (50, random_z0):
1154 for s_def in rf.S_DEFINITIONS:
1155 z = rf.s2z(s, test_z0, s_def=s_def)
1156 y = np.linalg.inv(z)
1157 np.testing.assert_allclose(rf.y2s(y, test_z0, s_def=s_def), s)
1158
1159 def test_unknown_s_def(self):
1160 # Test that Exception is raised when given unknown s_def
1161 s = np.array([0]).reshape(1, 1, 1)
1162 z0 = np.array([50])
1163 # These should work
1164 # These also test that functions work with dtype=float input
1165 rf.s2z(s, z0)
1166 rf.z2s(s, z0)
1167 rf.s2y(s, z0)
1168 rf.y2s(s, z0)
1169 with pytest.raises(Exception) as e:
1170 rf.s2z(s, z0, s_def='error')
1171 with pytest.raises(Exception) as e:
1172 rf.z2s(s, z0, s_def='error')
1173 with pytest.raises(Exception) as e:
1174 rf.y2s(s, z0, s_def='error')
1175 with pytest.raises(Exception) as e:
1176 rf.s2y(s, z0, s_def='error')
1177
1178 def test_sparam_renormalize(self):
1179 #Converting to other format and back to S-parameters should return the original network
1180 for ports in range(2, 6):
1181 s_random = self.rng.uniform(-10, 10, (self.freq.npoints, ports, ports)) +\
1182 1j * self.rng.uniform(-10, 10, (self.freq.npoints, ports, ports))
1183 test_ntwk = rf.Network(s=s_random, frequency=self.freq)
1184 random_z0 = self.rng.uniform(1, 100, size=(self.freq.npoints, ports)) +\
1185 1j*self.rng.uniform(-100, 100, size=(self.freq.npoints, ports))
1186 for test_z0 in (50, 20+60j, random_z0):
1187 for method in rf.S_DEFINITIONS:
1188 ntwk = rf.Network(s=test_ntwk.s, f=test_ntwk.f, z0=50)
1189 ntwk_renorm = ntwk.copy()
1190 ntwk_renorm.renormalize(test_z0, method)
1191 ntwk_renorm.renormalize(50, method)
1192 np.testing.assert_allclose(ntwk_renorm.s, ntwk.s)
1193
1194 def test_sparam_renorm_s2s(self):
1195 """
1196 Test changing S-parameter definition with complex ports
1197 """
1198 for ports in range(2, 6):
1199 s_random = self.rng.uniform(-10, 10, (self.freq.npoints, ports, ports)) +\
1200 1j * self.rng.uniform(-10, 10, (self.freq.npoints, ports, ports))
1201 test_ntwk = rf.Network(s=s_random, frequency=self.freq)
1202 random_z0 = self.rng.uniform(1, 100, size=(self.freq.npoints, ports)) +\
1203 1j*self.rng.uniform(-100, 100, size=(self.freq.npoints, ports))
1204 for def1 in rf.S_DEFINITIONS:
1205 for def2 in rf.S_DEFINITIONS:
1206 ntwk = rf.Network(s=test_ntwk.s, f=test_ntwk.f, z0=random_z0, s_def=def1)
1207 ntwk_renorm = ntwk.copy()
1208 ntwk_renorm.renormalize(ntwk.z0, s_def=def2)
1209 np.testing.assert_allclose(ntwk_renorm.z, ntwk.z)
1210 ntwk_renorm.renormalize(ntwk.z0, s_def=def1)
1211 np.testing.assert_allclose(ntwk_renorm.s, ntwk.s)
1212 np.testing.assert_allclose(ntwk_renorm.z0, ntwk.z0)
1213
1214 def test_sparam_renorm_different_z0(self):
1215 """
1216 Test changing S-parameter definition with complex ports.
1217 renormalize handles cases with same z0 and different z0 before and
1218 after conversion with different method.
1219 """
1220 for ports in range(2, 6):
1221 s_random = self.rng.uniform(-10, 10, (self.freq.npoints, ports, ports)) +\
1222 1j * self.rng.uniform(-10, 10, (self.freq.npoints, ports, ports))
1223 test_ntwk = rf.Network(s=s_random, frequency=self.freq)
1224 random_z0 = self.rng.uniform(1, 100, size=(self.freq.npoints, ports)) +\
1225 1j*self.rng.uniform(-100, 100, size=(self.freq.npoints, ports))
1226 random_z0_2 = self.rng.uniform(1, 100, size=(self.freq.npoints, ports)) +\
1227 1j*self.rng.uniform(-100, 100, size=(self.freq.npoints, ports))
1228 for def1 in rf.S_DEFINITIONS:
1229 for def2 in rf.S_DEFINITIONS:
1230 ntwk = rf.Network(s=test_ntwk.s, f=test_ntwk.f, z0=random_z0, s_def=def1)
1231 ntwk_renorm = ntwk.copy()
1232 ntwk_renorm.renormalize(random_z0_2, s_def=def2)
1233 np.testing.assert_allclose(ntwk_renorm.z, ntwk.z)
1234 ntwk_renorm.renormalize(ntwk.z0, s_def=def1)
1235 np.testing.assert_allclose(ntwk_renorm.s, ntwk.s)
1236 np.testing.assert_allclose(ntwk_renorm.z0, ntwk.z0)
1237
1238 def test_setters(self):
1239 s_random = self.rng.uniform(-10, 10, (self.freq.npoints, 2, 2)) +\
1240 1j * self.rng.uniform(-10, 10, (self.freq.npoints, 2, 2))
1241 ntwk = rf.Network(s=s_random, frequency=self.freq)
1242 ntwk.z0 = self.rng.uniform(1, 100, len(ntwk.z0)) + 1j*self.rng.uniform(-100, 100, len(ntwk.z0))
1243 ntwk.s = ntwk.s
1244 np.testing.assert_allclose(ntwk.s, s_random)
1245 ntwk.a = ntwk.a
1246 np.testing.assert_allclose(ntwk.s, s_random)
1247 ntwk.z = ntwk.z
1248 np.testing.assert_allclose(ntwk.s, s_random)
1249 ntwk.y = ntwk.y
1250 np.testing.assert_allclose(ntwk.s, s_random)
1251 ntwk.t = ntwk.t
1252 np.testing.assert_allclose(ntwk.s, s_random)
1253 ntwk.h = ntwk.h
1254 np.testing.assert_allclose(ntwk.s, s_random)
1255
1256 def test_s_def_setters(self):
1257 s_random = self.rng.uniform(-10, 10, (self.freq.npoints, 2, 2)) +\
1258 1j * self.rng.uniform(-10, 10, (self.freq.npoints, 2, 2))
1259 z0_scalar = 50
1260 z0_array_port = self.rng.uniform(1, 100, 2)
1261 z0_array_freq = self.rng.uniform(1, 100, self.freq.npoints) +\
1262 1j*self.rng.uniform(-100, 100, self.freq.npoints)
1263 z0_array_freq_port = self.rng.uniform(1, 100, (self.freq.npoints,2)) +\
1264 1j*self.rng.uniform(-100, 100, (self.freq.npoints,2))
1265
1266 for z0 in [z0_scalar, z0_array_port, z0_array_freq, z0_array_freq_port]:
1267 ntwk = rf.Network(s=s_random, frequency=self.freq, z0=z0)
1268
1269 s_traveling = rf.s2s(s_random, z0, 'traveling', ntwk.s_def)
1270 s_power = rf.s2s(s_random, z0, 'power', ntwk.s_def)
1271 s_pseudo = rf.s2s(s_random, z0, 'pseudo', ntwk.s_def)
1272
1273 ntwk.s_traveling = s_traveling
1274 np.testing.assert_allclose(ntwk.s, s_random)
1275 ntwk.s_power = s_power
1276 np.testing.assert_allclose(ntwk.s, s_random)
1277 ntwk.s_pseudo = s_pseudo
1278 np.testing.assert_allclose(ntwk.s, s_random)
1279
1280 np.testing.assert_allclose(ntwk.s_traveling, s_traveling)
1281 np.testing.assert_allclose(ntwk.s_power, s_power)
1282 np.testing.assert_allclose(ntwk.s_pseudo, s_pseudo)
1283
1284 def test_sparam_conversion_with_complex_char_impedance(self):
1285 """
1286 Renormalize a 2-port network wrt to complex characteristic impedances
1287 using power-waves definition of s-param
1288 Example based on scikit-rf issue #313
1289 """
1290 f0 = rf.Frequency(75.8, npoints=1, unit='GHz')
1291 s0 = np.array([
1292 [-0.194 - 0.228j, -0.721 + 0.160j],
1293 [-0.721 + 0.160j, +0.071 - 0.204j]])
1294 ntw = rf.Network(frequency=f0, s=s0, z0=50, name='dut')
1295
1296 # complex characteristic impedance to renormalize to
1297 zdut = 100 + 10j
1298
1299 # reference solutions obtained from ANSYS Circuit or ADS (same res)
1300 # case 1: z0=[50, zdut]
1301 s_ref = np.array([[
1302 [-0.01629813-0.29764199j, -0.6726785 +0.24747539j],
1303 [-0.6726785 +0.24747539j, -0.30104687-0.10693578j]]])
1304 np.testing.assert_allclose(rf.z2s(ntw.z, z0=[50, zdut]), s_ref)
1305 np.testing.assert_allclose(rf.renormalize_s(ntw.s, [50,50], [50,zdut]), s_ref)
1306
1307 # case 2: z0=[zdut, zdut]
1308 s_ref = np.array([[
1309 [-0.402829859501534 - 0.165007172677339j,-0.586542065592524 + 0.336098534178339j],
1310 [-0.586542065592524 + 0.336098534178339j,-0.164707376748782 - 0.21617153431756j]]])
1311 np.testing.assert_allclose(rf.z2s(ntw.z, z0=[zdut, zdut]), s_ref)
1312 np.testing.assert_allclose(rf.renormalize_s(ntw.s, [50,50], [zdut,zdut]), s_ref)
1313
1314 # Comparing Z and Y matrices from reference ones (from ADS)
1315 # Z or Y matrices do not depend of characteristic impedances.
1316 # Precision is 1e-4 due to rounded results in ADS export files
1317 z_ref = np.array([[
1318 [34.1507 -65.6786j, -37.7994 +73.7669j],
1319 [-37.7994 +73.7669j, 55.2001 -86.8618j]]])
1320 np.testing.assert_allclose(ntw.z, z_ref, atol=1e-4)
1321
1322 y_ref = np.array([[
1323 [0.0926 +0.0368j, 0.0770 +0.0226j],
1324 [0.0770 +0.0226j, 0.0686 +0.0206j]]])
1325 np.testing.assert_allclose(ntw.y, y_ref, atol=1e-4)
1326
1327 def test_sparam_conversion_vs_sdefinition(self):
1328 """
1329 Check that power-wave or pseudo-waves scattering parameters definitions
1330 give same results for real characteristic impedances
1331 """
1332 f0 = rf.Frequency(75.8, npoints=1, unit='GHz')
1333 s_ref = np.array([[ # random values
1334 [-0.1000 -0.2000j, -0.3000 +0.4000j],
1335 [-0.3000 +0.4000j, 0.5000 -0.6000j]]])
1336 ntw = rf.Network(frequency=f0, s=s_ref, z0=50, name='dut')
1337
1338 # renormalize s parameter according one of the definition.
1339 # As characteristic impedances are all real, should be all equal
1340 np.testing.assert_allclose(ntw.s, s_ref)
1341 np.testing.assert_allclose(rf.renormalize_s(ntw.s, 50, 50, s_def='power'), s_ref)
1342 np.testing.assert_allclose(rf.renormalize_s(ntw.s, 50, 50, s_def='pseudo'), s_ref)
1343 np.testing.assert_allclose(rf.renormalize_s(ntw.s, 50, 50, s_def='traveling'), s_ref)
1344
1345 # also check Z and Y matrices, just in case
1346 z_ref = np.array([[
1347 [18.0000 -16.0000j, 20.0000 + 40.0000j],
1348 [20.0000 +40.0000j, 10.0000 -80.0000j]]])
1349 np.testing.assert_allclose(ntw.z, z_ref, atol=1e-4)
1350
1351 y_ref = np.array([[
1352 [0.0251 +0.0023j, 0.0123 -0.0066j],
1353 [0.0123 -0.0066j, 0.0052 +0.0055j]]])
1354 np.testing.assert_allclose(ntw.y, y_ref, atol=1e-4)
1355
1356 # creating network by specifying s-params definition
1357 ntw_power = rf.Network(frequency=f0, s=s_ref, z0=50, s_def='power')
1358 ntw_pseudo = rf.Network(frequency=f0, s=s_ref, z0=50, s_def='pseudo')
1359 ntw_legacy = rf.Network(frequency=f0, s=s_ref, z0=50, s_def='traveling')
1360 self.assertTrue(ntw_power == ntw_pseudo)
1361 self.assertTrue(ntw_power == ntw_legacy)
1362
1363 def test_sparam_from_hfss_with_power_wave(self):
1364 """
1365 Open a Touchstone generated by HFSS with the power-wave definition.
1366 """
1367 pwfile = 'hfss_oneport_powerwave.s1p'
1368 pwfile_skrf = 'tmp_skrf_oneport_powerwave.s1p'
1369
1370 # s_def must be explicitly passed as 'power',
1371 # otherwise 'traveling' would have been assumed (being default HFSS setting)
1372 ntwk_orig = rf.Network(os.path.join(self.test_dir, pwfile))
1373 self.assertEqual(ntwk_orig.s_def, S_DEF_HFSS_DEFAULT)
1374
1375 ntwk_orig = rf.Network(os.path.join(self.test_dir, pwfile), s_def='power')
1376 self.assertEqual(ntwk_orig.s_def, 'power')
1377
1378 # write Touchstone file and read it. Results should be the same
1379 ntwk_orig.write_touchstone(os.path.join(self.test_dir, pwfile_skrf), write_z0=True, form='RI')
1380 ntwk_skrf = rf.Network(os.path.join(self.test_dir, pwfile_skrf))
1381
1382 # check if the s_def could be correctly recovered from scikit-rf's Touchstone file
1383 self.assertTrue(ntwk_orig.s_def == ntwk_skrf.s_def)
1384 self.assertTrue(ntwk_orig == ntwk_skrf)
1385
1386 def test_network_from_z_or_y(self):
1387 ' Construct a network from its z or y parameters '
1388 # test for both real and complex char. impedance
1389 # and for 2 frequencies
1390 z0 = [self.rng.random(), self.rng.random()+1j*self.rng.random()]
1391 freqs = np.array([1, 2])
1392 # generate arbitrary complex z and y
1393 z_ref = self.rng.random((2,3,3)) + 1j*self.rng.random((2,3,3))
1394 y_ref = self.rng.random((2,3,3)) + 1j*self.rng.random((2,3,3))
1395 # create networks from z or y and compare ntw.z to the reference
1396 # check that the conversions work for all s-param definitions
1397 for s_def in S_DEFINITIONS:
1398 ntwk = rf.Network(s_def=s_def)
1399 ntwk.z0 = rf.fix_z0_shape(z0, 2, 3)
1400 ntwk.frequency = Frequency.from_f(freqs, unit='GHz')
1401 # test #1: define the network directly from z
1402 ntwk.z = z_ref
1403 np.testing.assert_allclose(ntwk.z, z_ref)
1404 # test #2: define the network from s, after z -> s (s_def is important)
1405 ntwk.s = rf.z2s(z_ref, z0, s_def=s_def)
1406 np.testing.assert_allclose(ntwk.z, z_ref)
1407 # test #3: define the network directly from y
1408 ntwk.y = y_ref
1409 np.testing.assert_allclose(ntwk.y, y_ref)
1410 # test #4: define the network from s, after y -> s (s_def is important)
1411 ntwk.s = rf.y2s(y_ref, z0, s_def=s_def)
1412 np.testing.assert_allclose(ntwk.y, y_ref)
1413
1414 def test_z0_pure_imaginary(self):
1415 ' Test cases where z0 is pure imaginary '
1416 # test that conversion to Z or Y does not give NaN for pure imag z0
1417 for s_def in S_DEFINITIONS:
1418 ntwk = rf.Network(s_def=s_def)
1419 ntwk.z0 = np.array([50j, -50j])
1420 ntwk.frequency = Frequency.from_f(np.array([1000]), unit='GHz')
1421 ntwk.s = self.rng.random((1,2,2)) + self.rng.random((1,2,2))*1j
1422 self.assertFalse(np.any(np.isnan(ntwk.z)))
1423 self.assertFalse(np.any(np.isnan(ntwk.y)))
1424
1425 def test_z0_scalar(self):
1426 'Test a scalar z0'
1427 ntwk = rf.Network()
1428 ntwk.z0 = 1
1429 # Test setting the z0 before and after setting the s shape
1430 self.assertEqual(ntwk.z0, 1)
1431 ntwk.s = self.rng.random((1,2,2))
1432 ntwk.z0 = 10
1433 self.assertTrue(np.allclose(ntwk.z0, np.full((1,2), 10)))
1434
1435 def test_z0_vector(self):
1436 'Test a 1 dimensional z0'
1437 ntwk = rf.Network()
1438 z0 = [1,2]
1439 # Test setting the z0 before and after setting the s shape
1440 ntwk.z0 = [1,2] # Passing as List
1441 self.assertTrue(np.allclose(ntwk.z0, np.array(z0, dtype=complex)))
1442 ntwk.z0 = np.array(z0[::-1]) # Passing as np.array
1443 self.assertTrue(np.allclose(ntwk.z0, np.array(z0[::-1], dtype=complex)))
1444
1445 # If the s-array has been set, the z0 value should broadcast to the required shape
1446 ntwk.s = self.rng.random((3,2,2))
1447 ntwk.z0 = z0
1448 self.assertTrue(np.allclose(ntwk.z0, np.array([z0, z0, z0], dtype=complex)))
1449
1450 # If the s-array has been set and we want to set z0 along the frequency axis,
1451 # wer require the frequency vector to be set too.
1452 # Unfortunately the frequency vector and the s shape can distinguish
1453 z0 = [1,2,3]
1454 ntwk.s = self.rng.random((3,2,2))
1455 ntwk.z0 = z0[::-1]
1456
1457 ntwk.frequency = Frequency.from_f([1,2,3], unit='GHz')
1458 self.assertTrue(np.allclose(ntwk.z0, np.array([z0[::-1], z0[::-1]], dtype=complex).T))
1459
1460 def test_z0_matrix(self):
1461 ntwk = rf.Network()
1462 z0 = [[1,2]]
1463 ntwk.z0 = z0
1464 self.assertTrue(np.allclose(ntwk.z0, np.array(z0, dtype=complex)))
1465 ntwk.z0 = np.array(z0) + 1 # Passing as np.array
1466 self.assertTrue(np.allclose(ntwk.z0, np.array(z0, dtype=complex)+1))
1467
1468 # Setting the frequency is required to be set, as the matrix size is checked against the
1469 # frequency vector
1470 ntwk.s = self.rng.random((1,2,2))
1471 ntwk.frequency = Frequency.from_f([1], unit='GHz')
1472 ntwk.z0 = z0
1473 self.assertTrue(np.allclose(ntwk.z0, np.array(z0, dtype=complex)))
1474
1475 def test_z0_assign(self):
1476 """ Test that z0 getter returns a reference to _z0 so that it can
1477 be assigned to with array indexing"""
1478 ntwk = rf.Network(s=np.zeros((3,2,2)), f=[1,2,3])
1479 ntwk.z0[0, 0] = 2
1480 self.assertTrue(ntwk.z0[0, 0] == 2)
1481
1482 ntwk = rf.Network(s=np.zeros((3,2,2)), f=[1,2,3], z0=np.ones(3))
1483 ntwk.z0[0, 0] = 2
1484 self.assertTrue(ntwk.z0[0, 0] == 2)
1485
1486 ntwk = rf.Network(s=np.zeros((3,2,2)), f=[1,2,3], z0=np.ones((3,2)))
1487 ntwk.z0[0, 0] = 2
1488 self.assertTrue(ntwk.z0[0, 0] == 2)
1489
1490 def test_yz(self):
1491 tinyfloat = 1e-12
1492 ntwk = rf.Network()
1493 ntwk.z0 = np.array([28,75+3j])
1494 ntwk.frequency = Frequency.from_f(np.array([1000, 2000]), unit='GHz')
1495 ntwk.s = rf.z2s(np.array([[[1+1j,5,11],[40,5,3],[16,8,9+8j]],
1496 [[1,20,3],[14,10,16],[27,18,-19-2j]]]))
1497 self.assertTrue((abs(rf.y2z(ntwk.y)-ntwk.z) < tinyfloat).all())
1498 self.assertTrue((abs(rf.y2s(ntwk.y, ntwk.z0)-ntwk.s) < tinyfloat).all())
1499 self.assertTrue((abs(rf.z2y(ntwk.z)-ntwk.y) < tinyfloat).all())
1500 self.assertTrue((abs(rf.z2s(ntwk.z, ntwk.z0)-ntwk.s) < tinyfloat).all())
1501
1502 def test_mul(self):
1503 a = rf.N(f=[1,2],s=[1+2j, 3+4j],z0=1)
1504 # operating on networks
1505 self.assertTrue( ((a*a).s == np.array([[[-3+4j]],[[-7+24j]]])).all())
1506 # operating on numbers
1507 self.assertTrue( ((2*a*2).s == np.array([[[4+8j]],[[12+16j]]])).all())
1508 # operating on list
1509 self.assertTrue( ((a*[1,2]).s == np.array([[[1+2j]],[[6+8j]]])).all())
1510 self.assertTrue( (([1,2]*a).s == np.array([[[1+2j]],[[6+8j]]])).all())
1511
1512 def test_sub(self):
1513 a = rf.N(f=[1,2],s=[1+2j, 3+4j],z0=1)
1514 # operating on networks
1515 self.assertTrue( ((a-a).s == np.array([[[0+0j]],[[0+0j]]])).all())
1516 # operating on numbers
1517 self.assertTrue( ((a-(2+2j)).s == np.array([[[-1+0j]],[[1+2j]]])).all())
1518 # operating on list
1519 self.assertTrue( ((a-[1+1j,2+2j]).s == np.array([[[0+1j]],[[1+2j]]])).all())
1520
1521 def test_div(self):
1522 a = rf.N(f=[1,2],s=[1+2j, 3+4j],z0=1)
1523 # operating on networks
1524 self.assertTrue( ((a/a).s == np.array([[[1+0j]],[[1+0j]]])).all())
1525 # operating on numbers
1526 self.assertTrue( ((a/2.).s == np.array([[[.5+1j]],[[3/2.+2j]]])).all())
1527 # operating on list
1528 self.assertTrue( ((a/[1,2]).s == np.array([[[1+2j]],[[3/2.+2j]]])).all())
1529
1530 def test_add(self):
1531 a = rf.N(f=[1,2],s=[1+2j, 3+4j],z0=1)
1532 # operating on networks
1533 self.assertTrue( ((a+a).s == np.array([[[2+4j]],[[6+8j]]])).all())
1534 # operating on numbers
1535 self.assertTrue( ((a+2+2j).s == np.array([[[3+4j]],[[5+6j]]])).all())
1536 # operating on list
1537 self.assertTrue( ((a+[1+1j,2+2j]).s == np.array([[[2+3j]],[[5+6j]]])).all())
1538
1539
1540 def test_interpolate_linear(self):
1541 net = rf.Network(f=[0, 1, 3, 4], s=[0,1,9,16], f_unit="Hz")
1542
1543 interp = net.interpolate(rf.Frequency(0, 4, 5, unit="Hz"), kind="linear")
1544 assert np.allclose(interp.s[2], 5.0)
1545
1546 def test_interpolate_cubic(self):
1547 net = rf.Network(f=[0, 1, 3, 4], s=[0,1,9,16], f_unit="Hz")
1548
1549 interp = net.interpolate(rf.Frequency(0, 4, 5, unit="Hz"), kind="cubic")
1550 assert np.allclose(interp.s[2], 4.0)
1551
1552 def test_interpolate_rational(self):
1553 a = rf.N(f=np.linspace(1,2,5),s=np.linspace(0,1,5)*(1+1j),z0=1, f_unit="ghz")
1554 freq = rf.F.from_f(np.linspace(1,2,6,endpoint=True), unit='GHz')
1555 b = a.interpolate(freq, kind='rational')
1556 self.assertFalse(any(np.isnan(b.s)))
1557 # Test that the endpoints are the equal
1558 self.assertTrue(b.s[0] == a.s[0])
1559 self.assertTrue(b.s[-1] == a.s[-1])
1560 # Check that abs(S) is increasing
1561 self.assertTrue(all(np.diff(np.abs(b.s.flatten())) > 0))
1562 self.assertTrue(b.z0[0] == a.z0[0])
1563
1564 def test_interpolate_freq_cropped(self):
1565 a = rf.N(f=np.arange(20), s=np.arange(20)*(1+1j),z0=1, f_unit="ghz")
1566 freq = rf.F.from_f(np.linspace(1,2,3,endpoint=True), unit='GHz')
1567 for method in ('linear', 'cubic', 'quadratic', 'rational'):
1568 b = a.interpolate(freq, freq_cropped=False, kind=method)
1569 c = a.interpolate(freq, kind=method)
1570 self.assertTrue(np.allclose(b.s, c.s))
1571
1572 def test_interpolate_self(self):
1573 """Test resample."""
1574 a = rf.N(f=[1,2], s=[1+2j, 3+4j], z0=1)
1575 a.interpolate_self(4)
1576 self.assertEqual(len(a), 4)
1577 # also test the alias name
1578 a.resample(6)
1579 self.assertEqual(len(a), 6)
1580 # TODO: numerically test for correct interpolation
1581
1582 def test_slicer(self):
1583 a = rf.Network(f=[1,2,4,5,6],
1584 s=[1,1,1,1,1],
1585 z0=50,
1586 f_unit="ghz")
1587
1588 b = a['2-5ghz']
1589 tinyfloat = 1e-12
1590 self.assertTrue((abs(b.frequency.f - [2e9,4e9,5e9]) < tinyfloat).all())
1591
1592 # Network classifiers
1593 def test_is_reciprocal(self):
1594 a = rf.Network(f=[1],
1595 s=[[0, 1, 0],
1596 [0, 0, 1],
1597 [1, 0, 0]],
1598 z0=50)
1599 self.assertFalse(a.is_reciprocal(), 'A circulator is not reciprocal.')
1600 b = rf.Network(f=[1],
1601 s=[[0, 0.5, 0.5],
1602 [0.5, 0, 0.5],
1603 [0.5, 0.5, 0]],
1604 z0=50)
1605 self.assertTrue(b.is_reciprocal(), 'This power divider is reciprocal.')
1606 return
1607
1608 def test_is_symmetric(self):
1609 # 2-port
1610 a = rf.Network(f=[1, 2, 3],
1611 s=[[[-1, 0], [0, -1]],
1612 [[-2, 0], [0, -2]],
1613 [[1, 0], [0, 1]]],
1614 z0=50)
1615 self.assertTrue(a.is_symmetric(), 'A short is symmetric.')
1616 self.assertRaises(ValueError, a.is_symmetric, port_order={1: 2}) # error raised by renumber()
1617 a.s[0, 0, 0] = 1
1618 self.assertFalse(a.is_symmetric(), 'non-symmetrical')
1619
1620 # another 2-port (transmission line with 201 frequency samples)
1621 nw_line = rf.data.line
1622 self.assertTrue(nw_line.is_symmetric())
1623
1624 # another 2-port (ring slot with 201 frequency samples)
1625 nw_ringslot = rf.data.ring_slot
1626 self.assertFalse(nw_ringslot.is_symmetric())
1627
1628 # 3-port
1629 b = rf.Network(f=[1, 3],
1630 s=[[[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]],
1631 [[0, 0.2, 0.2], [0.2, 0, 0.2], [0.2, 0.2, 0]]],
1632 z0=50)
1633 with self.assertRaises(ValueError) as context:
1634 b.is_symmetric()
1635 self.assertEqual(str(context.exception),
1636 'Using is_symmetric() is only valid for a 2N-port network (N=2,4,6,8,...)')
1637
1638 # 4-port
1639 c = rf.Network(f=[1, 3, 5, 6],
1640 s=[[[0, 1j, 1, 0], [1j, 0, 0, 1], [1, 0, 0, 1j], [0, 1, 1j, 0]],
1641 [[0, 0.8j, 0.7, 0], [0.8j, 0, 0, 0.7], [0.7, 0, 0, 0.8j], [0, 0.7, 0.8j, 0]],
1642 [[0, 0.3j, 1, 0], [0.3j, 0, 0, 1], [1, 0, 0, 0.3j], [0, 1, 0.3j, 0]],
1643 [[0, -1j, -1, 0], [-1j, 0, 0, -1], [-1, 0, 0, -1j], [0, -1, -1j, 0]]],
1644 z0=50)
1645 self.assertTrue(c.is_symmetric(n=2), 'This quadrature hybrid coupler is symmetric.')
1646 self.assertTrue(c.is_symmetric(n=2, port_order={0: 1, 1: 2, 2: 3, 3: 0}),
1647 'This quadrature hybrid coupler is symmetric even after rotation.')
1648 with self.assertRaises(ValueError) as context:
1649 c.is_symmetric(n=3)
1650 self.assertEqual(str(context.exception), 'specified order n = 3 must be between 1 and N = 2, inclusive')
1651
1652 d = rf.Network(f=[1],
1653 s=[[1, 0, 0, 0],
1654 [1, 0, 0, 0],
1655 [1, 0, 0, 1],
1656 [0, 1, 0, 1]],
1657 z0=50)
1658 self.assertTrue(d.is_symmetric(n=1), 'This contrived non-reciprocal device has a line of symmetry.')
1659 self.assertFalse(d.is_symmetric(n=2), 'This device only has first-order line symmetry.')
1660 self.assertFalse(d.is_symmetric(port_order={0: 1, 1: 0}),
1661 'This device is no longer symmetric after reordering ports 1 and 2.')
1662 self.assertTrue(d.is_symmetric(port_order={0: 1, 1: 0, 2: 3, 3: 2}),
1663 'This device is symmetric after swapping ports 1 with 2 and 3 with 4.')
1664
1665 # 6-port
1666 x = rf.Network(f=[1],
1667 s=[[0, 0, 0, 0, 0, 0],
1668 [0, 1, 9, 0, 0, 0],
1669 [0, 0, 2, 0, 0, 0],
1670 [0, 0, 0, 2, 0, 0],
1671 [0, 0, 0, 9, 1, 0],
1672 [0, 0, 0, 0, 0, 0]],
1673 z0=50)
1674 self.assertFalse(x.is_symmetric(n=3))
1675 self.assertFalse(x.is_symmetric(n=2))
1676 self.assertTrue(x.is_symmetric(n=1))
1677 self.assertTrue(x.is_symmetric(n=1, port_order={-3: -1, -1: -3, 0: 2, 2: 0}))
1678
1679 # 8-port
1680 s8p_diag = [1j, -1j, -1j, 1j, 1j, -1j, -1j, 1j]
1681 s8p_mat = np.identity(8, dtype=complex)
1682 for row in range(8):
1683 s8p_mat[row, :] *= s8p_diag[row]
1684 y = rf.Network(f=[1],
1685 s=s8p_mat,
1686 z0=50)
1687 self.assertTrue(y.is_symmetric())
1688 self.assertTrue(y.is_symmetric(n=2))
1689 self.assertFalse(y.is_symmetric(n=4))
1690 return
1691
1692 def test_is_passive(self):
1693 a = rf.Network(f=[1],
1694 s=[[0, 0.5, 0.5],
1695 [0.5, 0, 0.5],
1696 [0.5, 0.5, 0]],
1697 z0=50)
1698 self.assertTrue(a.is_passive(), 'This power divider is passive.')
1699 b = rf.Network(f=[1],
1700 s=[[0, 0],
1701 [10, 0]],
1702 z0=50)
1703 self.assertFalse(b.is_passive(), 'A unilateral amplifier is not passive.')
1704 return
1705
1706 def test_is_lossless(self):
1707 a = rf.Network(f=[1],
1708 s=[[0, 0.5, 0.5],
1709 [0.5, 0, 0.5],
1710 [0.5, 0.5, 0]],
1711 z0=50)
1712 self.assertFalse(a.is_lossless(), 'A resistive power divider is lossy.')
1713 b = rf.Network(f=[1],
1714 s=[[0, -1j/np.sqrt(2), -1j/np.sqrt(2)],
1715 [-1j/np.sqrt(2), 1./2, -1./2],
1716 [-1j/np.sqrt(2), -1./2, 1./2]],
1717 z0=50)
1718 self.assertTrue(b.is_lossless(), 'This unmatched power divider is lossless.')
1719 return
1720
1721 def test_noise(self):
1722 a = self.ntwk_noise
1723
1724 nf = 10**(0.05)
1725 self.assertTrue(a.noisy)
1726 self.assertTrue(abs(a.nfmin[0] - nf) < 1.e-6, 'noise figure does not match original spec')
1727 self.assertTrue(abs(a.z_opt[0] - 50.) < 1.e-6, 'optimal resistance does not match original spec')
1728 self.assertTrue(abs(a.rn[0] - 0.1159*50.) < 1.e-6, 'equivalent resistance does not match original spec')
1729 self.assertTrue(np.all(abs(a.g_opt) < 1.e-6),
1730 'calculated optimal reflection coefficient does not match original coefficients')
1731
1732 b = rf.Network(f=[1, 2],
1733 s=[[[0, 1], [1, 0]], [[0, 1], [1, 0]]],
1734 z0=50, f_unit="ghz").interpolate(a.frequency)
1735 with self.assertRaises(ValueError) as context:
1736 b.n
1737 with self.assertRaises(ValueError) as context:
1738 b.f_noise
1739 self.assertEqual(str(context.exception), 'network does not have noise')
1740
1741 c = a ** b
1742 self.assertTrue(a.noisy)
1743 self.assertTrue(abs(c.nfmin[0] - nf) < 1.e-6, 'noise figure does not match original spec')
1744 self.assertTrue(abs(c.z_opt[0] - 50.) < 1.e-6, 'optimal resistance does not match original spec')
1745 self.assertTrue(abs(c.rn[0] - 0.1159*50.) < 1.e-6, 'equivalent resistance does not match original spec')
1746
1747 d = b ** a
1748 self.assertTrue(d.noisy)
1749 self.assertTrue(abs(d.nfmin[0] - nf) < 1.e-6, 'noise figure does not match original spec')
1750 self.assertTrue(abs(d.z_opt[0] - 50.) < 1.e-6, 'optimal resistance does not match original spec')
1751 self.assertTrue(abs(d.rn[0] - 0.1159*50.) < 1.e-6, 'equivalent resistance does not match original spec')
1752
1753 e = a ** a
1754 self.assertTrue(abs(e.nfmin[0] - (nf + (nf-1)/(10**2))) < 1.e-6, 'noise figure does not match Friis formula')
1755
1756 self.assertTrue(a.noisy)
1757 self.assertTrue(abs(a.nfmin[0] - nf) < 1.e-6, 'noise figure was altered')
1758 self.assertTrue(abs(a.z_opt[0] - 50.) < 1.e-6, 'optimal resistance was altered')
1759 self.assertTrue(abs(a.rn[0] - 0.1159*50.) < 1.e-6, 'equivalent resistance was altered')
1760
1761 tem = DistributedCircuit(z0_port = 50)
1762 inductor = tem.inductor(1e-9).interpolate(a.frequency)
1763
1764 f = inductor ** a
1765 expected_zopt = 50 - 2j*np.pi*1e+9*1e-9
1766 self.assertTrue(abs(f.z_opt[0] - expected_zopt) < 1.e-6, 'optimal resistance was not 50 ohms - inductor')
1767
1768
1769 return
1770
1771 def test_noise_dc_extrapolation(self):
1772 ntwk = self.ntwk_noise
1773 ntwk = ntwk["0-1.5GHz"] # using only the first samples, as ntwk_noise has duplicate x value
1774 s11 = ntwk.s11
1775 s11_dc = s11.extrapolate_to_dc(kind='cubic')
1776
1777 def test_dc_extrapolation_dc_sparam(self):
1778 zeros = np.zeros((self.ntwk1.nports, self.ntwk1.nports))
1779 net_dc = self.ntwk1.extrapolate_to_dc(dc_sparam=zeros)
1780 net_dc = self.ntwk1.extrapolate_to_dc(dc_sparam=zeros.tolist())
1781
1782 @pytest.mark.skipif("matplotlib" not in sys.modules, reason="Requires matplotlib in sys.modules.")
1783 def test_noise_deembed(self):
1784
1785
1786 f1_ =[75.5, 75.5]
1787 f2_=[75.5, 75.6]
1788 npt_ = [1,2] # single freq and multifreq
1789 for f1,f2,npt in zip (f1_,f2_,npt_) :
1790 freq=rf.Frequency(f1,f2,npt,'ghz')
1791 ntwk4_n = rf.Network(os.path.join(self.test_dir,'ntwk4_n.s2p'), f_unit='GHz').interpolate(freq)
1792 ntwk4 = rf.Network(os.path.join(self.test_dir,'ntwk4.s2p'),f_unit='GHz').interpolate(freq)
1793 thru = rf.Network(os.path.join(self.test_dir,'thru.s2p'),f_unit='GHz').interpolate(freq)
1794
1795 ntwk4_thru = ntwk4 ** thru
1796 ntwk4_thru.name ='ntwk4_thru'
1797 retrieve_thru = ntwk4.inv ** ntwk4_thru
1798 retrieve_thru.name ='retrieve_thru'
1799 self.assertEqual(retrieve_thru, thru)
1800 self.assertTrue(ntwk4_thru.noisy)
1801 self.assertTrue(retrieve_thru.noisy)
1802 self.assertTrue((abs(thru.nfmin - retrieve_thru.nfmin) < 1.e-6).all(),
1803 'nf not retrieved by noise deembed')
1804 self.assertTrue((abs(thru.rn - retrieve_thru.rn) < 1.e-6).all(),
1805 'rn not retrieved by noise deembed')
1806 self.assertTrue((abs(thru.z_opt - retrieve_thru.z_opt) < 1.e-6).all(),
1807 'noise figure does not match original spec')
1808
1809 ntwk4_n_thru = ntwk4_n ** thru
1810 ntwk4_n_thru.name ='ntwk4_n_thru'
1811 retrieve_n_thru = ntwk4_n.inv ** ntwk4_n_thru
1812 retrieve_n_thru.name ='retrieve_n_thru'
1813 self.assertTrue(ntwk4_n_thru.noisy)
1814 self.assertEqual(retrieve_n_thru, thru)
1815 self.assertTrue(ntwk4_n_thru.noisy)
1816 self.assertTrue(retrieve_n_thru.noisy)
1817 self.assertTrue((abs(thru.nfmin - retrieve_n_thru.nfmin) < 1.e-6).all(),
1818 'nf not retrieved by noise deembed')
1819 self.assertTrue((abs(thru.rn - retrieve_n_thru.rn) < 1.e-6).all(),
1820 'rn not retrieved by noise deembed')
1821 self.assertTrue((abs(thru.z_opt - retrieve_n_thru.z_opt) < 1.e-6).all(),
1822 'noise figure does not match original spec')
1823
1824 tuner, x,y,g = tuner_constellation()
1825 newnetw = thru.copy()
1826 nfmin_set=4.5
1827 gamma_opt_set=complex(.7,-0.2)
1828 rn_set=1
1829 newnetw.set_noise_a(thru.noise_freq, nfmin_db=nfmin_set, gamma_opt=gamma_opt_set, rn=rn_set )
1830 z = newnetw.nfdb_gs(g)[:,0]
1831 freq = thru.noise_freq.f[0]
1832
1833 if "matplotlib" in sys.modules:
1834 gamma_opt_rb, nfmin_rb = plot_contour(freq,x,y,z, min0max1=0, graph=False)
1835 self.assertTrue(abs(nfmin_set - nfmin_rb) < 1.e-2, 'nf not retrieved by noise deembed')
1836 self.assertTrue(abs(gamma_opt_rb.s[0,0,0] - gamma_opt_set) < 1.e-1, 'nf not retrieved by noise deembed')
1837
1838 def test_noise_interpolation(self):
1839
1840 # Get a handle for the test network. Note that the s-parameter frequency range is beyond that of the NF data
1841 ntwk = rf.Network(os.path.join(self.test_dir,'ntwk_noise_interp.s2p'))
1842
1843 # Pulling out the noise data should interpolate and fill extrapolated values with the default np.nan
1844 self.assertIn(True, np.isnan(ntwk.copy().n))
1845
1846 # Check that a particular fill value is NOT in the noise data
1847 fill_val = 12345 + 1j * 67890
1848 new_ntwk = ntwk.copy()
1849 self.assertNotIn(fill_val, new_ntwk.n)
1850
1851 # Change the interpolation fill value and check if it filled in properly
1852 new_ntwk = ntwk.copy()
1853 new_ntwk.noise_fill_value = fill_val
1854 self.assertIn(fill_val, new_ntwk.n)
1855
1856 def test_spar_interpolation(self):
1857
1858 # Create new frequency vectors beyond the original limits of ntwk1
1859 new_freqs_low = rf.Frequency.from_f(self.ntwk1.f / 2, unit="Hz")
1860 new_freqs_high = rf.Frequency.from_f(self.ntwk1.f * 2, unit="Hz")
1861
1862 # Test that no kwargs results in ValueErrors
1863 for new_f in (new_freqs_low, new_freqs_high):
1864 new_ntwk = self.ntwk1.copy()
1865 with self.assertRaises(ValueError) as context:
1866 new_ntwk.resample(new_f)
1867
1868 # Test that kwargs can let the resampling work
1869 for new_f in (new_freqs_low, new_freqs_high):
1870 new_ntwk = self.ntwk1.copy()
1871 new_ntwk.resample(new_f, bounds_error=False)
1872 self.assertIn(True, np.isnan(new_ntwk.s))
1873
1874 def test_se2gmm2se(self):
1875 # Test that se2gmm followed by gmm2se gives back the original network
1876 for z0 in [None, 45, 75]:
1877 ntwk4 = rf.Network(os.path.join(self.test_dir, 'cst_example_4ports.s4p'))
1878
1879 if z0 is not None:
1880 ntwk4.z0 = z0
1881
1882 ntwk4t = ntwk4.copy()
1883 self.assertTrue(np.all(ntwk4t.port_modes == "S"))
1884 ntwk4t.se2gmm(p=2)
1885 self.assertTrue(np.all(ntwk4t.port_modes == ["D", "D", "C", "C"]))
1886 ntwk4t.gmm2se(p=2)
1887 self.assertTrue(np.all(ntwk4t.port_modes == "S"))
1888
1889 self.assertTrue(np.allclose(ntwk4.s, ntwk4t.s))
1890 self.assertTrue(np.allclose(ntwk4.z0, ntwk4t.z0))
1891
1892 def test_se2gmm(self):
1893 # Test mixed mode conversion of two parallel thrus
1894 se = np.zeros((1,4,4), dtype=complex)
1895 se[:,2,0] = 1
1896 se[:,0,2] = 1
1897 se[:,3,1] = 1
1898 se[:,1,3] = 1
1899 net = rf.Network(s=se, f=[1], z0=50)
1900 gmm = np.zeros((1,4,4), dtype=complex)
1901 gmm[:,0,1] = 1
1902 gmm[:,1,0] = 1
1903 gmm[:,2,3] = 1
1904 gmm[:,3,2] = 1
1905 net.se2gmm(p=2)
1906 self.assertTrue(np.allclose(net.z0, np.array([[100,100,25,25]])))
1907 self.assertTrue(np.allclose(net.s, gmm))
1908
1909 def test_se2gmm_3port(self):
1910 # Test mixed mode conversion of ideal balun
1911 se = np.zeros((1,3,3), dtype=complex)
1912 se[:,2,0] = 1/2**0.5
1913 se[:,0,2] = 1/2**0.5
1914 se[:,2,1] = -1/2**0.5
1915 se[:,1,2] = -1/2**0.5
1916 net = rf.Network(s=se, f=[1], z0=50)
1917 gmm = np.zeros((1,3,3), dtype=complex)
1918 gmm[:,0,2] = 1
1919 gmm[:,2,0] = 1
1920 self.assertTrue(np.all(net.port_modes == "S"))
1921 net.se2gmm(p=1)
1922 self.assertTrue(np.all(net.port_modes == ["D", "C", "S"]))
1923 self.assertTrue(np.allclose(net.z0, np.array([[100,25,50]])))
1924 self.assertTrue(np.allclose(net.s, gmm))
1925
1926 def test_se2gmm_renorm(self):
1927 # Test that se2gmm renormalization is compatible with network renormalization
1928 freq = rf.Frequency(1, 1, 1, unit='GHz')
1929 # Single-ended ports
1930 for s_def in rf.S_DEFINITIONS:
1931 for ports in range(2, 10):
1932 # Number of differential pairs to convert
1933 for p in range(0, ports//2 + 1):
1934 # Create a random network, z0=50
1935 s_random = self.rng.uniform(-1, 1, (1, ports, ports)) +\
1936 1j * self.rng.uniform(-1, 1, (1, ports, ports))
1937 net = rf.Network(s=s_random, frequency=freq, z0=50)
1938 net_original = net.copy()
1939 net_renorm = net.copy()
1940
1941 # Random z0 for mixed mode ports
1942 z0 = self.rng.uniform(1, 100, 2*p) +\
1943 1j * self.rng.uniform(-100, 100, 2*p)
1944
1945 # Convert net to mixed mode with random z0
1946 net.se2gmm(p=p, z0_mm=z0, s_def=s_def)
1947
1948 # Convert net_renorm to mixed mode with different z0
1949 z0_mm = np.zeros(2*p, dtype=complex)
1950 z0_mm[:p] = 100
1951 z0_mm[p:] = 25
1952 net_renorm.se2gmm(p=p, z0_mm=z0_mm, s_def=s_def)
1953
1954 if p > 0:
1955 # S-parameters should be different
1956 self.assertFalse(np.allclose(net.s, net_renorm.s))
1957 else:
1958 # Same if no differential ports
1959 self.assertTrue(np.allclose(net.s, net_renorm.s))
1960
1961 # Renormalize net_renorm to the random z0
1962 # net and net_renorm should match after this
1963 # Single-ended ports stay 50 ohms
1964 full_z0 = 50 * np.ones(ports, dtype=complex)
1965 full_z0[:2*p] = z0
1966 net_renorm.renormalize(z_new=full_z0, s_def=s_def)
1967
1968 # Nets should match now
1969 self.assertTrue(np.allclose(net.z0, net_renorm.z0))
1970 self.assertTrue(np.allclose(net.s, net_renorm.s))
1971
1972 # Test that we get the original network back
1973 net.gmm2se(p=p, z0_se=50, s_def=s_def)
1974 self.assertTrue(np.allclose(net.z0, net_original.z0))
1975 self.assertTrue(np.allclose(net.s, net_original.s))
1976
1977
1978 def test_s_active(self):
1979 """
1980 Test the active s-parameters of a 2-ports network
1981 """
1982 s_ref = self.ntwk1.s
1983 # s_act should be equal to s11 if a = [1,0]
1984 np.testing.assert_array_almost_equal(rf.s2s_active(s_ref, [1, 0])[:,0], s_ref[:,0,0])
1985 # s_act should be equal to s22 if a = [0,1]
1986 np.testing.assert_array_almost_equal(rf.s2s_active(s_ref, [0, 1])[:,1], s_ref[:,1,1])
1987 # s_act should be equal to s11 if a = [1,0]
1988 np.testing.assert_array_almost_equal(self.ntwk1.s_active([1, 0])[:,0], s_ref[:,0,0])
1989 # s_act should be equal to s22 if a = [0,1]
1990 np.testing.assert_array_almost_equal(self.ntwk1.s_active([0, 1])[:,1], s_ref[:,1,1])
1991
1992 def test_vswr_active(self):
1993 """
1994 Test the active vswr-parameters of a 2-ports network
1995 """
1996 s_ref = self.ntwk1.s
1997 vswr_ref = self.ntwk1.s_vswr
1998 # vswr_act should be equal to vswr11 if a = [1,0]
1999 np.testing.assert_array_almost_equal(rf.s2vswr_active(s_ref, [1, 0])[:,0], vswr_ref[:,0,0])
2000 # vswr_act should be equal to vswr22 if a = [0,1]
2001 np.testing.assert_array_almost_equal(rf.s2vswr_active(s_ref, [0, 1])[:,1], vswr_ref[:,1,1])
2002 # vswr_act should be equal to vswr11 if a = [1,0]
2003 np.testing.assert_array_almost_equal(self.ntwk1.vswr_active([1, 0])[:,0], vswr_ref[:,0,0])
2004 # vswr_act should be equal to vswr22 if a = [0,1]
2005 np.testing.assert_array_almost_equal(self.ntwk1.vswr_active([0, 1])[:,1], vswr_ref[:,1,1])
2006
2007 def test_twport_to_nport(self):
2008 fpoints = 2
2009 nports = 4
2010 s = np.ones((fpoints, 2, 2), dtype=complex)
2011 f = rf.F(1, 10, fpoints, unit='GHz')
2012 twoport = rf.Network(s=s, frequency=f)
2013 nport = rf.twoport_to_nport(twoport, 0, 1, nports)
2014 zeros = np.zeros(fpoints, dtype=complex)
2015 for i in range(nports):
2016 for j in range(nports):
2017 if i in [0, 1] and j in [0, 1]:
2018 np.testing.assert_array_almost_equal(nport.s[:,i,j], twoport.s[:,i,j])
2019 else:
2020 np.testing.assert_array_almost_equal(nport.s[:,i,j], zeros)
2021
2022
2023 def test_generate_subnetworks_nportsbelow10(self):
2024 """
2025 Testing generation of one-port subnetworks for ports below 10
2026 """
2027 ntwk = rf.Network(os.path.join(self.test_dir,'ntwk.s32p'))
2028 np.testing.assert_array_almost_equal(
2029 ntwk.s[:,4,5],
2030 ntwk.s5_6.s[:,0,0]
2031 )
2032
2033 def test_generate_subnetworks_nportsabove10(self):
2034 """
2035 Testing generation of one-port subnetworks for ports above 10
2036 """
2037 ntwk = rf.Network(os.path.join(self.test_dir,'ntwk.s32p'))
2038 np.testing.assert_array_almost_equal(
2039 ntwk.s[:,1,15],
2040 ntwk.s2_16.s[:,0,0]
2041 )
2042
2043
2044 def test_generate_subnetwork_nounderscore(self):
2045 """
2046 Testing no underscore alias of one-port subnetworks for ports below 10.
2047 This is for backward compatibility with old code.
2048 """
2049 ntwk = rf.Network(os.path.join(self.test_dir,'ntwk.s32p'))
2050
2051 np.testing.assert_array_almost_equal(
2052 ntwk.s[:, 8, 8],
2053 ntwk.s99.s[:,0,0]
2054 )
2055
2056
2057 def test_generate_subnetworks_allports(self):
2058 """
2059 Testing generation of all one-port subnetworks in case of edge problems.
2060 """
2061 ntwk = rf.Network(os.path.join(self.test_dir,'ntwk.s32p'))
2062 for m in range(ntwk.nports):
2063 for n in range(ntwk.nports):
2064 np.testing.assert_array_almost_equal(
2065 ntwk.s[:,m,n],
2066 getattr(ntwk, f's{m+1}_{n+1}').s[:,0,0]
2067 )
2068
2069
2070 def test_subnetwork(self):
2071 """ Test subnetwork creation and recombination """
2072 tee = rf.data.tee # 3 port Network
2073
2074 # modify the z0 to dummy values just to check it works for any z0
2075 tee.z0 =self.rng.random(3) + 1j*self.rng.random(3)
2076
2077 # Using rf.subnetwork()
2078 # 2 port Networks as if one measures the tee with a 2 ports VNA
2079 tee12 = rf.subnetwork(tee, [0, 1]) # 2 port Network from ports 1 & 2, port 3 matched
2080 tee23 = rf.subnetwork(tee, [1, 2]) # 2 port Network from ports 2 & 3, port 1 matched
2081 tee13 = rf.subnetwork(tee, [0, 2]) # 2 port Network from ports 1 & 3, port 2 matched
2082 # recreate the original 3 ports Network from the thee 2-port sub-Networks
2083 ntw_list = [tee12, tee23, tee13]
2084 tee2 = rf.n_twoports_2_nport(ntw_list, nports=3)
2085 self.assertTrue(tee2 == tee)
2086
2087 # Same from the subnetwork() method.
2088 tee12 = tee.subnetwork([0, 1])
2089 tee23 = tee.subnetwork([1, 2])
2090 tee13 = tee.subnetwork([0, 2])
2091 ntw_list = [tee12, tee23, tee13]
2092 tee2 = rf.n_twoports_2_nport(ntw_list, nports=3)
2093 self.assertTrue(tee2 == tee)
2094
2095 def test_subnetwork_port_names(self):
2096 """ Test that subnetwork keeps port_names property. Issue #429 """
2097 self.ntwk1.port_names = ['A', 'B']
2098 extract_ports = ['A'] # list of port names to extract
2099 extract_ports_idx = [self.ntwk1.port_names.index(p) for p in extract_ports] # get port indices
2100 sub_nwk1 = self.ntwk1.subnetwork(extract_ports_idx)
2101 self.assertEqual(sub_nwk1.port_names, extract_ports)
2102
2103 tee = rf.data.tee
2104 tee.port_names = ['A', 'B', 'C']
2105 extract_ports = ['A', 'C']
2106 extract_ports_idx = [tee.port_names.index(p) for p in extract_ports]
2107 sub_nwk = tee.subnetwork(extract_ports_idx)
2108 self.assertEqual(sub_nwk.port_names, extract_ports)
2109
2110 def test_invalid_freq(self):
2111
2112 dat = np.arange(5)
2113 dat[4] = 3
2114
2115 with self.assertWarns(InvalidFrequencyWarning):
2116 freq = rf.Frequency.from_f(dat, unit='Hz')
2117
2118 s = np.tile(dat,4).reshape(2,2,-1).T
2119
2120 with self.assertWarns(InvalidFrequencyWarning):
2121 net = rf.Network(s=s, frequency=freq, z0=dat)
2122
2123 net.drop_non_monotonic_increasing()
2124
2125 self.assertTrue(np.allclose(net.f, freq.f[:4]))
2126 self.assertTrue(np.allclose(net.s, s[:4]))
2127 self.assertFalse(np.allclose(net.s.shape, s.shape))
2128
2129 def test_stability(self):
2130 net = rf.Network(f=[1], s=[[0, 1],[0, 0]], z0=50)
2131 self.assertTrue(net.stability == [np.inf])
2132
2133 net = rf.Network(f=[1], s=[[0, 1],[1, 0]], z0=50)
2134 self.assertTrue(net.stability == [1])
2135
2136 net = rf.Network(f=[1], s=np.eye(3), z0=50)
2137 with pytest.raises(ValueError):
2138 net.stability
2139
2140 def test_equality(self):
2141 s = self.rng.standard_normal((10, 2, 2))
2142 f1 = np.arange(10)
2143 f2 = np.arange(10)
2144 n1 = rf.Network(s=s,f=f1)
2145 n2 = rf.Network(s=s,f=f2)
2146 self.assertTrue(n1 == n2)
2147
2148 f2 = np.arange(11)
2149 n2 = rf.Network(s=s,f=f2)
2150 self.assertFalse(n1 == n2)
2151
2152 f2 = np.arange(10)
2153 n2 = rf.Network(s=s,f=f2)
2154 n2.s_def = 'pseudo'
2155 self.assertTrue(n1 == n2)
2156
2157 n2.z0 = n2.z0 +np.array([0+0.00001j])
2158 self.assertTrue(n1 == n2)
2159
2160 n2.z0 = n2.z0 +np.array([1+0j])
2161 self.assertFalse(n1 == n2)
2162
2163 f2 = 10 * f1
2164 n2 = rf.Network(s=s,f=f2)
2165 self.assertFalse(n1 == n2)
2166
2167 def test_stability_circle(self):
2168 # Check whether the load stability circle agrees with that calculated with ADS
2169 load_stability_circle_ads = np.loadtxt(os.path.join(self.test_dir, 'load_stability_circle_ads.csv'),
2170 encoding='utf-8', delimiter=',')
2171
2172 assert np.allclose(
2173 rf.complex_2_magnitude(self.fet['30GHz'].stability_circle(target_port=1, npoints=6)[:,0]),
2174 load_stability_circle_ads[:,0]
2175 )
2176
2177 assert np.allclose(
2178 rf.complex_2_degree(self.fet['30GHz'].stability_circle(target_port=1, npoints=6)[:,0]),
2179 load_stability_circle_ads[:,1]
2180 )
2181
2182 # Check whether the source stability circle agrees with that calculated with ADS
2183 source_stability_circle_ads = np.loadtxt(os.path.join(self.test_dir, 'source_stability_circle_ads.csv'),
2184 encoding='utf-8', delimiter=',')
2185
2186 assert np.allclose(
2187 rf.complex_2_magnitude(self.fet['30GHz'].stability_circle(target_port=0, npoints=6)[:,0]),
2188 source_stability_circle_ads[:,0]
2189 )
2190
2191 assert np.allclose(
2192 rf.complex_2_degree(self.fet['30GHz'].stability_circle(target_port=0, npoints=6)[:,0]),
2193 source_stability_circle_ads[:,1]
2194 )
2195
2196 # Check whether an error is raised when the network is not 2 port.
2197 net = rf.Network(f=[1], s=np.eye(3), z0=50)
2198 with pytest.raises(ValueError):
2199 net.stability_circle(target_port=1)
2200
2201 # Check whether an error is raised when the number of points is not positive.
2202 with pytest.raises(ValueError):
2203 net.stability_circle(target_port=1, npoints=0)
2204
2205 # Check whether an error is raised when an incorrect target_port is specified.
2206 with pytest.raises(ValueError):
2207 net.stability_circle(target_port='foobar')
2208
2209 def test_gain_circle(self):
2210 # Check whether the load stability circle agrees with that calculated with ADS
2211 load_gain_circle_ads = np.loadtxt(os.path.join(self.test_dir, 'load_gain_circle_ads.csv'), encoding='utf-8',
2212 delimiter=',')
2213
2214 assert np.allclose(
2215 rf.complex_2_magnitude(self.fet['30GHz'].gain_circle(target_port=1, gain=1.0, npoints=6)[:,0]),
2216 load_gain_circle_ads[:,0],
2217 )
2218
2219 assert np.allclose(
2220 rf.complex_2_degree(self.fet['30GHz'].gain_circle(target_port=1, gain=1.0, npoints=6)[:,0]),
2221 load_gain_circle_ads[:,1],
2222 )
2223
2224 # Check whether the source stability circle agrees with that calculated with ADS
2225 source_gain_circle_ads = np.loadtxt(os.path.join(self.test_dir, 'source_gain_circle_ads.csv'),
2226 encoding='utf-8', delimiter=',')
2227
2228
2229 assert np.allclose(
2230 rf.complex_2_magnitude(self.fet['30GHz'].gain_circle(target_port=0, gain=1.0, npoints=6)[:,0]),
2231 source_gain_circle_ads[:,0],
2232 )
2233
2234 assert np.allclose(
2235 rf.complex_2_degree(self.fet['30GHz'].gain_circle(target_port=0, gain=1.0, npoints=6)[:,0]),
2236 source_gain_circle_ads[:,1],
2237 )
2238
2239 # Check whether an error is raised when the network is not 2 port.
2240 net = rf.Network(f=[1], s=np.eye(3), z0=50)
2241 with pytest.raises(ValueError):
2242 net.gain_circle(target_port=1, gain=2.0)
2243
2244 # Check whether an error is raised when the number of points is not positive.
2245 with pytest.raises(ValueError):
2246 net.gain_circle(target_port=1, gain=2.0, npoints=0)
2247
2248 # Check whether an error is raised when an incorrect target_port is specified.
2249 with pytest.raises(ValueError):
2250 net.gain_circle(target_port='foobar', gain=2.0)
2251
2252 # Check whether the specified gain is too large.
2253 with pytest.raises(RuntimeWarning):
2254 self.fet['30GHz'].gain_circle(target_port=1, gain=100)
2255
2256 def test_nf_circle(self):
2257 # Check whether the noise figure circle agrees with that calculated with Microwave Office
2258 nf_circle_mwo = np.loadtxt(os.path.join(self.test_dir, 'nf_circle_mwo.csv'), encoding='utf-8',
2259 delimiter=',')
2260
2261 assert np.allclose(
2262 self.ntwk_noise["1GHz"].nf_circle(nf=1.0, npoints=6).flatten().real,
2263 nf_circle_mwo[:6,0],
2264 )
2265 assert np.allclose(
2266 self.ntwk_noise["1GHz"].nf_circle(nf=1.0, npoints=6).flatten().imag,
2267 nf_circle_mwo[:6,1],
2268 )
2269
2270 assert np.allclose(
2271 self.ntwk_noise["2GHz"].nf_circle(nf=2.0, npoints=6).flatten().real,
2272 nf_circle_mwo[6:12,0],
2273 )
2274 assert np.allclose(
2275 self.ntwk_noise["2GHz"].nf_circle(nf=2.0, npoints=6).flatten().imag,
2276 nf_circle_mwo[6:12,1],
2277 )
2278
2279 # Check whether an error is raised when the network is not 2 port.
2280 net = rf.Network(f=[1], s=np.eye(3), z0=50)
2281 with pytest.raises(ValueError):
2282 net.nf_circle(nf=1.0)
2283
2284 # Check whether an error is raised when the number of points is not positive.
2285 with pytest.raises(ValueError):
2286 net.nf_circle(nf=1.0, npoints=0)
2287
2288 # Check whether an error is raised when the network is missing noise data.
2289 with pytest.raises(ValueError):
2290 self.ntwk1.nf_circle(nf=1.0, npoints=0)
2291
2292 # Check whether the specified noise figure is too small.
2293 with warnings.catch_warnings(record=True) as w:
2294 warnings.simplefilter("always")
2295 self.ntwk_noise['1GHz'].nf_circle(nf=0.1)
2296
2297 # Check that a warning was raised
2298 assert len(w) > 0, "Expected a warning to be raised"
2299
2300 # Check that the warning is a RuntimeWarning
2301 assert any(item.category is RuntimeWarning for item in w), "Expected RuntimeWarning was not raised"
2302
2303 def test_de_embed_by_floordiv(self):
2304 ntwk_result_1 = self.ntwk1 // self.ntwk2
2305 ntwk_result_2 = self.ntwk1 // (self.ntwk2)
2306 np.testing.assert_array_almost_equal(ntwk_result_1.s, ntwk_result_2.s)
2307
2308 # By definition A // B => B.inv * A
2309 # By definition A // [B, C] => B.inv * A * C.inv
2310 # So, A // [B, C] should be equal to (A // B) * C.inv
2311 ntwk_result_3 = self.ntwk1 // (self.ntwk2, self.ntwk3)
2312 ntwk_result_4 = (self.ntwk1 // self.ntwk2) ** self.ntwk3.inv
2313 np.testing.assert_array_almost_equal(ntwk_result_3.s, ntwk_result_4.s)
2314
2315 # Check weather an error is raised when more than two networks are specified
2316 with pytest.raises(ValueError):
2317 ntwk_result_3 = self.ntwk1 // (self.ntwk1, self.ntwk2, self.ntwk3)
2318
2319 def test_fmt_trace_name(self):
2320 # Test trace name of differential thru
2321 s = np.zeros((1,4,4), dtype=complex)
2322 s[:,2,0] = 1
2323 s[:,0,2] = 1
2324 s[:,3,1] = 1
2325 s[:,1,3] = 1
2326 # single-ended
2327 se_thru = rf.Network(s=s, f=[1], z0=50)
2328 self.assertTrue(np.all(se_thru.port_modes == "S"))
2329 self.assertTrue(se_thru._fmt_trace_name(0, 0) == "11")
2330 self.assertTrue(se_thru._fmt_trace_name(1, 0) == "21")
2331 mm_thru = se_thru.copy()
2332 mm_thru.se2gmm(p=2)
2333 self.assertTrue(np.all(mm_thru.port_modes == ["D", "D", "C", "C"]))
2334 self.assertTrue(mm_thru._fmt_trace_name(0, 0) == "dd11")
2335 self.assertTrue(mm_thru._fmt_trace_name(1, 0) == "dd21")
2336 self.assertTrue(mm_thru._fmt_trace_name(2, 2) == "cc33")
2337 self.assertTrue(mm_thru._fmt_trace_name(3, 2) == "cc43")
2338 self.assertTrue(mm_thru._fmt_trace_name(2, 0) == "cd31")
2339 self.assertTrue(mm_thru._fmt_trace_name(1, 3) == "dc24")
2340
2341 def test_s_error(self):
2342 """Tests Network.s_error() method against AWR Microwave Office SMODEL measurement.
2343
2344 The error between s-parameters of Mini-circuits LFCN-2352+ at 25 C and 125 C will be
2345 computed using the four error functions using AWR Microwave Office's SMODEL measurement and
2346 Network.s_error().
2347 """
2348 TEST_DIR = Path(self.test_dir)
2349
2350 # load error data exported from AWR Microwave Office SMODEL measurement
2351 awr_data_file = TEST_DIR / 'smodel export from mwo.txt'
2352 awr_data = pd.read_csv(awr_data_file,delimiter="\t",index_col=0)
2353
2354 # load networks for LFCN-2352+ at 25 C and 125 C
2355 ntwkA = rf.Network(TEST_DIR / 'LFCN-2352+_Plus125degC.s2p')
2356 ntwkB = rf.Network(TEST_DIR / 'LFCN-2352+_Plus25degC.s2p')
2357
2358 awr_errorfunctions = [
2359 'DB(SModel(LFCN_2352__Plus125degC,1)) : LFCN_2352__Plus25degC',
2360 'DB(SModel(LFCN_2352__Plus125degC,2)) : LFCN_2352__Plus25degC',
2361 'DB(SModel(LFCN_2352__Plus125degC,3)) : LFCN_2352__Plus25degC',
2362 'DB(SModel(LFCN_2352__Plus125degC,4)) : LFCN_2352__Plus25degC']
2363
2364 skrf_errorfunctions = [
2365 "average_l1_norm",
2366 "average_l2_norm",
2367 "maximum_l1_norm",
2368 "average_normalized_l1_norm"]
2369
2370 # test the four error functions
2371 for awr_error_fcn,skrf_error_fcn in zip(awr_errorfunctions,skrf_errorfunctions):
2372 error_awr_dB = awr_data[awr_error_fcn].values
2373 error_skrf_dB = 20*np.log10(ntwkA.s_error(ntwkB,error_function=skrf_error_fcn))
2374 np.testing.assert_almost_equal(error_awr_dB,error_skrf_dB,decimal=3)
2375
2376 suite = unittest.TestLoader().loadTestsFromTestCase(NetworkTestCase)
2377 unittest.TextTestRunner(verbosity=2).run(suite)