Git Product home page Git Product logo

pyomeca's Introduction

logo DOI badge Actions Status Coverage Status PyPI Downloads

Pyomeca is a python library allowing you to carry out a complete biomechanical analysis; in a simple, logical and concise way.

Pyomeca documentation

See Pyomeca's documentation site.

Example

Pyomeca implements specialized functionalities commonly used in biomechanics. As an example, let's process the electromyographic data contained in this c3d file.

You can follow along without installing anything by using our binder server: Binder

from pyomeca import Analogs

data_path = "../tests/data/markers_analogs.c3d"
muscles = [
    "Delt_ant",
    "Delt_med",
    "Delt_post",
    "Supra",
    "Infra",
    "Subscap",
]
emg = Analogs.from_c3d(data_path, suffix_delimiter=".", usecols=muscles)
emg.plot(x="time", col="channel", col_wrap=3)

svg

emg_processed = (
    emg.meca.band_pass(order=2, cutoff=[10, 425])
    .meca.center()
    .meca.abs()
    .meca.low_pass(order=4, cutoff=5, freq=emg.rate)
    .meca.normalize()
)

emg_processed.plot(x="time", col="channel", col_wrap=3)

svg

import matplotlib.pyplot as plt

fig, axes = plt.subplots(ncols=2, figsize=(10, 4))

emg_processed.mean("channel").plot(ax=axes[0])
axes[0].set_title("Mean EMG activation")

emg_processed.plot.hist(ax=axes[1], bins=50)
axes[1].set_title("EMG activation distribution")

svg

See the documentation for more details and examples.

Features

  • Signal processing routine commonly used in biomechanics such as filters, normalization, onset detection, outliers detection, derivatives, etc.
  • Common matrix manipulation routines implemented such as getting Euler angles to/from a rototranslation matrix, creating a system of axes, setting a rotation or translation, transpose or inverse, etc.
  • Easy reading and writing interface to common files in biomechanics (c3d, csv, xlsx,mat, trc, sto, mot)
  • All of xarray's awesome features

The following illustration shows all of pyomeca's public API. An interactive version is available in the documentation.

api

Installation

Pyomeca itself is a pure Python package, but its dependencies are not. The easiest way to get everything installed is to use conda.

To install pyomeca with its recommended dependencies using the conda command line tool:

conda install -c conda-forge pyomeca

Now that you have installed pyomeca, you should be able to import it:

import pyomeca

Integration with other modules

Pyomeca is designed to work well with other libraries that we have developed:

  • pyosim: interface between OpenSim and pyomeca to perform batch musculoskeletal analyses
  • ezc3d: Easy to use C3D reader/writer in C++, Python and Matlab
  • biorbd: C++ interface and add-ons to the Rigid Body Dynamics Library, with Python and Matlab binders.

Bug reports & questions

Pyomeca is Apache-licensed and the source code is available on GitHub. If any questions or issues come up as you use pyomeca, please get in touch via GitHub issues. We welcome any input, feedback, bug reports, and contributions.

Citing Pyomeca

DOI

If you use pyomeca in your academic work, please consider citing our paper as:

@article{Martinez2020,
  doi = {10.21105/joss.02431},
  url = {https://doi.org/10.21105/joss.02431},
  year = {2020},
  publisher = {The Open Journal},
  volume = {5},
  number = {53},
  pages = {2431},
  author = {Romain Martinez and Benjamin Michaud and Mickael Begon},
  title = {`pyomeca`: An Open-Source Framework for Biomechanical Analysis},
  journal = {Journal of Open Source Software}
}

Please consider citing the xarray project, which pyomeca is based on:

@article{jors-xarray,
title = {Xarray: N-D labeled arrays and datasets in Python},
author = {Joe Hamman and Stephan Hoyer},
year = {2017},
journal = {Journal of Open Research Software}
}

Contributors

Pyomeca is an open-source project created and supported by the S2M lab.

pyomeca's People

Contributors

kilidsch avatar kthyng avatar pariterre avatar romainmartinez avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyomeca's Issues

to_c3d

Once pyomeca v2 is ready, a to_c3d() method would be a good addition to the next release!

ReadMe

Help me installing me!

Dependencies error

The command :
conda install pyomeca -cconda-forge
install pyomeca using Python 3.7 on Linux. But this version conflict with more recent version of numpy (or typing).

The fix is to force the install of python 3.9 after having installed pyomeca:
conda install python=3.9 -cconda-forge
But this is not elegant. The version 3.9 should be added to anaconda
@romainmartinez are you up to it? Or should I have a look?

troubles with xarrays and findpeaks

Hello everyone,

I tried to get resultant velocity from Markers data manually, as I cannot find proper method in docs. By bypass it worked and I got similar results to previous pyomeca versions, but output is still in xarray, while findpeaks from scipy is only for 1d data. I tried to put it into pandas, but still there are errors, that I do not fully understand.

I placed the notebook in the attachment.
przyspieszenie.zip

Or maybe there is a method to read c3d as it was in the previous versions?

Best regards,
Darek

Can't install Pyosim after recent update

I get this error when I try to install Pyosim library with !conda install -y --prefix /usr/local -c kzts opensim and import pyosim.
image
I haven't experienced this until recent updates. Pyosim hasn't been updated by several months, so I think maybe there are some conflicts between Pyosim and Pyomeca after the recent commits in Pyomeca.

Could you please help me to fix this? Thank you!

clean code

  • remove half-baked solutions
  • lint with black and add lint to Makefile

RT last line should be checked

During RT creation this should be checked:

data[3, :3, :] = 0
data[3, 3, :] = 1

I started the following implementation:

# Make sure last line reads [0, 0, 0, 1]
zeros = data[3, :3, :]
ones = data[3, 3, :]
if not np.alltrue(zeros == 0) or not np.alltrue(ones == 1):
    some_zeros = np.random.choice(zeros.ravel(), 5)
    some_ones = np.random.choice(ones.ravel(), 5)
    raise ValueError(
        "Last line does not read [0, 0, 0, 1].\n"
        f"Here are some values that should be 0: {some_zeros}\n"
        f"And others that should 1: {some_ones}"
    )

But I get errors on the from_transposed_rototrans, from_averaged_rototrans and from_markers methods, in both versions of pyomeca (v1 and v2).

Are these two lines necessary in your opinion or is it a bug we have?

latest supported python version

Hi,

Would you please tell me what the latest supported python version is? Does it support py 3.8?

Your help is much appreciated,

Cheers

Write unittest

A fairly amount of improvements are orphan of unittest. Let's fill them of joy by giving them a pytest God

getting columns from labels

Hi!

I am still noob, but since last correspondence with Pariterre, I had tons of other work so I am getting back to your library. Last time I successfully imported my file

import pyomeca
c = pyomeca.Markers3d.from_c3d('B0264_dollyo_air_P_T01.c3d')
c.get_labels

but then I stuck. from the labels i am interested in marker called RTOE. I tried to get values from it by c['RTOE'] but is wrong.

I would like to mention that I read examples but I cannot do anything from it. Please give me a hints, I am not here to have ready working code, just some directions. Eventually, is there any specific command to get velocity values for specific marker by some commands?

Best regards,
Darek

Import 3d positional data for conversion to other file formats

Hello -

I have acquired, through a markerless motion capture technology, joint positions (x,y,z only) for a series of joints, exported in a non-traditional mocap file format (usually I just throw it into a csv). I am now looking to animate them, and I was looking to convert those joint channels to a traditional motion capture file format without adding rotations. Is this possible? How would I accomplish this using this tool?

I also see that Pyosim could be used in conjunction with this. Is it possible to run an inverse kinematic solve as a means of joint correction on my data using these packages?

Thanks.

Recover the trajectory color

Hi,

I would like to express my gratitude for creating this helpful library.

I have a question regarding whether it's possible to use your library to retrieve the color of a marker.

Thank you for taking the time to respond to my question.

writing to csv problem

Hello,
I'm new to programming and github so I'm not sure if this is the correct place to ask this question, but I have a problem with converting my file from c3d to csv. I edited one of the examples and got rid of the errors and it seems to be working fine but after you take a look at the values they are totally incorrect. Anyone have idea what is wrong and how to repair this? As you can see below, for example y value should be around 100 but in a csv it is starting from 67.
(I'm including the code, the screenshot from motionbuilder where you can see the trajectory and values in the original file and a screenshot from a fragment of a created csv file)

`from pathlib import Path

from pyomeca import Markers3d, Analogs3d

Path to data

DATA_FOLDER = Path(r"C:\Users\Dom\Desktop\mggr\koncowe")
#MARKERS_CSV = DATA_FOLDER / "markers.csv"
MARKERS_C3D = DATA_FOLDER / "calosc_aktor_z_mieczem.c3d"
#ANALOGS_CSV = DATA_FOLDER / "analogs.csv"

markers_4 = Markers3d.from_c3d(MARKERS_C3D, idx=[0, 1, 2, 3])

markers_4.to_csv(r"C:\Users\Dom\Desktop\mggr\koncowe\atest.csv", header=True)`

image
image

derivative method in newest version

Hello after long time,

Old pyomeca helps me like 3240 times but I had long break. Pyomeca changes a lot and from user guide I know how to adress separate channel but for resultant velocity code looked like this:

vrtoe = (data[('B0346:LTOE')]/1000).derivative().norm()
v_RTOE = vrtoe.reshape(2841,1)
v_RTOE = pd.DataFrame(v_RTOE)
vrkne = (data[('B0346:LKNE')]/1000).derivative().norm()
v_RKNE = vrkne.reshape(2841,1)
v_RKNE = pd.DataFrame(v_RKNE)
vrasi = (data[('B0346:LASI')]/1000).derivative().norm()
v_RASI = vrasi.reshape(2841,1)
v_RASI = pd.DataFrame(v_RASI)
t = data.get_time_frames
t.shape
t = pd.DataFrame(t)
df_all_cols = pd.concat([t, v_RTOE,v_RKNE , v_RASI], axis = 1)
df_all_cols.columns =['t', 'v_RTOE','v_RKNE' , 'v_RASI' ]

But now this is not working witj error

vrtoe = (data.sel(channel="B0346:LTOE")/1000).derivative().norm()

'DataArray' object has no attribute 'derivative'

Am I doing it wrong or this function is not yet added in newest version?

Best regards,
Darek

rototrans matmul

Hi,
I think I'm doing something wrong but when I use matmul on rototrans object, the results is a scalar.
image

dev branch is useless

I feel that the dev branch unnecessarily complicates the collaboration workflow.
As we are already working on forks, PRs and using releases with tags I feel that we could only keep the master branch once the PR on pyomeca v2 is accepted?
@pariterre

Proper citation in JOSS

Dear authors,

I think the following publications are not properly cited:

I can follow the links provided and copy the "how to cite". Also, I find it useful to include the DOI if it exists. Please check and follow the citation rules of JOSS.

Thanks!

Dimitar

roadmap

Near-term

  • read c3d files (integrate btk in pyomeca)

Medium-term

Long-term

  • OpenSim wrapper

Averaged rototrans bug

As discussed in #88, there's some weird behavior on this Rototrans.from_averaged_rototrans() that could be the result of a bug.

Environment setup

git clone [email protected]:romainmartinez/pyomeca.git
cd pyomeca
conda env create
conda activate pyomeca
pip install -r requirements-dev.txt

Reproducible example

import numpy as np

from pyomeca import Angles, Rototrans

size = (3, 1, 100)

def test_rt_mean(rt, seq="xyz"):
    rt_mean = Rototrans.from_averaged_rototrans(rt)

    angles_mean = Angles.from_rototrans(rt_mean, seq).isel(time=0)
    angles_mean_ref = Angles.from_rototrans(rt, seq).mean(dim="time")

    np.testing.assert_array_almost_equal(angles_mean, angles_mean_ref, decimal=2)

This works

angles = Angles(np.random.rand(*size))
seq = "xyz"
rt = Rototrans.from_euler_angles(angles, seq)
test_rt_mean(rt)

this does not work

rt = Rototrans.from_random_data(size=size)
test_rt_mean(rt)

Which is the equivalent of

angles = Angles.from_random_data(size=size)
seq = "xyz"
rt = Rototrans.from_euler_angles(angles, seq)
test_rt_mean(rt)

from_random_data() is implemented as follows:

Angles(np.random.normal(*size).cumsum(-1))

Can you take a look at this @pariterre?

Install on Google Colab

Hello Romain,

I have been trying to install them and use them to get some simulation with OpenSim. I am not sure if I installed them properly esp. in a google notebook.

I managed to install ezc3d with some difficulty on Google Colab. (I guess the same idea can be done on Jupyter notebook); However, after trying your pyomeca, I get the following error (see the notebook please) :

_Could not find a version that satisfies the requirement ezc3d (from pyomeca==2018.3+2.g3584e40) (from versions: )

No matching distribution found for ezc3d (from pyomeca==2018.3+2.g3584e40)_

I am wonder if you could help me fix this and install it. I do appreciate it.
Cheers,
Hossein

delsys c3d

Hi, Thanks you so much for pyomeca.
For an ex-user of Matlab like me, your solution is very easy to use and very useful for my daily use in python while I mainly work with inertial unit data.
Actually, I have some troubles to import data from c3d generated by Delsys File Utility (hpf to c3d). Channel names contain specific characters (colon and dot) which cause errors during import. It's possible to fix this bug by manual renaming channels but I search a solution to avoid this time-consuming manipulation.

Problem With Google Colab Import

Problem With Google Colab Import

I can not import pyomeca or ezc3d in Google Colab environment.

When I put

# Install miniconda environment
!wget -c https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
!chmod +x Miniconda3-latest-Linux-x86_64.sh
!bash ./Miniconda3-latest-Linux-x86_64.sh -b -f -p /usr/local

import sys
sys.path.append('/usr/local/lib/python3.9/site-packages/')

# Download and install desired packages
!conda install -y --prefix /usr/local -c pyomeca -c conda-forge pyomeca

# Enjoy the packages
import ezc3d
import pyomeca

I receive in return


ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-8-471790ada190> in <module>()
      1 # Enjoy the packages
----> 2 import ezc3d
      3 import pyomeca

ModuleNotFoundError: No module named 'ezc3d'

---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------

The same error occurs if I try to import piomeca.
I already tried to change


# Download and install desired packages
!conda install -y --prefix /usr/local -c pyomeca -c conda-forge pyomeca

for


# Download and install desired packages
!conda install -y --prefix /usr/local -c pyomeca=3.9 -c conda-forge pyomeca

but I keep getting the same error.

Thanks.

How to install Pyomeca from the Pycharm Terminal for Win 10.

I apologize for my very easy question but I am beginner. I can use pyomeca in google colab but I can not install pyomeca in my computer. I use win 10 and I am try practice with the Pycharm. I believe that Pycharm has a venv, I dont know if this change anything .

I already tried:

count install -c count-forge pyomeca
conda install -c conda-forge/label/cf202003 pyomeca

I waited to long time but when a try:

import pyomeca

I receive in return:

" Traceback (most recent call last):
File "", line 1, in
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.3.2\plugins\python-ce\helpers\pydev_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'pyomeca'. "

or

"TypeError: Parameters to generic types must be types. Got NotImplemented."

I think that library pyomeca was installed mas but I not can import.

If anybody can help me.
Regards.

Review: Running EMG Example

Using the instructions on the repository I could not view the figures without first importing pyplot from matplotlib. Not sure if this was only a problem for me. System/Anaconda spec : Python 3.6.10, Windows 10 Enterprise, 64-bit

Marker visualization

It's really impressive how much pyomeca has progressed! Have you ever considered including some form of simple 3D marker visualization?

__next__ iterates over the wrong dimension

The __next__ method from the FrameDependentNpArray iterates over the wrong dimension:

markers_4 = pyoio.read_c3d(MARKERS_ANALOGS_C3D, idx=[0, 1, 2, 3],
                           kind='markers', prefix=':')
for i in markers_4:
    print(f'shape: {i.shape}')

Output

shape: (4, 580)

In this case, we want to iterate over each frame. So shape should be (4, 4)

Review: Additional examples for other data

Dear authors,

I appreciated the documentation and associated paper. The simplicity of the implementation and seemingly overlapping functions and methods for the different data types is useful for the beginning.

I have some small comments relating to documentation which could help the lower level user adapt and utilise the project.

First, it would be helpful to also be able to replicate the examples in your research paper as they are slightly different to the example you provide on the repository.

While the API functions were very well documented, there are two interrelated cases I think would greatly benefit the project.

  1. Not being familiar with the xrarry python type I had to search a little while to be able access individual data, i.e., the specific EMG channel , this would be handy for those wanting to look at a specific channel for example

  2. The examples provided on the repository as well as within your research paper are centered around EMG data. Given you present the toolbox as a complete package for all biomechanical data - some additional example for Markers and Angles would be nice to see.

Merge show_vtk and pyogui to pyoviz

We should merge show_vtk and pyogui into an independent package so that the visualizations are independent of pyomeca (I propose pyoviz). Thus, the dependencies of pyomeca are reduced (especially vtk & Qt) and the user always has the option to download pyoviz to use our visualization wrapper.

Review pyomeca: future directions

Dear authors,

Thanks a lot for the excelent documentation and setting up everything in accordance with the software best practices.

I want to better understand your future directions and vision about this project.

The API and the use cases seem nice, however, in terms of added value it does not bring much to the user except basic operations such as reading, writing, filtering and plotting. I would find it very useful, if this framework goes a step forward and provide functions for processing and extracting meaningful clinical outputs from the raw data. For example, it would be very nice if you provide common utilities for extracting the kinematics and kinetics ensembles per gait cycle, or calculate cadence, speed, etc.

On the other hand, by looking at the repositories under pyomeca it seems that you are working on some nice packages that try to manipulate c3d files or interface with OpenSim. Is pyomeca only related to the features that were described in the publication or is it going to be something bigger where you will provide additional modules in the future? Please indicate your vision about this project and things you plan to support in the future. Are the projects under pyomeca intended for this publication or they will be published in the future?

PyTest

The created environment as it is proposed in packaging for dev won't work because there is missing dependencies

Here is the error message :
ImportError: cannot import name 'MappingProxyType'

NOTE : This happened on two different computers

computing distance between markers

Hi!

I am wondering about the possibility to use this library to compute distance between two markers. In the mokka, only option is to create graph, but no possibility to export the data. I do not have such data from original research, so I want to collect a data from distance between two markers like shoulder and finger.

Best regards,
Darek

Pyomeca on Google Colab?

First of all, thank you for your effort developing pyomeca, I find it fantastic!
My only concern is about the installation process in some environments such as Google Colab or even Winpython. Is it possible to install it via pip or other easy to use command?

Thank you for your time.

resultant velocity - trubles with calling xarrays with same commands as in older pyomeca version.

Hello!

I am writing again with the same issue after 2 years. You guys updated pyomeca and old code is not working.

vrtoe = (data[('B0346:RTOE')]/1000).derivative().norm()
v_RTOE = vrtoe.reshape(2720,1)

I cannot acess the c3d data in a same way once it becomes xarrays.

Is there any way to use old version of pyomeca? or I need to acess every axis now for x,y,z and make computation to get resultant velocity. I was pretty content with previous solution. Xarray documentation did not helped me with finding code as simple as that, only how to get to arrays and extract them to dataframes. It is more time consuming than previous solution.

I would be grateful for every hit how to solve my issue

conda seems a better option

Why we should use conda

  • Does not require administrator privilege
  • Can handle packages and environment
  • One python by envs
  • The python used is different from the one used by the OS
  • easy to clean (rm -rf ~/miniconda3/) and easy to install
  • Works for all type of language (python, R, matlab, etc.)
  • Can convert a pip package into a conda package
  • Easy to upload a package
  • Compiled code seems easier to integrate into a python package
  • Can convert a python package into Linux/Windows/Mac with conda-convert

Why we should use pipenv

  • Can handle packages and environment in one command
  • New packages are automatically updated in the Pipfile (but Pycharm can automatically update a requirements.txt)

Great resources

From nothing to a working conda package

  1. Install miniconda
$ bash Miniconda2-4.3.11-Linux-x86_64.sh
  1. (optional) If you use fish shell, add the following line in your config.fish file:
set -gx PATH ~/miniconda3/bin $PATH
source (conda info --root)/etc/fish/conf.d/conda.fish
  1. Create an env:
$ conda update conda
$ conda create -n env_name python=3.6
$ conda activate env_name
  1. Install cookiecutter
$ conda config --add channels conda-forge
$ conda install cookiecutter
  1. Create the package template and build the package
$ cookiecutter https://github.com/conda/cookiecutter-conda-python.git
$ cd env_name
$ conda install conda-build
$ conda build conda.recipe/
  1. Upload to anaconda.org
conda install anaconda-client
anaconda login
anaconda upload ~/miniconda3/envs/env_name/conda-bld/linux-64/env_name[...].tar.bz2

[To be continued...]

travis only

We don't really need appveyor? We should move to Travis only to build with Linux, Windows & Mac.

Hopefully:

os:
  - windows
  - linux
  - osx

Slicing data using the square brackets

Hello!

Would that makes sense to allow slicing using text, instead of requiring to access via isel?
For instance, a["x", "marker1", :] would call in the background return a.isel(...)
I think it would make things much easier for someone who is not accustomed to xarray. If I recall well, we discussed this already, but I don't recall the reason not to do it. Recently I helped someone who did not know how to use xarrays precisely for the reason (and I must admit, I had to browse on internet myself quite a lot to perform what feels to be very simple tasks such a slicing data).

In terms of changes, I think it would be very minimal, but would greatly help the community!

Write a paper

Let's publish a paper!

I think JOSS is a good candidate.

I have linked the issues I would like to resolve before publication in the paper milestone.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.