Debian Codegraph @

skrf/io/mdif.py

raw symbols SCIP
1 """
2 .. module:: skrf.io.mdif
3
4 ========================================
5 mdif (:mod:`skrf.io.mdif`)
6 ========================================
7
8 Mdif class and utilities
9
10 .. autosummary::
11 :toctree: generated/
12
13 Mdif
14
15 """
16 from __future__ import annotations
17
18 from itertools import product
19 from pathlib import Path
20 from typing import TextIO
21
22 import numpy as np
23
24 from ..frequency import Frequency
25 from ..mathFunctions import magdeg_2_reim
26 from ..network import Network, y2s, z2s
27 from ..networkSet import NetworkSet
28 from ..util import get_fid
29
30
31 class Mdif:
32 """
33 Class to read Generalized MDIF N-port files.
34
35 Used to read the Generalized MDIF (GMDIF) file format [#]_ (.mdf extension).
36 These files are used store Network parameters which vary with frequency
37 and with one or more named parameters.
38
39 Parameters
40 ----------
41 file : str or file-object
42 mdif file to load
43
44 References
45 ----------
46 .. [#] https://awrcorp.com/download/faq/english/docs/Users_Guide/data_file_formats.html#generalized_mdif
47
48 Examples
49 --------
50 From filename
51
52 >>> m = rf.Mdif('network.mdf')
53
54 From file-object
55
56 >>> file = open('network.mdf')
57 >>> m = rf.Mdif(file)
58
59 List of named parameters defined in the MDIF file
60
61 >>> m.params
62
63 Convert the MDIF to a NetworkSet
64
65 >>> m.to_networkset()
66
67 Using the data as a `NetworkSet` allows you to select a set of Networks
68 from their named parameter values or interpolating between Networks.
69 See `skrf.networkset.NetworkSet`.
70
71 """
72
73 def __init__(self, file: str | Path | TextIO):
74 """
75 Constructor
76
77 Parameters
78 ----------
79 file : str, Path, or file-object
80 mdif file to load
81 """
82 with get_fid(file) as fid:
83 self.filename = fid.name
84 self._comments = self._parse_comments(fid)
85 self._params = []
86 self._networks = self._parse_mdif(fid)
87
88 @property
89 def params(self) -> list:
90 """
91 Named parameters list.
92
93 Returns
94 -------
95 list : list of string
96 List of the named parameters defined in the MDIF file
97
98 """
99 return self._params
100
101 @property
102 def comments(self) -> list:
103 """
104 Comments defined in MDIF file.
105
106 Returns
107 -------
108 list : list of string
109 MDIF file Comments
110
111 """
112 return self._comments
113
114 @property
115 def networks(self) -> list:
116 """
117 List of Networks.
118
119 Returns
120 -------
121 list : list of :class:`~skrf.network.Network`
122 List of the Network stored in the MDIF file.
123
124 """
125 return self._networks
126
127 def _parse_comments(self, fid) -> list:
128 """
129 Parse the comments stored in the MDIF file.
130
131 Parameters
132 ----------
133 fid : file object
134
135 Returns
136 -------
137 list : list of strings.
138
139 """
140 fid.seek(0)
141 comments = []
142 for line in fid:
143 if line.strip().startswith('!'):
144 comments.append(line[1:].strip())
145
146 # Break out after the first network starts, thereby only
147 # pulling out the comments for the entire NetworkSet, not
148 # everything for each network. That's pulled out later.
149 if line.strip().lower().startswith('begin'):
150 break
151
152 return comments
153
154
155 def _parse_data(self, block_data: list) -> Network:
156 """
157 Parse the block of data corresponding to a set of parameters to a Network.
158
159 Parameters
160 ----------
161 block_data : list of string
162 block of data to parse
163
164 Raises
165 ------
166 NotImplementedError
167 if the data are not recognized
168
169 Returns
170 -------
171 ntwk : rf.Network
172 Network
173
174 """
175 kinds = []
176 data_lines = []
177 comments = []
178
179 # Assumes default unit and format if not found during parsing
180 frequency_unit = 'hz'
181 parameter = None
182 formt = 'ri'
183 z0 = 50
184 nb_lines_per_freq = 1
185 ntwk_name = ''
186
187 # Flag for adding comments to the network
188 no_more_comments = False
189
190 # Extract and group parameter information and values
191 for line in block_data:
192 # Parse the option line (as in Touchstone)
193 if line.startswith('#'):
194 # Flag that no more comments are coming as we're now after the option line
195 no_more_comments = True
196
197 toks = line[1:].strip().split()
198 # fill the option line with the missing defaults
199 toks.extend(['ghz', 's', 'ma', 'r', '50'][len(toks):])
200 frequency_unit = toks[0].lower()
201 parameter = toks[1].lower()
202 formt = toks[2].lower()
203 z0 = toks[4]
204 if frequency_unit not in ['hz', 'khz', 'mhz', 'ghz']:
205 raise NotImplementedError(f'ERROR: illegal frequency_unit {frequency_unit}', )
206 if parameter not in 'syzgh':
207 raise NotImplementedError(f'ERROR: illegal parameter value {parameter}')
208 if formt not in ['ma', 'db', 'ri']:
209 raise NotImplementedError(f'ERROR: illegal format value {formt}')
210
211 elif line.strip().startswith('!'):
212 if line[1:].startswith(' network name:'):
213 ntwk_name = line.split(':')[-1].strip()
214
215 # Append the comments to the list of comments for that data block
216 if no_more_comments is not False:
217 comments.append(line.strip()[1:])
218
219 # Parameter kinds (s11, z21, ...) are described as
220 #
221 # % kind1 kind2 ...
222 # % ...
223 # % ... kindN
224 elif line.strip().lower().startswith('%'):
225 kinds.append(line[1:].split())
226
227 # Data are described as
228 #
229 # v_kind1 v_kind2 ...
230 # ...
231 # ... v_kindN
232 elif line.strip(): # ignore lines with only whitespace
233 data_lines.append(np.array(line.split(), dtype='float'))
234
235 # grouping the data_lines in a single line for each frequency
236 nb_lines_per_freq = len(kinds)
237 data_lines = [np.concatenate(data_lines[idx*nb_lines_per_freq:idx*nb_lines_per_freq + nb_lines_per_freq])
238 for idx in range(int(len(data_lines)/nb_lines_per_freq))]
239 kinds = [item for sublist in kinds for item in sublist] # flattening
240 kinds = [k.lower().replace('(complex)', '') for k in kinds] # cleaning
241 data = np.array(data_lines)
242 f = data[:,0]
243
244 # grouping two by two the columns convert data to complex arrays
245 if formt == 'ri':
246 values = data[:,1::2] + 1j*data[:,2::2]
247 elif formt == 'ma':
248 values = magdeg_2_reim(data[:,1::2], data[:,2::2])
249 elif formt == 'db':
250 values = ((10**(data[:,1::2]/20.0)) * np.exp(1j*np.pi/180 * data[:,2::2]))
251 else:
252 raise NotImplementedError('not implemented case')
253
254 # Extracting s-parameters, depending of the file formatting
255 # Nport in MDIF files exported by ADS
256 if ('s[1,1]' in kinds):
257 # deduce the rank (nb of ports) of the data
258 rank = round(np.sqrt(sum('s[' in s for s in kinds)))
259 s = np.zeros((len(f), rank, rank), dtype=complex)
260 for m in range(rank):
261 for n in range(rank):
262 s[:,m,n] = values[:, kinds.index(f's[{m+1},{n+1}]') - 1]
263
264 # Nport as in AWR MDIF file-format description
265 elif (parameter == 's') and all(k in kinds for k in ['n11x', 'n11y']):
266 rank = round(np.sqrt(sum('n' in s for s in kinds)/2))
267 s = values[:,:rank**2].reshape(len(f), rank, rank)
268 # if rank is 2 and S21 before S12, swap S21 and S12
269 if rank == 2 and (kinds.index('n21x') < kinds.index('n12x')):
270 s[:, 1, 0], s[:, 0, 1] = s[:, 0, 1].copy(), s[:, 1, 0].copy()
271
272 # no S-parameter are found. Maybe Z-param instead?
273 elif ('z[1,1]') in kinds:
274 # deduce the rank (nb of ports) of the data
275 rank = round(np.sqrt(sum('z[' in s for s in kinds)))
276 z = np.zeros((len(f), rank, rank), dtype=complex)
277 for m in range(rank):
278 for n in range(rank):
279 z[:,m,n] = values[:, kinds.index(f'z[{m+1},{n+1}]') - 1]
280 s = z2s(z, z0=z0)
281
282 # no S nor Z-parameter are found. Maybe Y-param instead?
283 elif ('y[1,1]') in kinds:
284 # deduce the rank (nb of ports) of the data
285 rank = round(np.sqrt(sum('y[' in s for s in kinds)))
286 y = np.zeros((len(f), rank, rank), dtype=complex)
287 for m in range(rank):
288 for n in range(rank):
289 y[:,m,n] = values[:, kinds.index(f'y[{m+1},{n+1}]') - 1]
290 s = y2s(z, z0=z0)
291
292 else:
293 raise NotImplementedError('Unrecognized case, probably not implemented')
294
295 # building the Network
296 freq = Frequency.from_f(f, unit=frequency_unit)
297 ntwk = Network(frequency=freq, s=s, z0=z0, name=ntwk_name, comments="\n".join(comments))
298
299 return ntwk
300
301 def _parse_mdif(self, fid) -> list:
302 """
303 MDIF parser.
304
305 Parameters
306 ----------
307 fid : file object
308
309 Returns
310 -------
311 list: list of Networks
312 """
313 fid.seek(0)
314
315 block_data = []
316 ntwks = []
317 params = dict()
318
319 in_data_block = False
320 in_noise_block = False
321
322 for line in fid:
323
324 # parse parameters:
325 #
326 # VAR param_name_1 = A
327 # ...
328 # VAR param_name_N = Z
329 if line.lower().startswith('var'):
330 # current parameter
331 param_name, param_value = (s.strip() for s in line[3:].split('='))
332 # remove the datatype "(blah)" in "varname(blah)" if any
333 param_name = param_name.split('(')[0]
334 # try to convert the value as a number
335 self._params.append(param_name) if param_name not in self.params else self.params
336 try:
337 params[param_name] = float(param_value)
338 except ValueError:
339 params[param_name] = param_value.replace('"', '')
340
341 # parse numerical data:
342 #
343 # begin XXX
344 # ....
345 # end
346 if line.lower().startswith('end'):
347 if in_data_block:
348 ntwk = self._parse_data(block_data)
349 ntwk.params = params
350 ntwks.append(ntwk)
351 # reset parsed values
352 in_data_block = False
353 params = dict()
354 if in_noise_block:
355 in_noise_block = False
356 noise_arr = np.array(
357 [e.split() for e in block_data if not e.startswith(("!", "#", "%"))]
358 ).astype(float)
359 freq, nfmin, gamma_opt_mag, gamma_opt_angle, rn = noise_arr.T
360 nfreq = Frequency.from_f(freq, unit=ntwk.frequency.unit)
361 gamma = gamma_opt_mag * np.exp(1j*np.deg2rad(gamma_opt_angle))
362 ntwk.set_noise_a(nfreq, nfmin, gamma, rn * ntwk.z0[0,0])
363
364 block_data = []
365
366 if in_data_block or in_noise_block:
367 block_data.append(line)
368
369 if line.lower().startswith("begin ndata"):
370 in_noise_block = True
371 elif line.lower().startswith('begin'):
372 in_data_block = True
373
374 return ntwks
375
376 def to_networkset(self) -> NetworkSet:
377 """
378 Return the MDIF data as a NetworkSet.
379
380 Returns
381 -------
382 ns : :class:`~skrf.networkSet.NetworkSet`
383
384 See Also
385 --------
386 from_networkset : Write a MDIF file from a NetworkSet.
387
388 """
389 ns = NetworkSet(self.networks)
390 ns.comments = self.comments
391 return ns
392
393 @staticmethod
394 def write(ns : NetworkSet,
395 filename : str,
396 values: dict | None = None,
397 data_types: dict | None = None,
398 comments: str | None = None,
399 *,
400 ads_compatible: bool = True,
401 **kwargs):
402 """
403 Write a MDIF file from a NetworkSet.
404
405 Parameters
406 ----------
407 ns : :class:`~skrf.networkSet.NetworkSet`
408 NetworkSet to get the data from.
409 filename : string
410 Output MDIF file name.
411 values : dictionary or None. Default is None.
412 The keys of the dictionary are MDIF variables and its values are
413 a list of the parameter values.
414 If None, then the values will be set to the NetworkSet names
415 and the datatypes will be set to "string".
416 data_types: dictionary or None. Default is None.
417 The keys are MDIF variables and the value are datatypes
418 specified by the following strings: "int", "double", and "string"
419 comments: list of strings
420 Comments to add to output_file.
421 Each list items is a separate comment line
422 ads_compatible: bool. Default is True.
423 Indicates whether to write the file in a format that
424 ADS will read properly.
425 **kwargs: dictionary with extra arguments to pass through to the
426 underlying write_touchstone() method in the Network class
427
428 See Also
429 --------
430 io.mdif.Mdif : MDIF file class
431 to_networkset : Return the MDIF data as a NetworkSet
432
433 """
434
435 if comments is None:
436 comments = []
437 if values is None:
438 if ns.has_params():
439 values = ns.params_values
440 else:
441 # using Network names as values
442 v = list()
443 for ntwk in ns:
444 v.append(ntwk.name)
445
446 values = {"name": v}
447
448 if data_types is None:
449 if ns.has_params():
450 data_types = ns.params_types
451 else:
452 # using Network names (->string)
453 data_types = {"name": "string"}
454
455 # Remove the return_string argument, as it's a required argument for this method
456 kwargs.pop('return_string', None)
457
458 # VAR datatypes
459 dict_types = dict({"int": "0", "double": "1", "string": "2"})
460
461 # open output_file
462 with open(filename, "w") as mdif:
463
464 # write comments
465 for c in comments:
466 mdif.write(f"! {c}\n")
467
468 nports = ns[0].nports
469 is_noisy = ns[0].noisy
470
471 optionstring = Mdif.__create_optionstring(nports)
472
473 for filenumber, ntwk in enumerate(ns):
474
475 mdif.write("!" + "-" * 79 + "\n")
476
477 for p in values:
478 # assign double as the datatype if none is specified
479 if p not in data_types:
480 data_types[p] = "double"
481
482 var_type = "" if ads_compatible else f"({dict_types[data_types[p]]})"
483 if data_types[p] == "string":
484 var_def_str = f'VAR {p}{var_type} = "{values[p][filenumber]}"'
485 else:
486 var_def_str = f"VAR {p}{var_type} = {values[p][filenumber]}"
487 mdif.write(var_def_str + "\n")
488
489 mdif.write("\nBEGIN ACDATA\n")
490 mdif.write(optionstring + "\n")
491 mdif.write("! network name: " + ntwk.name + "\n")
492
493 data = ntwk.write_touchstone(return_string=True, write_noise=False, **kwargs)
494 mdif.write(data)
495
496 if is_noisy:
497 # this "END" terminates "ACDATA" (s-parameters) and begins noise ("NDATA")
498 mdif.write("END\n\nBEGIN NDATA\n")
499 mdif.write("%F nfmin n11x n11y rn\n")
500 mdif.write(f"# {ntwk.frequency.unit} S MA R {ntwk.z0[0, 0].real}\n")
501 ntwk._write_noisedata(output=mdif)
502
503 mdif.write("END\n\n")
504
505 def __eq__(self, other) -> bool:
506 """
507 Test if two Mdif objects are equals.
508
509 Test the equality between the NetworkSet under the hood.
510
511 Parameters
512 ----------
513 other : :class:`~skrf.io.mdif.Mdif` object
514 Mdif object to compare with.
515
516 Returns
517 -------
518 bool
519
520 """
521 return self.to_networkset() == other.to_networkset()
522
523 @staticmethod
524 def __create_optionstring(nports):
525 """create the options string based on the number of ports. Used in the Touchstone and MDIF formats"""
526
527 if nports > 9:
528 corestring = "n{}_{}x n{}_{}y "
529 else:
530 corestring = "n{}{}x n{}{}y "
531
532 optionstring = "%F "
533
534 if nports == 2:
535 optionstring += "n11x n11y n21x n21y n12x n12y n22x n22y"
536
537 else:
538 # parse the option string for nports not equal to 2
539
540 for i in product(list(range(1, nports + 1)), list(range(1, nports + 1))):
541
542 optionstring += corestring.format(i[0], i[1], i[0], i[1])
543
544 # special case for nports = 3
545 if nports == 3:
546 # 3 ports
547 if not (np.remainder(i[1], 3)):
548 optionstring += "\n"
549
550 # touchstone spec allows only 4 data pairs per line
551 if nports >= 4:
552 if np.remainder(i[1], 4) == 0:
553 optionstring += "\n"
554 # NOTE: not sure if this is needed. Doesn't seem to be required by Microwave Office
555 if i[1] == nports:
556 optionstring += "\n"
557
558 return optionstring