Tool functions
Description
Functions to perform simple tasks that can be used throughout the toolbox and beyond.
Functions
Path functions
- krajjat.tool_functions.compute_subpath(path1, path2, separator='/', remove_leading_separators=True, remove_ending_separators=True)
Considering two absolute paths path1 and path2, where one is a parent path of the other, this function returns the subdirectories absent from the other.
New in version 2.0.
- Parameters:
path1 (str) – An absolute path.
path2 (str) – An absolute path.
separator (str) – The separator symbol between the elements of the path (default:
os.sep).remove_leading_separators (bool) – If True (default), the function will remove the leading separators from the subpath (e.g.
"/docs/file.txt"will become"docs/file.txt").remove_ending_separators (bool) – If True (default), the function will remove the ending separators from the subpath (e.g.
"/docs/files/"will become"/docs/files").
- Returns:
The subdirectories of one of the two paths that is absent from the other.
- Return type:
str
Example
>>> path1 = "C:/Users/Shawn/" >>> path2 = "C:/Users/Shawn/Music/Coldplay/A Rush of Blood to the Head/" >>> print(compute_subpath(path1, path2)) Music/Coldplay/A Rush of Blood to the Head
- krajjat.tool_functions.get_difference_paths(*paths, separator='/')
Returns, for each path, a list of the subfolders that are not common with all the other paths.
New in version 2.0.
- Parameters:
paths (str) – The paths, or a list of paths preceded by an asterisk
*.separator (str) – The separator symbol between the elements of the path (default:
"/").
- Returns:
A list containing a list for each path, which itself contains the subfolders that are not common with the other paths.
- Return type:
list(list(str))
Example
>>> path1 = "C:/Sequences/Raw/Subject1/Feb1/Sequence1" >>> path2 = "C:/Sequences/Resampled/Subject1/Mar1/Sequence1" >>> get_difference_paths(path1, path2) [['Raw', 'Feb1'], ['Original', 'Mar1']] >>> get_difference_paths(*[path1, path2]) [['Raw', 'Feb1'], ['Original', 'Mar1']]
- krajjat.tool_functions.get_objects_paths(*objects)
Returns a list of the attributes
pathof the objects passed as parameter (Sequence or Audio instances).New in version 2.0.
- Parameters:
objects (Sequence|Audio) – One or many Sequence or Audio instances, or a list of these objects preceded by an asterisk
*.- Returns:
A list of paths.
- Return type:
list(str)
Example
>>> sequence1 = Sequence("C:/Documents/Sequences/sequence1.json") >>> sequence2 = Sequence("C:/Documents/Sequences/sequence2.json") >>> get_objects_paths(sequence1, sequence2) ["C:/Documents/Sequences/sequence1.json", "C:/Documents/Sequences/sequence2.json"] >>> get_objects_paths(*[sequence1, sequence2])
- krajjat.tool_functions.sort_files_trailing_index(path, accepted_extensions=None, separator='_', ignore_files_without_index=True, error_if_missing_indices=True, error_if_multiple_extensions=True, object_type='sequence', verbosity=1, add_tabs=0)
Assuming a list of files where each name contains a trailing index (e.g. filename_42.ext), returns the list of files sorted by their trailing index.
Note
This function allows to order the files consistently across different file systems despite the lack of leading zeros in the index: some systems would place
pose_11.jsonalphabetically beforepose_2.json(1 comes before 2), while some other systems place it after as 11 is greater than 2. In order to avoid these inconsistencies, the function converts the number after the underscore into an integer to place it properly according to its index.New in version 2.0.
- Parameters:
path (str) – A path containing files where each name contains a trailing index (e.g. filename_42.ext).
accepted_extensions (str|list|None) – An extension, or a list containing the extensions accepted. Any file with a different extension will be ignored by the function. If set on None, all the extensions are accepted. Note that having multiple extensions in the target folder may raise an exception - see the parameter error_if_multiple_extensions.
separator (str) – A character, or series of characters to look for in the name of the file that separate the name of the file from its index (default: underscore
"_"). If the separator is blank, the function tries to find the trailing number.ignore_files_without_index (bool) – If set on False, the function returns an error when finding a file that does not contain the separator symbol and hence, cannot find the index. If set on True (default), the files without indices are simply ignored.
error_if_missing_indices (bool) – If set on True (default), the function checks, after sorting the files, if some expected indices are missing. For example, if a file_23.ext and a file_25.ext are found, but no file_24.ext, the function would return an error. If set on False, the function does not check for missing indices and returns the sorted files.
error_if_multiple_extensions (bool) – If set on True, raises an error if more than one of the accepted extensions are found in the folder. If set on False, does not raise an error - the function will, however, return an error if two files have the same index but with different extensions.
object_type (str) – The type of object that will be created from opening this file. This parameter only exists in order to return exceptions.
verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
add_tabs (int, optional) – Adds the specified amount of tabulations to the verbosity outputs. This parameter may be used by other functions to encapsulate the verbosity outputs by indenting them. In a normal use, it shouldn’t be set by the user.
Example
>>> # Let's consider a directory with the following files: `sequence_1.txt`, `sequence_10.txt`, >>> # `sequence_100.txt`, `sequence_11.txt` and `sequence_2.txt`. >>> print(sort_files_trailing_index("C:/Sequences")) ["sequence_1.txt", "sequence_2.txt", "sequence_10.txt", "sequence_11.txt", "sequence_100.txt"]
Name functions
- krajjat.tool_functions.get_objects_names(*objects)
Returns a list of the attributes
nameof the objects passed as parameter (Sequence or Audio instances).New in version 2.0.
- Parameters:
objects (Sequence|Audio) – One or many Sequence or Audio instances, or a list of these objects preceded by an asterisk
*.- Returns:
A list of names.
- Return type:
list(str)
Example
>>> sequence1 = Sequence("C:/Documents/Sequences/sequence1.json") >>> sequence2 = Sequence("C:/Documents/Sequences/sequence2.json", name="seq2") >>> get_objects_names(sequence1, sequence2) ["sequence1.json", "seq2"] >>> get_objects_names(*[sequence1, sequence2]) ["sequence1.json", "seq2"]
Sequence comparison functions
- krajjat.tool_functions.compute_different_joints(sequence1, sequence2, acceptable_rounding_decimal=5, verbosity=1)
Returns the number of joints having different coordinates between two sequences having the same amount of poses. This function can be used to check how many joints have been modified by a processing function.
New in version 2.0.
Note
To discard the rounding errors due to other functions, this function rounds the coordinates to the fifth decimal.
- Parameters:
sequence1 (Sequence) – A Sequence instance.
sequence2 (Sequence) – A Sequence instance.
acceptable_rounding_decimal (int) – The decimal at which to round the values to account for rounding errors (default: 5).
verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
int – The number of different joints between the two sequences.
int – The total number of joints in each of the sequences.
Example
>>> sequence_1 = Sequence("sequence_1.json") >>> sequence_1_corrected = sequence_1.correct_jitter(0.1, 2) >>> print(compute_different_joints(sequence_1, sequence_1_corrected)) (1, 9)
- krajjat.tool_functions.align_two_sequences(sequence1, sequence2, verbosity=1)
Checks if one sequence is a subset of another; if true, the function returns the indices at which the two sequences start synchronizing. Otherwise, it returns
False.New in version 2.0.
- Parameters:
sequence1 (Sequence) – A Sequence instance.
sequence2 (Sequence) – A Sequence instance.
verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
If one of the sequences is a subsequence of the other, the function returns a tuple of two integers, corresponding to the indices of the first and the second sequences where the two sequences synchronize, respectively. Otherwise, this function returns None.
- Return type:
tuple or None
Example
>>> sequence_1 = Sequence("C:/Users/Shawn/sequence_1.tsv") # This sequence is sampled at 10 Hz >>> sequence_2 = sequence_1.trim(start = 1) # We trim at 1s, meaning we remove the first 10 poses >>> print(align_two_sequences(sequence_1, sequence_2)) (0, 10)
- krajjat.tool_functions.align_multiple_sequences(*sequences, verbosity=1)
Returns the synchronized timestamps of multiple sequences. If one or more sequences passed as parameter are not subsets of other sequences or do not contain other sequences, their original timestamps are returned.
New in version 2.0.
- Parameters:
sequences (Sequence) – One or more Sequence instances.
verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
A list of synchronized timestamps arrays, matching the order the Sequence instances were passed as parameters.
- Return type:
list(list(float))
Example
>>> sequence_1 = Sequence("C:/Users/Irving/sequence_1.tsv") # This sequence is sampled at 10 Hz with 5 samples >>> sequence_2 = sequence_1.trim(start = 0.1) # We trim at 0.1s, meaning we remove the first pose >>> sequence_3 = sequence_1.trim(start = 0.3) # We trim at 0.3s, meaning we remove the first 3 poses >>> print(align_multiple_sequences(sequence_1, sequence_2, sequence_3)) [[0.0, 0.1, 0.2, 0.3, 0.4], [0.1, 0.2, 0.3, 0.4], [0.3, 0.4]]
- krajjat.tool_functions.sort_sequences_by_date(*sequences)
Takes multiple sequences as a parameter, and returns an array containing the same sequences, ordered by recording date. If at least one sequence of the array has an attribute
Sequence.date_recordingset on None, the function will throw an error.New in version 2.0.
- Parameters:
sequences (Sequence) – A list of Sequence instances.
- Returns:
A list of Sequence instances, ordered by date of recording.
- Return type:
list(Sequence)
- Raises:
MissingRecordingDateException – If the recording date is missing from one of the sequences.
Example
>>> sequence_1 = Sequence("C:/Users/Walter/sequence_1.tsv", name="seq_1") # Sequence recorded 2000-01-01 >>> sequence_2 = Sequence("C:/Users/Walter/sequence_1.tsv", name="seq_2") # Sequence recorded 2000-01-03 >>> sequence_3 = Sequence("C:/Users/Walter/sequence_1.tsv", name="seq_3") # Sequence recorded 2000-01-02 >>> print(sort_sequences_by_date(sequence_1, sequence_2, sequence_3)) [seq_1, seq_3, seq_2]
File reading functions
- krajjat.tool_functions.get_system_csv_separator()
Returns the separator (comma or semicolon) of the regional settings of the system; if it can’t access it, returns a comma by default.
New in version 2.0.
Note
This function detects the local decimal separator, and sets the csv delimiter on a semicolon (
";") if the local decimal separator is a comma (","). In any other case, the csv delimiter is set on a comma (","). Note that in certain cases, the result of this function may not be ideal (e.g. if the comma can be used as a symbol in the values of the csv file). In that case, you can force the csv delimiter to be the symbol of your choice by writing"csv,"or"csv;"when asked for a file extension.- Returns:
The character used as separator in csv files on the current system.
- Return type:
str
- krajjat.tool_functions.get_filetype_separator(extension)
Returns the separator used in specific text format files (comma, semicolon or tab). For csv, returns the separator used on the current system. For txt or tsv files (or any other extension), returns a tabulation symbol.
New in version 2.0.
- Parameters:
extension (str) – A file extension (csv, tsv or txt).
- Returns:
The character used as separator between values in the target file extension.
- Return type:
str
Examples
>>> get_filetype_separator("csv") "," >>> get_filetype_separator("tsv") " "
- krajjat.tool_functions.read_json(path)
Detects the encoding, loads and returns the content of a .json file.
New in version 2.0.
- Parameters:
path (str) – The path to a json file.
- Returns:
The content of the json file.
- Return type:
list|dict
Example
>>> read_json("winning_lottery_numbers.json") {"January 1": [4, 8, 15, 16, 23, 42], "January 2": [1, 2, 3, 5, 8, 13]}
- krajjat.tool_functions.read_text_table(path, convert_strings=True, separator=None, read_metadata=True, standardize_labels='auto', keyword_data_start='Timestamp', keyword_data_in_table=True, verbosity=1)
Detects the encoding, loads and returns the content of a .csv, .tsv or .txt file containing a table. The function also returns a dictionary containing the metadata contained in the file. The metadata is any line from the beginning of the file before the appearance of Timestamp or MARKER_NAME (for Qualisys files). Each line of the metadata must contain two elements: a key and a value, separated by one of the three accepted separators (tab,
","or";").New in version 2.0.
- Parameters:
path (str) – The path to a text file.
convert_strings (bool, optional) – If True (default), the function will try to convert the values from the table to other types (int, float, boolean).
separator (str|None, optional) – If None, the symbol separating each cell on a row in the file will be deduced from the extension, using
get_filetype_separator(). Otherwise, the value of this parameter will be used (e.g."\t",",",";").read_metadata (bool, optional) – If set on True (default), the function tries to find metadata leading the file, before the keyword “Timestamps” starts a new line.
keyword_data_start (str, optional) – The keyword that marks when to stop saving metadata and start saving data (default:
"Timestamp").keyword_data_in_table (bool, optional) – If True (default), the line starting with the keyword_data_start is included in the table. Otherwise, the table starts at the next available line.
standardize_labels (bool|str, optional) – If set on
"auto"(default), renames the Qualisys labels (if"HeadR"is detected in the joint labels - see Qualisys to Kualisys conversion). Enforce the renaming by setting this parameter on True.verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
list(list) – The content of the text file, with each sub-list containing the elements of a row of the file.
dict – The metadata of the recording, if contained in the text file. This parameter will return an empty dictionary if the file does not contain metadata.
- krajjat.tool_functions.read_xlsx(path, sheet=0, read_metadata=True, metadata_sheet=1, verbosity=1)
Loads and returns the content of a
.xlsx(Excel) file.New in version 2.0.
Note
If the Excel file is currently opened, Openpyxl will return a PermissionError. This function catches it and asks the user to press the Enter key once the Excel file is closed. This allows to resume a long processing without having to restart it from scratch.
- Parameters:
path (str) – The path to an Excel file.
sheet (int|str, optional) – The index of the Excel sheet (starts at 0, which is also the default value), or its name.
read_metadata (bool, optional) – If True, tries to find metadata in the sheet indicated by sheet_metadata. If False (default), the function returns only the first output.
metadata_sheet (int|str, optional) – The index of the Excel sheet containing the metadata (default: 1), or its name. If no second sheet is present, the function returns an empty dict (
{}) as its second parameter.verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
list(list) – The content of the Excel file, with each element of the list being a row of the Excel file.
dict – The metadata of the recording, if contained in the Excel file;
{}otherwise.
- krajjat.tool_functions.read_pandas_dataframe(path, verbosity=1)
Reads a file, and turns it into a Pandas dataframe.
New in version 2.0.
Note
If the Excel file is currently opened, pandas will return a PermissionError. This function catches it and asks the user to press the Enter key once the Excel file is closed. This allows to resume a long processing without having to restart it from scratch.
- Parameters:
path (str) – The path to the file containing data to turn to a pandas dataframe.
verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
`pandas.Dataframe <https – A pandas dataframe.
- Return type:
//pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_
- krajjat.tool_functions.convert_data_from_qtm(data, standardize_labels='auto', verbosity=1)
Processes and converts the data from a
.tsvfile produced by QTM, by stripping the header data, standardizing the name of the joint labels, and converting the distance unit from mm to m. This function then returns the loaded table, along with a dictionary containing the metadata of the recording.New in version 2.0.
- Parameters:
data (list(str)) – The data from a
.tsvQTM file with each line separated as the elements of a list.standardize_labels (bool|str, optional) – If set on
"auto"(default), renames the labels if"HeadR"is detected in the joint labels (see Qualisys to Kualisys conversion). Enforce the renaming by setting this parameter on True.verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
list(list(str)) – A table containing the QTM data, with each sub-list containing the elements of a row of the file.
dict – A dictionary containing the metadata from the recording contained in the file.
File writing functions
- krajjat.tool_functions.write_text_table(table, separator, path, metadata=None, separator_metadata=None, encoding='utf-8', verbosity=1)
Converts a table to a string, where elements on the same row are separated by a defined separator, and each row is separated by a line break.
New in version 2.0.
- Parameters:
table (list(list)) – A two-dimensional list where each element is a table row.
separator (str) – The character used to separate elements on the same row.
path (str) – The complete path of the text file to save.
metadata (dict|None, optional) – The metadata of the file, to write as the leading data in the text file.
separator_metadata (str|None, optional) – If not None (default), defines the content of the line separating the metadata from the table.
encoding (str, optional) – The encoding of the file to save. By default, the file is saved in UTF-8 encoding. This input can take any of the official Python accepted formats.
verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
The table in string version.
- Return type:
str
- krajjat.tool_functions.write_xlsx(table, path, sheet_name=None, metadata=None, metadata_sheet_name=None, verbosity=1)
Saves a table in a
.xlsxfile.New in version 2.0.
- Parameters:
table (list(list)) – A list where each sublist is a row of the table.
path (str) – The complete path of where to store the Excel file.
sheet_name (str|None, optional) – The name of the sheet containing the data. If None, a default name will be attributed to the sheet (
"Sheet").metadata (dict|None, optional) – A dictionary containing metadata keys and values. These will be saved in a separate second sheet, with each key/value pair on a different row.
metadata_sheet_name (str|None, optional) – The name of the sheet containing the metadata. If None, a default name will be attributed to the sheet (
"Sheet1").verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
Calculation functions
- krajjat.tool_functions.resample_data(array, original_timestamps, resampling_frequency, window_size=10000000.0, overlap_ratio=0.5, method='cubic', time_unit='s', verbosity=1)
Resamples an array to the resampling_frequency parameter. It first creates a new set of timestamps at the desired frequency, and then interpolates the original data to the new timestamps.
- Parameters:
array (list or np.ndarray) – An array of samples.
original_timestamps (list(float) or numpy.ndarray(float)) – A list or an array of the time points corresponding to the values of the data.
resampling_frequency (int or float) – The frequency at which you want to resample the array, in Hz. A frequency of 4 will return samples at 0.25 s intervals.
window_size (int, optional) – The size of the windows in which to cut the elements to perform the resampling. Cutting long arrays in windows allows to speed up the computation. If this parameter is set on None, the window size will be set on the number of elements. A good value for this parameter is generally 10 million (1e7). If this parameter is set on 0, on None or on a number of samples bigger than the amount of elements in the array, the window size is set on the length of the array.
overlap_ratio (float or None, optional) – The ratio of samples overlapping between each window. If this parameter is not None, each window will overlap with the previous (and, logically, the next) for an amount of samples equal to the number of samples in a window times the overlap ratio. Then, only the central values of each window will be preserved and concatenated; this allows to discard any “edge” effect due to the windowing. If the parameter is set on None or 0, the windows will not overlap.
method (str, optional) –
This parameter allows for various values:
"linear"performs a linear numpy.interp interpolation. This method, though simple, may not be very precise for upsampling naturalistic stimuli."cubic"performs a cubic interpolation via scipy.interpolate.CubicSpline. This method, while smoother than the linear interpolation, may lead to unwanted oscillations nearby strong variations in the data."pchip"performs a monotonic cubic spline interpolation (Piecewise Cubic Hermite Interpolating Polynomial) via scipy.interpolate.PchipInterpolator."akima"performs another type of monotonic cubic spline interpolation, using scipy.interpolate.Akima1DInterpolator."take"keeps one out of n samples from the original array. While being the fastest computation, it will be prone to imprecision if the downsampling factor is not an integer divider of the original frequency."interp1d_XXX"uses the function scipy.interpolate.interp1d <https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html>. The XXX part of the parameter can be replaced by"linear","nearest","nearest-up","zero", “slinear”, ``"quadratic","cubic","previous", and"next"(see the documentation of this function for specifics).
time_unit (str, optional) – The time unit of the time points. This parameter can take the following values: “ns”, “1ns”, “10ns”, “100ns”, “µs”, “1µs”, “10µs”, “100µs”, “ms”, “1ms”, “10ms”, “100ms”, “s” (default), “sec”, “1s”, “min”, “mn”, “h”, “hr”, “d”, “day”.
verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
numpy.ndarray(float) – The resampled values.
numpy.ndarray(float) – The resampled time points, at a fixed frequency.
Warning
This function allows both the upsampling and the downsampling of arrays. However, during any of these operations, the algorithm only estimates the real values of the samples. You should then consider the upsampling (and the downsampling, to a lesser extent) with care.
Example
>>> array = np.linspace(1, 0, 11) >>> original_timestamps = np.linspace(0, 2, 11) >>> resampling_frequency = 4 >>> resample_data(array, original_timestamps, resampling_frequency, method="linear", verbosity=0) ([1, 0.875, 0.75, 0.625, 0.5, 0.375, 0.25, 0.125, 0], [0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2])
- krajjat.tool_functions.resample_window(array, original_timestamps, resampled_timestamps, index_start_original, index_end_original, index_start_resampled, index_end_resampled, method='cubic', verbosity=1)
Performs and returns the resampling on a subarray of samples.
- Parameters:
array (list or np.ndarray) – An array of samples.
original_timestamps (list or np.ndarray) – An array containing the timestamps for each sample of the original array.
resampled_timestamps (list or np.ndarray) – An array containing the timestamps for each desired sample in the resampled array.
index_start_original (int) – The index in the array where the window starts.
index_end_original (int) – The index in the array where the window ends.
index_start_resampled (int) – The index in the resampled array where the window starts.
index_end_resampled (int) – The index in the resampled array where the window ends.
method (str, optional) –
This parameter allows for various values:
"linear"performs a linear numpy.interp interpolation. This method, though simple, may not be very precise for upsampling naturalistic stimuli."cubic"performs a cubic interpolation via scipy.interpolate.CubicSpline. This method, while smoother than the linear interpolation, may lead to unwanted oscillations nearby strong variations in the data."pchip"performs a monotonic cubic spline interpolation (Piecewise Cubic Hermite Interpolating Polynomial) via scipy.interpolate.PchipInterpolator."akima"performs another type of monotonic cubic spline interpolation, using scipy.interpolate.Akima1DInterpolator."take"keeps one out of n samples from the original array. While being the fastest computation, it will be prone to imprecision if the downsampling factor is not an integer divider of the original frequency."interp1d_XXX"uses the function scipy.interpolate.interp1d <https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html>. The XXX part of the parameter can be replaced by"linear","nearest","nearest-up","zero", “slinear”, ``"quadratic","cubic","previous", and"next"(see the documentation of this function for specifics).
verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
The envelope of the original array.
- Return type:
np.array
- krajjat.tool_functions.interpolate_data(data, time_points_data, time_points_interpolation, method='linear')
Interpolates incomplete data to a linear array of values.
New in version 2.0.
- Parameters:
data (list(float) or numpy.ndarray(float)) – A list or an array of values.
time_points_data (list(float) or numpy.ndarray(float)) – A list or an array of the time points corresponding to the values of the data.
time_points_interpolation (list(float) or numpy.ndarray(float)) – A list or an array of the time points to which interpolate the data.
method (str, optional) –
This parameter allows for various values:
"linear"performs a linear numpy.interp interpolation. This method, though simple, may not be very precise for upsampling naturalistic stimuli."cubic"performs a cubic interpolation via scipy.interpolate.CubicSpline. This method, while smoother than the linear interpolation, may lead to unwanted oscillations nearby strong variations in the data."pchip"performs a monotonic cubic spline interpolation (Piecewise Cubic Hermite Interpolating Polynomial) via scipy.interpolate.PchipInterpolator."akima"performs another type of monotonic cubic spline interpolation, using scipy.interpolate.Akima1DInterpolator."take"keeps one out of n samples from the original array. While being the fastest computation, it will be prone to imprecision if the downsampling factor is not an integer divider of the original frequency."interp1d_XXX"uses the function scipy.interpolate.interp1d <https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html>. The XXX part of the parameter can be replaced by"linear","nearest","nearest-up","zero", “slinear”, ``"quadratic","cubic","previous", and"next"(see the documentation of this function for specifics).
- Returns:
numpy.ndarray(float) – The interpolated values.
numpy.ndarray(float) – The interpolated time points (same as the parameter
time_points_interpolation).
Example
>>> array = np.linspace(1, 0, 11) >>> original_timestamps = np.linspace(0, 1, 11) >>> interpolation_timestamps = np.linspace(0.05, 0.95, 10) >>> interpolate_data(array, original_timestamps, interpolation_timestamps, "linear") ([0.95 0.85 0.75 0.65 0.55 0.45 0.35 0.25 0.15 0.05], [0.05 0.15 0.25 0.35 0.45 0.55 0.65 0.75 0.85 0.95])
- krajjat.tool_functions.pad(data, time_points_data, time_points_padding, padding_value=0, verbosity=1)
Given an array of values (
data) and its correspondingtime_points_data, and a larger arraytime_points_padding, pads the data array with the value specified inpadding_valuefor the time points present intime_points_paddingthat are absent fromtime_points_data.New in version 2.0.
- Parameters:
data (list(float) or numpy.ndarray(float)) – A list or an array of values.
time_points_data (list(float) or numpy.ndarray(float)) – A list or an array of the time points corresponding to the values of the data.
time_points_padding (list(float) or numpy.ndarray(float)) – A list or an array of time points containing the values from
time_points_data(or values equal up to the fifth decimal), with additional values at the beginning and/or at the end.padding_value (int|numpy.nan|float|str) – The value with which to pad the data (default: 0), or
"edge"to copy the value present at the edges of the data.verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
np.ndarray – The original data array, padded with zeros.
list – The array
time_points_padding, passed as parameter.
Example
>>> data = [5, 4, 3, 2, 1] >>> time_points_data = [1, 2, 3, 4, 5] >>> time_points_padding = [0, 1, 2, 3, 4, 5, 6, 7] >>> pad(data, time_points_data, time_points_padding, 0, verbosity=0) ([0 5 4 3 2 1 0 0], [0, 1, 2, 3, 4, 5, 6, 7])
- krajjat.tool_functions.add_delay(timestamps, delay)
Given an array of timestamps, adds or removes a delay to each timestamp.
New in version 2.0.
- Parameters:
timestamps (numpy.array|list(float)) – An array of timestamps.
delay (float) – The delay, positive or negative to add to each timestamp.
- Returns:
An array of timestamps with the delay specified as parameter.
- Return type:
list(float)
Example
>>> timestamps = [1, 2, 3, 4, 5] >>> add_delay(timestamps, 5) [6, 7, 8, 9, 10]
- krajjat.tool_functions.calculate_distance(joint1, joint2, axis=None)
Uses the Euclidian formula to calculate the distance between two joints. This can be used to calculate the distance travelled by one joint between two poses, or the distance between two joints on the same pose. If an axis is specified, the distance is calculated on this axis only.
New in version 2.0.
- Parameters:
- Returns:
The absolute distance, in meters, between the two joints.
- Return type:
float
Example
>>> sequence_1 = Sequence("sequences/leela/sequence_1.json", verbosity=0) >>> joint_1 = sequence_1.poses[0].joints["Head"] >>> joint_2 = sequence_1.poses[1].joints["Head"] >>> calculate_distance(joint_1, joint_2) 1.6885703516949238
- krajjat.tool_functions.calculate_consecutive_distances(array)
Given an array of values, calculates and returns the absolute distance travelled between each point and the previous. The length of the returned array will be one element smaller than the original array.
New in version 2.0.
- Parameters:
array (list(float)|numpy.array) – A list or array containing values.
- Returns:
An array of absolute distances, with a length of n-1 elements compared to the array parameter.
- Return type:
numpy.array
Example
>>> calculate_consecutive_distances([4, 8, 15, 16, 23, 42]) [4, 7, 1, 7, 19]
- krajjat.tool_functions.calculate_euclidian_distances(x_array, y_array, z_array=None)
Given two or three arrays of values, returns an array of euclidian distances between consecutive values.
New in version 2.0.
- Parameters:
x_array (list(float)|numpy.array) – A list or array containing positions on the x-axis.
y_array (list(float)|numpy.array) – A list or array containing positions on the y-axis.
z_array (list(float)|numpy.array|None) – A list or array containing positions on the z-axis (optional).
Example
>>> calculate_euclidian_distances([3, 4, 5], [5, 12, 13], [8, 15, 17]) [9.94987437 2.44948974]
- krajjat.tool_functions.calculate_derivative(array, derivative='velocity', window_length=7, poly_order=None, freq=1)
New in version 2.0.
- Parameters:
array (numpy.array|list) – An array of numbers representing the distance travelled for each pair of timestamps.
derivative (str|int, optional) –
The derivative to calculate, as an integer or as a string, among:
"velocity","speed", or1(default)"acceleration"or2"jerk"or3"snap","jounce", or4"crackle"or5"pop"or6Though probably unnecessary, any higher derivative can be referred to by an integer.
window_length (int, optional) – The length of the window for the Savitzky–Golay filter (default: 7). See scipy.signal.savgol_filter for more info.
poly_order (int|None, optional) –
The order of the polynomial for the Savitzky–Golay filter. If set on None, the polynomial will be set to one over the derivative rank. See scipy.signal.savgol_filter for more info.
freq (int|float, optional) – The frequency of the original data, in Hz (default: 1).
- krajjat.tool_functions.calculate_delay(pose1, pose2, absolute=False)
Returns the delay between two poses, in seconds.
New in version 2.0.
- Parameters:
- Returns:
The time, in seconds, between the two poses.
- Return type:
float
Note
By default, the time returned by the function is not an absolute value. In other words, if
pose1has a higher timestamp thanpose2, the returned value will be negative.Example
>>> sequence_1 = Sequence("C:/Users/Adrian/sequence_1.tsv") # Sampled at 10 Hz, each pose lasts 0.1 s >>> calculate_delay(sequence_1.poses[5], sequence_1.poses[6]) 0.1 >>> calculate_delay(sequence_1.poses[6], sequence_1.poses[5]) -0.1 >>> calculate_delay(sequence_1.poses[6], sequence_1.poses[5], absolute=True) 0.1
- krajjat.tool_functions.generate_random_joints(number_of_joints, x_scale=0.2, y_scale=0.3, z_scale=0.5)
Creates and returns a list of Joint objects with random coordinates. The coordinates are generated following a uniform distribution centered around 0 and with limits defined by
x_scale,y_scaleandz_scale.New in version 2.0.
- Parameters:
number_of_joints (int) – The number of random joints to generate.
x_scale (int|float) – The absolute maximum value of the random uniform distribution on the x-axis.
y_scale (int|float) – The absolute maximum value of the random uniform distribution on the y-axis.
z_scale (int|float) – The absolute maximum value of the random uniform distribution on the z axis.
- Returns:
A list of joints with randomized coordinates.
- Return type:
list(Joint)
- krajjat.tool_functions.get_number_of_windows(array_length_or_array, window_size, overlap_ratio=0, add_incomplete_window=True)
Given an array, calculates how many windows from the defined window_size can be created, with or without overlap.
New in version 2.0.
- Parameters:
array_length_or_array (list(int or float) or np.array(int or float) or int) – An array of numerical values, or its length.
window_size (int) – The number of array elements in each window.
overlap_ratio (int or float) – The ratio of array elements overlapping between each window and the next. In the case where the overlap converts to a non-integer amount of values, the closest upper integer is used (e.g., if the array is of length 10, the window size of length 5 and the overlap ratio of 0.5, the amount of values in the overlap will not be 2.5 but 3).
add_incomplete_window (bool) – If set on
True, the last window will be included even if its size is smaller thanwindow_size. Otherwise, it will be ignored.
- Returns:
The number of windows than can be created from the array.
- Return type:
int
Examples
>>> get_number_of_windows(100, 10, 0, True) 10 >>> get_number_of_windows(100, 10, 0.5, True) 19
- krajjat.tool_functions.get_window_length(array_length_or_array, number_of_windows, overlap_ratio, round_up=True)
Given an array to be split in a given overlapping number of windows, calculates the number of elements in each window.
New in version 2.0.
- Parameters:
array_length_or_array (list, np.ndarray or int) – An array of numerical values, or its length.
number_of_windows (int) – The number of windows to split the array in.
overlap_ratio (float) – The ratio of overlapping elements between each window.
round_up (bool, optional) – Specifies if the result should be returned rounded up to the nearest integer (default) or not.
- Returns:
The number of elements in each window. Note: the last window may have fewer elements than the others if the number of windows does not divide the result of \(array_length + (number_of_windows - 1) × overlap\).
- Return type:
int|float
Examples
>>> get_window_length(100, 10, 0) 10 >>> get_window_length(10, 8, 0.5) 3 >>> get_window_length(10, 8, 0.5, False) 2.22222222
- krajjat.tool_functions.divide_in_windows(array, window_size, overlap=0, add_incomplete_window=True)
Given an array of values, divides the array in windows of a size
window_size, with or without an overlap.New in version 2.0.
- Parameters:
array (list(int or float) or np.array(int or float)) – An array of numerical values.
window_size (int) – The number of array elements in each window.
overlap (int) – The number of array elements overlapping in each window.
add_incomplete_window (bool) – If set on
True, the last window will be added even if its size is smaller thanwindow_size. Otherwise, it will be ignored.
- Returns:
A list where each element is a window of size
window_size.- Return type:
list(list(int or float))
Example
>>> array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] >>> divide_in_windows(array, 5, 0) [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
Color functions
- krajjat.tool_functions.load_color_names()
Returns a dictionary containing the accepted color names, and a tuple of their 256-level RGBA codes as values. The colors are contained in
res/color_codes.txt. The color names follow the 140 HTML/CSS color names), and also contain all the accepted colors from Matplotlib <https://matplotlib.org/stable/gallery/color/named_colors.html>, with a few extra. You can find more info about the accepted colors in Color schemes.New in version 2.0.
- Returns:
dict(str – A dictionary of the color names and their RGBA values.
- Return type:
tuple(int))
- krajjat.tool_functions.load_color_schemes()
Returns a dictionary containing the color gradients saved in
res/color_gradients.txt.New in version 2.0.
- Returns:
dict(int – A dictionary with the name of color gradients as keys, and a list of their corresponding RGBA colors as values.
- Return type:
list(tuple(int, int, int, int)))
- krajjat.tool_functions.hex_color_to_rgb(color, include_alpha=None)
Converts a color from its hexadecimal value to its RGB or RGBA value.
- Parameters:
color (str) – The hexadecimal value of a color, with or without a leading number sign (
"#").include_alpha (bool|None, optional) – If
True, returns the RGB color with an alpha value. If an alpha value is not present in the hexadecimal value, the alpha channel will be set to 255. If set onNone(default), the returned value will contain an alpha value, only if the input color contains one. IfFalse, the returned value will never contain the alpha value.
- Returns:
A RGB or RGBA value.
- Return type:
tuple(int, int, int) or tuple(int, int, int, int)
Examples
>>> hex_color_to_rgb("#c0ffee") (192, 255, 238) >>> hex_color_to_rgb("#f0ccac1a") (240, 204, 172, 26)
- krajjat.tool_functions.rgb_color_to_hex(color, include_alpha=None)
Converts a color from its RGB or RGBA value to its hexadecimal value.
- Parameters:
color (tuple(int, int, int) or tuple(int, int, int, int)) – The RGB or RGBA value of a color.
include_alpha (bool|None, optional) – If
True, returns the hexadecimal color with an alpha value. If an alpha value is not present in the RGB value, the alpha channel will be set to ff. IfFalse, returns the hexadecimal color without an alpha value. IfNone(default), returns the hexadecimal color if the RGB color contains an alpha value.
- Returns:
A hexadecimal value, with a leading number sign (
"#").- Return type:
str
Examples
>>> rgb_color_to_hex((192, 255, 238)) "#c0ffee" >>> rgb_color_to_hex((240, 204, 172, 26)) "#f0ccac1a"
- krajjat.tool_functions.convert_color(color, color_format='RGB', include_alpha=True)
Converts a color to the desired format.
New in version 2.0.
- Parameters:
color (str or tuple(int, int, int) or tuple(int, int, int, int)) –
This parameter can take a number of forms:
The HTML/CSS name of a color (e.g.
"red"or"blanched almond"),The hexadecimal code of a color, starting with a number sign (
#, e.g."#ffcc00"or"#c0ffee").The RGB or RGBA tuple of a color (e.g.
(153, 204, 0)or(77, 77, 77, 255)).
color_format (str, optional) – The format in which you want to convert the color. This parameter can be
"RGB"(default),"RGBA"or"HEX".include_alpha (bool, optional) – If
True, returns the color with an alpha value. If an alpha value is not present in the original value, the alpha channel will be set to 255 (or ff).
- Returns:
A list of RGB or RGBA values, or hexadecimal strings with a leading number sign.
- Return type:
list(tuple(int, int, int)) or list(tuple(int, int, int, int)) or list(string)
Examples
>>> convert_color("red", "RGB") (255, 0, 0, 255) >>> convert_color("red", "HEX", False) "#ff0000"
- krajjat.tool_functions.convert_colors(color_scheme_or_colors, color_format='RGB', include_alpha=True)
Converts a list of colors to the desired format.
New in version 2.0.
- Parameters:
color_scheme_or_colors (str or list(str)) –
This parameter can take a number of forms:
The name of a color scheme: a string matching one of the color gradients available in Color schemes.
A list of colors: a list containing colors, either using:
Their HTML/CSS names (e.g.
"red"or"blanched almond"),Their hexadecimal code, starting with a number sign (
#, e.g."#ffcc00"or"#c0ffee").Their RGB or RGBA tuples (e.g.
(153, 204, 0)or(77, 77, 77, 255)).
These different codes can be used concurrently, e.g.
["red", (14, 18, 32), "#a1b2c3"].
color_format (str, optional) – The format in which you want to convert the colors. This parameter can be
"RGB"(default),"RGBA"or"HEX".include_alpha (bool, optional) – If
True, returns the colors with an alpha value. If an alpha value is not present in the original value, the alpha channel will be set to 255 (or ff).
- Returns:
A RGB or RGBA value, or a hexadecimal string with a leading number sign.
- Return type:
tuple(int, int, int) or tuple(int, int, int, int) or string
Examples
>>> colors = ["#ff0000", (255, 0, 0), "red", (255, 0, 0, 255)] >>> convert_colors(colors, "RGB") [(255, 0, 0, 255), (255, 0, 0, 255), (255, 0, 0, 255), (255, 0, 0, 255)] >>> convert_colors("default", "HEX", False) ['#9acd32', '#ff0000']
- krajjat.tool_functions.calculate_color_points_on_gradient(color_scheme, no_points)
Given a color scheme and a number of points, creates a list of equidistant colors to create a gradient.
- Parameters:
color_scheme (str|list) – The name of a color scheme (see Color schemes. for the available schemes), or a list of colors names, RGB or hexadecimal values.
no_points (int) – The number of colors to get on the gradient.
- Returns:
A list of colors in a progressive gradient following the colors of the color scheme.
- Return type:
list(tuple(int, int, int, int))
Examples
>>> color_scheme = ["red", "orange", "yellow"] >>> calculate_color_points_on_gradient(color_scheme, 9) [(255, 0, 0, 255), (255, 41, 0, 255), (255, 82, 0, 255), (255, 123, 0, 255), (255, 165, 0, 255), (255, 187, 0, 255), (255, 210, 0, 255), (255, 232, 0, 255), (255, 255, 0, 255)] >>> calculate_color_points_on_gradient("viridis", 7) [(66, 1, 86, 255), (60, 58, 122, 255), (48, 106, 140, 255), (32, 146, 140, 255), (74, 183, 110, 255), (148, 212, 83, 255), (252, 233, 59, 255)]
- krajjat.tool_functions.calculate_color_ratio(colors, ratio, type_return='RGB', include_alpha=True)
Given a gradient of colors, returns a color located at a specific ratio on the gradient.
New in version 2.0.
- Parameters:
colors (list(tuple(int, int, int)) or list(tuple(int, int, int, int))) – A list of RGB or RGBA color tuples.
ratio (float) – The ratio of the color, between 0 and 1, on the gradient. If this parameter is equal to or inferior to 0, the function will return the first color of the
colorsparameter. If the ratio is equal or superior to 1, the function will return the last color of thecolorsparameter.type_return (str, optional) – The way the color should be returned. If set on
"rgb"(default) or"rgba", the color will be returned as a tuple of integers. If set on"hex", the color will be returned as a string containing hexadecimal values, with a number sign (#) as a leading character.include_alpha (bool, optional) – If
True, returns the hexadecimal color with an alpha value. If an alpha value is not present in the RGB value, the alpha channel will be set to 255.
- Returns:
A color in RGB, RGBA or hex form.
- Return type:
list(tuple(int, int, int)) or list(tuple(int, int, int, int)) or str
Example
>>> calculate_color_ratio((0, 0, 0), (255, 255, 255), 0.5, "RGB", False) (127, 127, 127)
- krajjat.tool_functions.calculate_colors_by_values(dict_values, color_scheme='default', min_value=None, max_value=None, type_return='RGB', include_alpha=True)
Given a dictionary of values and a color scheme, returns a dictionary where each key is attributed to a color from the scheme. The extreme colors of the color scheme will be attributed to the extreme values of the dictionary; all the intermediate values are attributed their corresponding intermediate color on the gradient.
New in version 2.0.
- Parameters:
dict_values (dict(str: float or int)) – A dictionary where keys (e.g., joint labels) are attributed to values (floats or integers).
color_scheme (str|list) – A color scheme or a list of colors that can be parsed by the function
tool_functions.convert_colors_rgba().min_value (int|float, optional) – The value that will be attributed to the first color of the scheme. If not specified (default), the minimum value will be set on the minimum value of the dictionary
dict_values.max_value (int|float, optional) – The value that will be attributed to the last color of the scheme. If not specified (default), the maximum value will be set on the maximum value of the dictionary
dict_values.type_return (str, optional) – The way the color should be returned. If set on
"rgb"(default) or"rgba", the color will be returned as a tuple of integers. If set on"hex", the color will be returned as a string containing hexadecimal values, with a number sign (#) as a leading character.include_alpha (bool, optional) – If
True, returns the hexadecimal color with an alpha value. If an alpha value is not present in the RGB value, the alpha channel will be set to 255.
- Returns:
dict(str – A dictionary where each key is matched to an RGBA color.
- Return type:
tuple(int, int, int, int))
Example
>>> values = {"Head": 0.2, "Hand": 0.59} >>> colors = calculate_colors_by_values(values, "celsius") >>> colors["Head"] (64, 224, 208, 255) >>> colors["Hand"] (255, 170, 0, 255)
- krajjat.tool_functions.generate_random_color(random_alpha=False, color_format='RGB', include_alpha=True)
Generates a random color, and returns its RGB or HEX value.
New in version 2.0.
- Parameters:
random_alpha (bool) – If set on False (default), returns a color with an alpha value set on 255. If set on True, randomizes the alpha value in the color.
color_format (str) – The format of the color to be returned: either
"RGBA"(default),"RGB", or"HEX".include_alpha (bool) – If True (default), includes the alpha value in the returned color.
- Returns:
A tuple containing the RGB or RGBA values of a random color, or a string containing its hexadecimal value with a leading
#.- Return type:
tuple(int, int, int, int)|tuple(int, int, int)|str
Example
>>> generate_random_color() (255, 128, 64, 32)
Audio functions
- krajjat.tool_functions.scale_audio(audio_array, max_value, use_abs_values=False, set_lowest_at_zero=False, verbosity=1)
Scale an array of audio samples according to a maximum value. This function is used by the toolbox for display purposes.
- Parameters:
audio_array (list(int or float) or numpy.array(int or float)) – An array of audio samples.
max_value (int or float) – The value that will become the maximum value of the scaled array.
use_abs_values (bool, optional) – If set on
True, the values of the samples will be converted to absolute values. If set onFalse(default), the sign of the samples will be preserved.set_lowest_at_zero (bool, optional) – If set on
True, if the minimum sample value of the audio is over zero, the minimal value will be subtracted from all the samples. This parameter is set onFalseby default.verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
An array of scaled audio samples.
- Return type:
list(float)
- krajjat.tool_functions.stereo_to_mono(audio_data, mono_channel=0, verbosity=1)
Converts an audio array to mono.
New in version 2.0.
- Parameters:
audio_data (np.ndarray (1D or 2D)) – The parameter data resulting from reading a WAV file with scipy.io.wavfile.read.
mono_channel (int|str, optional) – Defines the method to use to convert multiple-channel WAV files to mono, By default, this parameter value is
0: the channel with index 0 in the WAV file is used as the array, while all the other channels are discarded. This value can be any of the channels indices (using1will preserve the channel with index 1, etc.). This parameter can also take the value"average": in that case, a new channel is created by averaging the values of all the channels of the WAV file.verbosity (int, optional) –
Sets how much feedback the code will provide in the console output:
0: Silent mode. The code won’t provide any feedback, apart from error messages.
1: Normal mode (default). The code will provide essential feedback such as progression markers and current steps.
2: Chatty mode. The code will provide all possible information on the events happening. Note that this may clutter the output and slow down the execution.
- Returns:
A 1D numpy array containing the audio converted to mono.
- Return type:
np.array
- krajjat.tool_functions.remove_average(array)
Removes the average of an array of values.
New in version 2.0.
- Parameters:
array (list|`np.ndarray <https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html>`_ (1D or 2D)) – An array of values, for example from an audio file.
Internal loading functions
- krajjat.tool_functions.load_joint_labels(system='kinect', part='all', label_style='original')
Loads and returns a list of joint labels from a file.
New in version 2.0.
- Parameters:
system (str, optional) – The system from which to load the joints. This parameter can be set on
"kinect"(default) or"qualisys"/"kualisys"to load a preset list of joints. It is also possible to pass a path to a file containing joints on different lines.part (str, optional) – The part of the joints to load. This parameter can be set on
"all"(default),"top"or"bottom". If the parametersystemis set on a path, this parameter is ignored.label_style (str, optional) –
- When used for loading Qualisys joints:
- · If set on
"original"(default), the returned joint labels are the original ones from the Qualisys system.
- · If set on
"new","replaced","krajjat"or"kualisys", the returned joint labels are the renamed Kualisys joint labels from the Krajjat toolbox. For more information, see Joint labels.
- · If set on
When used for paths, the function checks if each line contains two strings separated by a tab, and returns the list of the first strings if set on
"original", and the list of the second strings if set on"new"or"replaced".This parameter is ignored if
systemis set on"krajjat".
- Returns:
The list of the Kinect joint labels.
- Return type:
list(str)
- krajjat.tool_functions.load_qualisys_joint_label_conversion()
Returns a dictionary containing the original Qualisys joint labels as keys, and the renamed Kualisys joints labels as values. The dictionary is loaded from
res/kualisys_joint_labels.txt. For more information, see Joint labels.New in version 2.0.
- Returns:
dict(str – A dictionary with the original Qualisys joint labels as keys, and the Kualisys renamed joint labels as values.
- Return type:
str)
- krajjat.tool_functions.load_joint_connections(system='kinect', part='all')
Returns a list of joint pairs between which a line can be traced to form a skeleton.
New in version 2.0.
- Parameters:
system (str, optional) – The system from which to load the joints. This parameter can be set on
"kinect"(default) or"qualisys"/"kualisys"to load a preset list of joints. It is also possible to pass a path to a file containing joints on different lines.part (str, optional) – The part of the joints to load. This parameter can be set on
"all"(default),"top"or"bottom". If the parametersystemis set on a path, this parameter is ignored.
- Returns:
A list of sub-lists, each containing two elements (two joint labels).
- Return type:
list(list(str))
- krajjat.tool_functions.load_qualisys_to_kinect()
Loads a dictionary containing Kinect joint labels as keys, and a series of Kualisys joint labels as values. The Kinect joints can be averaged from the joints in values. The dictionary is loaded from
res/kualisys_to_kinect.txt. For more information, see Joint labels.New in version 2.0.
- Returns:
dict(str – A dictionary of Kinect joint labels as keys, and a series of Kualisys joint labels as values.
- Return type:
list(str))
- krajjat.tool_functions.load_joints_subplot_layout(joint_layout)
Returns a dictionary of the subplot positions of the joints on a skeleton graph. Loads the data from
"res/kinect_joints_subplot_layout.txt"or"res/kualisys_joints_subplot_layout.txt".New in version 2.0.
- Parameters:
joint_layout (str) – The layout to load, either
"kinect","kualisys"/"qualisys", or the path to a text file containing a custom layout.- Returns:
dict(str – A dictionary containing joint labels as keys, and subplot positions as values.
- Return type:
int)
- krajjat.tool_functions.load_joints_silhouette_layout(joint_layout)
Returns a dictionary of the positions and radii of the joints, and a list of the order in which to plot the joints for the function
plot_functions.plot_silhouette()Loads the data from"res/kinect_joints_silhouette_layout.txt","res/kualisys_joints_silhouette_layout.txt", or a custom file.New in version 2.0.
- Parameters:
joint_layout (str) – The layout to load, either
"kinect"or"qualisys"/"kualisys". This parameter can also be the path to a custom layout (in .txt). In that case, each line must contain a joint label, the horizontal position, the vertical position and the radius of the circle to plot, all separated by a tabulation. The positions and radius are expected to be specified in pixels. The output list of the function, which defines the order in which to plot the joints, is defined by the order of the joints in the file.- Returns:
dict(str (tuple)) – A dictionary containing joint labels as keys, and tuples containing three elements as values: the horizontal position, the vertical position, and the radius of the circle.
list(str) – The list of the joints, in the order they should be plotted.
- krajjat.tool_functions.load_default_steps_gui()
Loads the steps for the modification of the parameters in the GUI of the graphic functions, from the file
res/default_steps_gui.txt.New in version 2.0.
Time functions
- krajjat.tool_functions.convert_timestamp_to_seconds(timestamp, time_unit='s')
Converts a timestamp in the specified time unit to a timestamp in seconds.
New in version 2.0.
- Parameters:
timestamp (int|float) – A timestamp, in the unit specified by time_unit.
time_unit (str, optional) – The time unit of the timestamp. This parameter can take the following values: “ns”, “1ns”, “10ns”, “100ns”, “µs”, “1µs”, “10µs”, “100µs”, “ms”, “1ms”, “10ms”, “100ms”, “s”, “sec”, “1s”, “min”, “mn”, “h”, “hr”, “d”, “day”.
- Returns:
The converted timestamp, in seconds.
- Return type:
float
Examples
>>> convert_timestamp_to_seconds(5, "ms") 0.005 >>> convert_timestamp_to_seconds(1, "h") 3600
- krajjat.tool_functions.format_time(time, time_unit='s', time_format='hh:mm:ss')
Formats a given time in a given unit according to a time format.
New in version 2.0.
- Parameters:
time (int or float) – A value of time.
time_unit (str, optional) – The unit of the
timeparameter. This parameter can take the following values: “ns”, “1ns”, “10ns”, “100ns”, “µs”, “1µs”, “10µs”, “100µs”, “ms”, “1ms”, “10ms”, “100ms”, “s”, “sec”, “1s”, “min”, “mn”, “h”, “hr”, “d”, “day”.time_format (str, optional) – The format in which to return the time. Can be either “hh:mm:ss”, “hh:mm:ss.ms”, “hh:mm”, “mm:ss” or “mm:ss.ms”.
Examples
>>> format_time(1000, "s", "hh:mm:ss") "00:16:40" >>> format_time(1000, "s", "hh:mm:ss.ms") "00:16:40.000" >>> format_time(1000, "s", "mm:ss") "16:40" >>> format_time(1000, "s", "mm:ss.ms") "16:40.000"
- krajjat.tool_functions.time_unit_to_datetime(time, time_unit='s')
Turns any time unit into a
datetimeformat.New in version 2.0.
- Parameters:
time (int or float) – A value of time.
time_unit (str, optional) – The unit of the
timeparameter. This parameter can take the following values: “ns”, “1ns”, “10ns”, “100ns”, “µs”, “1µs”, “10µs”, “100µs”, “ms”, “1ms”, “10ms”, “100ms”, “s”, “sec”, “1s”, “min”, “mn”, “h”, “hr”, “d”, “day”.
Example
>>> time_unit_to_datetime(1000000, "ms") datetime.datetime(1, 1, 1, 0, 16, 40)
- krajjat.tool_functions.time_unit_to_timedelta(time, time_unit='s')
Turns any time unit into a
timedeltaformat.New in version 2.0.
- Parameters:
time (int or float) – A value of time.
time_unit (str, optional) – The unit of the
timeparameter. This parameter can take the following values: “ns”, “1ns”, “10ns”, “100ns”, “µs”, “1µs”, “10µs”, “100µs”, “ms”, “1ms”, “10ms”, “100ms”, “s”, “sec”, “1s”, “min”, “mn”, “h”, “hr”, “d”, “day”.
Example
>>> time_unit_to_timedelta(1000000, "ms") datetime.timedelta(0, 1000, 0)
Miscellaneous functions
- krajjat.tool_functions.show_progression(verbosity, current_iteration, goal, next_percentage, step=10)
Shows a percentage of progression if verbosity is equal to 1.
New in version 2.0.
- Parameters:
verbosity (int) – This parameter must be equal to 1 for the function to print information. If the value is set on 2 (chatty mode), the percentage will not be displayed, in favour of more detailed information related to the ongoing operations.
current_iteration (int or float) – The current iteration in a loop.
goal (int or float) – The stopping value of the loop.
next_percentage (int or float) – The next percentage at which to print the progression.
step (int or float, optional) – The step between each print of the progression.
- Returns:
The next percentage at which to print the progression.
- Return type:
int or float
Example
>>> next_percentage = 10 >>> goal = 100 >>> for i in range(goal): ... next_percentage = show_progression(1, i, goal, next_percentage) 10% 20̀% 30% 40% 50% 60% 70% 80M 90%
- krajjat.tool_functions.get_min_max_values_from_plot_dictionary(plot_dictionary, keys_to_exclude=None, xlim=None)
Returns the minimum and maximum values of all the graphs contained in a plot dictionary.
New in version 2.0.
- Parameters:
plot_dictionary (dict) – A dictionary with labels as keys and Graph elements, float, int or arrays as values.
keys_to_exclude (list(string)) – A list of keys of the dictionary to exclude from the search of the minimum and maximum values.
xlim (list(int|float, int|float), optional) – The limits of the horizontal axis of the graphs.
- Returns:
float – The minimum value detected in all the series.
float – The maximum value detected in all the series.
- krajjat.tool_functions.kwargs_parser(dictionary, suffix)
Given a dictionary of keyword arguments and a suffix, returns a dictionary that removes the suffix from the given keywords. If a key without the suffix already exists in the dictionary, it is left untouched and the key with the suffix is removed.
New in version 2.0.
- Parameters:
dictionary (dict) – A dictionary of keyword arguments.
suffix (str) – The suffix to look for in the keys of the dictionary.