Skip to main content

A minimalistic toolbox for extracting features from sport activity files

Project description

sport-activities-features --- A minimalistic toolbox for extracting features from sports activity files written in Python

PyPI Version PyPI - Python Version PyPI - Downloads Fedora package AUR package Packaging status Downloads GitHub license Documentation Status

GitHub repo size GitHub commit activity Average time to resolve an issue Percentage of issues still open All Contributors

DOI

๐Ÿ” Detailed insights โ€ข ๐Ÿ“ฆ Installation โ€ข ๐Ÿ“ฎ API โ€ข ๐Ÿ’ป Graphical User Interface โ€ข ๐ŸŒฆ๏ธ Historical weather data โ€ข ๐Ÿงฉ Overpass API, Open Elevation API & OpenTopoData integration ๐Ÿš€ Examples โ€ข ๐Ÿ”‘ License โ€ข ๐Ÿ“„ Cite us โ€ข ๐Ÿ“– Further read โ€ข ๐Ÿ”— Related frameworks โ€ข ๐Ÿซ‚ Contributors

Unleashing the Power of Sports Activity Analysis: A Framework Beyond Ordinary Metrics ๐Ÿš€

Prepare to dive into the thrilling world of sports activity analysis, where hidden geographic, topological, and personalized data await their grand unveiling. In this captivating journey, we embark on a quest to extract the deepest insights from the wealth of information generated by monitoring sports activities. Brace yourself for a framework that transcends the limitations of conventional analysis techniques. ๐Ÿ’ช๐Ÿ”

Traditional approaches often rely on integral metrics like total duration, total distance, and average heart rate, but they fall victim to the dreaded "overall metrics problem." These metrics fail to capture the essence of sports activities, omitting crucial components and leading to potentially flawed and misleading conclusions. They lack the ability to recognize distinct stages and phases of the activity, such as the invigorating warm-up, the endurance-testing main event, and the heart-pounding intervals. โฑ๏ธ๐Ÿšดโ€โ™€๏ธ๐Ÿ“ˆ

Fortunately, our sport-activities-framework rises above these limitations, revealing a comprehensive panorama of your sports activity files. This framework combines the power of identification and extraction methods to unlock a treasure trove of valuable data. Picture this :camera: : effortlessly identifying the number of hills, extracting average altitudes of these remarkable formations, measuring the total distance conquered on those inclines, and even deriving climbing ratios for a true measure of accomplishment (total distance of hills vs. total distance). But that's just the tip of the iceberg! The framework seamlessly integrates a multitude of extensions, including historical weather parsing, statistical evaluations, and ex-post visualizations that bring your data to life. ๐Ÿ—ป๐Ÿ“Š๐ŸŒฆ๏ธ

For those seeking to venture further, we invite you to explore the realms of scientific papers on data mining that delve into these captivating topics. Discover how our framework complements the world of generating and predicting automated sport training sessions, creating a harmonious synergy between theory and practice. ๐Ÿ“š๐Ÿ”ฌ๐Ÿ’ก

๐Ÿ” Detailed insights

Prepare to be astounded by the capabilities of the sport-activities-features framework. It effortlessly handles TCX & GPX activity files and harnesses the power of the Overpass API nodes. Presenting the range of functions at your disposal:

  • Unleash the integral metrics: From total distance to total duration and even calorie count, witness the extraction of these vital statistics with a single glance. ๐Ÿ“โฐ๐Ÿ”ฅ (See example)

  • Conquer the peaks: Ascend to new heights by extracting topographic features like the number of hills, their average altitudes, the total distance covered on these majestic slopes, and the thrilling climbing ratio. Prepare for a breathtaking adventure! โ›ฐ๏ธ๐Ÿ“ˆ๐Ÿง—โ€โ™‚๏ธ (See example)

  • Embark on a visual journey: Immerse yourself in the beauty of your accomplishments as you plot the identified hills on a mesmerizing map. Witness the landscape come alive before your eyes. ๐Ÿ—บ๏ธ๐Ÿž๏ธ๐Ÿ–Œ๏ธ (See example)

  • Embrace the rhythm of intervals: Explore the intervals within your sports activities, uncovering their numbers, durations, distances, and heart rates. Unveil the heartbeat of your performance! ๐Ÿƒโ€โ™€๏ธ๐Ÿ“Š๐Ÿ’“ (See example)

  • Calculate the training loads: Dive deep into the intricate world of training loads and discover the Banister TRIMP and Lucia TRIMP methods. Gain invaluable insights into optimizing your training regimen. ๐Ÿ“ˆโš–๏ธ๐Ÿ‹๏ธโ€โ™‚๏ธ (See example)

  • Weather the storm: Unlock the power of historical weather data from external services, adding a fascinating layer of context to your sports activities. โ˜€๏ธ๐ŸŒง๏ธโ›ˆ๏ธ

  • Unveil the secrets within coordinates: Explore the integral metrics of your activities within specific geographical areas, uncovering valuable data on distance, heart rate, and speed. Peer into the depths of your performance! ๐ŸŒ๐Ÿ“๐Ÿ“‰ (See example)

  • Embrace randomness: Extract activities from CSV files and indulge in the excitement of randomly selecting a specific number of activities. Embrace the element of surprise! ๐ŸŽฒ๐Ÿ“‚๐ŸŽ‰ (See example)

  • Conquer the dead ends: Unravel the mysteries of your sports activities by identifying the dead ends. Prepare to navigate the uncharted territories of your performance! ๐Ÿšง๐Ÿ—บ๏ธ๐Ÿ” (See example)

  • Unlock the format: Seamlessly convert TCX files to GPX, opening doors to even more possibilities. Adapt and conquer! โš™๏ธ๐Ÿ”„โœจ (See example)

And that's just the beginning! The sport-activities-framework holds countless other features, awaiting your exploration. Brace yourself for an exhilarating journey of discovery, where the ordinary becomes extraordinary, and your sports activities come alive like never before. ๐ŸŒŸ๐Ÿ”ฅ๐Ÿƒโ€โ™‚๏ธ

The framework comes with two (testing) benchmark datasets, which are freely available to download from: DATASET1, DATASET2.

๐Ÿ“ฆ Installation

pip

Install sport-activities-features with pip:

pip install sport-activities-features

Alpine Linux

To install sport-activities-features on Alpine, use:

$ apk add py3-sport-activities-features

Fedora Linux

To install sport-activities-features on Fedora, use:

$ dnf install python3-sport-activities-features

Arch Linux

To install sport-activities-features on Arch Linux, please use an AUR helper:

$ yay -Syyu python-sport-activities-features

๐Ÿ“ฎ API

There is a simple API for remote work with the sport-activities-features package available here.

๐Ÿ’ป Graphical User Interface

There is a simple Graphical User Interface for the sport-activities-features package available here.

๐ŸŒฆ๏ธ Historical weather data

Weather data parsed is collected from the Visual Crossing Weather API. Please note that this is an external unaffiliated service, and users must register to use the API. The service has a free tier (1000 Weather reports/day) but is otherwise operating on a pay-as-you-go model. For pricing and terms of use, please read the official documentation of the API provider.

๐Ÿงฉ Overpass API, Open Elevation API & OpenTopoData integration

Without performing activities, we can use the OpenStreetMap for the identification of hills, total ascent, and descent. This is done using the Overpass API which is a read-only API that allows querying of OSM map data. In addition to that altitude, data is retrieved by using the Open-Elevation API or OpenTopoData API which are open-source and free alternatives to the Google Elevation API. Both of the solutions can be used by using free publicly acessible APIs (Overpass, Open-Elevation, OpenTopoData) or can be self hosted on a server or as a Docker container (Overpass, Open-Elevation, OpenTopoData).

๐Ÿš€ Examples

Reading files

(*.TCX)

from sport_activities_features.tcx_manipulation import TCXFile

# Class for reading TCX files
tcx_file=TCXFile()
data = tcx_file.read_one_file("path_to_the_file") # Represents data as dictionary of lists

# Alternative choice
data = tcx_file.read_one_file("path_to_the_file", numpy_array= True) # Represents data as dictionary of numpy.arrays

(*.GPX)

from sport_activities_features.gpx_manipulation import GPXFile

# Class for reading GPX files
gpx_file=GPXFile()

# Read the file and generate a dictionary with 
data = gpx_file.read_one_file("path_to_the_file") # Represents data as dictionary of lists

# Alternative choice
data = gpx_file.read_one_file("path_to_the_file", numpy_array= True) # Represents data as dictionary of numpy.arrays

Extraction of topographic features

from sport_activities_features.hill_identification import HillIdentification
from sport_activities_features.tcx_manipulation import TCXFile
from sport_activities_features.topographic_features import TopographicFeatures
from sport_activities_features.plot_data import PlotData

# Read TCX file
tcx_file = TCXFile()
activity = tcx_file.read_one_file("path_to_the_file")

# Detect hills in data
Hill = HillIdentification(activity['altitudes'], 30)
Hill.identify_hills()
all_hills = Hill.return_hills()

# Extract features from data
Top = TopographicFeatures(all_hills)
num_hills = Top.num_of_hills()
avg_altitude = Top.avg_altitude_of_hills(activity['altitudes'])
avg_ascent = Top.avg_ascent_of_hills(activity['altitudes'])
distance_hills = Top.distance_of_hills(activity['positions'])
hills_share = Top.share_of_hills(distance_hills, activity['total_distance'])

Extraction of intervals

import sys
sys.path.append('../')

from sport_activities_features.interval_identification import IntervalIdentificationByPower, IntervalIdentificationByHeartrate
from sport_activities_features.tcx_manipulation import TCXFile

# Reading the TCX file
tcx_file = TCXFile()
activity = tcx_file.read_one_file("path_to_the_data")

# Identifying the intervals in the activity by power
Intervals = IntervalIdentificationByPower(activity["distances"], activity["timestamps"], activity["altitudes"], 70)
Intervals.identify_intervals()
all_intervals = Intervals.return_intervals()

# Identifying the intervals in the activity by heart rate
Intervals = IntervalIdentificationByHeartrate(activity["timestamps"], activity["altitudes"], activity["heartrates"])
Intervals.identify_intervals()
all_intervals = Intervals.return_intervals()

Parsing of Historical weather data from an external service

from sport_activities_features import WeatherIdentification
from sport_activities_features import TCXFile

# Read TCX file
tcx_file = TCXFile()
tcx_data = tcx_file.read_one_file("path_to_file")

# Configure visual crossing api key
visual_crossing_api_key = "weather_api_key" # https://www.visualcrossing.com/weather-api

# Explanation of elements - https://www.visualcrossing.com/resources/documentation/weather-data/weather-data-documentation/
weather = WeatherIdentification(tcx_data['positions'], tcx_data['timestamps'], visual_crossing_api_key)
weatherlist = weather.get_weather(time_delta=30)
tcx_weather = weather.get_average_weather_data(timestamps=tcx_data['timestamps'],weather=weatherlist)
# Add weather to TCX data
tcx_data.update({'weather':tcx_weather})

The weather list is of the following type:

     [
        {
            "temperature": 14.3,
            "maximum_temperature": 14.3,
            "minimum_temperature": 14.3,
            "wind_chill": null,
            "heat_index": null,
            "solar_radiation": null,
            "precipitation": 0.0,
            "sea_level_pressure": 1021.6,
            "snow_depth": null,
            "wind_speed": 6.9,
            "wind_direction": 129.0,
            "wind_gust": null,
            "visibility": 40.0,
            "cloud_cover": 54.3,
            "relative_humidity": 47.6,
            "dew_point": 3.3,
            "weather_type": "",
            "conditions": "Partially cloudy",
            "date": "2016-04-02T17:26:09+00:00",
            "location": [
                46.079871179535985,
                14.738618675619364
            ],
            "index": 0
        }, ...
    ]

Extraction of integral metrics

import sys
sys.path.append('../')

from sport_activities_features.tcx_manipulation import TCXFile

# Read TCX file
tcx_file = TCXFile()

integral_metrics = tcx_file.extract_integral_metrics("path_to_the_file")

print(integral_metrics)

Weather data extraction

from sport_activities_features.weather_identification import WeatherIdentification
from sport_activities_features.tcx_manipulation import TCXFile

#read TCX file
tcx_file = TCXFile()
tcx_data = tcx_file.read_one_file("path_to_the_file")

#configure visual crossing api key
visual_crossing_api_key = "API_KEY" # https://www.visualcrossing.com/weather-api

#return weather objects
weather = WeatherIdentification(tcx_data['positions'], tcx_data['timestamps'], visual_crossing_api_key)
weatherlist = weather.get_weather()

Using Overpass queried Open Street Map nodes

import overpy
from sport_activities_features.overpy_node_manipulation import OverpyNodesReader

# External service Overpass API (https://wiki.openstreetmap.org/wiki/Overpass_API) (can be self-hosted)
overpass_api = "https://lz4.overpass-api.de/api/interpreter"

# External service Open Elevation API (https://api.open-elevation.com/api/v1/lookup) (can be self-hosted)
open_elevation_api = "https://api.open-elevation.com/api/v1/lookup"

# OSM Way (https://wiki.openstreetmap.org/wiki/Way)
open_street_map_way = 164477980

overpass_api = overpy.Overpass(url=overpass_api)

# Get an example Overpass way
q = f"""(way({open_street_map_way});<;);out geom;"""
query = overpass_api.query(q)

# Get nodes of an Overpass way
nodes = query.ways[0].get_nodes(resolve_missing=True)

# Extract basic data from nodes (you can, later on, use Hill Identification and Hill Data Extraction on them)
overpy_reader = OverpyNodesReader(open_elevation_api=open_elevation_api)
# Returns {
#         'positions': positions, 'altitudes': altitudes, 'distances': distances, 'total_distance': total_distance
#         }
data = overpy_reader.read_nodes(nodes)

Extraction of data inside the area

import numpy as np
import sys
sys.path.append('../')

from sport_activities_features.area_identification import AreaIdentification
from sport_activities_features.tcx_manipulation import TCXFile

# Reading the TCX file.
tcx_file = TCXFile()
activity = tcx_file.read_one_file('path_to_the_data')

# Converting the read data to arrays.
positions = np.array([*activity['positions']])
distances = np.array([*activity['distances']])
timestamps = np.array([*activity['timestamps']])
heartrates = np.array([*activity['heartrates']])

# Area coordinates should be given in clockwise orientation in the form of 3D array (number_of_hulls, hull_coordinates, 2).
# Holes in area are permitted.
area_coordinates = np.array([[[10, 10], [10, 50], [50, 50], [50, 10]],
                             [[19, 19], [19, 21], [21, 21], [21, 19]]])

# Extracting the data inside the given area.
area = AreaIdentification(positions, distances, timestamps, heartrates, area_coordinates)
area.identify_points_in_area()
area_data = area.extract_data_in_area()

Identify interruptions

from sport_activities_features.interruptions.interruption_processor import InterruptionProcessor
from sport_activities_features.tcx_manipulation import TCXFile

"""
Identify interruption events from a TCX or GPX file.
"""

# read TCX file (also works with GPX files)
tcx_file = TCXFile()
tcx_data = tcx_file.read_one_file("path_to_the_data")

"""
Time interval = time before and after the start of an event
Min speed = Threshold speed to trigger an event/interruption (trigger when under min_speed)
overpass_api_url = Set to something self-hosted, or use a public instance from https://wiki.openstreetmap.org/wiki/Overpass_API
"""
interruptionProcessor = InterruptionProcessor(time_interval=60, min_speed=2,
                                              overpass_api_url="url_to_overpass_api")

"""
If classify is set to true, also discover if interruptions are close to intersections. Returns a list of [ExerciseEvent]
"""
events = interruptionProcessor.events(tcx_data, True)

Overpy (Overpass API) node manipulation

Generate TCXFile parsed like data object from overpy.Node objects

import overpy
from sport_activities_features.overpy_node_manipulation import OverpyNodesReader

# External service Overpass API (https://wiki.openstreetmap.org/wiki/Overpass_API) (can be self-hosted)
overpass_api = "https://lz4.overpass-api.de/api/interpreter"

# External service Open Elevation API (https://api.open-elevation.com/api/v1/lookup) (can be self-hosted)
open_elevation_api = "https://api.open-elevation.com/api/v1/lookup"

# OSM Way (https://wiki.openstreetmap.org/wiki/Way)
open_street_map_way = 164477980

overpass_api = overpy.Overpass(url=overpass_api)

# Get an example Overpass way
q = f"""(way({open_street_map_way});<;);out geom;"""
query = overpass_api.query(q)

# Get nodes of an Overpass way
nodes = query.ways[0].get_nodes(resolve_missing=True)

# Extract basic data from nodes (you can, later on, use Hill Identification and Hill Data Extraction on them)
overpy_reader = OverpyNodesReader(open_elevation_api=open_elevation_api)
# Returns {
#         'positions': positions, 'altitudes': altitudes, 'distances': distances, 'total_distance': total_distance
#         }
data = overpy_reader.read_nodes(nodes)

Missing elevation data extraction

from sport_activities_features import ElevationIdentification
from sport_activities_features import TCXFile

tcx_file = TCXFile()
tcx_data = tcx_file.read_one_file('path_to_file')

elevations = ElevationIdentification(tcx_data['positions'])
"""Adds tcx_data['elevation'] = eg. [124, 21, 412] for each position"""
tcx_data.update({'elevations':elevations})

Example of a visualization of the area detection

Area Figure

Example of visualization of dead-end identification

Dead End Figure

๐Ÿ”‘ License

This package is distributed under the MIT License. This license can be found online at http://www.opensource.org/licenses/MIT.

Disclaimer

This framework is provided as-is, and there are no guarantees that it fits your purposes or that it is bug-free. Use it at your own risk!

๐Ÿ“„ Cite us

I. Jr. Fister, L. Lukaฤ, A. Rajลกp, I. Fister, L. Peฤnik and D. Fister, "A minimalistic toolbox for extracting features from sport activity files", 2021 IEEE 25th International Conference on Intelligent Engineering Systems (INES), 2021, pp. 121-126, doi: 10.1109/INES52918.2021.9512927.

๐Ÿ“– Further read

[1] Awesome Computational Intelligence in Sports

๐Ÿ”— Related frameworks

[1] AST-Monitor: A wearable Raspberry Pi computer for cyclists

[2] TCXReader.jl: Julia package designed for parsing TCX files

[3] TCXWriter: A Tiny Library for writing/creating TCX files on Arduino

๐Ÿซ‚ Contributors

Thanks go to these wonderful people (emoji key):

alenrajsp
alenrajsp

๐Ÿ’ป โš ๏ธ ๐Ÿ’ก ๐Ÿ“– ๐Ÿค” ๐Ÿ› ๐Ÿšง
Iztok Fister Jr.
Iztok Fister Jr.

๐Ÿ’ป ๐Ÿ› โš ๏ธ ๐Ÿ’ก ๐Ÿ“– ๐Ÿค” ๐Ÿง‘โ€๐Ÿซ ๐Ÿ“ฆ ๐Ÿšง ๐Ÿ”ฃ
luckyLukac
luckyLukac

๐Ÿค” ๐Ÿ’ป ๐Ÿ› โš ๏ธ ๐Ÿ’ก
rhododendrom
rhododendrom

๐Ÿ’ป ๐ŸŽจ ๐Ÿ“– ๐Ÿค”
Luka Peฤnik
Luka Peฤnik

๐Ÿ’ป ๐Ÿ“– โš ๏ธ ๐Ÿ›
spelap
spelap

๐Ÿ’ป
Oromion
Oromion

๐Ÿšง ๐Ÿ›
Luka Koprivc
Luka Koprivc

๐Ÿ›
Nejc Graj
Nejc Graj

๐Ÿ›
MlinaricNejc
MlinaricNejc

๐Ÿ›
Tatookie
Tatookie

๐Ÿ’ป ๐Ÿ› โš ๏ธ ๐Ÿ’ก ๐Ÿšง
Zala Lahovnik
Zala Lahovnik

๐Ÿ“– ๐Ÿ’ป
Tadej Lahovnik
Tadej Lahovnik

๐Ÿ“–
HlisTilen
HlisTilen

๐Ÿ“–

This project follows the all-contributors specification. Contributions of any kind are welcome!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sport_activities_features-0.4.2.tar.gz (54.8 kB view details)

Uploaded Source

Built Distribution

sport_activities_features-0.4.2-py3-none-any.whl (57.1 kB view details)

Uploaded Python 3

File details

Details for the file sport_activities_features-0.4.2.tar.gz.

File metadata

  • Download URL: sport_activities_features-0.4.2.tar.gz
  • Upload date:
  • Size: 54.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.12.4 Linux/6.9.10-200.fc40.x86_64

File hashes

Hashes for sport_activities_features-0.4.2.tar.gz
Algorithm Hash digest
SHA256 2c0360b8ea071c22fb881e9eab5f0038d3a4e6992be328bc4d08be20835b14ce
MD5 01b094f54cf0d86a2f5e4aaa86affe6f
BLAKE2b-256 460c4ee6f799ea403c5304b6c15f561badb5036e9ed5a47f47bf8daeadeda3d2

See more details on using hashes here.

File details

Details for the file sport_activities_features-0.4.2-py3-none-any.whl.

File metadata

File hashes

Hashes for sport_activities_features-0.4.2-py3-none-any.whl
Algorithm Hash digest
SHA256 fee46b921bd09c746ea240e82a28a5200348bbf98936d5d9161d29079c4589eb
MD5 71d9cdb75098f00f62bca4f9a37ac6d5
BLAKE2b-256 ce0a04c33c02f66b8ab5e09d4df623b8aecb94704c20a188693c44f045d41538

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page