Utilities

Utilities module within the ketos library

This module provides a number of auxiliary methods.

ketos.utils.complex_value(mag, angle)[source]

Computes complex value from magnitude and phase angle.

Args:
mag: numpy array

Magnitude

angle: float or numpy array

Phase angle in radians

Returns:
c: numpy array

Complex value

ketos.utils.detect_peaks(df, distance=1, multiplicity=1, prominence=1.0, height=None, threshold=None)[source]

Detect peaks in time-series data.

The time-series data is provided in the form of a Pandas DataFrame object, where each column contains a different time series.

This is essentially a wrapper around a SciPy’s find_peaks method:

Args:
df: Pandas DataFrame

Data frame containing the input data.

distance: int

Minimum distance between adjacent peaks

multiplicity: int

Number of time series in which peaks must appear to be counted.

prominence: float

Required prominence of the peaks. The prominence of a peak measures how much a peak stands out from the surrounding baseline of the signal and is defined as the vertical distance between the peak and its lowest contour line. See also https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.peak_prominences.html#scipy.signal.peak_prominences

height: float

Required absolute height of the peaks.

threshold: float

Required threshold of peaks (the vertical distance to its neighbouring samples).

Returns:
y: Pandas DataFrame

Data frame containing the detected peaks

Example:
>>> from ketos.utils import detect_peaks
>>> import pandas as pd
>>>
>>> # create a two time series, where only the first contains a peak
>>> d = {'series1' : pd.Series([1.0, 2.3, 22.0, 2.2, 1.5]), 'series2': pd.Series([1.0, 2.3, 1.8, 2.2, 1.5])}
>>> df = pd.DataFrame(d)
>>> 
>>> # detect peaks with multiplicity 1 and prominence of at least 2.0
>>> peaks = detect_peaks(df=df, multiplicity=1, prominence=2.0)
>>> print(peaks)
[0 0 1 0 0]
>>> 
>>> # try again, but this time require multiplicity 2
>>> peaks = detect_peaks(df=df, multiplicity=2, prominence=2.0)
>>> print(peaks)
[0 0 0 0 0]
ketos.utils.ensure_dir(file_path)[source]

Ensure that destination directory exists.

If the directory does not exist, it is created. If it already exists, nothing happens.

Args:
file_path: str

Full path to destination

ketos.utils.factors(n)[source]

Returns sorted set of all divisors of n

Args:
n: int

Integer number

Returns:
s: set

Sorted set of all divisors of n

ketos.utils.get_member(cls, member_name)[source]

Query class member by name.

Returns ValueError if class does not contain a member by that name.

Args:
cls: Class

Class

member_name: str

Member name

Returns:
member:

The class member

ketos.utils.morlet_func(time, frequency, width, displacement, norm=True, dfdt=0)[source]

Compute Morlet wavelet function

The function is implemented as in Eq. (15) in John Ashmead, “Morlet Wavelets in Quantum Mechanics”, Quanta 2012; 1: 58-70, with the replacement f -> 2*pi*f*s, to allow f to be identified with the physical frequency.

Args:
time: float or numpy array

Time in seconds at which the function is to be evaluated

frequency: float

Wavelet frequency in Hz

width: float

Wavelet width in seconds (1-sigma width of the Gaussian envelope function)

displacement: float

Wavelet centroid in seconds

norm: bool

Include [pi^1/4*sqrt(sigma)]^-1 normalization factor

dfdt: float

Rate of change in frequency as a function of time in Hz per second. If dfdt is non-zero, the frequency is computed as

f = frequency + (time - displacement) * dfdt

Returns:
y: float or numpy array

Value of Morlet wavelet function at time t

Example:
>>> from ketos.utils import morlet_func
>>> 
>>> time = np.array([-1., 0., 0.5])
>>> f = morlet_func(time=time, frequency=10, width=3, displacement=0)
>>> print(f)
[0.41022718 0.43366254 0.42768108]
ketos.utils.ndim(a)[source]

Returns the number of dimensions of a list/tuple/array.

Args:
a: list, tuple or numpy array

Object that we wish to obtain the dimension of

Returns:
n: int

Number of dimensions

Example:
>>> from ketos.utils import ndim
>>> 
>>> x = [[0, 1, 2, 3],(4, 5)]
>>> print(ndim(x))
2
ketos.utils.nearest_values(x, i, n)[source]

Returns the n values nearest to index i from the array x.

Here, nearest refers to the position in the array, not the value.

Args:
x: numpy array

Input values

i: int

Index

n: int

Number of neighboring values

Returns:
y: numpy array

n values nearest to index i from the array x

Example:
>>> from ketos.utils import nearest_values
>>> 
>>> x = np.array([1.0, 4.0, 5.1, 6.0, 0.2, 0.3, 10.0])
>>> y = nearest_values(x=x, i=3, n=3)
>>> print(y)
[5.1 6.  0.2]
ketos.utils.octave_bands(band_min=- 1, band_max=9)[source]

Compute the min, central, and max frequency value of the specified octave bands, using the following formulas,

f_centre = 10^3 * 2^p , f_min = f_centre / sqrt(2) , f_max = f_centre * sqrt(2) ,

where p = band_number - 5

Args:
band_min: int

Lower octave band

band_max: int

Upper octave band

Returns:
fcentre: numpy array

Central frequency of each band (in Hz)

flow: numpy array

Minimum frequency of each band (in Hz)

fhigh: numpy array

Maximum frequency of each band (in Hz)

Example:
>>> from ketos.utils import octave_bands
>>> 
>>> fc, fmin, fmax = octave_bands(1, 3)
>>> print(fc)
[ 62.5 125.  250. ]
ketos.utils.octave_bands_json(band_min, band_max)[source]

Produce a string of the specified octave bands in json format

Args:
band_min: int

Lower octave band

band_max: int

Upper octave band

Returns:
s: str

json format string

Example:
>>> from ketos.utils import octave_bands_json
>>> 
>>> s = octave_bands_json(1, 2)
ketos.utils.random_floats(size=1, low=0, high=1, seed=1)[source]

Returns a random number or numpy array of randum numbers uniformly distributed in the half-open interval [low, high)

Args:
size: int

Number of random numbers to be generated

low: float

Lower value

high: float

Upper value (not included)

seed: int

Seed for the random number generator

Returns:
res: float or numpy array

Generated random number(s)

Example:
>>> from ketos.utils import random_floats
>>> 
>>> x = random_floats(3, 0.4, 7.2)
>>> print(x)
[3.23574963 5.29820656 0.40077775]
ketos.utils.str_is_int(s, signed=True)[source]

Check if a given string represents a (signed) integer.

Args:
s: str

Input string.

signed: bool

Check if string represents a signed integer (default) or unsigned.

Returns:
res: bool

Result of check

ketos.utils.tostring(box, decimals=None)[source]

Convert an array, tuple or list into a string.

Args:
box: array, tuple or list

Array, tuple or list that will be converted into a string.

decimals: int

Number of decimals that will be kept in the conversion to string.

Returns:
s: str

String representation of array/tuple/list.

Example:
>>> from ketos.utils import tostring
>>> 
>>> y = [[0, 1, 2, 3],(4, 5)]
>>> print(tostring(y))
[[0,1,2,3],[4,5]]