From 9a6e4c185043984e2dff356ac7a254e4e64da263 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Che=CC=81nier?= Date: Mon, 24 Aug 2026 17:33:20 -0400 Subject: [PATCH 01/10] [26-create-a-new-biofeedback-module-for-the-propulsion-force] Feature completed, but unit test needs to be finalized. --- src/biofeedback_pushrim_kinetics.py | 96 ++++++++++++++++++++++ tests/test_biofeedback_pushrim_kinetics.py | 23 ++++++ 2 files changed, 119 insertions(+) create mode 100644 src/biofeedback_pushrim_kinetics.py create mode 100644 tests/test_biofeedback_pushrim_kinetics.py diff --git a/src/biofeedback_pushrim_kinetics.py b/src/biofeedback_pushrim_kinetics.py new file mode 100644 index 0000000..1247bd5 --- /dev/null +++ b/src/biofeedback_pushrim_kinetics.py @@ -0,0 +1,96 @@ +"""Calculations for pushrim kinetics biofeedback.""" + +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 + + +def calculate_pushrim_kinetics_biofeedback( + nw: NextWheel | NextWheelDummy, *, show_plot: bool = False +) -> dict[str, Any]: + """ + Calculate pushrim kinetics biofeedback. + + Parameters + ---------- + nw + The NextWheel instance to fetch data from. + 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. + + """ + # Fetch the most recent data + data = nw.fetch() + + # 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 + ) + 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 + out: dict[str, Any] = {} + 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) + + # Equal number of points + ts.resample( + np.linspace(ts.time[0], ts.time[-1], len(ts.time)), in_place=True + ) + + final_frequency = float(N_POINTS) / (ts.time[-1] - ts.time[0]) + ts = ktk.filters.butter(ts, final_frequency / 2) + ts.resample(final_frequency, in_place=True) + out["Ftot"] = ts.data["Ftot"] + + if show_plot: + ts.plot(["Forces", "Ftot"]) + + return out diff --git a/tests/test_biofeedback_pushrim_kinetics.py b/tests/test_biofeedback_pushrim_kinetics.py new file mode 100644 index 0000000..00bfe76 --- /dev/null +++ b/tests/test_biofeedback_pushrim_kinetics.py @@ -0,0 +1,23 @@ +"""Just a script for now, will become a proper unit test later.""" + +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 +from nextwheel_dummy import NextWheel + + +nw = NextWheel() + +while True: + biofeedback_pushrim_kinetics.calculate_pushrim_kinetics_biofeedback(nw) + plt.pause(0.1) + plt.cla() From 637944088ebe7bdbc2f58f481ba07d1dc7bd2633 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Che=CC=81nier?= Date: Tue, 25 Aug 2026 12:22:06 -0400 Subject: [PATCH 02/10] [26-create-a-new-biofeedback-module-for-the-propulsion-force] More modular --- src/biofeedback_pushrim_kinetics.py | 31 +++++++++++++++++----- tests/test_biofeedback_pushrim_kinetics.py | 5 ++-- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/src/biofeedback_pushrim_kinetics.py b/src/biofeedback_pushrim_kinetics.py index 1247bd5..daf0ed0 100644 --- a/src/biofeedback_pushrim_kinetics.py +++ b/src/biofeedback_pushrim_kinetics.py @@ -15,16 +15,38 @@ N_PUSHES = 3 # Number of pushes to calculate on + +class GlobalVariables(): + """Contain the module's global variables.""" + # The NextWheel instance + nw: NextWheel | NextWheelDummy = NextWheelDummy() + + +global_variables = GlobalVariables() + + +def init(**kwargs) -> None: + """Create the NextWheel instance.""" + pass + + +def process(**kwargs) -> None: + """Run the process once.""" + data = global_variables.nw.fetch() + out = calculate_pushrim_kinetics_biofeedback(data) + print(out) + + def calculate_pushrim_kinetics_biofeedback( - nw: NextWheel | NextWheelDummy, *, show_plot: bool = False + data: dict[str, ktk.TimeSeries], *, show_plot: bool = False ) -> dict[str, Any]: """ Calculate pushrim kinetics biofeedback. Parameters ---------- - nw - The NextWheel instance to fetch data from. + data + Dictionary of TimeSeries as returned by NextWheel.fetch(). show_plot Optional. True to show a plot of the processed data. @@ -37,9 +59,6 @@ def calculate_pushrim_kinetics_biofeedback( - "Ftot": the Ftot curve, in newton. """ - # Fetch the most recent data - data = nw.fetch() - # Keep the last seconds if data["Analog"].time[-1] - TIME_SPAN > data["Analog"].time[0]: data["Analog"] = data["Analog"].get_ts_after_time( diff --git a/tests/test_biofeedback_pushrim_kinetics.py b/tests/test_biofeedback_pushrim_kinetics.py index 00bfe76..deef48a 100644 --- a/tests/test_biofeedback_pushrim_kinetics.py +++ b/tests/test_biofeedback_pushrim_kinetics.py @@ -12,12 +12,11 @@ import biofeedback_pushrim_kinetics -from nextwheel_dummy import NextWheel -nw = NextWheel() +biofeedback_pushrim_kinetics.init() while True: - biofeedback_pushrim_kinetics.calculate_pushrim_kinetics_biofeedback(nw) + biofeedback_pushrim_kinetics.process() plt.pause(0.1) plt.cla() From 72e1f4d6892e43e2035097d7564235b7a5deae21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Che=CC=81nier?= Date: Tue, 1 Sep 2026 10:49:06 -0400 Subject: [PATCH 03/10] [26-create-a-new-biofeedback-module-for-the-propulsion-force] biofeedback_pushrim_kinetics done, not tested yet with Godot. --- src/biofeedback_pushrim_kinetics.py | 54 ++++++++++++++++++---- src/main.py | 33 ++++++------- tests/test_biofeedback_pushrim_kinetics.py | 16 ++++--- 3 files changed, 69 insertions(+), 34 deletions(-) diff --git a/src/biofeedback_pushrim_kinetics.py b/src/biofeedback_pushrim_kinetics.py index daf0ed0..68f9039 100644 --- a/src/biofeedback_pushrim_kinetics.py +++ b/src/biofeedback_pushrim_kinetics.py @@ -1,5 +1,6 @@ """Calculations for pushrim kinetics biofeedback.""" +from dataclasses import dataclass from typing import Any import kineticstoolkit as ktk @@ -8,6 +9,7 @@ from nextwheel import NextWheel from nextwheel_dummy import NextWheel as NextWheelDummy +from python_bridge import sender TIME_SPAN = 5 # Number of seconds to show on the rolling plot N_POINTS = 300 # Number of points in the rolling plot @@ -15,26 +17,58 @@ N_PUSHES = 3 # Number of pushes to calculate on +@dataclass +class PushrimKineticsBiofeedback: + """Contains the NextWheel instance and processing methods.""" -class GlobalVariables(): - """Contain the module's global variables.""" # 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) + + def process(self) -> None: + """Process data and send back to Godot, called regularly.""" + nextwheel_data = self.nw.fetch() + processed_data = calculate_pushrim_kinetics_biofeedback(nextwheel_data) + sender.send( + { + "command": "biofeedback_pushrim_kinetics_process", + "data": processed_data, + } + ) + + +# %% Public interface for main.py -global_variables = GlobalVariables() +# Create the instance +pkb = PushrimKineticsBiofeedback(nw=NextWheel()) -def init(**kwargs) -> None: - """Create the NextWheel instance.""" - pass +def connect(ip: str) -> None: + """Connect to the NextWheel.""" + pkb.connect(ip) def process(**kwargs) -> None: """Run the process once.""" - data = global_variables.nw.fetch() - out = calculate_pushrim_kinetics_biofeedback(data) - print(out) + pkb.process() + + +# %% Processing functions def calculate_pushrim_kinetics_biofeedback( @@ -107,7 +141,7 @@ def calculate_pushrim_kinetics_biofeedback( final_frequency = float(N_POINTS) / (ts.time[-1] - ts.time[0]) ts = ktk.filters.butter(ts, final_frequency / 2) ts.resample(final_frequency, in_place=True) - out["Ftot"] = ts.data["Ftot"] + out["FtotCurve"] = ts.data["Ftot"].tolist() if show_plot: ts.plot(["Forces", "Ftot"]) diff --git a/src/main.py b/src/main.py index 9b9dcb9..dc9d018 100644 --- a/src/main.py +++ b/src/main.py @@ -17,6 +17,9 @@ For run_mode == "stop", the function listed in COMMAND_MAPPING[command] stops being executed consinuously. + +Command "close" is reserved for closing the python bridge. + """ import os @@ -24,29 +27,16 @@ from typing import Any import biofeedback +import biofeedback_pushrim_kinetics as bf_pk import data_logging from python_bridge import GODOT_TO_PYTHON_PORT, IP, Receiver, sender - -class PrivateVariables: - """Keep track of private variables.""" - - is_running: bool = True - - -_private_vars = PrivateVariables _running_commands: dict[str, dict[str, Any]] = {} -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": []}) + sender.send({"command": "ready", "data": []}) def _test(arg1: str, arg2: int) -> None: @@ -63,7 +53,8 @@ def _test(arg1: str, arg2: int) -> None: "test": _test, "biofeedback_update": biofeedback.biofeedback_update, "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, @@ -78,8 +69,9 @@ def _test(arg1: str, arg2: int) -> None: # Send "ready" to Godot _send_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"] @@ -88,6 +80,11 @@ def _test(arg1: str, arg2: int) -> None: print(f"{run_mode} : {command} {args}") + if command == "close": + # Close now + stay_in_loop = False + break + if run_mode == "start": if command not in _running_commands: _running_commands[command] = {"args": args} @@ -103,7 +100,7 @@ def _test(arg1: str, arg2: int) -> None: raise ValueError("frequency must be 'start', 'stop' or 'once'") # Do not execute repeating commands after shutdown request - if not _private_vars.is_running: + if not stay_in_loop: break # Execute every repeating command diff --git a/tests/test_biofeedback_pushrim_kinetics.py b/tests/test_biofeedback_pushrim_kinetics.py index deef48a..23afe1d 100644 --- a/tests/test_biofeedback_pushrim_kinetics.py +++ b/tests/test_biofeedback_pushrim_kinetics.py @@ -1,4 +1,4 @@ -"""Just a script for now, will become a proper unit test later.""" +"""Test for biofeedback_pushrim_kinetics module.""" import matplotlib.pyplot as plt import pytest @@ -14,9 +14,13 @@ import biofeedback_pushrim_kinetics +def test_run_doesnt_crash(): + """Check that running the function won't crash.""" + biofeedback_pushrim_kinetics.connect("dummy") -biofeedback_pushrim_kinetics.init() -while True: - biofeedback_pushrim_kinetics.process() - plt.pause(0.1) - plt.cla() + for i in range(10): + biofeedback_pushrim_kinetics.process() + + +if __name__ == "__main__": # pragma: no cover + pytest.main([__file__]) From 066ee3f0e79077c6a732946d3271a4eb7e15054b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Che=CC=81nier?= Date: Tue, 1 Sep 2026 18:02:34 -0400 Subject: [PATCH 04/10] [26-create-a-new-biofeedback-module-for-the-propulsion-force] Kinda work, but not always. Probably full of race conditions. --- src/biofeedback_pushrim_kinetics.py | 3 +++ src/main.py | 20 ++++++++++++++++++-- src/python_bridge.py | 17 ++++++++++++++++- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/biofeedback_pushrim_kinetics.py b/src/biofeedback_pushrim_kinetics.py index 68f9039..3974f3f 100644 --- a/src/biofeedback_pushrim_kinetics.py +++ b/src/biofeedback_pushrim_kinetics.py @@ -141,6 +141,9 @@ def calculate_pushrim_kinetics_biofeedback( final_frequency = float(N_POINTS) / (ts.time[-1] - ts.time[0]) ts = ktk.filters.butter(ts, final_frequency / 2) ts.resample(final_frequency, in_place=True) + + ts.data["Ftot"][ts.isnan("Ftot")] = 0.0 + out["FtotCurve"] = ts.data["Ftot"].tolist() if show_plot: diff --git a/src/main.py b/src/main.py index dc9d018..8296576 100644 --- a/src/main.py +++ b/src/main.py @@ -31,11 +31,15 @@ import data_logging from python_bridge import GODOT_TO_PYTHON_PORT, IP, Receiver, sender + + + _running_commands: dict[str, dict[str, Any]] = {} def _send_ready() -> None: """Send ready to Godot.""" + print("Ready.") sender.send({"command": "ready", "data": []}) @@ -94,7 +98,13 @@ def _test(arg1: str, arg2: int) -> None: _running_commands.pop(command) elif run_mode == "once": - COMMAND_MAPPING[command](**command_dict["args"]) + try: + COMMAND_MAPPING[command](**command_dict["args"]) + except Exception as e: + print("======================") + print(f"Exception in command {command} with args {args}.") + print("Traceback:") + print(e) else: raise ValueError("frequency must be 'start', 'stop' or 'once'") @@ -105,7 +115,13 @@ def _test(arg1: str, arg2: int) -> None: # Execute every repeating command for command in _running_commands: - COMMAND_MAPPING[command](**_running_commands[command]["args"]) + try: + COMMAND_MAPPING[command](**_running_commands[command]["args"]) + except Exception as e: + print("======================") + print(f"Exception in command {command} with args {args}.") + print("Traceback:") + print(e) # Quit os._exit(0) diff --git a/src/python_bridge.py b/src/python_bridge.py index e4bbb40..735884b 100644 --- a/src/python_bridge.py +++ b/src/python_bridge.py @@ -18,11 +18,16 @@ import json import socket from typing import Any +from itertools import cycle +import time + IP = "127.0.0.1" GODOT_TO_PYTHON_PORT = 4243 PYTHON_TO_GODOT_PORT = 4242 DATA_SIZE = 1024 # bytes +MAX_SEND_RATE = 10 # Max number of data sent per second + class Receiver: @@ -89,6 +94,9 @@ def __init__(self, ip: str, port: int): self.ip = ip self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self._spinner = cycle("|/-\\") + self._last_time = time.time() + def send( self, @@ -106,8 +114,15 @@ def send( """ json_message = json.dumps(data).encode("utf-8") + + while(_time := time.time() < self._last_time + 1/MAX_SEND_RATE): + time.sleep(1/MAX_SEND_RATE) + self._last_time = _time + self.socket.sendto(json_message, (self.ip, self.port)) - print(f"Sending {data}") + + # Make the spinner advance + print(next(self._spinner), end="\r", flush=True) # Create a sender instance to be imported by the different modules From fa495466e3459591cc90d2d37bd3412caf69fb9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Che=CC=81nier?= Date: Wed, 2 Sep 2026 11:19:53 -0400 Subject: [PATCH 05/10] [26-create-a-new-biofeedback-module-for-the-propulsion-force] Started wheelsims/#78 --- src/biofeedback_pushrim_kinetics.py | 14 ++---- src/main.py | 67 +++++++++++------------------ 2 files changed, 28 insertions(+), 53 deletions(-) diff --git a/src/biofeedback_pushrim_kinetics.py b/src/biofeedback_pushrim_kinetics.py index 3974f3f..e2b120a 100644 --- a/src/biofeedback_pushrim_kinetics.py +++ b/src/biofeedback_pushrim_kinetics.py @@ -40,16 +40,10 @@ def connect(self, ip: str) -> None: else: self.nw = NextWheel(ip) - def process(self) -> None: + def process(self) -> dict: """Process data and send back to Godot, called regularly.""" nextwheel_data = self.nw.fetch() - processed_data = calculate_pushrim_kinetics_biofeedback(nextwheel_data) - sender.send( - { - "command": "biofeedback_pushrim_kinetics_process", - "data": processed_data, - } - ) + return calculate_pushrim_kinetics_biofeedback(nextwheel_data) # %% Public interface for main.py @@ -63,9 +57,9 @@ def connect(ip: str) -> None: pkb.connect(ip) -def process(**kwargs) -> None: +def process(**kwargs) -> dict: """Run the process once.""" - pkb.process() + return pkb.process() # %% Processing functions diff --git a/src/main.py b/src/main.py index 8296576..305e65a 100644 --- a/src/main.py +++ b/src/main.py @@ -25,32 +25,26 @@ import os from collections.abc import Callable from typing import Any +import time +import traceback import biofeedback import biofeedback_pushrim_kinetics as bf_pk import data_logging from python_bridge import GODOT_TO_PYTHON_PORT, IP, Receiver, sender + # How many seconds to sleep before polling UDP again once it's empty +SLEEP_TIME_ON_EMPTY_UDP_BUFFER = 1/60 # s -_running_commands: dict[str, dict[str, Any]] = {} -def _send_ready() -> None: - """Send ready to Godot.""" - print("Ready.") - sender.send({"command": "ready", "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] = { @@ -71,57 +65,44 @@ 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"}) stay_in_loop = True # Listening Godot requests while True: # Execute every command in the UDP buffer while command_dict := receiver.receive(): + print(command_dict) command = command_dict["command"] - run_mode = command_dict["run_mode"] - args = command_dict["args"] + kwargs = command_dict["kwargs"] + command_id = command_dict["id"] - print(f"{run_mode} : {command} {args}") + print(f"{command} {kwargs}") if command == "close": # Close now stay_in_loop = False break - 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) + 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() - elif run_mode == "once": - try: - COMMAND_MAPPING[command](**command_dict["args"]) - except Exception as e: - print("======================") - print(f"Exception in command {command} with args {args}.") - print("Traceback:") - print(e) + # Send back the return value + sender.send({"id": command_id, "value": return_value}) - else: - raise ValueError("frequency must be 'start', 'stop' or 'once'") # Do not execute repeating commands after shutdown request if not stay_in_loop: break - # Execute every repeating command - for command in _running_commands: - try: - COMMAND_MAPPING[command](**_running_commands[command]["args"]) - except Exception as e: - print("======================") - print(f"Exception in command {command} with args {args}.") - print("Traceback:") - print(e) + # Wait some time before checking if a new request was received + time.sleep(SLEEP_TIME_ON_EMPTY_UDP_BUFFER) + # Quit os._exit(0) From 1f28b43f2c0197a59fc74b023559fdbfd73253a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Che=CC=81nier?= Date: Wed, 2 Sep 2026 14:40:19 -0400 Subject: [PATCH 06/10] [26-create-a-new-biofeedback-module-for-the-propulsion-force] Working biofeedback_pushrim_kinetics (begin), working datalog, with code quality check. However biofeedback (kinematics) is very complex and is difficult to adapt for now. --- src/biofeedback_pushrim_kinetics.py | 1 - src/data_logging.py | 10 ++++++---- src/main.py | 26 +++++++++++--------------- src/python_bridge.py | 16 ---------------- tests/test_datalog.py | 20 ++++++++++++-------- tests/test_python_bridge.py | 12 ++++++------ 6 files changed, 35 insertions(+), 50 deletions(-) diff --git a/src/biofeedback_pushrim_kinetics.py b/src/biofeedback_pushrim_kinetics.py index e2b120a..f5cc7a3 100644 --- a/src/biofeedback_pushrim_kinetics.py +++ b/src/biofeedback_pushrim_kinetics.py @@ -9,7 +9,6 @@ from nextwheel import NextWheel from nextwheel_dummy import NextWheel as NextWheelDummy -from python_bridge import sender TIME_SPAN = 5 # Number of seconds to show on the rolling plot N_POINTS = 300 # Number of points in the rolling plot 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 305e65a..5e22523 100644 --- a/src/main.py +++ b/src/main.py @@ -23,22 +23,19 @@ """ import os -from collections.abc import Callable -from typing import Any import time import traceback +from collections.abc import Callable +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 - # How many seconds to sleep before polling UDP again once it's empty -SLEEP_TIME_ON_EMPTY_UDP_BUFFER = 1/60 # s - - - - +# 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 _test(arg1: int, arg2: int) -> list: @@ -65,27 +62,27 @@ def _test(arg1: int, arg2: int) -> list: # Create the receiver receiver = Receiver(ip=IP, port=GODOT_TO_PYTHON_PORT, timeout=0.0) # Send "ready" to Godot - sender.send({"id":"ready"}) + sender.send({"id": "ready", "value": None}) + print("Ready.") stay_in_loop = True # Listening Godot requests while True: # Execute every command in the UDP buffer while command_dict := receiver.receive(): - print(command_dict) command = command_dict["command"] kwargs = command_dict["kwargs"] command_id = command_dict["id"] - print(f"{command} {kwargs}") - if command == "close": # Close now stay_in_loop = False break try: - return_value = COMMAND_MAPPING[command](**command_dict["kwargs"]) + return_value = COMMAND_MAPPING[command]( + **command_dict["kwargs"] + ) except Exception: return_value = None print("======================") @@ -94,7 +91,7 @@ def _test(arg1: int, arg2: int) -> list: # 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 stay_in_loop: @@ -103,6 +100,5 @@ def _test(arg1: int, arg2: int) -> list: # 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/python_bridge.py b/src/python_bridge.py index 735884b..f5b6ea5 100644 --- a/src/python_bridge.py +++ b/src/python_bridge.py @@ -18,16 +18,11 @@ import json import socket from typing import Any -from itertools import cycle -import time - IP = "127.0.0.1" GODOT_TO_PYTHON_PORT = 4243 PYTHON_TO_GODOT_PORT = 4242 DATA_SIZE = 1024 # bytes -MAX_SEND_RATE = 10 # Max number of data sent per second - class Receiver: @@ -94,9 +89,6 @@ def __init__(self, ip: str, port: int): self.ip = ip self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - self._spinner = cycle("|/-\\") - self._last_time = time.time() - def send( self, @@ -114,15 +106,7 @@ def send( """ json_message = json.dumps(data).encode("utf-8") - - while(_time := time.time() < self._last_time + 1/MAX_SEND_RATE): - time.sleep(1/MAX_SEND_RATE) - self._last_time = _time - self.socket.sendto(json_message, (self.ip, self.port)) - - # Make the spinner advance - print(next(self._spinner), end="\r", flush=True) # Create a sender instance to be imported by the different modules 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..06125d4 100644 --- a/tests/test_python_bridge.py +++ b/tests/test_python_bridge.py @@ -43,22 +43,22 @@ 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] except Exception as e: raise e From 3973c912d8a85cdcab633d556d33ac8f85cb1e75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Che=CC=81nier?= Date: Thu, 10 Sep 2026 09:33:18 -0400 Subject: [PATCH 07/10] [26-create-a-new-biofeedback-module-for-the-propulsion-force] Adapting bioffedback to new new python bridge --- src/biofeedback.py | 70 ++-------------------------------------------- 1 file changed, 3 insertions(+), 67 deletions(-) diff --git a/src/biofeedback.py b/src/biofeedback.py index 82e5f67..c9a0c9d 100644 --- a/src/biofeedback.py +++ b/src/biofeedback.py @@ -592,56 +592,6 @@ def _send_data_godot( 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] @@ -800,11 +750,8 @@ def _execute_analysis_pipeline( LIMIT_DURATION_CURRENT_WINDOW: float, ) -> tuple[float, float]: """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 +761,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"], @@ -831,17 +777,7 @@ def _execute_analysis_pipeline( kinematics_data["cycles"], ) - end_time = time.time() - - _runtime_state["new_cycle_log"] = _print_log( - _runtime_state["new_cycle_log"], - kinematics_data["cycles"], - _runtime_state["current_window_data"], - end_time, - start_time, - ) - - return start_time, end_time + return # %% Main From 232b0e035d47083d81e7fed8a3d2ee2bfc23208e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laboratoire=20de=20recherche=20en=20mobilit=C3=A9=20et=20s?= =?UTF-8?q?yst=C3=A8mes=20adapt=C3=A9s?= Date: Thu, 10 Sep 2026 11:35:05 -0400 Subject: [PATCH 08/10] Mainly doc modification --- src/main.py | 29 +++++++++++++++++++---------- tests/test_python_bridge.py | 3 +++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/main.py b/src/main.py index 5e22523..9b776e7 100644 --- a/src/main.py +++ b/src/main.py @@ -3,25 +3,32 @@ 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. -For run_mode == "stop", the function listed in COMMAND_MAPPING[command] stops -being executed consinuously. +The script returns values using JSON strings of this form: + { + "id": str, + "value": Any + } -Command "close" is reserved for closing the python bridge. +where id is the same as it was received, and value is the function's +return value. """ +print("Initializing wheelsims_analysis...") + +# ruff: disable[E402] +# because we want the text to appear in the console without delay import os import time import traceback @@ -33,6 +40,8 @@ import data_logging from python_bridge import GODOT_TO_PYTHON_PORT, IP, Receiver, sender +# ruff: enable[E402] + # How many seconds to sleep before polling UDP again once it's empty SLEEP_TIME_ON_EMPTY_UDP_BUFFER = 1 / 60 # s SPINNER = cycle("|/-\\") diff --git a/tests/test_python_bridge.py b/tests/test_python_bridge.py index 06125d4..e006c21 100644 --- a/tests/test_python_bridge.py +++ b/tests/test_python_bridge.py @@ -60,6 +60,9 @@ def test_python_bridge(): 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 finally: From ac40826966a7c94909aded51bb052aaa3f142d08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laboratoire=20de=20recherche=20en=20mobilit=C3=A9=20et=20s?= =?UTF-8?q?yst=C3=A8mes=20adapt=C3=A9s?= Date: Thu, 10 Sep 2026 14:50:47 -0400 Subject: [PATCH 09/10] Removed Literals everywhere, it overcomplicated everything. Also now works back with Godot (even every feedback activated at the same time) --- src/biofeedback.py | 201 ++++++++++++++----------------------- src/main.py | 7 +- src/propulsion_patterns.py | 65 ++++-------- tests/test_biofeedback.py | 13 ++- 4 files changed, 108 insertions(+), 178 deletions(-) diff --git a/src/biofeedback.py b/src/biofeedback.py index c9a0c9d..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,65 +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 _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] @@ -666,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. @@ -748,10 +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.""" if _runtime_state["data"] is None: - return + return {} _runtime_state["current_window_data"] = _analyze_current_window( _runtime_state["data"], @@ -761,7 +684,7 @@ def _execute_analysis_pipeline( ) if _runtime_state["current_window_data"] is None: - return + return {} kinematics_data["cycles"] = _update_data_cycles( kinematics_data["cycles"], @@ -772,12 +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() + + label_push_pattern = str( + kinematics_data["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, + } + + _runtime_state["new_cycle_send"][side] += 1 - return + return data # %% Main @@ -816,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/main.py b/src/main.py index 9b776e7..8f62af0 100644 --- a/src/main.py +++ b/src/main.py @@ -25,7 +25,10 @@ """ -print("Initializing wheelsims_analysis...") +print("--------------------") +print(" WheelSims Analysis ") +print("--------------------") +print("Importing Python Modules...") # ruff: disable[E402] # because we want the text to appear in the console without delay @@ -55,7 +58,7 @@ def _test(arg1: int, arg2: int) -> list: COMMAND_MAPPING: dict[str, Callable] = { "test": _test, - "biofeedback_update": biofeedback.biofeedback_update, + "biofeedback_kinematics": biofeedback.biofeedback_kinematics, "biofeedback_stop": biofeedback.biofeedback_stop, "biofeedback_pushrim_kinetics_connect": bf_pk.connect, "biofeedback_pushrim_kinetics_process": bf_pk.process, 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/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 = [ From e9f4d3821893f525b47c9a66a5860d0433d95f90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laboratoire=20de=20recherche=20en=20mobilit=C3=A9=20et=20s?= =?UTF-8?q?yst=C3=A8mes=20adapt=C3=A9s?= Date: Thu, 10 Sep 2026 16:13:37 -0400 Subject: [PATCH 10/10] Better resampling in biofeedback_pushrim_kinetics --- src/biofeedback_pushrim_kinetics.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/biofeedback_pushrim_kinetics.py b/src/biofeedback_pushrim_kinetics.py index f5cc7a3..9adddfe 100644 --- a/src/biofeedback_pushrim_kinetics.py +++ b/src/biofeedback_pushrim_kinetics.py @@ -14,6 +14,7 @@ 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 @@ -38,6 +39,7 @@ def connect(self, ip: str) -> None: 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.""" @@ -86,11 +88,24 @@ def calculate_pushrim_kinetics_biofeedback( - "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 ) @@ -111,7 +126,6 @@ def calculate_pushrim_kinetics_biofeedback( pass # Calculate parameters - out: dict[str, Any] = {} Fpeak: list[float] = [] n_pushes = ts.count_events("push") if n_pushes >= N_PUSHES: @@ -126,13 +140,7 @@ def calculate_pushrim_kinetics_biofeedback( else: out["Fpeak"] = np.mean(Fpeak) - # Equal number of points - ts.resample( - np.linspace(ts.time[0], ts.time[-1], len(ts.time)), in_place=True - ) - final_frequency = float(N_POINTS) / (ts.time[-1] - ts.time[0]) - ts = ktk.filters.butter(ts, final_frequency / 2) ts.resample(final_frequency, in_place=True) ts.data["Ftot"][ts.isnan("Ftot")] = 0.0