pyvib.common module

class pyvib.common.color[source]

Bases: object

BLUE = '\x1b[94m'
BOLD = '\x1b[1m'
CYAN = '\x1b[96m'
DARKCYAN = '\x1b[36m'
END = '\x1b[0m'
GREEN = '\x1b[92m'
PURPLE = '\x1b[95m'
RED = '\x1b[91m'
UNDERLINE = '\x1b[4m'
YELLOW = '\x1b[93m'
pyvib.common.db(x, r=1)[source]

relative value in dB

TODO: Maybe x should be rescaled to ]0..1].? log10(0) = inf.

Parameters:
  • x (array like)
  • r (float, optional) – Reference value. default = 1

Notes

https://en.wikipedia.org/wiki/Decibel#Field_quantities_and_root-power_quantities

pyvib.common.import_npz(npz_file, namespace={'TERMINATION_MESSAGES': {None: 'Status returned `None`. Error.', -1: 'Improper input parameters status returned from `leastsq`', 0: 'The maximum number of iterations is exceeded.', 1: '`gtol` termination condition is satisfied. (small change in Jacobian)', 2: '`ftol` termination condition is satisfied. (small change in cost)', 3: '`xtol` termination condition is satisfied. (small step)', 4: 'Both `ftol`(cost) and `xtol`(step) termination conditions are satisfied.'}, '__builtins__': {'ArithmeticError': <class 'ArithmeticError'>, 'AssertionError': <class 'AssertionError'>, 'AttributeError': <class 'AttributeError'>, 'BaseException': <class 'BaseException'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'BufferError': <class 'BufferError'>, 'BytesWarning': <class 'BytesWarning'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionError': <class 'ConnectionError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'EOFError': <class 'EOFError'>, 'Ellipsis': Ellipsis, 'EnvironmentError': <class 'OSError'>, 'Exception': <class 'Exception'>, 'False': False, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'FutureWarning': <class 'FutureWarning'>, 'GeneratorExit': <class 'GeneratorExit'>, 'IOError': <class 'OSError'>, 'ImportError': <class 'ImportError'>, 'ImportWarning': <class 'ImportWarning'>, 'IndentationError': <class 'IndentationError'>, 'IndexError': <class 'IndexError'>, 'InterruptedError': <class 'InterruptedError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'KeyError': <class 'KeyError'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'LookupError': <class 'LookupError'>, 'MemoryError': <class 'MemoryError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'NameError': <class 'NameError'>, 'None': None, 'NotADirectoryError': <class 'NotADirectoryError'>, 'NotImplemented': NotImplemented, 'NotImplementedError': <class 'NotImplementedError'>, 'OSError': <class 'OSError'>, 'OverflowError': <class 'OverflowError'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'RecursionError': <class 'RecursionError'>, 'ReferenceError': <class 'ReferenceError'>, 'ResourceWarning': <class 'ResourceWarning'>, 'RuntimeError': <class 'RuntimeError'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'SyntaxError': <class 'SyntaxError'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'SystemError': <class 'SystemError'>, 'SystemExit': <class 'SystemExit'>, 'TabError': <class 'TabError'>, 'TimeoutError': <class 'TimeoutError'>, 'True': True, 'TypeError': <class 'TypeError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'UserWarning': <class 'UserWarning'>, 'ValueError': <class 'ValueError'>, 'Warning': <class 'Warning'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, '_PYVIB_SETUP_': False, '__build_class__': <built-in function __build_class__>, '__debug__': True, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__import__': <built-in function __import__>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': 'builtins', '__package__': '', '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'bool': <class 'bool'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'classmethod': <class 'classmethod'>, 'compile': <built-in function compile>, 'complex': <class 'complex'>, 'copyright': Copyright (c) 2001-2017 Python Software Foundation. All Rights Reserved. Copyright (c) 2000 BeOpen.com. All Rights Reserved. Copyright (c) 1995-2001 Corporation for National Research Initiatives. All Rights Reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All Rights Reserved., 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for supporting Python development. See www.python.org for more information., 'delattr': <built-in function delattr>, 'dict': <class 'dict'>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'enumerate': <class 'enumerate'>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'filter': <class 'filter'>, 'float': <class 'float'>, 'format': <built-in function format>, 'frozenset': <class 'frozenset'>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'help': Type help() for interactive help, or help(object) for help about object., 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'int': <class 'int'>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'license': See https://www.python.org/psf/license/, 'list': <class 'list'>, 'locals': <built-in function locals>, 'map': <class 'map'>, 'max': <built-in function max>, 'memoryview': <class 'memoryview'>, 'min': <built-in function min>, 'next': <built-in function next>, 'object': <class 'object'>, 'oct': <built-in function oct>, 'open': <built-in function open>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'property': <class 'property'>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'range': <class 'range'>, 'repr': <built-in function repr>, 'reversed': <class 'reversed'>, 'round': <built-in function round>, 'set': <class 'set'>, 'setattr': <built-in function setattr>, 'slice': <class 'slice'>, 'sorted': <built-in function sorted>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'sum': <built-in function sum>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'vars': <built-in function vars>, 'zip': <class 'zip'>}, '__cached__': '/home/docs/checkouts/readthedocs.org/user_builds/pyvib/envs/latest/lib/python3.6/site-packages/pyvib-0.2.dev1-py3.6.egg/pyvib/__pycache__/common.cpython-36.pyc', '__doc__': None, '__file__': '/home/docs/checkouts/readthedocs.org/user_builds/pyvib/envs/latest/lib/python3.6/site-packages/pyvib-0.2.dev1-py3.6.egg/pyvib/common.py', '__loader__': <_frozen_importlib_external.SourceFileLoader object>, '__name__': 'pyvib.common', '__package__': 'pyvib', '__spec__': ModuleSpec(name='pyvib.common', loader=<_frozen_importlib_external.SourceFileLoader object>, origin='/home/docs/checkouts/readthedocs.org/user_builds/pyvib/envs/latest/lib/python3.6/site-packages/pyvib-0.2.dev1-py3.6.egg/pyvib/common.py'), 'color': <class 'pyvib.common.color'>, 'db': <function db>, 'import_npz': <function import_npz>, 'itertools': <module 'itertools' (built-in)>, 'lm': <function lm>, 'math': <module 'math' from '/home/docs/checkouts/readthedocs.org/user_builds/pyvib/envs/latest/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'>, 'matrix_square_inv': <function matrix_square_inv>, 'meanVar': <function meanVar>, 'mmul_weight': <function mmul_weight>, 'next_pow2': <function next_pow2>, 'norm': <function norm>, 'normalize_columns': <function normalize_columns>, 'np': <module 'numpy' from '/home/docs/.pyenv/versions/3.6.4/lib/python3.6/site-packages/numpy/__init__.py'>, 'prime_factor': <function prime_factor>, 'rescale': <function rescale>, 'svd': <function svd>, 'weightfcn': <function weightfcn>, 'window': <function window>})[source]

Load npz file and unpack data/dictionary to the given namespace

It is necessary to explicit call the function with globals() even if it is set as default value here. The docs states that the scope is the defining module not the calling.

Example for oneliner without using namespace(can only be used local) for varName in data.files:

exec(varName + ” = data[‘” + varName + “’]”)

https://docs.python.org/3/library/functions.html#globals

pyvib.common.lm(fun, x0, jac, info=2, nmax=50, lamb=None, ftol=1e-08, xtol=1e-08, gtol=1e-08, args=(), kwargs={})[source]
Solve a nonlinear least-squares problem using levenberg marquardt
algorithm. See also :scipy-optimize:func:`scipy.optimize.least_squares`
Parameters:
  • fun (callable) – Function which computes the vector of residuals

  • x0 (array_like with shape (n,) or float) – Initial guess on independent variables.

  • jac (callable) – Method of computing the Jacobian matrix (an m-by-n matrix, where element (i, j) is the partial derivative of f[i] with respect to x[j]).

  • ftol (float, optional) – Tolerance for termination by the change of the cost function. Default is 1e-8. The optimization process is stopped when dF < ftol * F, and there was an adequate agreement between a local quadratic model and the true model in the last step.

  • xtol (float, optional) – Tolerance for termination by the change of the independent variables. Default is 1e-8.

  • gtol (float, optional) – Tolerance for termination by the norm of the gradient. Default is 1e-8.

  • info ({0, 1, 2}, optional) –

    Level of algorithm’s verbosity:
    • 0 (default) : work silently.
    • 1 : display a termination report.
    • 2 : display progress during iterations
pyvib.common.matrix_square_inv(A)[source]

Calculate the inverse of the matrix square root of A Calculate X such that XX = inv(A) A is assumed positive definite, thus the all singular values are strictly positive. Given the svd decomposition A=UsVᴴ, we see that AAᴴ = Us²Uᴴ (remember (UsV)ᴴ = VᴴsUᴴ) and it follows that (AAᴴ)⁻¹/² = Us⁻¹Uᴴ :returns: X – Inverse of matrix square root of A :rtype: ndarray(n,n)

Notes

See the comments here. https://math.stackexchange.com/questions/106774/matrix-square-root

pyvib.common.meanVar(Y, isnoise=False)[source]

Y = fft(y)/nsper

Parameters:Y (ndarray (ndof, nsper, nper)) – Y is the fft of y
pyvib.common.mmul_weight(mat, weight)[source]

Add weight. Computes the Jacobian of the weighted error e_W(f) = W(f,:,:)*e(f)

pyvib.common.next_pow2(i)[source]

Find the next power of two

>>> int(next_pow2(5))
8
>>> int(next_pow2(250))
256
pyvib.common.normalize_columns(mat)[source]
pyvib.common.prime_factor(n)[source]

Find the prime factorization of n

Efficient implementation. Find the factorization by trial division, using the optimization of dividing only by two and the odd integers.

An improvement on trial division by two and the odd numbers is wheel factorization, which uses a cyclic set of gaps between potential primes to greatly reduce the number of trial divisions. Here we use a 2,3,5-wheel

Factoring wheels have the same O(sqrt(n)) time complexity as normal trial division, but will be two or three times faster in practice.

>>> list(factors(90))
[2, 3, 3, 5]
pyvib.common.rescale(x, mini=None, maxi=None)[source]

Rescale x to 0-1.

If mini and maxi is given, then they are used as the values that get scaled to 0 and 1, respectively

Notes

To 0..1: z_i = (x_i− min(x)) / (max(x)−min(x))

Or custom range: a = (maxval-minval) / (max(x)-min(x)) b = maxval - a * max(x) z = a * x + b

pyvib.common.weightfcn(cov)[source]

Calculate weight. For subspace is the square inverse of covG. For pnlss it is the square inverse of covY

pyvib.common.window(iterable, n=3)[source]

Returns a sliding window (of width n) over data from the iterable s -> (s0,s1,…s[n-1]), (s1,s2,…,sn), …