diff --git a/src/biofeedback.py b/src/biofeedback.py index 82e5f67..697b35e 100644 --- a/src/biofeedback.py +++ b/src/biofeedback.py @@ -12,7 +12,7 @@ """ import time -from typing import Final, Literal, TypedDict +from typing import Any, Final, TypedDict import kineticstoolkit as ktk import matplotlib.pyplot as plt @@ -20,7 +20,6 @@ import optitrack as ot import propulsion_patterns -from python_bridge import sender # %% Public variables # Current analysis window (n s). @@ -76,7 +75,7 @@ class DataSide(TypedDict): id_streaming: str local_meta2: np.ndarray - side: Literal["left", "right"] + side: str # either "left" or "right" wheel_center: np.ndarray @@ -94,7 +93,7 @@ class Areas(TypedDict): Array of coordinates representing the push path for this segment. """ - sign: Literal["positive", "negative"] + sign: str # "positive" or "negative" area: float recovery_phase: np.ndarray push_phase: np.ndarray @@ -136,9 +135,9 @@ class PushCycle(TypedDict): possible. """ - in_push: dict[Literal["time", "value"], float] - recovery: dict[Literal["time", "value"], float] - end_push: dict[Literal["time", "value"], float] + in_push: dict[str, float] # keys are "time" or "value" + recovery: dict[str, float] # keys are "time" or "value" + end_push: dict[str, float] # keys are "time" or "value" range: float velocity_max: float push_frequency: float @@ -146,16 +145,7 @@ class PushCycle(TypedDict): areas: list[Areas] | None A1: float | None A2: float | None - label_push_pattern: ( - Literal[ - "Pumping (PM)", - "Semi-Circular (SC)", - "Single-Loop (SLOP)", - "Double-Loop (DLOP)", - "", - ] - | None - ) + label_push_pattern: str | None class KtkDataAndCycles(TypedDict): @@ -191,13 +181,13 @@ class RuntimeState(TypedDict): Counter or index tracking cycles sent to the biofeedback display. """ - run_mode: Literal["start", "stop", "offline"] + run_mode: str # "start", "stop" or "offline" data: dict[str, ktk.TimeSeries] | None current_window_data: ( - dict[Literal["left", "right"], KtkDataAndCycles] | None - ) - new_cycle_log: dict[Literal["left", "right"], int] - new_cycle_send: dict[Literal["left", "right"], int] + dict[str, KtkDataAndCycles] | None + ) # where str is "left" or "right + new_cycle_log: dict[str, int] # where str is "left" or "right + new_cycle_send: dict[str, int] # where str is "left" or "right class KinematicsData(TypedDict): @@ -210,8 +200,8 @@ class KinematicsData(TypedDict): Full continuous time-series history aggregated since the session start. """ - cycles: dict[Literal["left", "right"], list] - ts_full: dict[Literal["left", "right"], ktk.TimeSeries | None] + cycles: dict[str, list] # where str is "left" or "right + ts_full: dict[str, ktk.TimeSeries | None] # where str is "left" or "right # %% Private variables @@ -249,14 +239,12 @@ def biofeedback_stop() -> None: kinematics_data["ts_full"]["left"] is not None and kinematics_data["ts_full"]["right"] is not None ): - dict_ts_propulsion_cycles: dict[ - Literal["left", "right"], ktk.TimeSeries - ] = { + dict_ts_propulsion_cycles: dict[str, ktk.TimeSeries] = { "left": kinematics_data["ts_full"]["left"], "right": kinematics_data["ts_full"]["right"], } - dict_cycles: dict[Literal["left", "right"], list[PushCycle]] = { + dict_cycles: dict[str, list[PushCycle]] = { "left": kinematics_data["cycles"]["left"], "right": kinematics_data["cycles"]["right"], } @@ -292,15 +280,15 @@ def biofeedback_stop() -> None: plt.show() -def biofeedback_update( +def biofeedback_kinematics( coordinates_left_wheel_center: tuple[float, float, float], coordinates_right_wheel_center: tuple[float, float, float], coordinates_left_hand: tuple[float, float, float], coordinates_right_hand: tuple[float, float, float], wheel_diameter: float, -) -> None: +) -> dict[str, Any]: """ - Execute an update iteration for the biofeedback (live and offline modes). + Execute an iteration for the biofeedback (live and offline modes). Handles the streaming state machine: initializes OptiTrack on startup, fetches new tracking frames in 'start' mode, or processes pre-loaded local @@ -344,9 +332,9 @@ def biofeedback_update( print(e) if not _runtime_state["data"]: - return + return {} - _execute_analysis_pipeline( + return _execute_analysis_pipeline( _runtime_state, kinematics_data, coordinates, @@ -355,30 +343,32 @@ def biofeedback_update( elif _runtime_state["run_mode"] == "offline": if not _runtime_state["data"]: - return + return {} - _execute_analysis_pipeline( + return _execute_analysis_pipeline( _runtime_state, kinematics_data, coordinates, LIMIT_DURATION_CURRENT_WINDOW, ) + return {} + # %% Private functions def _analyze_current_window( data: dict[str, ktk.TimeSeries], arg: Arg, - prev_data_cycles: dict[Literal["left", "right"], list], + prev_data_cycles: dict[str, list], limit_duration: float = LIMIT_DURATION_CURRENT_WINDOW, -) -> dict[Literal["left", "right"], KtkDataAndCycles]: +) -> dict[str, KtkDataAndCycles]: # where str is "left" or "right" """ Extract kinematics and validated propulsion cycles. Processing is limited to the current real-time data window. """ # Initialize the current window data - current_window_data: dict[Literal["left", "right"], KtkDataAndCycles] = { + current_window_data: dict[str, KtkDataAndCycles] = { "left": {"ts": None, "cycles": None}, "right": {"ts": None, "cycles": None}, } @@ -447,20 +437,16 @@ def _analyze_current_window( def _update_data_cycles( - cycles: dict[Literal["left", "right"], list[PushCycle]], - current_window_data: dict[Literal["left", "right"], KtkDataAndCycles], -) -> dict[Literal["left", "right"], list[PushCycle]]: + cycles: dict[str, list[PushCycle]], + current_window_data: dict[str, KtkDataAndCycles], +) -> dict[str, list[PushCycle]]: # where str is "left" or "right" """ Update global cycle history upon cycle detection. Appends newly identified propulsion cycles to the continuous historical log """ try: - sides: tuple[Literal["left", "right"], Literal["left", "right"]] = ( - "left", - "right", - ) - for side in sides: + for side in ("left", "right"): # Skip if no cycles were detected for this side in the # current window current_cycles = current_window_data[side]["cycles"] @@ -489,16 +475,12 @@ def _update_data_cycles( def _update_ts_full( - ts_full: dict[Literal["left", "right"], ktk.TimeSeries | None], - current_window_data: dict[Literal["left", "right"], KtkDataAndCycles], -) -> dict[Literal["left", "right"], ktk.TimeSeries | None]: + ts_full: dict[str, ktk.TimeSeries | None], + current_window_data: dict[str, KtkDataAndCycles], +) -> dict[str, ktk.TimeSeries | None]: # where str is "left" or "right" """Update the global timeserie of Meta2 with newly detected timeserie.""" try: - sides: tuple[Literal["left", "right"], Literal["left", "right"]] = ( - "left", - "right", - ) - for side in sides: + for side in ("left", "right"): ts = current_window_data[side]["ts"] if ts is None: @@ -533,115 +515,6 @@ def _update_ts_full( return ts_full -def _send_data_godot( - new_cycle_send: dict[Literal["left", "right"], int], - cycles: dict[Literal["left", "right"], list[PushCycle]], -) -> dict[Literal["left", "right"], int]: - """ - Send computed kinematics metrics to Godot upon cycle detection. - - Streams the median push frequency and push pattern geometry of the last - three cycles via python_bridge, then increments the sent cycle counter. - """ - sides: tuple[Literal["left", "right"], Literal["left", "right"]] = ( - "left", - "right", - ) - - for side in sides: - if ( - len(cycles[side]) >= 3 - and len(cycles[side]) == new_cycle_send[side] - ): - mean_push_frequency = float( - np.median( - [ - cycles[side][-1]["push_frequency"], - cycles[side][-2]["push_frequency"], - cycles[side][-3]["push_frequency"], - ] - ) - ) - - last_push_pattern_1 = cycles[side][-1][ - "normalised_push_pattern" - ].tolist() - last_push_pattern_2 = cycles[side][-2][ - "normalised_push_pattern" - ].tolist() - last_push_pattern_3 = cycles[side][-3][ - "normalised_push_pattern" - ].tolist() - - label_push_pattern = str(cycles[side][-1]["label_push_pattern"]) - - data = { - side: { - "mean_push_frequency": mean_push_frequency, - "last_push_pattern_1": last_push_pattern_1, - "last_push_pattern_2": last_push_pattern_2, - "last_push_pattern_3": last_push_pattern_3, - "label_push_pattern": label_push_pattern, - } - } - - sender.send({"command": "biofeedback_update", "data": data}) - - new_cycle_send[side] += 1 - - return new_cycle_send - - -def _print_log( - new_cycle_log: dict[Literal["left", "right"], int], - cycles: dict[Literal["left", "right"], list[PushCycle]], - current_window_data: dict[Literal["left", "right"], KtkDataAndCycles], - end: float, - start: float, -) -> dict[Literal["left", "right"], int]: - """ - Display push data when a cycle is detected. - - (ex) side : push n°X | - execution duration: X.XXXXXX | - time windowed: X.XX | - Push Pattern: last [X, Y, Z] - """ - try: - sides: tuple[Literal["left", "right"], Literal["left", "right"]] = ( - "left", - "right", - ) - for side in sides: - ts = current_window_data[side]["ts"] - - if ts is None: - continue - - if len(cycles[side]) == new_cycle_log[side]: - push_frequency = cycles[side][-1]["push_frequency"] - label_push_pattern = cycles[side][-1]["label_push_pattern"] - - duration_cycle_analized = ts.time[-1] - ts.time[0] - - print( - f"{f'{side}':<8} " - f" : Push n°{len(cycles[side]):<3} | " - f"Time execution: {end - start:<8.6f} s | " - "Time data windowed: " - f"{duration_cycle_analized:<4.2f} s | " - f"{push_frequency:<4.2f} Pushes per second | " - f"Push pattern: {label_push_pattern}" - ) - - new_cycle_log[side] += 1 - - except Exception as e: - print(f"print_log : {e}") - - return new_cycle_log - - def _initialize_data_side(arg: Arg) -> list[DataSide]: """Initialize and structures calibration coordinates for both sides.""" # Get and convert coordinates to homogeneous arrays [X, Y, Z, 1.0] @@ -716,7 +589,7 @@ def _compute_local_kinematics( data_windowed: dict[str, ktk.TimeSeries], data_side: list[DataSide], n: int, -) -> tuple[ktk.TimeSeries, Literal["left", "right"]]: +) -> tuple[ktk.TimeSeries, str]: # where str is "left" or "right" """ Transform tracking data into local kinematics. @@ -798,13 +671,10 @@ def _execute_analysis_pipeline( kinematics_data: KinematicsData, arg: Arg, LIMIT_DURATION_CURRENT_WINDOW: float, -) -> tuple[float, float]: +) -> dict[str, Any]: """Run kinematic analysis and distribute results.""" - start_time = time.time() - if _runtime_state["data"] is None: - end_time = time.time() - return start_time, end_time + return {} _runtime_state["current_window_data"] = _analyze_current_window( _runtime_state["data"], @@ -814,8 +684,7 @@ def _execute_analysis_pipeline( ) if _runtime_state["current_window_data"] is None: - end_time = time.time() - return start_time, end_time + return {} kinematics_data["cycles"] = _update_data_cycles( kinematics_data["cycles"], @@ -826,22 +695,44 @@ def _execute_analysis_pipeline( _runtime_state["current_window_data"], ) - _runtime_state["new_cycle_send"] = _send_data_godot( - _runtime_state["new_cycle_send"], - kinematics_data["cycles"], - ) + data: dict[str, dict[str, Any]] = {} + for side in ("left", "right"): + if len(kinematics_data["cycles"][side]) >= 3: + mean_push_frequency = float( + np.median( + [ + kinematics_data["cycles"][side][-1]["push_frequency"], + kinematics_data["cycles"][side][-2]["push_frequency"], + kinematics_data["cycles"][side][-3]["push_frequency"], + ] + ) + ) + + last_push_pattern_1 = kinematics_data["cycles"][side][-1][ + "normalised_push_pattern" + ].tolist() + last_push_pattern_2 = kinematics_data["cycles"][side][-2][ + "normalised_push_pattern" + ].tolist() + last_push_pattern_3 = kinematics_data["cycles"][side][-3][ + "normalised_push_pattern" + ].tolist() - end_time = time.time() + label_push_pattern = str( + kinematics_data["cycles"][side][-1]["label_push_pattern"] + ) - _runtime_state["new_cycle_log"] = _print_log( - _runtime_state["new_cycle_log"], - kinematics_data["cycles"], - _runtime_state["current_window_data"], - end_time, - start_time, - ) + data[side] = { + "mean_push_frequency": mean_push_frequency, + "last_push_pattern_1": last_push_pattern_1, + "last_push_pattern_2": last_push_pattern_2, + "last_push_pattern_3": last_push_pattern_3, + "label_push_pattern": label_push_pattern, + } + + _runtime_state["new_cycle_send"][side] += 1 - return start_time, end_time + return data # %% Main @@ -880,7 +771,7 @@ def _execute_analysis_pipeline( try: while True: - biofeedback_update(**arg) + biofeedback_kinematics(**arg) except KeyboardInterrupt: print("Biofeedback closed") biofeedback_stop() diff --git a/src/biofeedback_pushrim_kinetics.py b/src/biofeedback_pushrim_kinetics.py new file mode 100644 index 0000000..9adddfe --- /dev/null +++ b/src/biofeedback_pushrim_kinetics.py @@ -0,0 +1,153 @@ +"""Calculations for pushrim kinetics biofeedback.""" + +from dataclasses import dataclass +from typing import Any + +import kineticstoolkit as ktk +import numpy as np +from kineticstoolkit_extensions import pushrimkinetics as pk +from nextwheel import NextWheel + +from nextwheel_dummy import NextWheel as NextWheelDummy + +TIME_SPAN = 5 # Number of seconds to show on the rolling plot +N_POINTS = 300 # Number of points in the rolling plot + +N_PUSHES = 3 # Number of pushes to calculate on +RESAMPLE_FREQUENCY = 240 # Resample everything to this freq before processing + + +@dataclass +class PushrimKineticsBiofeedback: + """Contains the NextWheel instance and processing methods.""" + + # The NextWheel instance + nw: NextWheel | NextWheelDummy = NextWheelDummy() + + # Functions + def connect(self, ip: str) -> None: + """ + Connect to the NextWheel. + + Parameters + ---------- + ip + IP address of the NextWheel, or "dummy" to simulate a wheel that + sends prerecorded data. + """ + if ip == "dummy": + self.nw = NextWheelDummy() + else: + self.nw = NextWheel(ip) + self.nw.start_streaming() + + def process(self) -> dict: + """Process data and send back to Godot, called regularly.""" + nextwheel_data = self.nw.fetch() + return calculate_pushrim_kinetics_biofeedback(nextwheel_data) + + +# %% Public interface for main.py + +# Create the instance +pkb = PushrimKineticsBiofeedback(nw=NextWheel()) + + +def connect(ip: str) -> None: + """Connect to the NextWheel.""" + pkb.connect(ip) + + +def process(**kwargs) -> dict: + """Run the process once.""" + return pkb.process() + + +# %% Processing functions + + +def calculate_pushrim_kinetics_biofeedback( + data: dict[str, ktk.TimeSeries], *, show_plot: bool = False +) -> dict[str, Any]: + """ + Calculate pushrim kinetics biofeedback. + + Parameters + ---------- + data + Dictionary of TimeSeries as returned by NextWheel.fetch(). + show_plot + Optional. True to show a plot of the processed data. + + Returns + ------- + dict[str, Any] + A dictionary with those keys: + - "Fpeak": the calculated peak force over the last pushes, or 0.0 if + there were not enough pushes. + - "Ftot": the Ftot curve, in newton. + + """ + # Default output + out: dict[str, Any] = { + "Fpeak": 0.0, + "FtotCurve": [0 for _ in range(N_POINTS)], + } + + # Return if no data + if len(data["Analog"].time) == 0: + return out + + # Keep the last seconds + if data["Analog"].time[-1] - TIME_SPAN > data["Analog"].time[0]: + data["Analog"] = data["Analog"].get_ts_after_time( + data["Analog"].time[-1] - TIME_SPAN + ) + + # Resample + data["Analog"].resample(RESAMPLE_FREQUENCY, in_place=True) + data["Encoder"].resample( + data["Analog"].time, extrapolate=True, in_place=True + ) + ts = data["Analog"].merge(data["Encoder"]) + + # Process kinetics + ts = pk.remove_offsets(ts) + ts.data["Ftot"] = np.sqrt(np.sum(ts.data["Forces"] ** 2, axis=1)) + try: + ts = ktk.cycles.detect_cycles( + ts, + "Ftot", + event_names=("push", "recovery"), + thresholds=(10, 5), + min_durations=(0.1, 0.2), + ) + except IndexError: # no cycle detected + pass + + # Calculate parameters + Fpeak: list[float] = [] + n_pushes = ts.count_events("push") + if n_pushes >= N_PUSHES: + for i_push in range(n_pushes - N_PUSHES, n_pushes): + subts = ts.get_ts_between_events( + "push", "recovery", i_push, i_push + ) + Fpeak.append(np.max(subts.data["Ftot"])) + + if len(Fpeak) == 0: + out["Fpeak"] = 0.0 + else: + out["Fpeak"] = np.mean(Fpeak) + + final_frequency = float(N_POINTS) / (ts.time[-1] - ts.time[0]) + ts.resample(final_frequency, in_place=True) + + ts.data["Ftot"][ts.isnan("Ftot")] = 0.0 + + out["FtotCurve"] = ts.data["Ftot"].tolist() + + if show_plot: + ts.plot(["Forces", "Ftot"]) + + return out diff --git a/src/data_logging.py b/src/data_logging.py index 0511ef0..89544d6 100644 --- a/src/data_logging.py +++ b/src/data_logging.py @@ -58,7 +58,7 @@ def log_row(self, data_lines: np.ndarray) -> None: """ if self.file and not self.file.closed: for row in data_lines: - self.file.write("\t".join(map(str, row)) + "\n") + self.file.write(",".join(map(str, row)) + "\n") else: raise ValueError(f"File {self.file.name('\\')[-1]} is closed.") @@ -261,9 +261,9 @@ def _make_header( """ header = [ - ["time"] + ['"time"'] + [ - data_headers[i] + "[:," + str(j) + "]" + '"' + data_headers[i] + "[:," + str(j) + ']"' for i in range(len(data_headers)) for j in range(data_columns[i]) ] @@ -329,7 +329,9 @@ def _save_ts( """ if len(ts.time) > 0: if filetype not in session_writers: - header = [["time"] + list(ts.to_dataframe().columns)] + header = [ + ['"time"'] + [f'"{s}"' for s in ts.to_dataframe().columns] + ] filename = _make_filename(scene, filetype, session_details) _make_file( os.path.join(str(session_details.trial_folder), filename), diff --git a/src/main.py b/src/main.py index 9b9dcb9..8f62af0 100644 --- a/src/main.py +++ b/src/main.py @@ -3,67 +3,65 @@ This script listens for JSON strings of this form: { + "id": str, "command": str, - "args": any - "run_mode": "once", "start" or "stop" + "kwargs": dict[str, Any] } -For run_mode == "once", the function listed in COMMAND_MAPPING[command] is -executed once. +where command is a key of COMMAND_MAPPING, kwargs are the arguments sent to +the function in COMMAND_MAPPING, and id is any unique ID, that serves to match +the returned value to its caller. -For run_mode == "start", the function listed in COMMAND_MAPPING[command] starts -being executed continuously. Many functions can be started at the same time; -in this case they are executed one after the other, continuously. +Command "close" is reserved for closing the python bridge. + +The script returns values using JSON strings of this form: + { + "id": str, + "value": Any + } + +where id is the same as it was received, and value is the function's +return value. -For run_mode == "stop", the function listed in COMMAND_MAPPING[command] stops -being executed consinuously. """ +print("--------------------") +print(" WheelSims Analysis ") +print("--------------------") +print("Importing Python Modules...") + +# ruff: disable[E402] +# because we want the text to appear in the console without delay import os +import time +import traceback from collections.abc import Callable -from typing import Any +from itertools import cycle import biofeedback +import biofeedback_pushrim_kinetics as bf_pk import data_logging from python_bridge import GODOT_TO_PYTHON_PORT, IP, Receiver, sender +# ruff: enable[E402] -class PrivateVariables: - """Keep track of private variables.""" - - is_running: bool = True - - -_private_vars = PrivateVariables -_running_commands: dict[str, dict[str, Any]] = {} - +# How many seconds to sleep before polling UDP again once it's empty +SLEEP_TIME_ON_EMPTY_UDP_BUFFER = 1 / 60 # s +SPINNER = cycle("|/-\\") -def _close(args=None): - """Close the Python app.""" - print("\nClose Python app...") - _private_vars.is_running = False - -def _send_ready() -> None: - """Send ready to Godot.""" - sender.send({"command": "ready", "args": {}, "data": []}) - - -def _test(arg1: str, arg2: int) -> None: +def _test(arg1: int, arg2: int) -> list: """Answer to test command (used in unit tests).""" - sender.send( - { - "command": "test", - "data": [arg1, arg2, 1, 2, 3], - } - ) + time.sleep(1) + return [arg1, arg2, 1, 2, 3] COMMAND_MAPPING: dict[str, Callable] = { "test": _test, - "biofeedback_update": biofeedback.biofeedback_update, + "biofeedback_kinematics": biofeedback.biofeedback_kinematics, "biofeedback_stop": biofeedback.biofeedback_stop, - "close": _close, + "biofeedback_pushrim_kinetics_connect": bf_pk.connect, + "biofeedback_pushrim_kinetics_process": bf_pk.process, "start_logging": data_logging.start_log, "create_trial": data_logging.create_trial, "data_logging": data_logging.save_data, @@ -76,39 +74,43 @@ def _test(arg1: str, arg2: int) -> None: # Create the receiver receiver = Receiver(ip=IP, port=GODOT_TO_PYTHON_PORT, timeout=0.0) # Send "ready" to Godot - _send_ready() + sender.send({"id": "ready", "value": None}) + print("Ready.") + stay_in_loop = True # Listening Godot requests - while _private_vars.is_running: + while True: # Execute every command in the UDP buffer while command_dict := receiver.receive(): command = command_dict["command"] - run_mode = command_dict["run_mode"] - args = command_dict["args"] - - print(f"{run_mode} : {command} {args}") - - if run_mode == "start": - if command not in _running_commands: - _running_commands[command] = {"args": args} - - elif run_mode == "stop": - if command in _running_commands: - _running_commands.pop(command) - - elif run_mode == "once": - COMMAND_MAPPING[command](**command_dict["args"]) - - else: - raise ValueError("frequency must be 'start', 'stop' or 'once'") + kwargs = command_dict["kwargs"] + command_id = command_dict["id"] + + if command == "close": + # Close now + stay_in_loop = False + break + + try: + return_value = COMMAND_MAPPING[command]( + **command_dict["kwargs"] + ) + except Exception: + return_value = None + print("======================") + print(f"Exception in command {command} with kwargs {kwargs}.") + traceback.print_exc() + + # Send back the return value + sender.send({"id": command_id, "value": return_value}) + print(next(SPINNER), end="\r", flush=True) # Do not execute repeating commands after shutdown request - if not _private_vars.is_running: + if not stay_in_loop: break - # Execute every repeating command - for command in _running_commands: - COMMAND_MAPPING[command](**_running_commands[command]["args"]) + # Wait some time before checking if a new request was received + time.sleep(SLEEP_TIME_ON_EMPTY_UDP_BUFFER) # Quit os._exit(0) diff --git a/src/propulsion_patterns.py b/src/propulsion_patterns.py index 816fc4e..f4b1624 100644 --- a/src/propulsion_patterns.py +++ b/src/propulsion_patterns.py @@ -16,7 +16,7 @@ before passing them to any functions in this module. """ -from typing import Literal, TypedDict +from typing import TypedDict import kineticstoolkit as ktk import matplotlib.pyplot as plt @@ -60,7 +60,7 @@ class SignedAreas(TypedDict): Array of coordinates representing the push path for this segment. """ - sign: Literal["positive", "negative"] + sign: str # "positive" or "negative" area: float recovery_phase: np.ndarray push_phase: np.ndarray @@ -76,8 +76,8 @@ class SegmentedCycle(TypedDict): Time (s) and coordinate value (m) marking the end of the push phase. """ - in_push: dict[Literal["time", "value"], float] - end_push: dict[Literal["time", "value"], float] + in_push: dict[str, float] # where str is "time" or "value" + end_push: dict[str, float] # where str is "time" or "value" class FilteredCycle(TypedDict): @@ -97,9 +97,9 @@ class FilteredCycle(TypedDict): Maximum velocity reached during the cycle. """ - in_push: dict[Literal["time", "value"], float] - recovery: dict[Literal["time", "value"], float] - end_push: dict[Literal["time", "value"], float] + in_push: dict[str, float] # where str is "time" or "value" + recovery: dict[str, float] # where str is "time" or "value" + end_push: dict[str, float] # where str is "time" or "value" range: float velocity_max: float @@ -140,9 +140,9 @@ class AnalyzedCycle(TypedDict): possible. """ - in_push: dict[Literal["time", "value"], float] - recovery: dict[Literal["time", "value"], float] - end_push: dict[Literal["time", "value"], float] + in_push: dict[str, float] # where str is "time" or "value" + recovery: dict[str, float] # where str is "time" or "value" + end_push: dict[str, float] # where str is "time" or "value" range: float velocity_max: float push_frequency: float @@ -150,16 +150,7 @@ class AnalyzedCycle(TypedDict): areas: list[SignedAreas] | None A1: float | None A2: float | None - label_push_pattern: ( - Literal[ - "Pumping (PM)", - "Semi-Circular (SC)", - "Single-Loop (SLOP)", - "Double-Loop (DLOP)", - "", - ] - | None - ) + label_push_pattern: str | None # %% Public functions @@ -499,13 +490,7 @@ def classify_push_pattern( pattern_a2_sc_threshold: float = PATTERN_A2_SC_THRESHOLD, pattern_a2_slop_threshold: float = PATTERN_A2_SLOP_THRESHOLD, ) -> tuple[ - Literal[ - "Pumping (PM)", - "Semi-Circular (SC)", - "Single-Loop (SLOP)", - "Double-Loop (DLOP)", - "", - ], + str, float | None, float | None, list[SignedAreas] | None, @@ -557,17 +542,6 @@ def classify_push_pattern( recovery_time=recovery_time, ) - # Compute label push pattern - PatternLabel = Literal[ - "Pumping (PM)", - "Semi-Circular (SC)", - "Single-Loop (SLOP)", - "Double-Loop (DLOP)", - "", - ] - - label_push_pattern: PatternLabel = "" - if push_phase is None or recovery_phase is None: A1 = None A2 = None @@ -595,11 +569,10 @@ def classify_push_pattern( def plot_bilateral_cycles( - dict_ts_propulsion_cycles: dict[Literal["left", "right"], ktk.TimeSeries], + dict_ts_propulsion_cycles: dict[str, ktk.TimeSeries], dict_cycles: ( - dict[Literal["left", "right"], list[AnalyzedCycle]] - | dict[Literal["left", "right"], list[SegmentedCycle]] - ), + dict[str, list[AnalyzedCycle]] | dict[str, list[SegmentedCycle]] + ), # where str is "left" or "right" ) -> None: """ Plot bilateral hand kinematics with highlighted propulsion cycles. @@ -613,11 +586,7 @@ def plot_bilateral_cycles( plt.figure() plt.suptitle("Bilateral kinematics") - sides: tuple[Literal["left", "right"], Literal["left", "right"]] = ( - "left", - "right", - ) - for side in sides: + for side in ("left", "right"): ts_full = dict_ts_propulsion_cycles[side] if ts_full is None: @@ -654,7 +623,7 @@ def plot_bilateral_cycles( def plot_unilateral_push_patterns( ts_propulsion_cycles: ktk.TimeSeries, cycles: list[AnalyzedCycle], - side: Literal["left", "right", "unspecified"] = "unspecified", + side: str = "unspecified", # or "left" or "right" wheel_diameter: float = WHEEL_DIAMETER, ) -> None: """ diff --git a/src/python_bridge.py b/src/python_bridge.py index e4bbb40..f5b6ea5 100644 --- a/src/python_bridge.py +++ b/src/python_bridge.py @@ -107,7 +107,6 @@ def send( """ json_message = json.dumps(data).encode("utf-8") self.socket.sendto(json_message, (self.ip, self.port)) - print(f"Sending {data}") # Create a sender instance to be imported by the different modules diff --git a/tests/test_biofeedback.py b/tests/test_biofeedback.py index 7e6f40f..7c6a8f9 100644 --- a/tests/test_biofeedback.py +++ b/tests/test_biofeedback.py @@ -25,7 +25,7 @@ def test_with_udp_data_from_motive(): Validate the biofeedback update loop using prerecorded OptiTrack data. This test simulates an offline real-time stream by incrementally feeding - time series segments into the "biofeedback_update" pipeline. It verifies + time series segments into the "biofeedback_kinematics" pipeline. It verifies that the expected number of propulsion cycles and full kinematics time series samples are extracted. It also confirms that the detected propulsion cycles are classified with the expected push pattern labels, ensuring that @@ -60,7 +60,7 @@ def test_with_udp_data_from_motive(): data_temp["201"] = data["201"].get_ts_before_index(i) data_temp["202"] = data["202"].get_ts_before_index(i) biofeedback._runtime_state["data"] = data_temp - biofeedback.biofeedback_update(**arg) + biofeedback.biofeedback_kinematics(**arg) results = biofeedback.kinematics_data.copy() biofeedback.biofeedback_stop() @@ -72,9 +72,12 @@ def test_with_udp_data_from_motive(): len(results["ts_full"]["right"].time), ] - assert [8, 8, 1224, 1224] == y_1, ( - f"TEST FAILED: Exp: [8, 8, 1224, 1224] | Got: {y_1} | " - ) + assert [ + 8, + 8, + 1224, + 1224, + ] == y_1, f"TEST FAILED: Exp: [8, 8, 1224, 1224] | Got: {y_1} | " # Verify the push pattern labels of the detected cycles y_2 = [ diff --git a/tests/test_biofeedback_pushrim_kinetics.py b/tests/test_biofeedback_pushrim_kinetics.py new file mode 100644 index 0000000..23afe1d --- /dev/null +++ b/tests/test_biofeedback_pushrim_kinetics.py @@ -0,0 +1,26 @@ +"""Test for biofeedback_pushrim_kinetics module.""" + +import matplotlib.pyplot as plt +import pytest +import os +import sys + + +root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.append(os.path.join(root_dir, "src")) +sys.path.append(root_dir) + + +import biofeedback_pushrim_kinetics + + +def test_run_doesnt_crash(): + """Check that running the function won't crash.""" + biofeedback_pushrim_kinetics.connect("dummy") + + for i in range(10): + biofeedback_pushrim_kinetics.process() + + +if __name__ == "__main__": # pragma: no cover + pytest.main([__file__]) diff --git a/tests/test_datalog.py b/tests/test_datalog.py index ac2e082..cab1fc3 100644 --- a/tests/test_datalog.py +++ b/tests/test_datalog.py @@ -7,7 +7,7 @@ """ import os - +import sys import shutil import time from datetime import date, datetime @@ -16,7 +16,12 @@ import numpy as np import pandas as pd -from src import data_logging + +root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.append(os.path.join(root_dir, "src")) +sys.path.append(root_dir) + +import data_logging arg = { "folder": os.getcwd(), @@ -39,14 +44,14 @@ wheels = { "file": "right", "headers": ["Analog", "IMU", "Encoder", "Power"], - "sample": "nextwheel_fetch.ktk.zip", + "sample": root_dir + "/tests/data/nextwheel_fetch.ktk.zip", "data": None, } motion = { "file": "rigidbody", "headers": ["102", "201", "202"], - "sample": "optitrack_untransformed.ktk.zip", + "sample": root_dir + "/tests/data/optitrack_untransformed.ktk.zip", "data": None, } @@ -129,7 +134,7 @@ def test_create_trial(): session_details.trial_folder, writers["player_trajectory"].file.name.split("\\")[-1], ), - sep="\t", + sep=",", ) assert list(data.columns) == ["time"] + [ @@ -261,7 +266,7 @@ def test_save_data(): session_details.trial_folder, writers["player_trajectory"].file.name.split("\\")[-1], ), - sep="\t", + sep=",", ) for col in data.columns: @@ -344,8 +349,7 @@ def test_save_ts(): ) data = pd.read_csv( - os.path.join(session_details.trial_folder, filename), - sep="\t", + os.path.join(session_details.trial_folder, filename), sep="," ) data_header = list( diff --git a/tests/test_python_bridge.py b/tests/test_python_bridge.py index f5f37be..e006c21 100644 --- a/tests/test_python_bridge.py +++ b/tests/test_python_bridge.py @@ -43,22 +43,25 @@ def test_python_bridge(): try: received_data = receiver.receive() - assert received_data["command"] == "ready" - assert received_data["data"] == [] + assert received_data["id"] == "ready" + assert received_data["value"] == None # Check that we can send a test command sender.send( { "command": "test", - "args": {"arg1": "test", "arg2": 123.45}, - "run_mode": "once", + "kwargs": {"arg1": "test", "arg2": 123.45}, + "id": "test_123_456", } ) # Check that we receive something received_data = receiver.receive() - assert received_data["command"] == "test" - assert received_data["data"] == ["test", 123.45, 1, 2, 3] + assert received_data["id"] == "test_123_456" + assert received_data["value"] == ["test", 123.45, 1, 2, 3] + + # Close the bridge + sender.send({"command": "close", "kwargs": {}, "id": "close"}) except Exception as e: raise e