Utilities (.utils)
Utilities (.utils)#
This module contains utility functions used by all modules or functions that have multiple applications such as filtering, finding zero-crossings, finding the nearest value in a signal.
- class worklab.utils.Timer(name='', text='Elapsed time: {:0.4f} seconds', start=True)[source]#
Simple timer for timing code(blocks).
- Parameters
name (str) – name of timer, gets saved in Timer.timers optional
text (str) – custom text, optional
start (bool) – automatically start the timer when it’s initialized, default is True
- exception worklab.utils.TimerError[source]#
A custom exception used to report errors in use of Timer class
- worklab.utils.binned_stats(array, bins=10, pad=True, func=<function mean>, nan_func=<function nanmean>)[source]#
Apply a compatible Numpy function to every bin samples (e.g. mean or std).
- Parameters
array (np.array) – array which has to be searched
bins (int) – number of samples to be averaged
pad (bool) – whether to pad the array with NaNs if needed
func – function that is used when no padding is applied
nan_func – function that is used when padding is applied
- Returns
means – array with the mean for every bin samples.
- Return type
np.array
- worklab.utils.calc_inertia(weight=0.8, radius=0.295, length=0.675, period=1.0)[source]#
Calculate the inertia of an object based on the trifilar pendulum equation.
- Parameters
weight (float) – total mass of the object, default is 0.8
radius (float) – radius of the object, default is 0.295
length (float) – length of the trifilar pendulum
period (float) – observed oscillation period
- Returns
inertia – inertia [kgm2]
- Return type
float
- worklab.utils.camel_to_snake(name: str)[source]#
Turns CamelCased text into snake_cased text.
- Parameters
name (str) – StringToConvert
- Returns
converted_string
- Return type
str
- worklab.utils.coast_down_velocity(t, v0, c1, c2, m)[source]#
Solution for the non-linear differential equation M(dv/dt) + c1*v**2 + c2 = 0. Returns the instantaneous velocity decreasing with time (t) for the friction coefficients c1 and c2 for an object with a fixed mass (M)
- Parameters
t (np.array) –
v0 (float) –
c1 (float) –
c2 (float) –
m (float) –
- Return type
np.array
- worklab.utils.find_nearest(array, value, index=False)[source]#
Find the nearest value in an array or the index thereof.
- Parameters
array (np.array) – array which has to be searched
value (float) – value that you are looking for
index (bool) – whether you want the index
- Returns
value or index of the nearest value
- Return type
np.array
- worklab.utils.find_peaks(data, cutoff=1.0, minpeak=5.0, min_dist=5)[source]#
Finds positive peaks in signal and returns indices of start and stop.
- Parameters
data (pd.Series, np.array) – any signal that contains peaks above minpeak that dip below cutoff
cutoff (float) – where the peak gets cut off at the bottom, basically a hysteresis band
minpeak (float) – minimum peak height of wave
min_dist (int) – minimum sample distance between peak candidates, can be used to speed up algorithm
- Returns
peaks – dictionary with start, end, and peak index of each peak
- Return type
dict
- worklab.utils.interpolate_array(x, y, kind='linear', fill_value='extrapolate', assume=True)[source]#
Simple function to interpolate an array with Scipy’s interp1d. Also extrapolates NaNs.
- Parameters
x (np.array) – time array (without NaNs)
y (np.array) – array with potential NaNs
kind (str) – kind of filter, default is “linear”
fill_value (str) – fill value, default is “extrapolate”
assume (bool) – assume that the array is sorted (performance), default is True
- Returns
y – interpolated y-array
- Return type
np.array
- worklab.utils.lowpass_butter(array, sfreq=100.0, cutoff=20.0, order=2)[source]#
Apply a simple zero-phase low-pass Butterworth filter on an array.
- Parameters
array (np.array) – input array to be filtered
sfreq (float) – sample frequency of the signal, default is 100
cutoff (float) – cutoff frequency for the filter, default is 20
order (int) – order of the filter, default is 2
- Returns
array – filtered array
- Return type
np.array
- worklab.utils.make_calibration_spline(calibration_points)[source]#
Makes a pre-1.0.4 calibration spline for the Esseda wheelchair ergometer.
- Parameters
calibration_points (dict) – dict with left: np.array, right: np.array
- Returns
spl_line – dict with left: np.array, right: np.array containing the interpolated splines
- Return type
dict
- worklab.utils.make_linear_calibration_spline(calibration_points)[source]#
Makes a post-1.0.4 calibration spline for the Esseda wheelchair ergometer.
- Parameters
calibration_points (dict) – dict with left: np.array, right: np.array
- Returns
spl_line – dict with left: np.array, right: np.array containing the interpolated splines
- Return type
dict
- worklab.utils.mask_from_iterable(array, floor_values, ceil_values)[source]#
Combines multiple masks from iterable into one mask (e.g. can be used to select multiple time slices).
- Parameters
array (np.array) – array to apply mask on
floor_values (list) – minimum values in array
ceil_values (list) – maximum values in array
- Returns
mask
- Return type
np.array
- worklab.utils.merge_chars(chars)[source]#
Merges list or tuple of binary characters to single string
- Parameters
chars (list, tuple) – list or tuple of binary characters
- Returns
concatenated characters
- Return type
str
- worklab.utils.metamax_to_s(dt)[source]#
Calculates time in seconds from h:mm:ss.000 to seconds
- Parameters
dt (pd.Series) – series with h:mm:ss.000
- Returns
time – time in seconds
- Return type
pd.Series
- worklab.utils.nonlinear_fit_coast_down(time, vel, total_weight)[source]#
Performs a nonlinear fit on coast-down data, returning c1 and c2.
- Parameters
time (np.array) –
vel (np.array) –
total_weight (float) –
- Returns
c1, c2
- Return type
tuple
- worklab.utils.pd_dt_to_s(dt)[source]#
Calculates time in seconds from datetime or string.
- Parameters
dt (pd.Series) – datetime instance or a string with H:m:s data
- Returns
time – time in seconds
- Return type
pd.Series
- worklab.utils.pd_interp(df, interp_column, at)[source]#
Resamples (and extrapolates) DataFrame with Scipy’s interp1d, this was more performant than the pandas one for some reason.
- Parameters
df (pd.DataFrame) – target DataFrame
interp_column (str) – column to interpolate on, e.g. “time”
at (np.array) – column to interpolate to
- Returns
interp_df – interpolated DataFrame
- Return type
pd.DataFrame
- worklab.utils.pick_directory(initialdir=None)[source]#
Open a window to select a directory
- Parameters
initialdir (str) – directory to start from
- Returns
directory – full path to selected directory
- Return type
str
- worklab.utils.pick_file(initialdir=None)[source]#
Open a window to select a single file
- Parameters
initialdir (str) – directory to start from
- Returns
filename – full path to picked file
- Return type
str
- worklab.utils.pick_files(initialdir=None)[source]#
Open a window to select multiple files
- Parameters
initialdir (str) – directory to start from
- Returns
filename – full path to picked file
- Return type
list
- worklab.utils.pick_save_file(initialdir=None)[source]#
Open a window to select a savefile
- Parameters
initialdir (str) – directory to start from
- Returns
directory – full path to selected savefile
- Return type
str
- worklab.utils.power_per_min(data_ergo, dur, start_spiro)[source]#
Calculates the power achieved per min in a graded exercise test, needed for the Wasserman plot
- Parameters
data_ergo (pd.DataFrame) – processed ergometer data dictionary with dataframes
dur (int) – duration of max test in seconds
start_spiro (float or int) – duration of the rest measurement just before the maximal exercise test.
- Returns
power – a dataframe containing the mean power output per step, showed as a continuous signal
- Return type
pd.DataFrame
- worklab.utils.signal_lag(y1, y2, sfreq=100, cutoff=6, order=2, plot=True, verbose=True)[source]#
Data alignment function, based on cross-correlation, that can align two devices. Input parameters need to be equal sample frequencies (i.e., a priori interpolation)
Aligns 2 datasets based on given input variables, after low bandpass filtering. It is advised to use speed data for alignment.
- Parameters
y1 (np.array, pd.Series) – Variable from first device which lag of y2 is calculated on, preferably velocity array
y2 (np.array, pd.Series) – Variable from second device which is compared to y1, preferably velocity array
sfreq (float) – sample frequency of the signal, default is 100
cutoff (float) – cutoff frequency for the filter, default is 6
order (int) – order of the filter, default is 2
plot (boolean) – can be used to plot the correlation line, default = True
verbose (boolean) – can be used to print out the samples that y2 lags compared to y1, default = True
- Returns
delay (int) – the number of samples that y2 should be shifted to correlate maximally to y1
maxcorr (int) – the correlation between y2 and y1, if shifted according to the delay
See also
- worklab.utils.split_dataframe(df, inds)[source]#
Split a dataframe on a list of indices. For example a dataframe that contains multiple sessions of wheelchair ergometer data.
- Parameters
df (pd.DataFrame) – target dataframe
inds (list) – list of indices where the dataframe should be split
- Returns
list of dataframes
- Return type
list
- worklab.utils.zerocross1d(x, y, indices=False)[source]#
Find the zero crossing points in 1d data.
Find the zero crossing events in a discrete data set. Linear interpolation is used to determine the actual locations of the zero crossing between two data points showing a change in sign. Data point which are zero are counted in as zero crossings if a sign change occurs across them. Note that the first and last data point will not be considered whether they are zero.
- Parameters
x (np.array, pd.Series) – time/sample variable
y (np.array, pd.Series) – y variable
indices (bool) – return indices or not, default is False
- Returns
position in time and optionally the index of the sample before the zero-crossing
- Return type
np.array