Debian Codegraph @

skrf/io/general.py

raw symbols SCIP
1 """
2 .. module:: skrf.io.general
3
4 ========================================
5 general (:mod:`skrf.io.general`)
6 ========================================
7
8 General input/output functions for reading and writing skrf objects
9
10
11 Pickle functions
12 ------------------
13
14 The read/write methods use the pickle module. These should only be used
15 for temporary storage.
16
17 .. autosummary::
18 :toctree: generated/
19
20 read
21 read_all
22 read_all_networks
23 write
24 write_all
25 save_sesh
26
27
28 Spreadsheets
29 -----------------------------
30
31 .. autosummary::
32 :toctree: generated/
33
34 network_2_spreadsheet
35 networkset_2_spreadsheet
36
37 Pandas dataframe
38 ----------------------------------
39
40 .. autosummary::
41 :toctree: generated/
42
43 network_2_dataframe
44
45 Statistics
46 ----------
47
48 .. autosummary::
49 :toctree: generated/
50
51 statistical_2_touchstone
52
53 JSON
54 -------
55
56 .. autosummary::
57 :toctree: generated/
58
59 TouchstoneEncoder
60 to_json_string
61 from_json_string
62
63
64 """
65 from __future__ import annotations
66
67 import glob
68 import inspect
69 import json
70 import os
71 import pickle
72 import sys
73 import warnings
74 from io import StringIO
75 from pathlib import Path
76 from pickle import UnpicklingError
77 from typing import Any
78
79 import numpy as np
80 from pandas import DataFrame, ExcelWriter, Series
81
82 from ..frequency import Frequency
83 from ..network import Network
84 from ..networkSet import NetworkSet
85 from ..util import get_extn, get_fid
86
87
88 def _get_extension(inst: Any) -> str:
89 """File extension conventions for skrf objects.
90 """
91 from ..calibration.calibration import Calibration
92 from ..media import Media
93
94 extensions = [
95 (Frequency, "freq"),
96 (Network, "ntwk"),
97 (NetworkSet, "ns"),
98 (Calibration, "cal"),
99 (Media, "med"),
100 ]
101
102 for cls, ext in extensions:
103 print(cls, ext)
104 if isinstance(inst, cls):
105 return ext
106 return "p"
107
108 def read(file, *args, **kwargs):
109 r"""
110 Read skrf object[s] from a pickle file.
111
112 Reads a skrf object that is written with :func:`write`, which uses
113 the :mod:`pickle` module.
114
115 Parameters
116 ----------
117 file : str, Path, or file-object
118 name of file, or a file-object
119 \*args, \*\*kwargs : arguments and keyword arguments
120 passed through to pickle.load
121
122
123 .. note::
124 If `file` is a:
125
126 * a file-object, it is left open
127
128 * a filename, then a file-object is opened and closed.
129
130 * a file-object and reading fails, then the position is reset back to 0 using seek if possible.
131
132
133 Examples
134 --------
135 >>> n = rf.Network(f=[1,2,3],s=[1,1,1],z0=50)
136 >>> n.write('my_ntwk.ntwk')
137 >>> n_2 = rf.read('my_ntwk.ntwk')
138
139 See Also
140 --------
141 read : read a skrf object
142 write : write skrf object[s]
143 read_all : read all skrf objects in a directory
144 write_all : write dictionary of skrf objects to a directory
145 """
146 fid = get_fid(file, mode='rb')
147 try:
148 obj = pickle.load(fid, *args, **kwargs)
149 except (UnpicklingError, UnicodeDecodeError):
150 # if fid is seekable then reset to beginning of file
151 fid.seek(0)
152
153 if isinstance(file, str):
154 # we created the fid so close it
155 fid.close()
156 raise
157
158 if isinstance(file, str):
159 # we created the fid so close it
160 fid.close()
161
162 return obj
163
164 def write(file, obj, overwrite = True):
165 """
166 Write skrf object[s] to a file.
167
168 This uses the :mod:`pickle` module to write skrf objects to a file.
169 Note that you can write any pickl-able python object. For example,
170 you can write a list or dictionary of :class:`~skrf.network.Network`
171 objects
172 or :class:`~skrf.calibration.calibration.Calibration` objects. This
173 will write out a single file. If you would like to write out a
174 separate file for each object, use :func:`write_all`.
175
176 Parameters
177 ----------
178 file : file, Path, or string
179 File or filename to which the data is saved. If file is a
180 file-object, then the filename is unchanged. If file is a
181 string, an appropriate extension will be appended to the file
182 name if it does not already have an extension.
183
184 obj : an object, or list/dict of objects
185 object or list/dict of objects to write to disk
186
187 overwrite : Boolean
188 if file exists, should it be overwritten?
189
190
191 .. note::
192 If `file` is a string, but doesn't contain a suffix, one is chosen
193 automatically. Here are the extensions:
194
195
196 ==================================================== ===============
197 skrf object extension
198 ==================================================== ===============
199 :class:`~skrf.frequency.Frequency` '.freq'
200 :class:`~skrf.network.Network` '.ntwk'
201 :class:`~skrf.networkSet.NetworkSet` '.ns'
202 :class:`~skrf.calibration.calibration.Calibration` '.cal'
203 :class:`~skrf.media.media.Media` '.med'
204 other '.p'
205 ==================================================== ===============
206
207 .. note::
208 To make the file written by this method cross-platform, the pickling
209 protocol 2 is used. See :mod:`pickle` for more info.
210
211 Examples
212 --------
213 Convert a touchstone file to a pickled Network,
214
215 >>> n = rf.Network('my_ntwk.s2p')
216 >>> rf.write('my_ntwk',n)
217 >>> n_red = rf.read('my_ntwk.ntwk')
218
219 Writing a list of different objects
220
221 >>> n = rf.Network('my_ntwk.s2p')
222 >>> ns = rf.NetworkSet([n,n,n])
223 >>> rf.write('out',[n,ns])
224 >>> n_red = rf.read('out.p')
225
226 See Also
227 --------
228 read : read a skrf object
229 write : write skrf object[s]
230 read_all : read all skrf objects in a directory
231 write_all : write dictionary of skrf objects to a directory
232 skrf.network.Network.write : write method of Network
233 skrf.calibration.calibration.Calibration.write : write method of Calibration
234
235
236 """
237 if isinstance(file, str):
238 extn = get_extn(file)
239 if extn is None:
240 # if there is not extension add one
241 file += f".{_get_extension(obj)}"
242
243 if os.path.exists(file):
244 if not overwrite:
245 warnings.warn('file exists, and overwrite option is False. Not writing.', stacklevel=2)
246 return
247
248 with open(file, 'wb') as fid:
249 pickle.dump(obj, fid, protocol=2)
250
251 else:
252 fid = file
253 pickle.dump(obj, fid, protocol=2)
254 fid.close()
255
256 def read_all(dir: str | Path = '.', sort = True, contains = None, f_unit = None,
257 obj_type=None, files: list=None, recursive=False) -> dict:
258 """
259 Read all skrf objects in a directory.
260
261 Attempts to load all files in `dir`, using :func:`read`. Any file
262 that is not readable by skrf is skipped. Optionally, simple filtering
263 can be achieved through the use of `contains` argument.
264
265 Parameters
266 ----------
267 dir : str or Path, optional
268 the directory to load from, default \'.\'
269 sort: boolean, default is True
270 filenames sorted by https://docs.python.org/3/library/stdtypes.html#list.sort without arguments
271 contains : str, optional
272 if not None, only files containing this substring will be loaded
273 f_unit : ['hz','khz','mhz','ghz','thz']
274 for all :class:`~skrf.network.Network` objects, set their
275 frequencies's :attr:`~skrf.frequency.Frequency.f_unit`
276 obj_type : str
277 Name of skrf object types to read (ie 'Network')
278 files : list, optional
279 list of files to load, bypasses dir parameter.
280 recursive : bool, optional
281 If True, search in the specified directory and all other nested directories
282
283 Returns
284 -------
285 out : dictionary
286 dictionary containing all loaded skrf objects. keys are the
287 filenames without extensions, and the values are the objects
288
289
290 Examples
291 --------
292 >>> rf.read_all('skrf/data/')
293 {'delay_short': 1-Port Network: 'delay_short', 75-110 GHz, 201 pts, z0=[ 50.+0.j],
294 'line': 2-Port Network: 'line', 75-110 GHz, 201 pts, z0=[ 50.+0.j 50.+0.j],
295 'ntwk1': 2-Port Network: 'ntwk1', 1-10 GHz, 91 pts, z0=[ 50.+0.j 50.+0.j],
296 'one_port': one port Calibration: 'one_port', 500-750 GHz, 201 pts, 4-ideals/4-measured,
297 ...
298
299 >>> rf.read_all('skrf/data/', obj_type = 'Network')
300 {'delay_short': 1-Port Network: 'delay_short', 75-110 GHz, 201 pts, z0=[ 50.+0.j],
301 'line': 2-Port Network: 'line', 75-110 GHz, 201 pts, z0=[ 50.+0.j 50.+0.j],
302 'ntwk1': 2-Port Network: 'ntwk1', 1-10 GHz, 91 pts, z0=[ 50.+0.j 50.+0.j],
303
304 >>> rf.read_all(files = ['skrf/data/delay_short.s1p', 'skrf/data/line.s2p'], obj_type = 'Network')
305 {'delay_short': 1-Port Network: 'delay_short', 75-110 GHz, 201 pts, z0=[ 50.+0.j],
306 'line': 2-Port Network: 'line', 75-110 GHz, 201 pts, z0=[ 50.+0.j 50.+0.j]}
307
308 See Also
309 ----------
310 read : read a skrf object
311 write : write skrf object[s]
312 read_all : read all skrf objects in a directory
313 write_all : write dictionary of skrf objects to a directory
314 """
315
316 # Convert a Path object to a string
317 dir = str(dir.resolve()) if isinstance(dir, Path) else dir
318
319 out={}
320
321 filelist = []
322 if files is None:
323 if recursive:
324 if not dir.endswith(os.path.sep):
325 dir += os.path.sep
326 dir += '**'
327 for filename in glob.iglob(os.path.join(dir, '*.s*p'), recursive=recursive):
328 filelist.append(filename)
329 else:
330 filelist.extend(files)
331
332 if sort is True:
333 filelist.sort()
334
335 for filename in filelist:
336 if contains is not None and contains not in filename:
337 continue
338 fullname = filename
339 keyname = os.path.splitext(filename.split(os.path.sep)[-1])[0]
340 try:
341 out[keyname] = read(fullname)
342 continue
343 except Exception:
344 pass
345
346 try:
347 out[keyname] = Network(fullname)
348 continue
349 except Exception:
350 pass
351
352 if f_unit is not None:
353 for keyname in out:
354 try:
355 out[keyname].frequency.unit = f_unit
356 except Exception:
357 pass
358
359 if obj_type is not None:
360 out = {k: out[k] for k in out if
361 isinstance(out[k],sys.modules[__name__].__dict__[obj_type])}
362
363 return out
364
365
366 def read_all_networks(*args, **kwargs):
367 """
368 Read all networks in a directory.
369
370 This is a convenience function. It just calls::
371
372 read_all(*args,obj_type='Network', **kwargs)
373
374 See Also
375 --------
376 read_all
377 """
378 return read_all(*args,obj_type='Network', **kwargs)
379
380 ran = read_all_networks
381
382 def write_all(dict_objs, dir='.', *args, **kwargs):
383 r"""
384 Write a dictionary of skrf objects individual files in `dir`.
385
386 Each object is written to its own file. The filename used for each
387 object is taken from its key in the dictionary. If no extension
388 exists in the key, then one is added. See :func:`write` for a list
389 of extensions. If you would like to write the dictionary to a single
390 output file use :func:`write`.
391
392
393 .. note::
394 Any object in dict_objs that is pickl-able will be written.
395
396
397 Parameters
398 ----------
399 dict_objs : dict
400 dictionary of skrf objects
401 dir : str
402 directory to save skrf objects into
403 \*args, \*\*kwargs :
404 passed through to :func:`~skrf.io.general.write`. `overwrite`
405 option may be of use.
406
407 See Also
408 --------
409 read : read a skrf object
410 write : write skrf object[s]
411 read_all : read all skrf objects in a directory
412 write_all : write dictionary of skrf objects to a directory
413
414 Examples
415 --------
416 Writing a diction of different skrf objects
417
418 >>> from skrf.data import line, short
419 >>> d = {'ring_slot':ring_slot, 'one_port_cal':one_port_cal}
420 >>> rf.write_all(d)
421
422 """
423 if not os.path.exists('.'):
424 raise OSError(f'No such directory: {dir}')
425
426
427
428 for k in dict_objs:
429 filename = k
430 obj = dict_objs[k]
431
432 extn = get_extn(filename)
433 if extn is None:
434 # if there is not extension add one
435 filename += f".{_get_extension(obj)}"
436 try:
437 with open(os.path.join(dir+'/', filename), 'wb') as fid:
438 write(fid, obj,*args, **kwargs)
439 except Exception as inst:
440 print(inst)
441 warnings.warn(f'couldnt write {k}: {inst}', stacklevel=2)
442
443 pass
444
445 def save_sesh(dict_objs, file='skrfSesh.p', module='skrf', exclude_prefix='_'):
446 """
447 Save all `skrf` objects in the local namespace.
448
449 This is used to save current workspace in a hurry, by passing it the
450 output of :func:`locals` (see Examples). Note this can be
451 used for other modules as well by passing a different `module` name.
452
453 Parameters
454 ----------
455 dict_objs : dict
456 dictionary containing `skrf` objects. See the Example.
457 file : str or file-object, optional
458 the file to save all objects to
459 module : str, optional
460 the module name to grep for.
461 exclude_prefix: str, optional
462 dont save objects which have this as a prefix.
463
464 See Also
465 --------
466 read : read a skrf object
467 write : write skrf object[s]
468 read_all : read all skrf objects in a directory
469 write_all : write dictionary of skrf objects to a directory
470
471
472 Examples
473 --------
474 Write out all skrf objects in current namespace.
475
476 >>> rf.write_all(locals(), 'mysesh.p')
477
478
479 """
480 objects = {}
481 print('pickling: ')
482 for k in dict_objs:
483 try:
484 if module in inspect.getmodule(dict_objs[k]).__name__:
485 try:
486 pickle.dumps(dict_objs[k])
487 if k[0] != '_':
488 objects[k] = dict_objs[k]
489 print(k+', ')
490 finally:
491 pass
492
493 except(AttributeError, TypeError):
494 pass
495 if len (objects ) == 0:
496 print('nothing')
497
498 write(file, objects)
499
500 def load_all_touchstones(dir = '.', contains=None, f_unit=None):
501 """
502 Loads all touchtone files in a given dir into a dictionary.
503
504 Notes
505 -------
506
507
508 Parameters
509 -----------
510 dir : string
511 the path
512 contains : string
513 a string the filenames must contain to be loaded.
514 f_unit : ['hz','mhz','ghz']
515 the frequency unit to assign all loaded networks. see
516 :attr:`frequency.Frequency.unit`.
517
518 Returns
519 ---------
520 ntwkDict : a dictionary with keys equal to the file name (without
521 a suffix), and values equal to the corresponding ntwk types
522
523 Examples
524 ----------
525 >>> ntwk_dict = rf.load_all_touchstones('.', contains ='20v')
526
527 See Also
528 -----------
529 read_all
530 """
531 ntwkDict = {}
532
533 for f in os.listdir (dir):
534 if contains is not None and contains not in f:
535 continue
536 keyname,extn = os.path.splitext(f)
537 extn = extn.lower()
538 try:
539 if extn[1]== 's' and extn[-1]=='p':
540 ntwkDict[keyname]=(Network(dir +'/'+f))
541 if f_unit is not None:
542 ntwkDict[keyname].frequency.unit=f_unit
543 except Exception:
544 pass
545 return ntwkDict
546
547 def write_dict_of_networks(ntwkDict, dir='.'):
548 """
549 Saves a dictionary of networks touchstone files in a given directory
550
551 The filenames assigned to the touchstone files are taken from
552 the keys of the dictionary.
553
554 Parameters
555 -----------
556 ntwkDict : dictionary
557 dictionary of :class:`Network` objects
558 dir : string
559 directory to write touchstone file to
560
561
562 """
563 warnings.warn('Deprecated. use write_all.', DeprecationWarning, stacklevel=2)
564 for ntwkKey in ntwkDict:
565 ntwkDict[ntwkKey].write_touchstone(filename = dir+'/'+ntwkKey)
566
567 def read_csv(filename):
568 """
569 Read a 2-port s-parameter data from a csv file.
570
571 Specifically, this reads a two-port csv file saved from a Rohde Schwarz
572 ZVA-40, and possibly other network analyzers. It returns into a
573 :class:`Network` object.
574
575 Parameters
576 ------------
577 filename : str
578 name of file
579
580 Returns
581 --------
582 ntwk : :class:`Network` object
583 the network representing data in the csv file
584 """
585
586 ntwk = Network(name=filename[:-4])
587 try:
588 data = np.loadtxt(filename, skiprows=3,delimiter=',',\
589 usecols=range(9))
590 s11 = data[:,1] +1j*data[:,2]
591 s21 = data[:,3] +1j*data[:,4]
592 s12 = data[:,5] +1j*data[:,6]
593 s22 = data[:,7] +1j*data[:,8]
594 ntwk.s = np.array([[s11, s21],[s12,s22]]).transpose().reshape(-1,2,2)
595 except(IndexError):
596 data = np.loadtxt(filename, skiprows=3,delimiter=',',\
597 usecols=range(3))
598 ntwk.s = data[:,1] +1j*data[:,2]
599
600 ntwk.frequency.f = data[:,0]
601
602 return ntwk
603
604
605 ## file conversion
606 def statistical_2_touchstone(file_name, new_file_name=None,\
607 header_string='# GHz S RI R 50.0'):
608 """
609 Converts Statistical file to a touchstone file.
610
611 Converts the file format used by Statistical and other Dylan Williams
612 software to standard touchstone format.
613
614 Parameters
615 ----------
616 file_name : string
617 name of file to convert
618 new_file_name : string
619 name of new file to write out (including extension)
620 header_string : string
621 touchstone header written to first beginning of file
622
623 """
624 remove_tmp_file = new_file_name is None
625 if remove_tmp_file:
626 new_file_name = 'tmp-'+file_name
627
628 # This breaks compatibility with python 2.6 and older
629 with open(file_name) as old_file, open(new_file_name, 'w') as new_file:
630 new_file.write(f'{header_string}\n')
631 for line in old_file:
632 new_file.write(line)
633
634 if remove_tmp_file:
635 os.rename(new_file_name,file_name)
636
637 def network_2_spreadsheet(ntwk: Network, file_name: str | Path = None,
638 file_type: str = 'excel', form: str ='db', *args, **kwargs):
639 r"""
640 Write a Network object to a spreadsheet, for your boss.
641
642 Write the s-parameters of a network to a spreadsheet, in a variety
643 of forms. This functions makes use of the pandas module, which in
644 turn makes use of the xlrd module. These are imported during this
645 function call. For more details about the file-writing functions
646 see the `pandas.DataFrom.to_???` functions.
647
648
649 .. note::
650 The frequency unit used in the spreadsheet is take from
651 `ntwk.frequency.unit`
652
653
654 Parameters
655 ----------
656 ntwk : :class:`~skrf.network.Network` object
657 the network to write
658 file_name : str, Path or None
659 the file_name to write. if None, ntwk.name is used.
660 file_type : ['csv','excel','html']
661 the type of file to write. See `pandas.DataFrame.to_???` functions.
662 form : 'db','ma','ri'
663 format to write data,
664 * db = db, deg
665 * ma = mag, deg
666 * ri = real, imag
667 \*args, \*\*kwargs :
668 passed to `pandas.DataFrame.to_???` functions.
669
670
671 See Also
672 --------
673 networkset_2_spreadsheet : writes a spreadsheet for many networks
674 """
675 file_extns = {'csv':'csv','excel':'xls','html':'html'}
676
677 form = form.lower()
678 if form not in ['db','ri','ma']:
679 raise ValueError('`form` must be either `db`,`ma`,`ri`')
680
681
682 file_type = file_type.lower()
683 if file_type not in file_extns.keys():
684 raise ValueError('file_type must be `csv`,`html`,`excel` ')
685 if ntwk.name is None and file_name is None:
686 raise ValueError('Either ntwk must have name or give a file_name')
687
688
689 if file_name is None and 'excel_writer' not in kwargs.keys():
690 file_name = ntwk.name + '.'+file_extns[file_type]
691
692 d = {}
693 index = ntwk.frequency.f_scaled
694
695 if form =='db':
696 for m,n in ntwk.port_tuples:
697 d[f'S{ntwk._fmt_trace_name(m,n)} Log Mag(dB)'] = \
698 Series(ntwk.s_db[:,m,n], index = index)
699 d[f'S{ntwk._fmt_trace_name(m,n)} Phase(deg)'] = \
700 Series(ntwk.s_deg[:,m,n], index = index)
701 elif form =='ma':
702 for m,n in ntwk.port_tuples:
703 d[f'S{ntwk._fmt_trace_name(m,n)} Mag(lin)'] = \
704 Series(ntwk.s_mag[:,m,n], index = index)
705 d[f'S{ntwk._fmt_trace_name(m,n)} Phase(deg)'] = \
706 Series(ntwk.s_deg[:,m,n], index = index)
707 elif form =='ri':
708 for m,n in ntwk.port_tuples:
709 d[f'S{ntwk._fmt_trace_name(m,n)} Real'] = \
710 Series(ntwk.s_re[:,m,n], index = index)
711 d[f'S{ntwk._fmt_trace_name(m,n)} Imag'] = \
712 Series(ntwk.s_im[:,m,n], index = index)
713
714 df = DataFrame(d)
715 df.__getattribute__(f'to_{file_type}')(file_name,
716 index_label=f'Freq({ntwk.frequency.unit})', **kwargs)
717
718 def network_2_dataframe(ntwk: Network, attrs: list[str] =None,
719 ports: list[tuple[int, int]] = None, port_sep: str | None = None):
720 """
721 Convert one or more attributes of a network to a pandas DataFrame.
722
723 Parameters
724 ----------
725 ntwk : :class:`~skrf.network.Network` object
726 the network to write
727 attrs : list Network attributes
728 like ['s_db','s_deg']
729 ports : list of tuples
730 list of port pairs to write. defaults to ntwk.port_tuples
731 (like [(0,0)])
732 port_sep : string
733 defaults to None, which means a empty string "" is used for
734 networks with lower than 10 ports. (s_db 11, s_db 21)
735 For more than ten ports a "_" is used to avoid ambiguity.
736 (s_db 1_1, s_db 2_1)
737
738 Returns
739 -------
740 df : pandas DataFrame Object
741 """
742 if attrs is None:
743 attrs = ["s_db"]
744 if ports is None:
745 ports = ntwk.port_tuples
746
747 if port_sep is None:
748 port_sep = "_" if ntwk.nports > 10 else ""
749
750 d = {}
751 for attr in attrs:
752 attr_array = getattr(ntwk, attr)
753 for m, n in ports:
754 d[f'{attr} {m+1}{port_sep}{n+1}'] = attr_array[:, m, n]
755 return DataFrame(d, index=ntwk.frequency.f)
756
757 def networkset_2_spreadsheet(ntwkset: NetworkSet, file_name: str = None, file_type: str = 'excel',
758 *args, **kwargs):
759 r"""
760 Write a NetworkSet object to a spreadsheet, for your boss.
761
762 Write the s-parameters of a each network in the networkset to a
763 spreadsheet. If the `excel` file_type is used, then each network,
764 is written to its own sheet, with the sheetname taken from the
765 network `name` attribute.
766 This functions makes use of the pandas module, which in turn makes
767 use of the xlrd module. These are imported during this function.
768
769
770 .. note::
771 The frequency unit used in the spreadsheet is take from
772 `ntwk.frequency.unit`
773
774
775 Parameters
776 ----------
777 ntwkset : :class:`~skrf.networkSet.NetworkSet` object
778 the network to write
779 file_name : str, None
780 the file_name to write. if None, ntwk.name is used.
781 file_type : ['csv','excel','html']
782 the type of file to write. See `pandas.DataFrame.to_???` functions.
783 form : 'db','ma','ri'
784 format to write data,
785 * db = db, deg
786 * ma = mag, deg
787 * ri = real, imag
788 \*args, \*\*kwargs :
789 passed to `pandas.DataFrame.to_???` functions.
790
791
792 See Also
793 --------
794 networkset_2_spreadsheet : writes a spreadsheet for many networks
795 """
796 if ntwkset.name is None and file_name is None:
797 raise(ValueError('Either ntwkset must have name or give a file_name'))
798 if file_name is None:
799 file_name = ntwkset.name
800
801 if file_type == 'excel':
802 # add file extension if missing
803 if not file_name.endswith('.xlsx'):
804 file_name += '.xlsx'
805 with ExcelWriter(file_name) as writer:
806 [network_2_spreadsheet(k, writer, sheet_name=k.name, **kwargs) for k in ntwkset]
807 else:
808 [network_2_spreadsheet(k,*args, **kwargs) for k in ntwkset]
809
810
811 StringBuffer = StringIO
812
813
814 class TouchstoneEncoder(json.JSONEncoder):
815 """
816 Serializes Network object by converting arrays to lists,
817 splitting complex numbers into real and imaginary,
818 and breaking down frequency objects into dicts.
819 """
820 def default(self, obj):
821 if isinstance(obj, np.ndarray):
822 return obj.tolist()
823 if isinstance(obj, complex):
824 return np.real(obj), np.imag(obj) # split into [real, im]
825 if isinstance(obj, Frequency):
826 return {'flist': obj.f_scaled.tolist(), 'funit': obj.unit}
827 return json.JSONEncoder.default(self, obj)
828
829
830 def to_json_string(network):
831 """
832 Dumps Network to JSON string.
833
834 Faster than converting and saving as touchstone.
835 Safer than pickling (no arbitrary code execution on load).
836
837 Parameters
838 ----------
839 network: :class:`~skrf.network.Network` object
840 A Network object to be serialized and returned as a JSON string.
841
842 Returns
843 -------
844 json : str
845 JSON string representation of a network object.
846 """
847 return json.dumps(network.__dict__, cls=TouchstoneEncoder)
848
849
850 def from_json_string(obj_string):
851 """
852 Loads network object from JSON string representation.
853
854 Parameters
855 ----------
856 obj_string : str
857 JSON string representation of a network object.
858
859 Returns
860 -------
861 ntwk : :class:`~skrf.network.Network` object
862 A Network object, rebuilt from JSON.
863 """
864 obj = json.loads(obj_string)
865 ntwk = Network()
866 ntwk.variables = obj['variables']
867 ntwk.name = obj['name']
868 ntwk.comments = obj['comments']
869 ntwk.port_names = obj['port_names']
870 ntwk.z0 = np.array(obj['_z0'])[..., 0] + np.array(obj['_z0'])[..., 1] * 1j # recreate complex numbers
871 ntwk.s = np.array(obj['_s'])[..., 0] + np.array(obj['_s'])[..., 1] * 1j
872 ntwk.frequency = Frequency.from_f(np.array(obj['_frequency']['flist']),
873 unit=obj['_frequency']['funit'])
874 return ntwk