Debian Codegraph @

skrf/util.py

raw symbols SCIP
1 """
2
3 .. currentmodule:: skrf.util
4 ========================================
5 util (:mod:`skrf.util`)
6 ========================================
7
8 Holds utilities that are general conveniences.
9
10
11 Time-related utilities
12 ----------------------
13 .. autosummary::
14 :toctree: generated/
15
16 now_string
17 now_string_2_dt
18
19 ProgressBar
20
21 Array-related functions
22 -----------------------
23 .. autosummary::
24 :toctree: generated/
25
26 find_nearest
27 find_nearest_index
28 has_duplicate_value
29 smooth
30
31 File-related functions
32 ----------------------
33 .. autosummary::
34 :toctree: generated/
35
36 get_fid
37 get_extn
38 basename_noext
39 git_version
40 unique_name
41 findReplace
42 dict_2_recarray
43
44 General Purpose Objects
45 -----------------------
46 .. autosummary::
47 :toctree: generated/
48
49 HomoList
50 HomoDict
51
52 """
53 from __future__ import annotations
54
55 import collections
56 import contextlib
57 import fnmatch
58 import os
59 import pprint
60 import re
61 import sys
62 import warnings
63 from collections.abc import Callable, Iterable
64 from datetime import datetime
65 from functools import wraps
66 from pathlib import Path
67 from subprocess import PIPE, Popen
68 from typing import Any, TypeVar
69
70 import numpy as np
71
72 from .constants import Number
73
74 try:
75 import matplotlib.pyplot as plt
76 from matplotlib.axes import Axes
77 from matplotlib.figure import Figure
78 except ImportError:
79 Figure = TypeVar("Figure")
80 Axes = TypeVar("Axes")
81 pass
82
83 def plotting_available() -> bool:
84 return "matplotlib" in sys.modules
85
86 def partial_with_docs(func, *args1, **kwargs1):
87 @wraps(func)
88 def method(self, *args2, **kwargs2):
89 return func(self, *args1, *args2, **kwargs1, **kwargs2)
90 return method
91
92 def axes_kwarg(func):
93 """
94 This decorator checks if a :class:`matplotlib.axes.Axes` object is passed,
95 if not the current axis will be gathered through :func:`plt.gca`.
96
97 Raises
98 ------
99 RuntimeError
100 When trying to run the decorated function without matplotlib
101 """
102
103 @wraps(func)
104 def wrapper(*args, **kwargs):
105 ax = kwargs.pop('ax', None)
106 try:
107 if ax is None:
108 ax = plt.gca()
109 except NameError as err:
110 raise RuntimeError("Plotting is not available") from err
111 func(*args, ax=ax, **kwargs)
112
113 return wrapper
114
115 def copy_doc(copy_func: Callable) -> Callable:
116 """Use Example: copy_doc(self.copy_func)(self.func) or used as deco"""
117 def wrapper(func: Callable) -> Callable:
118 func.__doc__ = copy_func.__doc__
119 return func
120 return wrapper
121
122 def figure(*args, **kwargs) -> Figure:
123 """
124 Wraps the matplotlib figure call and raises if not available.
125
126 Raises
127 ------
128 RuntimeError
129 When trying to get subplots without matplotlib installed.
130 """
131
132 try:
133 return plt.figure(*args, **kwargs)
134 except NameError as err:
135 raise RuntimeError("Plotting is not available") from err
136
137 def subplots(*args, **kwargs) -> tuple[Figure, np.ndarray]:
138 """
139 Wraps the matplotlib subplots call and raises if not available.
140
141 Raises
142 ------
143 RuntimeError
144 When trying to get subplots without matplotlib installed.
145 """
146
147 try:
148 return plt.subplots(*args, **kwargs)
149 except NameError as err:
150 raise RuntimeError("Plotting is not available") from err
151
152 def now_string() -> str:
153 """
154 Return a unique sortable string, representing the current time.
155
156 Nice for generating date-time stamps to be used in file-names,
157 the companion function :func:`now_string_2_dt` can be used
158 to read these string back into datetime objects.
159
160 Returns
161 -------
162 now : string
163 current date-time stamps.
164
165 See Also
166 --------
167 now_string_2_dt
168
169 """
170 return datetime.now().__str__().replace('-','.').replace(':','.').replace(' ','.')
171
172
173 def now_string_2_dt(s: str) -> datetime:
174 """
175 Converts the output of :func:`now_string` to a datetime object.
176
177 Parameters
178 ----------
179 s : str
180 date-time stamps string as generated by :func:`now_string`
181
182 Returns
183 -------
184 dt : datetime
185 date-time stamps
186
187 See Also
188 --------
189 now_string
190
191 """
192 return datetime(*[int(k) for k in s.split('.')])
193
194
195 def find_nearest(array: np.ndarray, value: Number) -> Number:
196 """
197 Find the nearest value in array.
198
199 Parameters
200 ----------
201 array : np.ndarray
202 array we are searching for a value in
203 value : element of the array
204 value to search for
205
206 Returns
207 --------
208 found_value : an element of the array
209 the value that is numerically closest to `value`
210
211 """
212 idx = find_nearest_index(array, value)
213 return array[idx]
214
215
216 def find_nearest_index(array: np.ndarray, value: Number) -> int:
217 """
218 Find the nearest index for a value in array.
219
220 Parameters
221 ----------
222 array : np.ndarray
223 array we are searching for a value in
224 value : element of the array
225 value to search for
226
227 Returns
228 --------
229 found_index : int
230 the index at which the numerically closest element to `value`
231 was found at
232
233 References
234 ----------
235 taken from http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array
236
237 """
238 return (np.abs(array-value)).argmin()
239
240
241 def slice_domain(x: np.ndarray, domain: tuple):
242 """
243 Returns a slice object closest to the `domain` of `x`
244
245 domain = x[slice_domain(x, (start, stop))]
246
247 Parameters
248 ----------
249 vector : np.ndarray
250 an array of values
251 domain : tuple
252 tuple of (start,stop) values defining the domain over
253 which to slice
254
255 Examples
256 --------
257 >>> x = linspace(0,10,101)
258 >>> idx = slice_domain(x, (2,6))
259 >>> x[idx]
260
261 """
262 start = find_nearest_index(x, domain[0])
263 stop = find_nearest_index(x, domain[1])
264 return slice(start, stop+1)
265
266 # file IO
267
268
269 def get_fid(file, *args, **kwargs):
270 r"""
271 Return a file object, given a filename or file object.
272
273 Useful when you want to allow the arguments of a function to
274 be either files or filenames
275
276 Parameters
277 ----------
278 file : str/unicode, Path, or file-object
279 file to open
280 \*args, \*\*kwargs : arguments and keyword arguments to `open()`
281
282 Returns
283 -------
284 fid : file object
285
286 """
287 if isinstance(file, (str, Path)):
288 return open(file, *args, **kwargs)
289 else:
290 return file
291
292
293 def get_extn(filename: str | Path) -> str:
294 """
295 Get the extension from a filename.
296
297 The extension is defined as everything passed the last '.'.
298 Returns None if it ain't got one
299
300 Parameters
301 ----------
302 filename : string or Path
303 the filename
304
305 Returns
306 -------
307 ext : string, None
308 either the extension (not including '.') or None if there
309 isn't one
310
311 """
312
313 if isinstance(filename, Path):
314 return filename.suffix.strip('.') or None
315
316 ext = os.path.splitext(filename)[-1]
317 if len(ext) == 0:
318 return None
319 else:
320 return ext[1:]
321
322
323 def basename_noext(filename: str) -> str:
324 """
325 Get the basename and strips extension.
326
327 Parameters
328 ----------
329 filename : string
330 the filename
331
332 Returns
333 -------
334 basename : str
335 file basename (ie. without extension)
336
337 """
338 return os.path.splitext(os.path.basename(filename))[0]
339
340
341 # git
342 def git_version(modname: str) -> str:
343 """
344 Return output 'git describe', executed in a module's root directory.
345
346 Parameters
347 ----------
348 modname : str
349 module name
350
351 Returns
352 -------
353 out : str
354 output of 'git describe'
355
356 """
357 mod = __import__(modname)
358 mod_dir = os.path.split(mod.__file__)[0]
359 p = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE, cwd=mod_dir)
360
361 try:
362 out, er = p.communicate()
363 except(OSError):
364 return None
365
366 out = out.strip('\n')
367 if out == '':
368 return None
369 return out
370
371
372 def dict_2_recarray(d: dict, delim: str, dtype: list[tuple]) -> np.ndarray:
373 """
374 Turn a dictionary of structured keys to a record array of objects.
375
376 This is useful if you save data-base like meta-data in the form
377 or file-naming conventions, aka 'the poor-mans database'
378
379 Parameters
380 ----------
381 d : dict
382 dictionary of structured keys
383 delim : str
384 delimiter string
385 dtype : list of tuple
386 list of type, where a type is tuple like ('type_name', type)
387
388 Returns
389 -------
390 ra : numpy.array
391
392 Examples
393 --------
394 Given a directory of networks like:
395
396 >>> ls
397 a1,0.0,0.0.s1p a1,3.0,3.0.s1p a2,3.0,-3.0.s1p b1,-3.0,3.0.s1p
398 ...
399
400 you can sort based on the values or each field, after defining their
401 type with `dtype`. The `values` field accesses the objects.
402
403 >>> d = rf.read_all_networks('/tmp/')
404 >>> delim = ','
405 >>> dtype = [('name', object), ('voltage', float), ('current', float)]
406 >>> ra = dict_2_recarray(d=rf.ran(dir), delim=delim, dtype =dtype)
407
408 then you can sift like you do with numpy arrays
409
410 >>> ra[ra['voltage'] < 3]['values']
411 array([1-Port Network: 'a2,0.0,-3.0', 450-800 GHz, 101 pts, z0=[ 50.+0.j],
412 1-Port Network: 'b1,0.0,3.0', 450-800 GHz, 101 pts, z0=[ 50.+0.j],
413 1-Port Network: 'a1,0.0,-3.0', 450-800 GHz, 101 pts, z0=[ 50.+0.j],
414 """
415
416 split_keys = [tuple(k.split(delim)+[d[k]]) for k in d.keys()]
417 x = np.array(split_keys, dtype=dtype+[('values',object)])
418 return x
419
420
421 def findReplace(directory: str, find: str, replace: str, file_pattern: str):
422 r"""
423 Find/replace some txt in all files in a directory, recursively.
424
425 This was found in [1]_ .
426
427 Parameters
428 ----------
429 directory : str
430 path of a directory
431 find : str
432 pattern to search for
433 replace : str
434 string to replace with
435 file_pattern : str
436 file pattern for filtering. Ex: '\*.txt'.
437
438 Examples
439 --------
440 >>> rf.findReplace('some_dir', 'find this', 'replace with this', '*.txt')
441
442 References
443 ----------
444 .. [1] http://stackoverflow.com/questions/4205854/python-way-to-recursively-find-and-replace-string-in-text-files
445 """
446 for path, _dirs, files in os.walk(os.path.abspath(directory)):
447 for filename in fnmatch.filter(files, file_pattern):
448 filepath = os.path.join(path, filename)
449 with open(filepath) as f:
450 s = f.read()
451 s = s.replace(find, replace)
452 with open(filepath, "w") as f:
453 f.write(s)
454
455
456 # general purpose objects
457
458 class HomoList(collections.abc.Sequence):
459 """
460 A Homogeneous Sequence.
461
462 Provides a class for a list-like object which contains
463 homogeneous values. Attributes of the values can be accessed through
464 the attributes of HomoList. Searching is done like numpy arrays.
465
466 Initialized from a list of all the same type
467
468 >>> h = HomoDict([Foo(...), Foo(...)])
469
470 The individual values of `h` can be access in identical fashion to
471 Lists.
472
473 >>> h[0]
474
475 Assuming that `Foo` has property `prop` and function `func` ...
476
477 Access elements' properties:
478
479 >>> h.prop
480
481 Access elements' functions:
482
483 >>> h.func()
484
485 Searching:
486
487 >>> h[h.prop == value]
488 >>> h[h.prop < value]
489
490 Multiple search:
491
492 >>> h[set(h.prop==value1) & set( h.prop2==value2)]
493
494 Combos:
495
496 >>> h[h.prop==value].func()
497 """
498
499
500 def __init__(self, list_):
501 self.store = list(list_)
502
503 def __eq__(self, value):
504 return [k for k in range(len(self)) if self.store[k] == value ]
505
506 def __ne__(self, value):
507 return [k for k in range(len(self)) if self.store[k] != value ]
508
509 def __gt__(self, value):
510 return [k for k in range(len(self)) if self.store[k] > value ]
511
512 def __ge__(self, value):
513 return [k for k in range(len(self)) if self.store[k] >= value ]
514
515 def __lt__(self, value):
516 return [k for k in range(len(self)) if self.store[k] < value ]
517
518 def __le__(self, value):
519 return [k for k in range(len(self)) if self.store[k] <= value ]
520
521 def __getattr__(self, name):
522 return self.__class__(
523 [k.__getattribute__(name) for k in self.store])
524
525 def __getitem__(self, idx):
526 try:
527 return self.store[idx]
528 except(TypeError):
529 return self.__class__([self.store[k] for k in idx])
530
531
532 def __call__(self, *args, **kwargs):
533 return self.__class__(
534 [k(*args,**kwargs) for k in self.store])
535
536 def __setitem__(self, idx, value):
537 self.store[idx] = value
538
539 def __delitem__(self, idx):
540 del self.store[idx]
541
542 def __iter__(self):
543 return iter(self.store)
544
545 def __len__(self):
546 return len(self.store)
547
548 def __str__(self):
549 return pprint.pformat(self.store)
550
551 def __repr__(self):
552 return pprint.pformat(self.store)
553
554
555 class HomoDict(collections.abc.MutableMapping):
556 """
557 A Homogeneous Mutable Mapping.
558
559 Provides a class for a dictionary-like object which contains
560 homogeneous values. Attributes of the values can be accessed through
561 the attributes of HomoDict. Searching is done like numpy arrays.
562
563 Initialized from a dictionary containing values of all the same type
564
565 >>> h = HomoDict({'a':Foo(...),'b': Foo(...), 'c':Foo(..)})
566
567 The individual values of `h` can be access in identical fashion to
568 Dictionaries.
569
570 >>> h['key']
571
572 Assuming that `Foo` has property `prop` and function `func` ...
573
574 Access elements' properties:
575
576 >>> h.prop
577
578 Access elements' functions:
579
580 >>> h.func()
581
582 Searching:
583
584 >>> h[h.prop == value]
585 >>> h[h.prop < value]
586
587 Multiple search:
588
589 >>> h[set(h.prop==value1) & set( h.prop2==value2)]
590
591 Combos:
592
593 >>> h[h.prop==value].func()
594 """
595 def __init__(self, dict_):
596 self.store = dict(dict_)
597
598 def __eq__(self, value):
599 return [k for k in self.store if self.store[k] == value ]
600
601 def __ne__(self, value):
602 return [k for k in self.store if self.store[k] != value ]
603
604 def __gt__(self, value):
605 return [k for k in self.store if self.store[k] > value ]
606
607 def __ge__(self, value):
608 return [k for k in self.store if self.store[k] >= value ]
609
610 def __lt__(self, value):
611 return [k for k in self.store if self.store[k] < value ]
612
613 def __le__(self, value):
614 return [k for k in self.store if self.store[k] <= value ]
615
616 def __getattr__(self, name):
617 return self.__class__(
618 {k: getattr(self.store[k],name) for k in self.store})
619
620 def __getitem__(self, key):
621 if isinstance(key, str):
622 return self.store[key]
623 else:
624 c = self.__class__({k:self.store[k] for k in key})
625 return c
626 #if len(c) == 1:
627 # return c.store.values()[0]
628 #else:
629 # return c
630
631 def __call__(self, *args, **kwargs):
632 return self.__class__(
633 {k: self.store[k](*args, **kwargs) for k in self.store})
634
635 def __setitem__(self, key, value):
636 self.store[key] = value
637
638 def __delitem__(self, key):
639 del self.store[key]
640
641 def __iter__(self):
642 return iter(self.store)
643
644 def __len__(self):
645 return len(self.store)
646
647 def __str__(self):
648 return pprint.pformat(self.store)
649
650 def __repr__(self):
651 return pprint.pformat(self.store)
652
653
654 def copy(self):
655 return HomoDict(self.store)
656
657
658 def filter_nones(self):
659 self.store = {k:self.store[k] for k in self.store \
660 if self.store[k] is not None}
661
662 def filter(self, **kwargs):
663 """
664 Filter self based on kwargs
665
666 This is equivalent to:
667
668 >>> h = HomoDict(...)
669 >>> for k in kwargs:
670 >>> h = h[k ==kwargs[k]]
671 >>> return h
672
673 prefixing the kwarg value with a '!' causes a not equal test (!=)
674
675 Examples
676 ----------
677 >>> h = HomoDict(...)
678 >>> h.filter(name='jean', age = '18', gender ='!female')
679
680 """
681 a = self
682 for k in kwargs:
683 if kwargs[k][0] == '!':
684 a = a[a.__getattr__(k) != kwargs[k][1:]]
685 else:
686 a = a[a.__getattr__(k) == kwargs[k]]
687 return a
688
689
690 def has_duplicate_value(value: Any, values: Iterable, index: int) -> bool | int:
691 """
692 Check if there is another value of the current index in the list.
693
694 Parameters
695 ----------
696 value : Any
697 any value in a list
698 values : Iterable
699 the iterable containing the values
700 index : int
701 the index of the current item we are checking for.
702
703 Returns
704 -------
705 index : bool or int
706 returns None if no duplicate found, or the index of the first found duplicate
707
708 Examples
709 --------
710 >>> rf.has_duplicate_value(0, [1, 2, 0, 3, 0], -1) # -> 2
711 >>> rf.has_duplicate_value(0, [1, 2, 0, 3, 0], 2) # -> 4
712 >>> rf.has_duplicate_value(3, [1, 2, 0, 3, 0], 0) # -> 3
713 >>> rf.has_duplicate_value(3, [1, 2, 0, 3, 0], 3) # -> False
714 """
715
716 for i, val in enumerate(values):
717 if i == index:
718 continue
719 if value == val:
720 return i
721 return False
722
723
724 def unique_name(name: str, names: list, exclude: int = -1) -> str:
725 """
726 Pass in a name and a list of names, and increment with _## as necessary to ensure a unique name.
727
728 Parameters
729 ----------
730 name : str
731 the chosen name, to be modified if necessary
732 names : list
733 list of names (str)
734 exclude : int, optional
735 the index of an item to be excluded from the search. Default is -1.
736
737 Returns
738 -------
739 unique_name : str
740
741 """
742 if not has_duplicate_value(name, names, exclude):
743 return name
744 else:
745 if re.match(r"_\d\d", name[-3:]):
746 name_base = name[:-3]
747 suffix = int(name[-2:])
748 else:
749 name_base = name
750 suffix = 1
751
752 for num in range(suffix, 100, 1):
753 name = f"{name_base:s}_{num:02d}"
754 if not has_duplicate_value(name, names, exclude):
755 break
756 return name
757
758
759 def smooth(x: np.ndarray, window_len: int = 11, window: str = 'flat') -> np.ndarray:
760 """
761 Smooth the data using a window with requested size.
762
763 Based on the function from the scipy cookbook [#]_
764
765 This method is based on the convolution of a scaled window with the signal.
766 The signal is prepared by introducing reflected copies of the signal
767 (with the window size) in both ends so that transient parts are minimized
768 in the beginning and end part of the output signal.
769
770 Parameters
771 ----------
772 x : numpy.array
773 the input signal
774 window_len : int, optional
775 the dimension of the smoothing window; should be an odd integer.
776 Default is 11.
777 window : str, optional
778 the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
779 flat window will produce a moving average smoothing. Default is 'flat'
780
781 Returns
782 -------
783 y : numpy.array
784 The smoothed signal
785
786 Examples
787 --------
788 >>> t = linspace(-2, 2, 0.1)
789 >>> x = sin(t) + randn(len(t))*0.1
790 >>> y = smooth(x)
791
792 See Also
793 --------
794 numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
795 scipy.signal.lfilter
796
797 Note
798 ----
799 `length(output) != length(input)`.
800 To correct this: `return y[(window_len/2-1):-(window_len/2)]` instead of just `y`.
801
802 References
803 ----------
804 .. [#] http://scipy-cookbook.readthedocs.io/items/SignalSmooth.html
805
806 """
807
808 if x.ndim != 1:
809 raise ValueError("smooth only accepts 1 dimension arrays.")
810
811 if x.size < window_len:
812 raise ValueError("Input vector needs to be bigger than window size.")
813
814 if window_len < 3:
815 return x
816
817 if window not in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
818 raise ValueError("Window is one of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")
819
820 s = np.r_[x[window_len - 1:0:-1], x, x[-2:-window_len - 1:-1]]
821 if window == 'flat': # moving average
822 w = np.ones(window_len, 'd')
823 else:
824 w = eval('np.' + window + '(window_len)')
825 y = np.convolve(w / w.sum(), s, mode='same')
826 return y[window_len-1:-(window_len-1)]
827
828
829 class ProgressBar:
830 """
831 A progress bar based off of the notebook/ipython progress bar from PyMC.
832
833 Useful when waiting for long operations such as taking a large number
834 of VNA measurements that may take a few minutes.
835
836 Examples
837 --------
838 >>> from time import sleep
839 >>> pb = rf.ProgressBar(10)
840 >>> for idx in range(10):
841 >>> sleep(1)
842 >>> pb.animate(idx)
843
844 """
845 def __init__(self, iterations: int, label: str = "iterations"):
846 """
847 Progress bar constructor.
848
849 Parameters
850 ----------
851 iterations : int
852 Number of expected iterations
853 label : str, optional
854 Progress bar label, by default "iterations"
855 """
856 self.iterations = iterations
857 self.label = label
858 self.prog_bar = '[]'
859 self.fill_char = '*'
860 self.width = 50
861 self.__update_amount(0)
862
863 def animate(self, iteration: int):
864 """
865 Animate the progress bar.
866
867 Parameters
868 ----------
869 iteration : int
870 current iteration
871 """
872 print('\r', self, end='')
873 sys.stdout.flush()
874 self.update_iteration(iteration + 1)
875
876 def update_iteration(self, elapsed_iter: int):
877 self.__update_amount((elapsed_iter / float(self.iterations)) * 100.0)
878 self.prog_bar += ' %d of %s %s complete' % (elapsed_iter, self.iterations, self.label)
879
880 def __update_amount(self, new_amount: int):
881 percent_done = int(round((new_amount / 100.0) * 100.0))
882 all_full = self.width - 2
883 num_hashes = int(round((percent_done / 100.0) * all_full))
884 self.prog_bar = '[' + self.fill_char * num_hashes + ' ' * (all_full - num_hashes) + ']'
885 pct_place = (len(self.prog_bar) // 2) - len(str(percent_done))
886 pct_string = '%d%%' % percent_done
887 self.prog_bar = self.prog_bar[0:pct_place] + \
888 (pct_string + self.prog_bar[pct_place + len(pct_string):])
889
890 def __str__(self):
891 return str(self.prog_bar)
892
893
894 @contextlib.contextmanager
895 def suppress_numpy_warnings(**kw):
896 olderr = np.seterr(**kw)
897 yield
898 np.seterr(**olderr)
899
900
901 def suppress_warning_decorator(msg):
902 def suppress_warnings_decorated(func):
903 @wraps(func)
904 def suppressed_func(*k, **kw):
905 with warnings.catch_warnings():
906 warnings.filterwarnings("ignore", message=f"{msg}.*")
907 res = func(*k, **kw)
908 return res
909 return suppressed_func
910 return suppress_warnings_decorated