### Setup Python Environment with uv Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Install uv and then use it to pin a Python version and synchronize dependencies from pyproject.toml. Rerun with a different version for testing. ```bash uv python pin 3.11 uv sync ``` -------------------------------- ### get_all_lab_example_data_paths Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/data.rst Retrieves the file paths for all available lab example datasets. ```APIDOC ## get_all_lab_example_data_paths ### Description Returns a list of file paths pointing to the example datasets recorded in a lab environment. ### Function get_all_lab_example_data_paths ``` -------------------------------- ### Access Example IMU Data Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Import and use the function to get example IMU data within scripts or examples. ```python from mobgap.example_data import get_healthy_example_imu_data ``` -------------------------------- ### Install MobGap Locally from Cloned Repository Source: https://github.com/mobilise-d/mobgap/blob/main/README.md Clone the MobGap repository and install it locally using pip. This is useful if you encounter issues with the direct installation methods or want to work with the source code. ```bash git clone https://github.com/mobilise-d/mobgap.git cd mobgap pip install . ``` -------------------------------- ### Example Algorithm Class Structure Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/project_structure.md Demonstrates the structure of an algorithm class, including inheritance, docstring formatting, and initialization parameters. Use this as a template for new algorithms. ```python from typing import Any import pandas as pd from tpcp import cf from typing_extensions import Self, Unpack from mobgap.data_transform import EpflDedriftedGaitFilter from mobgap.data_transform.base import BaseFilter from mobgap.initial_contacts.base import BaseIcDetector, base_icd_docfiller @base_icd_docfiller class IcdIonescu(BaseIcDetector): """Implementation of the initial_contacts algorithm by McCamley et al. (2012) [1]_ modified by Ionescu et al. (2020) [2]_ The algorithm includes the following steps starting from vertical acceleration of the lower-back during a gait sequence: 1. Resampling: 100 Hz --> 40 Hz 2. Band-pass filtering --> lower cut-off: 0.15 Hz; higher cut-off: 3.14 Hz 3. Cumulative integral --> cumulative trapezoidal integration 4. Continuous Wavelet Transform (CWT) --> Ricker wavelet 5. Zero crossings detection 6. Detect peaks between zero crossings --> negative peaks = ICs This is based on the implementation published as part of the mobilised project [3]_ However, this implementation deviates from the original implementation in some places. For details, see the notes section and the examples. Parameters ---------- pre_filter A pre-processing filter to apply to the data before the initial_contacts algorithm is applied. cwt_width The width of the wavelet Other Parameters ---------------- %(other_parameters)s Attributes ---------- %(ic_list_)s Notes ----- Points of deviation from the original implementation and their reasons: - We use a different downsampling method, which should be "more" correct from a signal theory perspective, but will yield slightly different results. - We use a slightly different approach when it comes to the detection of the peaks between the zero crossings. However, the results of this step are identical to the matlab implementation. .. [1] J. McCamley, M. Donati, E. Grimpampi, C. Mazzà, "An enhanced estimate of initial contact and final contact instants of time using lower trunk inertial sensor data", Gait & Posture, vol. 36, no. 2, pp. 316-318, 2012. .. [2] A. Paraschiv-Ionescu, A. Soltani and K. Aminian, "Real-world speed estimation using single trunk IMU: methodological challenges for impaired gait patterns," 2020 42nd Annual International Conference of the IEEE Engineering in Medicine & Biology Society (EMBC), Montreal, QC, Canada, 2020, pp. 4596-4599, doi: 10.1109/EMBC44109.2020.9176281. .. [3] https://github.com/mobilise-d/Mobilise-D-TVS-Recommended-Algorithms/blob/master/ICDA/Library/SD_algo_AMC.m """. pre_filter: BaseFilter cwt_width: float # Some constants of the algorithms _INTERNAL_FILTER_SAMPLING_RATE_HZ: int = 40 def __init__(self, *, pre_filter: BaseFilter = cf(EpflDedriftedGaitFilter()), cwt_width: float = 9.0) -> None: self.pre_filter = pre_filter self.cwt_width = cwt_width @base_icd_docfiller def detect(self, data: pd.DataFrame, *, sampling_rate_hz: float, **_: Unpack[dict[str, Any]]) -> Self: """%(detect_short)s. %(detect_info)s Parameters ---------- %(detect_para)s %(detect_return)s """ # Setting the Other Parameters self.data = data self.sampling_rate_hz = sampling_rate_hz # Here is where the actual Algo implementation lives ... # Setting teh results self.ic_list_ = ... return self ``` -------------------------------- ### Install MobGap from Source using pip Source: https://github.com/mobilise-d/mobgap/blob/main/README.md Install the latest unreleased version of MobGap directly from its GitHub repository using pip. This command upgrades the installation if MobGap is already present. ```bash pip install "git+https://github.com/mobilise-d/mobgap.git" --upgrade ``` -------------------------------- ### Install MobGap using pip Source: https://github.com/mobilise-d/mobgap/blob/main/README.md Install the MobGap package using pip. Ensure you have a supported Python version (3.9 or higher) installed. ```bash pip install mobgap ``` -------------------------------- ### LabExampleDataset Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/data.rst An example dataset class for laboratory data. ```APIDOC ## LabExampleDataset ### Description This class serves as an example for handling laboratory-based gait datasets. ### Class LabExampleDataset ``` -------------------------------- ### Algorithm Class Structure Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/project_structure.md Illustrates the inheritance hierarchy for algorithm classes, starting from tpcp.Algorithm and progressing to base classes and specific algorithm implementations. ```python tpcp.Algorithm -> Basic setting of parameters | Base -> Basic interface to ensure all algos of the same type use the same input and outputs for their | action methods | | -> A improved version of an algorithm, when it does not make sense to toggle the improvement via an inputparameter on the algorithm ``` -------------------------------- ### Data Loading: LabExampleDataset / load_mobilised_matlab_format Source: https://context7.com/mobilise-d/mobgap/llms.txt Provides interfaces for loading example IMU data and participant metadata. `LabExampleDataset` offers a high-level interface, while `load_mobilised_matlab_format` allows loading custom .mat files. ```APIDOC ## Data Loading: `LabExampleDataset` / `load_mobilised_matlab_format` `LabExampleDataset` is a high-level dataset class wrapping the bundled TVS-subset example data. `load_mobilised_matlab_format` provides a low-level functional interface to load Mobilise-D `.mat` files. Both expose IMU data, participant metadata, and optionally reference system parameters (INDIP, Stereophoto). ```python from mobgap.data import LabExampleDataset, load_mobilised_matlab_format, parse_reference_parameters # High-level dataset interface dataset = LabExampleDataset(reference_system="INDIP") single_trial = dataset.get_subset(cohort="HA", participant_id="002", test="Test5", trial="Trial2") imu_data = single_trial.data_ss # Single-sensor DataFrame (acc_x/y/z, gyr_x/y/z columns) sampling_rate = single_trial.sampling_rate_hz participant_meta = single_trial.participant_metadata # e.g. {"sensor_height_m": 1.03} recording_meta = single_trial.recording_metadata ref = single_trial.reference_parameters_ print(ref.wb_list) # Walking bout list (start, end, avg_cadence_spm, avg_stride_length_m, ...) print(ref.ic_list) # Initial contacts (ic, lr_label columns) print(ref.stride_parameters) # Functional interface for custom .mat files from mobgap.data import get_all_lab_example_data_paths paths = get_all_lab_example_data_paths() data = load_mobilised_matlab_format(paths[("HA", "002")] / "data.mat", reference_system="INDIP") test = data["Test11"] print(test.imu_data["LowerBack"]) # raw IMU DataFrame print(test.metadata["sampling_rate_hz"]) ref_paras = parse_reference_parameters( test.raw_reference_parameters["wb"], data_sampling_rate_hz=test.metadata["sampling_rate_hz"], ref_sampling_rate_hz=test.metadata["reference_sampling_rate_hz"], debug_info="Test11", ) print(ref_paras.ic_list) ``` ``` -------------------------------- ### Run a Poe Task Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Execute a specific command-line task using poethepoet, for example, running tests. ```bash uv run poe test ``` -------------------------------- ### Use Test Fixtures in Tests Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Example of using pytest fixtures, such as 'healthy_example_imu_data', within a test file without explicit imports in the test file itself. ```python # Without import in any valid test file def test_myfunc(healthy_example_imu_data): ... ``` -------------------------------- ### Preview Documentation with Poe Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Preview the built HTML documentation by running this poethepoet task. A URL will be displayed in the terminal. ```bash uv run poe docs_preview ``` -------------------------------- ### __init__ Source: https://github.com/mobilise-d/mobgap/blob/main/docs/templates/class.rst Initializes the class. ```APIDOC ## __init__ ### Description Initializes the class. ### Method __init__ ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example explicitly documented in the source) ### Response (No response details explicitly documented in the source) ``` -------------------------------- ### Build Documentation with Poe Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Build the project's HTML documentation using Sphinx via a poethepoet task. ```bash uv run poe docs ``` -------------------------------- ### Class Initialization Source: https://github.com/mobilise-d/mobgap/blob/main/docs/templates/class_with_private.rst Details the constructor for the class. ```APIDOC ## __init__ __init__() ### Description Initializes a new instance of the class. ### Method __init__ ### Parameters This method does not explicitly list parameters in the source. Refer to the class definition for details. ``` -------------------------------- ### Class Initialization with Private Members Source: https://github.com/mobilise-d/mobgap/blob/main/docs/templates/class_with_private.rst Demonstrates the initialization of a class that contains private members. Ensure all required arguments are provided during instantiation. ```python class MyClass: def __init__(self, public_var, private_var): self.public_var = public_var self._private_var = private_var def get_private_var(self): return self._private_var def set_private_var(self, value): self._private_var = value # Example usage: my_instance = MyClass(10, 20) print(my_instance.public_var) # Output: 10 print(my_instance.get_private_var()) # Output: 20 my_instance.set_private_var(30) print(my_instance.get_private_var()) # Output: 30 ``` -------------------------------- ### start_end_array_to_bool_array Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/utils/array_handling.rst Converts an array of start and end indices into a boolean array. This is the inverse operation of `bool_array_to_start_end_array`. ```APIDOC ## start_end_array_to_bool_array ### Description Converts an array of start and end indices into a boolean array. ### Parameters * **start_end_array** (numpy.ndarray) - A 2D numpy array of shape (n_intervals, 2) where each row contains the start and end index of an interval. * **size** (int) - The total size of the boolean array to create. If not provided, it will be inferred from the `start_end_array`. ### Returns numpy.ndarray: A 1D boolean numpy array of the specified size. ``` -------------------------------- ### Run Formatting with Poe Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Execute the code formatting task using poethepoet and ruff. Recommended to run before pushing code. ```bash uv run poe format ``` -------------------------------- ### merge_intervals Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/utils/array_handling.rst Merges overlapping or adjacent intervals in a given array of intervals. Intervals are represented as pairs of start and end indices. ```APIDOC ## merge_intervals ### Description Merges overlapping or adjacent intervals in a given array of intervals. ### Parameters * **intervals** (numpy.ndarray) - A 2D numpy array of shape (n_intervals, 2) where each row contains the start and end index of an interval. ### Returns numpy.ndarray: A 2D numpy array of shape (n_merged_intervals, 2) with merged intervals. ``` -------------------------------- ### List Available Poe Tasks Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Run this command to see all the command-line tasks configured with poethepoet. ```bash $ uv run poe ... CONFIGURED TASKS format format_unsafe lint Lint all files with ruff. ci_check Check all potential format and linting issues. test Run Pytest with coverage. docs Build the html docs using Sphinx. docs_clean Remove all old build files and build a clean version of the docs. docs_linkcheck Check all links in the built html docs. docs_preview Preview the built html docs. version Bump the version number in all relevant files. conf_jupyter Add a new jupyter kernel for the project. remove_jupyter Remove the project specific jupyter kernel. ``` -------------------------------- ### bool_array_to_start_end_array Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/utils/array_handling.rst Converts a boolean array representing intervals into a start and end index array. `True` values are interpreted as active intervals. ```APIDOC ## bool_array_to_start_end_array ### Description Converts a boolean array representing intervals into a start and end index array. ### Parameters * **bool_array** (numpy.ndarray) - A 1D boolean numpy array where `True` indicates an active interval. ### Returns numpy.ndarray: A 2D numpy array of shape (n_intervals, 2) where each row contains the start and end index of an interval. ``` -------------------------------- ### Run Linting with Poe Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Execute the code linting task using poethepoet and ruff. Recommended to run before pushing code. ```bash uv run poe lint ``` -------------------------------- ### Clone Repository Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Use this command to clone the project repository. Refer to the troubleshooting section for any issues. ```bash git clone https://github.com/mobilise-d/mobgap.git cd mobgap ``` -------------------------------- ### Extracting a region from a dataset Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/common_datatypes.md Demonstrates how to extract a time-period from a dataset using start and end indices, following Python's slicing conventions. The end index is exclusive. ```python-console >>> dataset.iloc[start : end] ``` -------------------------------- ### WsNaive Algorithm Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/walking_speed.rst The WsNaive class provides a straightforward implementation for calculating walking speed. ```APIDOC ## WsNaive ### Description Provides a naive implementation for calculating walking speed. ### Class `mobgap.walking_speed.WsNaive` ``` -------------------------------- ### Assemble Walking Bouts with StrideSelection and WbAssembly Source: https://context7.com/mobilise-d/mobgap/llms.txt Filter strides using StrideSelection based on parameter thresholds or duration, then assemble valid walking bouts with WbAssembly. Requires a stride_list DataFrame and sampling rate. ```python import pandas as pd from mobgap.wba import ( StrideSelection, WbAssembly, IntervalParameterCriteria, IntervalDurationCriteria, MaxBreakCriteria, NStridesCriteria, LeftRightCriteria, ) # Assume stride_list is a DataFrame with columns: start, end, foot, stride_length, duration # (indexed by s_id) # Step 1: Filter invalid strides stride_filter_rules = [ ("sl_thres", IntervalParameterCriteria("stride_length", lower_threshold=0.3, upper_threshold=2.5)), ("dur_thres", IntervalDurationCriteria(min_duration_s=0.4, max_duration_s=2.0)), ] stride_sel = StrideSelection(stride_filter_rules) stride_sel.filter(stride_list, sampling_rate_hz=100) print(stride_sel.filtered_stride_list_) print(stride_sel.excluded_stride_list_) # filtered-out strides print(stride_sel.exclusion_reasons_) # which rule triggered each exclusion # Step 2: Assemble walking bouts wb_rules = [ ("max_break", MaxBreakCriteria(max_break_s=3.0, remove_last_ic="per_foot", consider_end_as_break=True)), ("min_strides", NStridesCriteria(min_strides=5)), ("lr_check", LeftRightCriteria()), ] wb_assembly = WbAssembly(wb_rules) wb_assembly.assemble(stride_sel.filtered_stride_list_, sampling_rate_hz=100) print(wb_assembly.annotated_stride_list_) # strides with wb_id column print(f"Found {len(wb_assembly.wbs_)} walking bouts") ``` -------------------------------- ### Basic Git Branch Workflow Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Standard commands for pushing a new branch and updating it after fetching changes from the main branch. Use `--force-with-lease` for safe force pushing. ```bash git push origin new-branch-name ``` ```bash git fetch origin main git rebase origin/main # resolve potential conflicts git push origin new-branch-name --force-with-lease ``` ```bash git switch main git branch -D new-branch-name ``` -------------------------------- ### SlEmulationPipeline Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/stride_length.rst The SlEmulationPipeline class provides a pipeline for stride length emulation. ```APIDOC ## SlEmulationPipeline ### Description Provides a pipeline for stride length emulation, likely combining multiple steps or algorithms. ### Class `mobgap.stride_length.pipeline.SlEmulationPipeline` ``` -------------------------------- ### Pipelines Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/cadence.rst Pipeline for Cadence Emulation. ```APIDOC ## CadEmulationPipeline ### Description A pipeline for emulating cadence estimation. ### Method (Not specified, likely a class constructor and methods to run the pipeline) ### Endpoint (Not applicable, this is an SDK class) ### Parameters (Not specified in the source) ### Request Example (Not specified in the source) ### Response (Not specified in the source) ``` -------------------------------- ### Clean Documentation Build Files with Poe Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Force a clean build of the documentation by removing old files using this poethepoet task. This may take longer than a normal build. ```bash uv run poe docs_clean ``` -------------------------------- ### Run Development Tasks with Poe Source: https://github.com/mobilise-d/mobgap/blob/main/README.md Execute common development tasks such as formatting, linting, and testing using the poethepoet tool. Ensure code quality before pushing changes. ```bash >>> poetry run poe ... ``` -------------------------------- ### Walking Bout Rules Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/wba.rst Classes defining criteria for walking bout assembly and summarization. ```APIDOC ## Walking Bout Rules ### Description These classes define the criteria for assembling walking bouts and summarizing the results, including left/right leg considerations, maximum breaks, and number of strides. ### Classes - `mobgap.wba.LeftRightCriteria` - `mobgap.wba.MaxBreakCriteria` - `mobgap.wba.NStridesCriteria` - `mobgap.wba.BaseWbCriteria` - `mobgap.wba.BaseSummaryCriteria` ``` -------------------------------- ### Estimate Cadence from Initial Contacts (Python) Source: https://context7.com/mobilise-d/mobgap/llms.txt Use `CadFromIc` to compute per-second cadence from existing initial contacts with step-to-step smoothing. Alternatively, `CadFromIcDetector` wraps an IC detector to re-run detection internally for cadence-optimized results. Both store results in `.cadence_per_sec_`. ```python from mobgap.cadence import CadFromIc, CadFromIcDetector from mobgap.initial_contacts import IcdShinImproved from mobgap.data import LabExampleDataset from mobgap.utils.conversions import to_body_frame trial = LabExampleDataset(reference_system="INDIP").get_subset( cohort="HA", participant_id="001", test="Test5", trial="Trial2" ) ref = trial.reference_parameters_relative_to_wb_ gs_id = ref.wb_list.index[0] data_in_gs = trial.data_ss.iloc[ref.wb_list.start.iloc[0]:ref.wb_list.end.iloc[0]] ics_in_gs = ref.ic_list[["ic"]].loc[gs_id] # Option 1: Use existing ICs cad = CadFromIc() cad.calculate(data_in_gs, initial_contacts=ics_in_gs, sampling_rate_hz=trial.sampling_rate_hz) print(cad.cadence_per_sec_) # sec_center_samples cadence_spm # 50 108.2 # 150 112.0 ... avg_cad = cad.cadence_per_sec_["cadence_spm"].mean() print(f"Average cadence: {avg_cad:.1f} steps/min") # Option 2: Re-detect ICs internally (cadence-optimized detector) cad_detector = CadFromIcDetector(IcdShinImproved()) cad_detector.calculate( to_body_frame(data_in_gs), initial_contacts=ics_in_gs, sampling_rate_hz=trial.sampling_rate_hz ) print(cad_detector.cadence_per_sec_) print(cad_detector.internal_ic_list_) # ICs used internally ``` -------------------------------- ### List of Configured Poe Tasks Source: https://github.com/mobilise-d/mobgap/blob/main/README.md Overview of available development tasks managed by poethepoet, including formatting, linting, testing, documentation building, and version management. ```bash CONFIGURED TASKS format format_unsafe lint Lint all files with ruff. ci_check Check all potential format and linting issues. test Run Pytest with coverage. test_ci Run Pytest with coverage and fail on missing snapshots. docs Build the html docs using Sphinx. docs_clean Remove all old build files and build a clean version of the docs. docs_linkcheck Check all links in the built html docs. docs_preview Preview the built html docs. version Bump the version number in all relevant files. conf_jupyter Add a new jupyter kernel for the project. remove_jupyter Remove the project specific jupyter kernel. update_example_data Update the example data registry. ``` -------------------------------- ### Use Original GsdIluz Peak Detection Algorithm Source: https://github.com/mobilise-d/mobgap/blob/main/CHANGELOG.md To use the original peak detection algorithm from the MATLAB implementation, instantiate GsdIluz with `GsdIluz.PredefinedParameters.original`. ```python GsdIluz(**GsdIluz.PredefinedParameters.original) ``` -------------------------------- ### as_samples Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/utils/conversions.rst Converts a time-based measurement to a sample-based measurement. ```APIDOC ## as_samples ### Description Converts a time-based measurement to a sample-based measurement. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Walking Bout Assembly Class Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/wba.rst The WbAssembly class is the main component for assembling walking bouts. ```APIDOC ## WbAssembly Class ### Description The main class for performing Walking Bout Assembly, consolidating stride and interval information. ### Class `mobgap.wba.WbAssembly` ``` -------------------------------- ### Run Pre-configured Gait Analysis Pipelines Source: https://context7.com/mobilise-d/mobgap/llms.txt Utilize `MobilisedPipelineHealthy`, `MobilisedPipelineImpaired`, or `MobilisedPipelineUniversal` for end-to-end gait analysis. These pipelines accept a dataset trial and output aggregated, per-walking-bout, and per-stride parameters. Customization is possible by modifying pipeline components or parameters. ```python import pandas as pd from mobgap.data import LabExampleDataset from mobgap.pipeline import MobilisedPipelineHealthy, MobilisedPipelineImpaired, MobilisedPipelineUniversal from mobgap.gait_sequences import GsdAdaptiveIonescu dataset = LabExampleDataset() # Run healthy pipeline on a single trial trial_ha = dataset.get_subset(cohort="HA").get_subset(test="Test11")[0] pipeline_ha = MobilisedPipelineHealthy() pipeline_ha.safe_run(trial_ha) print(pipeline_ha.aggregated_parameters_) # single-row summary for the recording print(pipeline_ha.per_wb_parameters_) # one row per walking bout print(pipeline_ha.per_stride_parameters_) # one row per stride (within valid WBs) # Run impaired pipeline trial_ms = dataset.get_subset(cohort="MS").get_subset(test="Test11")[0] pipeline_ms = MobilisedPipelineImpaired().safe_run(trial_ms) print(pipeline_ms.per_wb_parameters_) # Universal pipeline auto-selects healthy vs impaired meta_pipeline = MobilisedPipelineUniversal( pipelines=[("healthy", MobilisedPipelineHealthy()), ("impaired", MobilisedPipelineImpaired())] ) # Batch processing across entire dataset per_wb_all, agg_all = {}, {} for trial in LabExampleDataset(): pipe = meta_pipeline.clone().safe_run(trial) if not (wb := pipe.per_wb_parameters_).empty: per_wb_all[trial.group_label] = wb if not (agg := pipe.aggregated_parameters_).empty: agg_all[trial.group_label] = agg per_wb_df = pd.concat(per_wb_all) print(per_wb_df.head()) # Modify pipeline: swap GSD algorithm pipe_custom = MobilisedPipelineHealthy(gait_sequence_detection=GsdAdaptiveIonescu(min_n_steps=3)) pipe_custom.safe_run(trial_ha) print(pipe_custom.aggregated_parameters_) # Modify deeply nested parameter meta_mod = MobilisedPipelineUniversal().set_params( pipelines__healthy__gait_sequence_detection__pre_filter__order=50 ) meta_mod.safe_run(trial_ha) ``` -------------------------------- ### Run Tests with TVS Dataset Source: https://github.com/mobilise-d/mobgap/blob/main/README.md Execute the test suite, ensuring that tests requiring the TVS dataset are run by setting the MOBGAP_TVS_DATASET_PATH environment variable. ```bash MOBGAP_TVS_DATASET_PATH="/path/to/tvs/dataset" poe test ``` -------------------------------- ### Base Classes Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/pipeline.rst Provides the foundational base class for all mobilized pipelines. ```APIDOC ## BaseMobilisedPipeline ### Description The base class for all mobilized pipeline implementations, providing common functionalities and structure. ``` -------------------------------- ### Pre-configured Analysis Pipelines Source: https://context7.com/mobilise-d/mobgap/llms.txt End-to-end pipelines for analyzing gait data, offering different configurations for specific cohorts or universal application. ```APIDOC ## Pre-configured Pipelines: `MobilisedPipelineHealthy`, `MobilisedPipelineImpaired`, `MobilisedPipelineUniversal` End-to-end pipelines that accept a dataset trial and output aggregated parameters, per-walking-bout parameters, and per-stride parameters. `MobilisedPipelineHealthy` (GsdIluz + IcdShinImproved + LrcUllrich) targets HA/COPD/CHF cohorts; `MobilisedPipelineImpaired` (GsdAdaptiveIonescu + IcdShinImproved + LrcUllrich) targets PD/PFF/MS. `MobilisedPipelineUniversal` auto-selects based on participant cohort. ### Healthy Pipeline Targets HA/COPD/CHF cohorts. ```python import pandas as pd from mobgap.data import LabExampleDataset from mobgap.pipeline import MobilisedPipelineHealthy dataset = LabExampleDataset() # Run healthy pipeline on a single trial trial_ha = dataset.get_subset(cohort="HA").get_subset(test="Test11")[0] pipeline_ha = MobilisedPipelineHealthy() pipeline_ha.safe_run(trial_ha) print(pipeline_ha.aggregated_parameters_) # single-row summary for the recording print(pipeline_ha.per_wb_parameters_) # one row per walking bout print(pipeline_ha.per_stride_parameters_) # one row per stride (within valid WBs) ``` ### Impaired Pipeline Targets PD/PFF/MS cohorts. ```python import pandas as pd from mobgap.data import LabExampleDataset from mobgap.pipeline import MobilisedPipelineImpaired dataset = LabExampleDataset() # Run impaired pipeline trial_ms = dataset.get_subset(cohort="MS").get_subset(test="Test11")[0] pipeline_ms = MobilisedPipelineImpaired().safe_run(trial_ms) print(pipeline_ms.per_wb_parameters_) ``` ### Universal Pipeline Auto-selects between healthy and impaired pipelines based on participant cohort. ```python import pandas as pd from mobgap.data import LabExampleDataset from mobgap.pipeline import MobilisedPipelineHealthy, MobilisedPipelineImpaired, MobilisedPipelineUniversal # Universal pipeline auto-selects healthy vs impaired meta_pipeline = MobilisedPipelineUniversal( pipelines=[("healthy", MobilisedPipelineHealthy()), ("impaired", MobilisedPipelineImpaired())] ) # Batch processing across entire dataset per_wb_all, agg_all = {}, for trial in LabExampleDataset(): pipe = meta_pipeline.clone().safe_run(trial) if not (wb := pipe.per_wb_parameters_).empty: per_wb_all[trial.group_label] = wb if not (agg := pipe.aggregated_parameters_).empty: agg_all[trial.group_label] = agg per_wb_df = pd.concat(per_wb_all) print(per_wb_df.head()) ``` ### Customizing Pipelines Pipelines can be customized by swapping components or modifying parameters. ```python from mobgap.pipeline import MobilisedPipelineHealthy from mobgap.gait_sequences import GsdAdaptiveIonescu # Modify pipeline: swap GSD algorithm pipe_custom = MobilisedPipelineHealthy(gait_sequence_detection=GsdAdaptiveIonescu(min_n_steps=3)) # Example usage with a trial (assuming trial_ha is defined) # pipe_custom.safe_run(trial_ha) # print(pipe_custom.aggregated_parameters_) # Modify deeply nested parameter from mobgap.pipeline import MobilisedPipelineUniversal meta_mod = MobilisedPipelineUniversal().set_params( pipelines__healthy__gait_sequence_detection__pre_filter__order=50 ) # Example usage with a trial (assuming trial_ha is defined) # meta_mod.safe_run(trial_ha) ``` ``` -------------------------------- ### Estimate Stride Length using Zijlstra Model (Python) Source: https://context7.com/mobilise-d/mobgap/llms.txt Implements the Zijlstra inverted-pendulum model to calculate per-second stride length from accelerometer data. Requires sensor height. Results are stored in `.stride_length_per_sec_`. For improved accuracy, orientation correction using methods like MadgwickAHRS can be applied. ```python from mobgap.stride_length import SlZijlstra from mobgap.orientation_estimation._madgwick import MadgwickAHRS from mobgap.data import LabExampleDataset from mobgap.utils.conversions import to_body_frame trial = LabExampleDataset(reference_system="INDIP").get_subset( cohort="HA", participant_id="001", test="Test5", trial="Trial2" ) ref = trial.reference_parameters_relative_to_wb_ gs_id = ref.wb_list.index[0] data_in_gs = to_body_frame(trial.data["LowerBack"].iloc[ref.wb_list.start.iloc[0]:ref.wb_list.end.iloc[0]]) ics_in_gs = ref.ic_list.loc[gs_id] sensor_height = trial.participant_metadata["sensor_height_m"] # Using predefined scaling parameters (validated on MSProject dataset) sl = SlZijlstra(**SlZijlstra.PredefinedParameters.step_length_scaling_factor_ms_ms) sl.calculate( data=data_in_gs, initial_contacts=ics_in_gs, sensor_height_m=sensor_height, sampling_rate_hz=trial.sampling_rate_hz, ) print(sl.stride_length_per_sec_) # sec_center_samples stride_length_m # 50 1.32 # 150 1.29 ... # With Madgwick orientation correction for improved accuracy sl_reoriented = SlZijlstra( orientation_method=MadgwickAHRS(beta=0.2), **SlZijlstra.PredefinedParameters.step_length_scaling_factor_ms_ms, ) sl_reoriented.calculate(data_in_gs, initial_contacts=ics_in_gs, sensor_height_m=sensor_height, sampling_rate_hz=trial.sampling_rate_hz) print(sl_reoriented.stride_length_per_sec_) print(sl.raw_step_length_per_step_) # step-level intermediate output ``` -------------------------------- ### LRC Pipelines Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/laterality.rst Provides access to pipelines for emulating LRC. ```APIDOC ## Pipelines ### LrcEmulationPipeline **Description:** Pipeline for emulating Left-Right Classification (LRC). ``` -------------------------------- ### Walking Bout Assembly: StrideSelection, WbAssembly Source: https://context7.com/mobilise-d/mobgap/llms.txt Filters strides and assembles them into walking bouts. StrideSelection filters individual strides, while WbAssembly groups the filtered strides into coherent walking bouts. ```APIDOC ## Walking Bout Assembly: `StrideSelection`, `WbAssembly` ### Description `StrideSelection` filters strides by parameter thresholds or duration. `WbAssembly` groups remaining strides into valid walking bouts using rule-based termination and inclusion criteria. Output in `.annotated_stride_list_` and `.wbs_`. ### Step 1: Filter invalid strides #### Method ```python from mobgap.wba import StrideSelection, IntervalParameterCriteria, IntervalDurationCriteria # Assume stride_list is a DataFrame with columns: start, end, foot, stride_length, duration # (indexed by s_id) stride_filter_rules = [ ("sl_thres", IntervalParameterCriteria("stride_length", lower_threshold=0.3, upper_threshold=2.5)), ("dur_thres", IntervalDurationCriteria(min_duration_s=0.4, max_duration_s=2.0)), ] stride_sel = StrideSelection(stride_filter_rules) stride_sel.filter(stride_list, sampling_rate_hz=100) print(stride_sel.filtered_stride_list_) print(stride_sel.excluded_stride_list_) # filtered-out strides print(stride_sel.exclusion_reasons_) # which rule triggered each exclusion ``` ### Step 2: Assemble walking bouts #### Method ```python from mobgap.wba import WbAssembly, MaxBreakCriteria, NStridesCriteria, LeftRightCriteria wb_rules = [ ("max_break", MaxBreakCriteria(max_break_s=3.0, remove_last_ic="per_foot", consider_end_as_break=True)), ("min_strides", NStridesCriteria(min_strides=5)), ("lr_check", LeftRightCriteria()), ] wb_assembly = WbAssembly(wb_rules) wb_assembly.assemble(stride_sel.filtered_stride_list_, sampling_rate_hz=100) print(wb_assembly.annotated_stride_list_) print(f"Found {len(wb_assembly.wbs_)} walking bouts") ``` ``` -------------------------------- ### Utilities Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/data_transform.rst Utility functions for data transformation pipelines. ```APIDOC ## Utilities ### Description This section lists available utility functions. ### Functions - **chain_transformers**: Chains multiple transformers together to create a processing pipeline. ``` -------------------------------- ### Release New Version Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Use this command to update the version number in relevant files when preparing for a new release. After running, update the changelog and GitHub release notes. ```bash uv run poe version {major|minor|patch} ``` -------------------------------- ### Full Pipelines Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/pipeline.rst These classes represent different configurations of the full pipeline for analyzing sensor data. ```APIDOC ## GenericMobilisedPipeline ### Description Represents a generic pipeline for mobilized data analysis. ## MobilisedPipelineHealthy ### Description Represents a pipeline specifically configured for analyzing data from healthy individuals. ## MobilisedPipelineImpaired ### Description Represents a pipeline specifically configured for analyzing data from individuals with impairments. ## MobilisedPipelineUniversal ### Description Represents a universal pipeline applicable to a wide range of mobilized data analysis scenarios. ``` -------------------------------- ### Create and Push New Feature Branch Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/developer_guide.md Standard git commands to create a new feature branch from main, push it to the remote repository, and initiate a merge request. Remember to prefix WIP merge requests with 'WIP: '. ```bash git switch main git pull origin main git switch -c new-branch-name git push origin new-branch-name ``` -------------------------------- ### Load Mobilise-D Data Source: https://context7.com/mobilise-d/mobgap/llms.txt Load IMU data and reference parameters using either the high-level `LabExampleDataset` or the low-level `load_mobilised_matlab_format` function. Ensure the `reference_system` is correctly specified. ```python from mobgap.data import LabExampleDataset, load_mobilised_matlab_format, parse_reference_parameters # High-level dataset interface dataset = LabExampleDataset(reference_system="INDIP") single_trial = dataset.get_subset(cohort="HA", participant_id="002", test="Test5", trial="Trial2") imu_data = single_trial.data_ss # Single-sensor DataFrame (acc_x/y/z, gyr_x/y/z columns) sampling_rate = single_trial.sampling_rate_hz participant_meta = single_trial.participant_metadata # e.g. {"sensor_height_m": 1.03} recording_meta = single_trial.recording_metadata ref = single_trial.reference_parameters_ print(ref.wb_list) # Walking bout list (start, end, avg_cadence_spm, avg_stride_length_m, ...) print(ref.ic_list) # Initial contacts (ic, lr_label columns) print(ref.stride_parameters) # Functional interface for custom .mat files from mobgap.data import get_all_lab_example_data_paths paths = get_all_lab_example_data_paths() data = load_mobilised_matlab_format(paths[("HA", "002")] / "data.mat", reference_system="INDIP") test = data["Test11"] print(test.imu_data["LowerBack"]) # raw IMU DataFrame print(test.metadata["sampling_rate_hz"]) ref_paras = parse_reference_parameters( test.raw_reference_parameters["wb"], data_sampling_rate_hz=test.metadata["sampling_rate_hz"], ref_sampling_rate_hz=test.metadata["reference_sampling_rate_hz"], debug_info="Test11", ) print(ref_paras.ic_list) ``` -------------------------------- ### BaseSlCalculator Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/stride_length.rst The base class for all Stride Length calculators. ```APIDOC ## BaseSlCalculator ### Description This is the base class for all stride length calculators within the module, defining the common interface and structure. ### Class `mobgap.stride_length.base.BaseSlCalculator` ``` -------------------------------- ### Base Classes Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/cadence.rst Base classes for cadence calculators. ```APIDOC ## BaseCadCalculator ### Description Base class for all cadence calculators. ### Method (Not specified, likely a class constructor) ### Endpoint (Not applicable, this is an SDK class) ### Parameters (Not specified in the source) ### Request Example (Not specified in the source) ### Response (Not specified in the source) ``` -------------------------------- ### Gait Sequence Detection Algorithms Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/gait_sequences.rst This section lists the available algorithms for detecting gait sequences. ```APIDOC ## Gait Sequence Detection Algorithms This section lists the available algorithms for detecting gait sequences. ### Available Algorithms: - **GsdIluz**: An algorithm for gait sequence detection. - **GsdIonescu**: Another algorithm for gait sequence detection. - **GsdAdaptiveIonescu**: An adaptive version of the Ionescu algorithm for gait sequence detection. ``` -------------------------------- ### Base Classes Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/data_transform.rst Base classes for creating custom transformers and filters. ```APIDOC ## Base Classes ### Description This section lists the base classes for creating custom data transformation components. ### Classes - **BaseTransformer**: Abstract base class for all transformers. - **BaseFilter**: Abstract base class for all filters. - **FixedFilter**: Base class for filters with fixed parameters. - **ScipyFilter**: Base class for filters that wrap SciPy filter functions. - **IdentityFilter**: A filter that performs no transformation. ``` -------------------------------- ### Initialize Sensor to Global Orientation Source: https://github.com/mobilise-d/mobgap/blob/main/docs/guides/coordinate_system.md Defines the initial rotation matrix representing the sensor's neutral orientation in the global coordinate system. This is crucial for sensor fusion algorithms. ```python import numpy as np # Initial orientation of the sensor in the global coordinate system R = np.array([[0, 0, 1], [0, -1, 0], [1, 0, 0]]) ``` -------------------------------- ### Modify Gait Sequence Detection Parameters Source: https://context7.com/mobilise-d/mobgap/llms.txt Demonstrates how to modify parameters for the GsdIluz and GsdAdaptiveIonescu algorithms for gait sequence detection. Ensure imu_data and trial.sampling_rate_hz are available. ```python gsd_mod = GsdIluz(window_length_s=5, window_overlap=0.8) gsd_mod.detect(imu_data, sampling_rate_hz=trial.sampling_rate_hz) print(gsd_mod.gs_list_) ``` ```python gsd_adaptive = GsdAdaptiveIonescu(min_n_steps=3) gsd_adaptive.detect(imu_data, sampling_rate_hz=trial.sampling_rate_hz) print(gsd_adaptive.gs_list_) ``` -------------------------------- ### IcdEmulationPipeline Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/initial_contacts.rst A pipeline for emulating initial contact detection scenarios. ```APIDOC ## IcdEmulationPipeline ### Description A pipeline for emulating initial contact detection scenarios. ### Class `mobgap.initial_contacts.pipeline.IcdEmulationPipeline` ``` -------------------------------- ### GaitDatasetFromData Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/data.rst A generic loader class for creating gait datasets from provided data. ```APIDOC ## GaitDatasetFromData ### Description This class provides a generic way to load gait datasets from existing data structures. ### Class GaitDatasetFromData ``` -------------------------------- ### Estimate Walking Speed from Cadence and Stride Length (Python) Source: https://context7.com/mobilise-d/mobgap/llms.txt Derives per-second walking speed using the formula: speed = cadence × stride_length / 2. Stores the result in `.walking_speed_per_sec_`. This method requires pre-calculated cadence and stride length data. ```python from mobgap.walking_speed import WsNaive from mobgap.cadence import CadFromIc from mobgap.stride_length import SlZijlstra from mobgap.data import LabExampleDataset from mobgap.utils.conversions import to_body_frame trial = LabExampleDataset(reference_system="INDIP").get_subset( cohort="HA", participant_id="001", test="Test5", trial="Trial2" ) ref = trial.reference_parameters_relative_to_wb_ gs_id = ref.wb_list.index[0] data_in_gs = to_body_frame(trial.data_ss.iloc[ref.wb_list.start.iloc[0]:ref.wb_list.end.iloc[0]]) ics = ref.ic_list.loc[gs_id] cad = CadFromIc().calculate(data_in_gs, initial_contacts=ics[["ic"]], sampling_rate_hz=trial.sampling_rate_hz) sl = SlZijlstra(**SlZijlstra.PredefinedParameters.step_length_scaling_factor_ms_ms).calculate( data=data_in_gs, initial_contacts=ics, sensor_height_m=trial.participant_metadata["sensor_height_m"], sampling_rate_hz=trial.sampling_rate_hz, ) ws = WsNaive() ws.calculate( data_in_gs, initial_contacts=ics, cadence_per_sec=cad.cadence_per_sec_, stride_length_per_sec=sl.stride_length_per_sec_, sampling_rate_hz=trial.sampling_rate_hz, **trial.participant_metadata, ) print(ws.walking_speed_per_sec_) # sec_center_samples walking_speed_mps # 50 1.19 ``` -------------------------------- ### get_matching_ics Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/initial_contacts.rst Retrieves matching initial contacts. ```APIDOC ## get_matching_ics ### Description Retrieves matching initial contacts. ### Function `mobgap.initial_contacts.evaluation.get_matching_ics` ``` -------------------------------- ### Prepare TVS Data Script Source: https://github.com/mobilise-d/mobgap/blob/main/scripts/tvs_data_preperation/README.md Python script to rename IDs and reorganize the TVS dataset into a new folder structure for release. Adjust file paths within the script as needed. ```python prepare_tvs_data.py ``` -------------------------------- ### Gait Sequence Detection: GsdIluz, GsdIonescu, GsdAdaptiveIonescu Source: https://context7.com/mobilise-d/mobgap/llms.txt Algorithms for segmenting continuous IMU recordings into gait sequence intervals. They all expose a `.detect()` method and store results in `.gs_list_`. ```APIDOC ## Gait Sequence Detection: `GsdIluz`, `GsdIonescu`, `GsdAdaptiveIonescu` Algorithms that segment continuous IMU recordings into gait sequence intervals. All expose a `.detect(data, sampling_rate_hz)` method and store results in `.gs_list_` (DataFrame with `start`, `end` sample columns, indexed by `gs_id`). ```python from mobgap.gait_sequences import GsdIluz, GsdIonescu, GsdAdaptiveIonescu from mobgap.data import LabExampleDataset from mobgap.utils.conversions import to_body_frame trial = LabExampleDataset().get_subset(cohort="MS", participant_id="001", test="Test11", trial="Trial1") imu_data = to_body_frame(trial.data_ss) # Default algorithm (used in MobilisedPipelineHealthy) gsd = GsdIluz() gsd.detect(imu_data, sampling_rate_hz=trial.sampling_rate_hz) print(gsd.gs_list_) # start end # gs_id # 1 0 3200 # 2 5100 8800 ... ``` ``` -------------------------------- ### SlZijlstra Algorithm Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/stride_length.rst The SlZijlstra class implements a specific algorithm for stride length calculation. ```APIDOC ## SlZijlstra ### Description Implements the SlZijlstra algorithm for stride length calculation. ### Class `mobgap.stride_length.SlZijlstra` ``` -------------------------------- ### IcdIonescu Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/initial_contacts.rst An algorithm for initial contact detection based on Ionescu's method. ```APIDOC ## IcdIonescu ### Description An algorithm for initial contact detection based on Ionescu's method. ### Class `mobgap.initial_contacts.IcdIonescu` ``` -------------------------------- ### Gait Sequence Detection Pipelines Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/gait_sequences.rst This section details the pipelines available for GSD. ```APIDOC ## Gait Sequence Detection Pipelines This section details the pipelines available for GSD. ### GsdEmulationPipeline - **Description**: A pipeline designed for emulating gait sequence detection scenarios. ``` -------------------------------- ### Helper Functions Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/pipeline.rst Utility functions for iterating through gait sequences and creating aggregated dataframes. ```APIDOC ## GsIterator ### Description An iterator for processing gait sequences. ## iter_gs ### Description A function to iterate over gait sequences. ## create_aggregate_df ### Description Creates an aggregated DataFrame from pipeline results. ``` -------------------------------- ### Interval Rules Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/wba.rst Classes defining criteria for interval parameters and duration. ```APIDOC ## Interval Rules ### Description These classes define the rules and criteria for interval parameters and duration used in walking bout analysis. ### Classes - `mobgap.wba.IntervalParameterCriteria` - `mobgap.wba.IntervalDurationCriteria` - `mobgap.wba.BaseIntervalCriteria` ``` -------------------------------- ### BaseWsCalculator Base Class Source: https://github.com/mobilise-d/mobgap/blob/main/docs/modules/walking_speed.rst The base class for all walking speed calculators, defining the common interface. ```APIDOC ## BaseWsCalculator ### Description Base class for walking speed calculators. ### Class `mobgap.walking_speed.base.BaseWsCalculator` ```