November 2023
Forschung

Gait Analysis with 29 lines of Python code – programming with the OpenGo text export

Robert

Erfahren Sie, wie 29 Zeilen Python-Code die Gangdaten von Moticons OpenGo-Sensor-Einlagen analysieren können. Zeichnen Sie programmgesteuert Kurven der Gesamtkraft pro Schritt für verschiedene Gehgeschwindigkeiten.
moticon opengo software in comparison view showing ground reaction forces and step events of 3 different gait speeds

Teile via

Themen in diesem Artikel

This article describes a full workflow for programmatically analyzing gait data collected using Moticon’s OpenGo Sensor Insoles, from the recording of data to the creation of a step analysis plot. We will see how 29 lines of Python code are sufficient to achieve the following: For walking data collected at three different speeds, plot the per-step total force curves for each of the walking speeds, separately.

workflow from collecting gait data with Moticon OpenGo sensor insoles to plotting step-wise ground reaction forces

Collecting and Analyzing Gait Data

We will use a Python script to work on text files exported from the OpenGo Software. The following functions of the OpenGo Software will simplify our processing pipeline:

  • The text export automatically synchronizes the left and right side sensor insole data to a common time axis. As a result, we obtain a “tabular” output where each time point (= data row) has a left and right sensor insole data sample.
  • By running the gait report, a step detection algorithm automatically detects step events, and stores these step events in a data channel along with the sensor insole data. The text export output will then contain the step event channels (for left and right, separately), so our Python script can make use of them.

Let’s get started! The required resources are summarized in the subsequent section.

  1. First, collect some data of short walking trials. Using tags in the OpenGo App, we collect data of normal, slow, and fast walking in three separate measurements (see above screenshot).
  2. After recording a short trial for each of the walking speeds, we transfer the data from the OpenGo Sensor Insoles to the OpenGo Software. The tags can be seen in the Analyze screen’s listview in the column “Tag”.
  3. We use the gait report function (Report section) for automatically detecting steps. By selecting the root folder, the gait report runs on all measurements. The gait report output itself is not of interest here, just the detected steps.
  4. To inspect the detected step events, turn on the “left steps” and “right steps” channels (under “Other”) in the line graph widget of the Analyze screen. The step events are encoded as integer values for left and right steps, separately. They are shown as dashed curves here:
moticon opengo software in comparison view showing ground reaction forces and step events of 3 different gait speeds
  1. We can now export all data as text files (.txt), using the text export function of the Report section. The text files will also contain the detected step events as separate data channels (columns). Note: If a measurement is edited by the cut/crop tools, the step events are removed and the gait report must be re-run.

Let us now create a Python script in the same folder as the exported text files. With 29 lines of Python code, as shown in below Code Example 1, you can create the following diagram. It shows how the total force curve (in terms of its shape, duration, and force peaks) during the ground contact depends on the walking speed:

plotted vertical ground reaction force curves from 3 different gait speeds created from Moticon OpenGo raw sensor insole data

Required Resources

The above-described gait analysis workflow requires the following:

[How to install Git from the original Git website, start a local repository, check in a simple Python ‚hello world‘ script, and run it in the Git bash?](https://chat.openai.com/share/10ea7ec4-de10-434d-85a1-1491e570c035)

Benefits of script-based data analysis

With the workflow described above, we would like to encourage researchers with little programming experience to go from spreadsheets to Python scripts. This provides major benefits:

  • Reproducibility: With spreadsheets, the cleaning of data, sequence extraction, computation of intermediate output, and calculation of final results (e.g. statistics) is hard to reproduce and document. In contrast, a script-based approach can read in the same raw input files each time the procedure is started, perform a chain of documented data processing steps, and provide plots and final statistics in one go. It is therefore transparent and easy to repeat.
  • Project iterations and agility: Projects using a spreadsheet-based data analysis often wait with the data post-processing and analysis until the data collection phase has been completed. This comes with various drawbacks. In contrast, a script-based analysis supports the exact opposite: The script development can start with the first available (exploratory) dataset, and its results may even suggest an iteration of the experimental setup. Furthermore, the automation of repetitive tasks makes it much easier to follow different analysis paths in a shorter amount of time.
  • Version control: Script-based analysis allows you to write code that can be version-controlled using tools like Git. This makes it easier to track changes, collaborate with others, and reproduce results. Different versions of the code can be re-applied whenever new/additional measurement data is available.
  • Extensibility: You can easily extend script-based analysis by incorporating machine learning, statistical modeling, and other advanced techniques to gain deeper insights from your data. Follow-up projects can benefit from code created in previous work, and extensive software libraries tackling a scientific field can be built over time.
  • Scalability: Script-based analysis can handle large datasets and complex analyses more efficiently than spreadsheets.
Code example 1
				
					import matplotlib.pyplot as plt import numpy as np
import os

for i, f in enumerate([fn for fn in os.listdir(".") if fn.endswith(".txt")]):
 # Text files from OpenGo Software, painted with Matplotlib standard colors.
 data: np.array = np.genfromtxt(f, delimiter="t", dtype=None, comments="#")
 color: str = [c[ color=""] for c in plt.rcParams['axes.prop_cycle']][i]

 # Extract the tag. It's in line 8 of the text export file, after a colon.
 with open(f, "r") as file:
 tag: str = file.readlines()[7].split(":")[1].strip()

 # In column 53 (index 52), an integer value encodes the detected left gait events.
 heel_strike_idx: np.array = np.where(data[:, 52] == 11)[0] # 11 = left heel strike
 toe_off_idx: np.array = np.where(data[:, 52] == 15)[0] # 15 = left toe off

 # Column 24 (index 23) contains the total force of the left side.
 for h, t in zip(heel_strike_idx, toe_off_idx):
 plt.plot(data[h-5:t+5, 0] - data[h-5, 0], data[h-5:t+5, 23], label=tag, color=color)

plt.title("Total force curve of all detected left steps")
plt.xlabel("Time (s)")
plt.ylabel("Total force (N)")
plt.grid(True)
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys()) # Avoid duplicate legend entries
plt.savefig("gait_analysis.png")
				
			
Code example 2
Code example 3

Select your desired system

The cutting edge test based outcome assessment system for health professionals and trainers

The most versatile toolkit for free data acquisition and comprehensive analytics in research

Have a general inquiry?

Write us a message for general questions about products and solutions or if you’d like to discuss other topics.


Wähle Deine Produktelinie

Mobile Ganganalysen und sportmotorische Tests für Trainer und Therapeuten – objektiv und effizient.

Das flexible System für freie Datenerfassung und fortgeschrittene Analysen in der Forschung.

Du möchtest eine Anfrage stellen?

Schreibe uns eine Nachricht zu allgemeinen Fragen über Produkte oder zu anwendungsbezogenen Themen, die Du besprechen möchtest.


Das Formular wurde erfolgreich gesendet.

Wir werden uns in Kürze mit dir in Verbindung setzen.

moticon-rego-sensor-insole-live-event

Immer einen Schritt voraus!

Abonniere unseren Newsletter für die neuesten Informationen zu Fallstudien, Webinaren, Produkt-Updates und Neuigkeiten bei Moticon

Hole dir Unterstützung

Finde Antworten zu den häufigsten Fragen in unseren FAQ

Beschreibe Dein Problem so detailliert wie möglich. Hänge Screenshots oder Daten an, sofern das hilfreich ist.


Need help?
Want a live demo?
Interested in prices?
Want to say hello?
Always just a call away
+49 89 2000 301 60
Du brauchst Unterstützung?
Du möchtest eine Live Demo?
Interessiert an Preisen?
Du hast Fragen?
Nur einen Anruf entfernt
+49 89 2000 301 60

The form was sent successfully.

You will be contacted shortly.

Get support

Check our FAQ database for answers to frequently asked questions

Describe your issue in as much detail as possible. Include screenshots or files if applicable.