Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
261 changes: 76 additions & 185 deletions src/biofeedback.py

Large diffs are not rendered by default.

153 changes: 153 additions & 0 deletions src/biofeedback_pushrim_kinetics.py
Original file line number Diff line number Diff line change
@@ -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
10 changes: 6 additions & 4 deletions src/data_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down Expand Up @@ -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])
]
Expand Down Expand Up @@ -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),
Expand Down
126 changes: 64 additions & 62 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
Loading