Modules

Anomaly

Anomaly Filter

This module contains pyCGM2 anomaly filters to deal with either an anomaly detector procedure or an anomaly correction procedure

check out the script : Teststest_anomalies.py for examples

class pyCGM2.Anomaly.anomalyFilters.AnomalyCorrectionFilter(acq, filename, procedure)

anomaly corrector filter

Parameters
class pyCGM2.Anomaly.anomalyFilters.AnomalyDetectionFilter(acq, filename, procedure, **kwargs)

Anomaly detector filter

Parameters
Kwargs:

frameRange (list): frame boundaries

AnomalyDetectionProcedure

This module gathers anomaly detectors on markers, events, force plate signals and anthropometric data

check out the script : Teststest_anomalies.py for example

class pyCGM2.Anomaly.anomalyDetectionProcedures.AnomalyDetectionProcedure

abstract marker detector procedure

class pyCGM2.Anomaly.anomalyDetectionProcedures.AnthropoDataAnomalyProcedure(mp)

atnthropometric data anomaly detector

run(acq, filename, options)

run the procedure

Parameters
  • acq (btk.Acquisition) – a btk acquisition instantce

  • filename (str) – filename

  • options (dict) – passed options ( Not used so far)

class pyCGM2.Anomaly.anomalyDetectionProcedures.ForcePlateAnomalyProcedure

force plate anomaly detector

run(acq, filename, options)

run the procedure

Parameters
  • acq (btk.Acquisition) – a btk acquisition instantce

  • filename (str) – filename

  • options (dict) – passed options

Note

frameRange ([int, int]) is one key of the options argument

class pyCGM2.Anomaly.anomalyDetectionProcedures.GaitEventAnomalyProcedure

gait event anomaly detector

run(acq, filename, options)

run the procedure

Parameters
  • acq (btk.Acquisition) – a btk acquisition instantce

  • filename (str) – filename

  • options (dict) – passed options ( Not used so far)

class pyCGM2.Anomaly.anomalyDetectionProcedures.MarkerAnomalyDetectionRollingProcedure(markers, plot=False, **kwargs)

marker anomaly detection from rolling statistics

Parameters
  • markers (list) – marker labels;

  • plot (bool) – enable plot

Kwargs:

aprioriError (double): a priori error on the marker trajectory window (int): size of the rolling windows treshold (int) : detector threshold assoiated to the standard deviation method (str) : mean or median

run(acq, filename, options)

run the procedure

Parameters
  • acq (btk.Acquisition) – a btk acquisition instantce

  • filename (str) – filename

  • options (dict) – passed options from the filter

AnomalyCorrectionProcedure

class pyCGM2.Anomaly.anomalyCorrectionProcedures.MarkerAnomalyCorrectionProcedure(markers, anomalyIndexes, plot=False, **kwargs)

procedure to correct marker anomaly

Parameters
  • markers (list) – marker labels

  • anomalyIndexes (list) – indexes of the detected anomalies

  • plot (bool) – enable plot

Keyword Arguments

distance_threshold (float) – distance threshold between indexes

run(acq, filename)

run the procedure

Parameters
  • acq (btk.Acquisition) – a btk acquisition instantce

  • filename (str) – filename

EMG module

emgManager

class pyCGM2.EMG.emgManager.EmgManager(DATA_PATH, emgSettings=None)

Class to manage emg settings ( ie the emg.settings file)

Parameters
  • DATA_PATH (str) – data folder path

  • emgSettings (str,Optional[None]) – content of the emg.settings file

getChannelSection()

return the channel section of the emg settings

getChannels()

return the channel labels

getMuscles()

return the muscles

getNormalActivity()

return the normal activity muscle reference

getProcessingSection()

return the processing section of the emg settings

getSides()

return side of each emg

emgFilters

This module contains emg filters handling emg procedures

check out the script : Tests est_EMG.py for examples

class pyCGM2.EMG.emgFilters.BasicEmgProcessingFilter(acq, labels)

Filter for filtering emg signals with a high pass filter

Parameters
  • acq (Btk.Acquisition) – btk acquisition instance

  • labels (list) – emg labels.

run()

Run the filter

setHighPassFrequencies(low, up)

Set the frequency boudaries of your emg Butterworth high-pass filter.

Parameters
  • low (float) – lower frequency

  • up (float) – upper frequency

class pyCGM2.EMG.emgFilters.DiscreteEMGFilter(discreteEMGProcedure, analysis, emgLabels, emgMuscles, emgContexts, subjInfo=None, condExpInfo=None)

Filter for handing procedure.

the goal of this filter is to return a Pandas dataframe.

Parameters
  • discreteEMGProcedure (pyCGM2.EMG.discreteEmgProcedures.procedure) – a discrete emg procedure instance.

  • analysis (pyCGM2.Processing.analysis.Analysis) – A pycgm2 analysis instance

  • emgLabels (list) – emg labels

  • emgMuscles (list) – muscle matching emg labels

  • emgContexts (list) – side of each emg labels

  • subjInfo (dict,Optional[None]) – dictionary decribing the subject. Items will be added to the generated pandas dataframe

  • condExpInfo (dict,Optional[None]) – dictionary decribing the experiment conditions. Items will be added to the generated pandas dataframe

getOutput()

run the procedure and get outputs

Returns

pandas.Dataframe – DataFrame

setCondExpInf(condExpInfo)

set experiment condition info

Parameters

condExpInfo (dict) – dictionary decribing the experiment conditions. Items will be added to the generated pandas dataframe

setSubjInfo(subjInfo)

set subject info

Parameters

subjInfo (dict) – dictionary decribing the subject. Items will be added to the generated pandas dataframe

class pyCGM2.EMG.emgFilters.EmgCoActivationFilter(analysis, context)

Filter for computing coactivation index

Parameters
run()

run ethe filter

The coactivation section of the pyCGM2-Analysis instance is updated with descriptive statistics

setCoactivationMethod(concreteCA)

set the coactivation procedure

Parameters

concreteCA (pyCGM2.EMG.Coactivation) – Coactivation procedure instance

setEMG1(label)

set the label of the first emg signal

Parameters

label (str) – emg label

setEMG2(label)

set the label of the second emg signal

Parameters

label (str) – emg label

class pyCGM2.EMG.emgFilters.EmgEnvelopProcessingFilter(acq, labels)

Filter for processing emg envelop from low-pass filter :param acq: btk acquisition instance :type acq: Btk.Acquisition :param labels: emg labels. :type labels: list

run()

Run the filter

setCutoffFrequency(fc)

Set the cut-off frequency.

Parameters

fc (float) – cut-off frequency

class pyCGM2.EMG.emgFilters.EmgNormalisationProcessingFilter(analysis, label, context)

Filter for normalizing emg signals in amplitude

Parameters
processAnalysis()

Process the pyCGM2 analysis instance

New labels with the suffix _Norm is created in the section emgStats.data of the pyCGM2 analysis instance

processC3d()

Process all c3d filenames

Each c3d are updated and include a new analog label with the suffix _Norm

run()

run the filter

setC3ds(datPath, c3ds, fileSuffix=None)

Set a list of c3d.

Parameters
  • datPath (str) – Folder data path

  • c3ds (list) – the names of c3d

  • fileSuffix (str,optional) – suffix added to c3d filenames

setMaxMethod(EnumEmgNorm, Value=None)

set a normalisation method

Parameters
  • EnumEmgNorm (pyCGM2.Enums) – method

  • Value (float,Optional) – force the denominator value

setThresholdFromOtherAnalysis(analysis)

Set an other pyCGM2 analysis instance as normalisation denominator

Parameters

analysis (pyCGM2.Processing.analysis.Analysis) – A pycgm2 analysis instance

coactivationProcedures

This module contains co-activation procedures

check out the script : Tests est_EMG.py for examples

class pyCGM2.EMG.coactivationProcedures.FalconerCoActivationProcedure

Coactivation index according falconer and Winter

Falconer K, Winter DA. Quantitative assessment of cocontraction at the ankle joint in walking. Electromyogr Clin Neurophysiol. 1985;25:135–149. [PubMed] [Google Scholar]

run(emg1, emg2)

run the procedure.

Parameters
  • emg1 (str) – emg label .

  • emg2 (str) – emg label

Returns

list – Coactivation index

class pyCGM2.EMG.coactivationProcedures.UnithanCoActivationProcedure

Coactivation procedure according Unithan et al, 1996

Unnithan VB, Dowling JJ, Frost G, Volpe Ayub B, Bar-Or O. Cocontraction and phasic activity during GAIT in children with cerebral palsy. Electromyogr Clin Neurophysiol. 1996;36:487–494.

run(emg1, emg2)

run the procedure.

Parameters
  • emg1 (str) – emg label .

  • emg2 (str) – emg label

Returns

list – Coactivation index

discreteEmgProcedures

Module containes Filter and Procedure for extracting discrete value ( e.g : amplitude) from each emg signal

class pyCGM2.EMG.discreteEmgProcedures.AmplitudesProcedure

This procedure computes EMG amplitude for each gait phases

detect(analysisInstance, emgLabels, emgMuscles, emgContexts)

Compute amplitudes

Parameters
  • analysis (pyCGM2.Processing.analysis.Analysis) – A pycgm2 analysis instance

  • emgLabels (list) – emg labels

  • emgMuscles (list) – muscle matching emg labels

  • emgContexts (list) – side of each eamg labels

normalActivation

The module contains convenient function for getting the normal emg activity of the muscles listed in the file (pyCGM2/Data/normativeData/emg/normalActivation.json).

pyCGM2.EMG.normalActivation.getNormalBurstActivity(muscle, fo)

get onsets and offsets of a specific muscle.

Parameters
  • muscle (str) – muscle label listed in normalActivation.json

  • fo (int) – foot off frame

pyCGM2.EMG.normalActivation.getNormalBurstActivity_fromCycles(muscle, ff, begin, fo, end, apf)

get onsets and offsets of a specific muscle from .

Parameters
  • muscle (str) – muscle label listed in normalActivation.json

  • ff (int) – first frame of the btk.acquisition

  • begin (int) – initial frame of cycle

  • fo (int) – foot off frame

  • end (int) – final frame of the cycle

  • apf (int) – nNumber of analog sample per frame

Event

eventFilters

The module contains filter for detecting foot contact events.

check out the script : Tests est_events.py for examples

class pyCGM2.Events.eventFilters.EventFilter(procedure, acq)

Event filter to handle an event procedure

detect()

Run the motion filter

eventProcedures

The module contains procedures for detecting foot contact event.

check out the script : Tests est_events.py for examples

class pyCGM2.Events.eventProcedures.ZeniProcedure

Gait Event detection from Zeni et al, 2008

detect(acq)

detect events

Parameters

acq (Btk.Acquisition) – a btk acquisition instance

Returns

frames indicating the left foot strike, the left foot off, the right foot strike and the right foot off respectively

Return type

int,int,int,int

setFootOffOffset(value)

set a systematic offset to each foot off event

Parameters

value (int) – frame offset

setFootStrikeOffset(value)

set a systematic offset to each foot strike event

Parameters

value (int) – frame offset

force Plates module

forcePlates

The module contains convenient functions for working with force plate.

check out the script : Tests est_forcePlateMatching.py for examples

pyCGM2.ForcePlates.forceplates.ForcePlateIntegration(ReactionForce, mass, frameInit=0, frameEnd=None, v0=[0, 0, 0], p0=[0, 0, 0], analogFrequency=1000)

integration of the reaction force

Parameters
  • ReactionForce (array[frames,3) – ground reaction force

  • mass (double) – bodymass

  • frameInit (int,Optional[0]) – initial frame of the area of interest

  • frameEnd (int,Optional[None]) – initial frame of the area of interest.

  • v0 (list,Optional[0,0,0]) – initial velocity.

  • p0 (list,Optional[0,0,0]) – initial position.

  • analogFrequency (double,optional[1000]) – analog frequency.

pyCGM2.ForcePlates.forceplates.addForcePlateGeneralEvents(btkAcq, mappedForcePlate)

add maximum force plate as general event

Parameters
  • btkAcq (btk.acquisition) – btk acquisition instance

  • mappedForcePlate (str) – letters indicated foot assigned to a force plate (eg LRX)

pyCGM2.ForcePlates.forceplates.appendForcePlateCornerAsMarker(btkAcq)

update a btk acquisition with force plate corners as marker

Parameters

btkAcq (Btk.Acquisition) – a btk acquisition instance

pyCGM2.ForcePlates.forceplates.correctForcePlateType5(btkAcq)

Correct acquisition with force plate of type 5

Parameters

btkAcq (btk.acquisition) – btk acquisition instance

pyCGM2.ForcePlates.forceplates.matchingFootSideOnForceplate(btkAcq, enableRefine=True, forceThreshold=50, left_markerLabelToe='LTOE', left_markerLabelHeel='LHEE', right_markerLabelToe='RTOE', right_markerLabelHeel='RHEE', display=False, mfpa=None)

Convenient function detecting foot in contact with a force plate

This function firsly assign foot side to FP from minimal distance with the application point of reaction force. A refinement is done subsequently, it confirm if foot side is valid. A foot is invalided if :

  • FP output no data superior to the set threshold

  • Foot markers are not contain in the polygon defined by force plate corner

Parameters
  • btkAcq (Btk.Acquisition) –

  • enableRefine (bool,Optional) – enable refinement from vertical force of the foot assigned from marker position.

  • forceThreshold (double,Optional[50]) – vertical force threshold.

  • left_markerLabelToe (type,Optional[LTOE]) – marker label of the left toe.

  • left_markerLabelHeel (type,Optional[LHEE]) – marker label of the left heel.

  • right_markerLabelToe (type,Optional[RTOE]) – marker label of the right toe.

  • right_markerLabelHeel (type,Optional[RHEE]) – marker label of the right heel.

  • display (bool,Optional[false]) – display n figures (where n is the force plate number) presenting relative distance between mid foot and the orgin of the force plate.

  • mfpa (str,Optional[None]) – force plate manually assigned from Vicon Eclipse.

Gap

GapFilters

The module contains filter and procedure for filling gap

check out the script : Tests est_gap.py for examples

class pyCGM2.Gap.gapFilters.GapFillingFilter(procedure, acq)

Gap filter

Parameters
  • procedure (pyCGM2.Gap.gapFillingProcedures.GapProcedure) – a gap filling procedure instance

  • acq (Btk.Acquisition) – a btk acquisition instance

fill(markers=None)

fill gap according the specified procedure

GapProcedures

The module contains filter and procedure for filling gap

check out the script : Tests est_gap.py for examples

class pyCGM2.Gap.gapFillingProcedures.LowDimensionalKalmanFilterProcedure

gap fill procedure according Burke et al. (Job 2016)

Burke, M.; Lasenby, J. (2016) Estimating missing marker positions using low dimensional Kalman smoothing. In : Journal of biomechanics, vol. 49, n° 9, p. 1854–1858. DOI: 10.1016/j.jbiomech.2016.04.016.

Inspector

inspectorFilters

Module contain the filter for running inspector procedure.

class pyCGM2.Inspector.inspectorFilters.InspectorFilter(acq, filename, procedure, **kwargs)

pyCGM2 filter

inspectorProcedures

Module contains inspector procedure.

An inspector just inspect the content of an acquisition. It doesn’t alter it.

class pyCGM2.Inspector.inspectorProcedures.MarkerPresenceDetectionProcedure(markers=None)

Procedure to check marker presence in the acquisition.

Parameters

markers (list,Optional[None]) – marker labels

Model

anthropometricMeasurement

bodySegmentParameters

class pyCGM2.Model.bodySegmentParameters.Bsp(iModel)

Body Segment Parameter of the lower limb according Dempster 1995

Reference

Dempster. (1955). Body Segment Parameter Data for 2-D Studies

compute()

Compute body segment parameters of a Model

classmethod setParameters(bspSegmentLabel, segmentLength, bodymass)

Compute body parameter of a selected lower limb segment

Parameters
  • bspSegmentLabel (str) – segment label defined in the class object TABLE

  • segmentLength (double) – length of the segment

  • bodymass (double) – mass of the subject

frame

this module gathers two classes (Node and Frame), important for the construction of a model

A Frame is a representation of a coordinate system at a specific time. Its main attributes are the rotation matrix and the translation vectors.

A Frame can collect Node instances. A Node represents a 3d point expressed in a local coordinate system

class pyCGM2.Model.frame.Frame

A Frame represents a coordinate system

addNode(nodeLabel, position, positionType='Global', desc='')

Append a Node to a Frame

Parameters
  • nodeLabel (str) – node label

  • position (array(3,)) – a translation vector

  • positionType (str,Optional) – two choice Global or Local

  • desc (str,Optional) – description

copyNode(nodeLabel, nodeToCopy)

Copy a node and add it or update a existant node

Parameters
  • nodeLabel (str) – the node label

  • nodeToCopy (str) – the label of the node to copy

eraseNodes()

Erase all nodes

getAngleAxis()

Get the angle axis

getGlobalPosition(nodeLabel)

Return the global position

Parameters

nodeLabel (str) – the node label

getNodeIndex(nodeLabel)

Get the node index

Parameters

nodeLabel (str) – the node label

getNodeLabels(display=True)

Display all node labels

getNode_byIndex(index)

Get a node from its index

Parameters

index (int) – index of the node within the list

getNode_byLabel(label)

Get a node from its label

Args:

label(str): the node label

getNodes()

Return all node instances

getRotation()

Get rotation matrix

Returns

array ((3,3) – a rotation matrix

getTranslation()

Get translation vector

isNodeExist(nodeLabel)

Check if a node exists from its label

Parameters

nodeLabel (str) – the node label

setRotation(R)

Set the rotation matrix

Parameters

R (array(3,3) – a rotation matrix

setTranslation(t)

Set the translation vector

Parameters

t (array(3,)) – a translation vector

update(R, t)

Update both the rotation matrix and the translation vector

Parameters
  • R (array(3,3) – a rotation matrix

  • t (array(3,)) – a translation vector

updateAxisFromRotation(R)

Update the rotation matrix

Parameters

R (array(3,3) – a rotation matrix

updateNode(nodeLabel, localArray, globalArray, desc='')

Update a node

Parameters
  • nodeLabel (str) – the node label

  • localArray (array(3)) – local position

  • globalArray (array(3)) – global position

  • desc (str,Optional) – description

class pyCGM2.Model.frame.Node(label, desc='')

A node is a local position of a 3D point in a coordinate system

Note

Automatically, the suffix “_node” ends the node label

Parameters
  • label (str) – desired label of the node

  • desc (str,Optional) – description

computeGlobal(rot, t)

Compute global position from local

Parameters
  • rot (array((3,3)) – a rotation matrix

  • t (array((1,3)) – a translation vector

computeLocal(rot, t)

Compute local position from global position

Parameters
  • rot (array(3,3)) – a rotation matrix

  • t (array((1,3))) – a translation vector

getDescription()

Get the node description

getGlobal()

Get the global coordinates of the node

getLabel()

Get the node label

getLocal()

Get the local coordinates of the node

setDescription(description)

Set description of the node

Parameters

description (str) – description

pyCGM2.Model.frame.angleAxisFromQuaternion(Quaternion)

Calculates the AngleAxis representation from a quaternion

Parameters

Quaternion (array(4)) – a quaternion

pyCGM2.Model.frame.getQuaternionFromMatrix(RotMat)

Calculates the quaternion representation from a rotation matrix.

Algorithm in Ken Shoemake’s article in 1987 SIGGRAPH course notes article “Quaternion Calculus and Fast Animation”.

Parameters

RotMat (array(3,3)) – Rotation matrix

pyCGM2.Model.frame.setFrameData(a1, a2, sequence)

Set axes and rotation matrix of a coordinate system from 2 vectors and a sequence

The sequence can be all combinaison of XYZ. If the second letter is prefixed by i, the opposite vector to the cross product a1, a2 is considered

Parameters
  • a1 (array(1,3)) – first vector

  • a2 (array(1,3)) – second vector

  • sequence (str) – construction sequence (XYZ, XYiZ,…)

model

class pyCGM2.Model.model.AnatomicalReferential

A AnatomicalReferential represents a anatomical coordinate system constructed from either tracking or calibration markers during a static pose

A AnatomicalReferential inherits from Referential.

class pyCGM2.Model.model.ClinicalDescriptor(dataType, jointOrSegmentLabel, indexes, coefficients, offsets, **options)

A clinical descriptor.

Parameters
  • dataType (enums.DataType) – type of data (ie Angle, Moment,… ( see enums))

  • jointOrSegmentLabel (str) – label of the joint or the segment

  • indexes (list(3)) – indexes of the outputs

  • coefficients (list(3)) – coefficients to apply on the ouputs

  • offsets (list(3)) – offset to apply on the ouputs ( eg, 180 degree substraction )

Kwargs:

projection(enums.MomentProjection): coordinate system used to project the joint moment

```python

ClinicalDescriptor(enums.DataType.Angle,”LHip”, [0,1,2],[-1.0,-1.0,-1.0], [0.0,0.0,0.0]

```

class pyCGM2.Model.model.Joint(label, proxLabel, distLabel, sequence, nodeLabel)

a Joint is the common point between a proximal and a distal segment

Parameters
  • label (str) – label of the chain

  • proxLabel (str) – label of the proximal segment

  • distLabel (str) – label of the distal segment

  • sequence (str) – sequence angle

class pyCGM2.Model.model.Model

Abstract class Model.

A Model is made of segments, joints, body segment parameters

addAnthropoInputParameters(iDict, optional=None)

Add measured anthropometric data to the model

Parameters
  • iDict (dict) – required anthropometric data

  • optionalMp (dict,Optional) – optional anthropometric data

addChain(label, indexSegmentList)

Add a segment chain

Parameters
  • label (str) – label of the chain

  • indexSegmentList (list) – indexes of the segment which constitute the chain

addJoint(label, proxLabel, distLabel, sequence, nodeLabel)

Add a joint

Parameters
  • label (str) – label of the chain

  • proxLabel (str) – label of the proximal segment

  • distLabel (str) – label of the distal segment

  • sequence (str) – sequence angle

addSegment(label, index, sideEnum, calibration_markers=[], tracking_markers=[], cloneOf=False)

Add a segment

Parameters
  • label (str) – label of the segment

  • index (str) – index of the segment

  • sideEnum (pyCGM2.enums) – body side

  • calibration_markers (list) – labels of the calibration markers

  • tracking_markers (list) – labels of the tracking markers

displayStaticCoordinateSystem(aquiStatic, segmentLabel, targetPointLabel, referential='Anatomic')

Display a coordinate system. Its Axis are represented by 3 virtual markers suffixed by (_X,_Y,_Z)

Parameters
  • aquiStatic (btkAcquisition) – btkAcquisition instance from a static c3d

  • segmentLabel (str) – segment label

  • targetPointLabel (str) – label of the point defining axis limits

  • referential (str,Optional) – type of segment coordinate system you want to display.

  • (choiceAnatomic or technical, default: Anatomic )

getBodyPart()

[Obsolete] return the body part represented by the model

getCentreOfMass()

return the center of mass trajectory

getClinicalDescriptor(dataType, jointOrSegmentLabel, projection=None)

return a clinical descriptor

Parameters
  • jointOrSegmentLabel (str) – segment or joint label.

  • dataType (pyCGM2.enums.DataType) – data type.

  • projection (enums.MomentProjection,Optional[None]) – joint moment projection

getJoint(label)

Get a Joint from its label

Parameters

label (str) – label of the joint

getJointList()

Get the Joint labels

getProperty(propertyLabel)

Return a property

Parameters

propertyLabel (str) – the properted label

getSegment(label)

Get Segment from its label

Parameters

label (str) – label of the Segment

getSegmentByIndex(index)

Get Segment from its index

Parameters

index (int) – index of the Segment

getSegmentIndex(label)

Get Segment index from its label

Parameters

label (str) – label of the Segment

getSegmentList()

Get the Segment labels

isCalibrationProperty(label)

check if a calibration property exists from its label

Parameters

label (str) – the properted label

isProperty(label)

check if a property exists from its label

Parameters

label (str) – the properted label

removeJoint(jointlabels)

Remove joint from its label

Parameters

jointlabels (list) – joint labels to remove

removeSegment(segmentlabels)

Remove Segment from its label

Parameters

label (list) – segment labels to remove

setBodyPart(bodypart)

[Obsolete] Specify which body part is represented by the model

setCalibrationProperty(propertyLabel, value)

Set or update the calibration property dictionary.

Parameters
  • propertyLabel (str) – the property label

  • value (All) – the property value

setCentreOfMass(com)

Set the center of mass trajectory

Parameters

com (array(n,3)) – Description of parameter com.

setClinicalDescriptor(jointOrSegmentLabel, dataType, indexes, coefficients, offsets, **options)

set a clinical descriptor

Parameters
  • jointOrSegmentLabel (str) – segment or joint label.

  • dataType (pyCGM2.enums.DataType) – data type.

  • indexes (list) – indexes

  • coefficients (list) – coefficients to apply on outputs

  • offsets (list) – offsets to apply on outputs

Kwargs:

projection(enums.MomentProjection): coordinate system used to project the joint moment

```python

model.setClinicalDescriptor(“LHip”,enums.DataType.Angle, [0,1,2],[-1.0,-1.0,-1.0], [0.0,0.0,0.0]

```

setProperty(propertyLabel, value)

Set or update the property dictionary.

Parameters
  • propertyLabel (str) – the property label

  • value (All) – the property value

setStaticFilename(name)

Set the static filename used for static calibration

Parameters

name (str) – the filename

updateSegmentFromCopy(targetLabel, segmentToCopy)

Update a segment from a copy of an other segment instance

Parameters
  • targetLabel (str) – label of the segment

  • segmentToCopy (pyCGM2.Model.CGM2.model.Segment) – a segment instance

class pyCGM2.Model.model.Model6Dof
class pyCGM2.Model.model.Referential

A Referential defined a segmental coordinate system. The two main atributes of a Referential instance are:

  • the static attribute ( ie a Frame instance) which characterized

the mean pose from the static trial

  • the motion attribute ( ie a list of Frame instance) which characterized

the pose at each time-frame of the dynamic trial

addMotionFrame(Frame)

Append a Frame to the motion attribute

Parameters

Frame (pyCGM2.Model.CGM2.frame.Frame) – a Frame instance

getNodeTrajectory(label)

Return the trajectory of a node

Parameters

label (str) – label of the desired node

getOriginTrajectory()

Return the trajectory of the origin

setStaticFrame(Frame)

Set the static pose

Parameters

Frame (pyCGM2.Model.CGM2.frame.Frame) – a Frame instance

class pyCGM2.Model.model.Segment(label, index, sideEnum, calibration_markers=[], tracking_markers=[])

A Segment represents a rigid body

Parameters
  • label (str) – label

  • index (str) – index

  • sideEnum (pyCGM2.enums) – body side

  • lst_markerlabel (list) – calibration and tracking markers

  • tracking_markers (list) – tracking markers

addCalibrationMarkerLabel(labels)

Add a calibration marker

Parameters

labels (str or list) – marker label

addExternalDeviceWrench(btkWrench)

Add an external device wrench

Parameters

btkWrench (btk.Wrench) – a btk wrench instance

addTechnicalReferential(label)

Add a technical referential

Parameters

label (str) – given label of the technical frame

addTrackingMarkerLabel(labels)

Add a tracking marker

Parameters

labels (str or list) – marker labels

downSampleExternalDeviceWrenchs(appf)

Downsample external device wrenchs

Parameters

appf (int) – analog point per frame

getAngularAcceleration(sampleFrequency)

Return the angular acceleration

getAngularVelocity(sampleFrequency, method='conventional')

Return the angular velocity

Parameters
  • sampleFrequency (double) – point frequency

  • method (str,Optional) – method used for computing the angular velocity

  • pig) ((conventional or) –

Notes:

The conventional method computes angular velocity through the matrix product $dot{R}R^t$

The pig method duplicates a bodybuilder code of the plug-in gait in which the velocity is computed from differentation between the next and previous pose

getComAcceleration(pointFrequency, method='spline', **options)

Get global linear acceleration of the centre of mass

Parameters
  • pointFrequency (double) – point frequency

  • method (str,Optional) – derivation method (spline, spline fitting)

Kwargs:

order(int): low pass filter order fc(double): low pass filter cut-off frequency

getComTrajectory(exportBtkPoint=False, btkAcq=None)

Return the trajectory of the centre of mass

Parameters
  • exportBtkPoint (bool) – enable export as btk.point

  • btkAcq (btk acquisition) – a btk acquisition instance

getComVelocity(pointFrequency, method='spline')

Get the linear velocity of the centre of mass

Parameters
  • pointFrequency (double) – point frequency

  • method (str,Optional) – derivation method (spline, spline fitting)

getReferential(label)

Return a referential from its label

Parameters

label (str) – technical referential label

isExternalDeviceWrenchsConnected()

Detect external device wrenchs

removeTrackingMarker(labels)

Aemove a tracking marker

Parameters

label (str) – label

setComPosition(array3)

Set local position of the centre of mass

Parameters

array (array(3)) – centre of mass position

setInertiaTensor(array33)

Set segment inertia tensor

Parameters

array (array(3,3)) – tensor of inertia

setLength(value)

Set segment length

Parameters

value (double) – length

setMass(value)

Set segment mass

Parameters

value (double) – mass

setRog(value)

Set segment radius of giration

Parameters

value (double) – radius of giration

zeroingExternalDevice()

Zeroing external device wrench

zeroingProximalWrench()

Zeroing proximal wrench

class pyCGM2.Model.model.TechnicalReferential(label)

A TechnicalReferential represents a Technical coordinate system constructed from tracking markers

A TechnicalReferential inherits from Referential.

Parameters

label (str) – label of the technical referential

setRelativeMatrixAnatomic(array)

Set the relative rigid rotation of the anatomical Referential expressed in the technical referential (\(R^a_t\)).

Parameters

array (numpy.array(3,3) – rigid rotation

modelDecorator

this module gathers classes/ functions for calibrating a model, ie locating joint centres and axis

class pyCGM2.Model.modelDecorator.AnkleCalibrationDecorator(iModel)

Concrete cgm decorator altering the ankle joint

Parameters

iModel (CGM2.cgm.CGM) – a CGM instance

fromAjcMarker(acq, leftAJC_label='LAJC', rightAJC_label='RAJC', side='both')

AJC positioned from virtual AJC marker trajectory computed from an other process

Parameters
  • acq (btkAcquisition) – an acquisition with the virtual AJC marker trajectory

  • leftAJC_label (str,Optional[LAJC]) – left virtual AJC label

  • rightAJC_label (str,Optional[RAJC]) – right virtual AJC label

  • side (str,Optional[True]) – body side

midMaleolus(acq, side='both', leftLateralAnkleLabel='LANK', leftMedialAnkleLabel='LMED', rightLateralAnkleLabel='RANK', rightMedialAnkleLabel='RMED', markerDiameter=14, widthFromMp=True)

Compute the ankle joint centre from mid maleolus.

Parameters
  • acq (btkAcquisition) – a btk acquisition instance of a static c3d

  • side (str,Optional[True]) – body side

  • leftLateralAnkleLabel (str,Optional[LANK]) – label of the left lateral ankle marker

  • leftMedialAnkleLabel (str,Optional[LMED]) – label of the left medial ankle marker

  • rightLateralAnkleLabel (str,Optional[RANK]) – label of the right lateral ankle marker

  • rightMedialAnkleLabel (str,Optional[RMED]) – label of the right medial ankle marker

  • markerDiameter (double,Optional[14]) – marker diameter

  • widthFromMp (bool,Optional[True]) – knee with from model anthropometric parameters

class pyCGM2.Model.modelDecorator.Cgm1ManualOffsets(iModel)

Replicate behaviour of the CGM1 if segmental offset manaully altered

Args

iModel (CGM2.cgm.CGM): a CGM instance

compute(acq, side, thighoffset, markerDiameter, tibialTorsion, shankoffset)

run the processing

Args

acq (btk.Acquisition): an aquisition instance of a static c3d side (str): body side thighoffset (double): thigh offset markerDiameter (double): diameter of marker shankoffset (double): shank offset tibialTorsion (double): tibial torsion

class pyCGM2.Model.modelDecorator.DecoratorModel(iModel)
class pyCGM2.Model.modelDecorator.HipJointCenterDecorator(iModel)

Concrete CGM decorators altering the hip joint centre

Parameters

iModel (CGM2.cgm.CGM) – a CGM instance

bell(side='both')

Use of the Bell’s regressions

Parameters

side (str,Optional[both]) – body side

custom(position_Left=0, position_Right=0, side='both', methodDesc='custom')

Locate hip joint centres manually

Parameters
  • position_Left (np.array(3,)) – position of the left hip center in the pelvis referential

  • position_Right (np.array(3,)) – position of the right hip center in the pelvis referential

  • side (str,Optional[both]) – body side

  • methodDesc (str,Optional[Custom]) – short description of the method

Note:

  • look out the pelvis referential. It has to be similar to the cgm1 pelvis referential.

davis(side='both')

Use of the Davis’s regressions

Parameters

side (str,Optional[both]) – body side

fromHjcMarker(acq, leftHJC_label='LHJC', rightHJC_label='RHJC', side='both')

HJC positioned from a virtual HJC marker trajectory computed from an other process

Parameters
  • acq (btk.Acquisition) – an aquisition instance with the virtual HJC marker trajectories

  • leftHJC_label (str,Optional["LHJC"]) – label of the left vritual HJC marker

  • rightHJC_label (str,Optional["RHJC"]) – label of the right vritual HJC marker

  • side (str,Optional[both]) – body side

hara(side='both')

Use of the Hara’s regressions

Parameters

side (str,Optional[both]) – body side

harrington(predictors=HarringtonPredictor.Native, side='both')

Use of the Harrington’s regressions

Parameters
  • predictors (pyCGM2.enums,Optional[enums.HarringtonPredictor.Native]) – harrington’s predictors to use

  • side (str,Optional[both]) – body side

class pyCGM2.Model.modelDecorator.Kad(iModel, iAcq)

A concrete CGM decorator altering the knee joint centre from the Knee Aligment device

Args

iModel (CGM2.cgm.CGM): a CGM instance iAcq (btk.Acquisition): btk aquisition instance of a static c3d with the KAD

compute(side='both', markerDiameter=14)

Run the KAD processing

Parameters
  • side (str,Optional[both]) – body side

  • markerDiameter (double,Optional[14]) – diameter of the marker

class pyCGM2.Model.modelDecorator.KneeCalibrationDecorator(iModel)

Concrete cgm decorator altering the knee joint

Parameters

iModel (CGM2.cgm.CGM) – a CGM instance

calibrate2dof(side, **kwargs)

run the calibration2Dof method

Parameters

side (str) – body side

Kargs:

indexFirstFrame (int): start frame indexLastFrame (int): last frame sequence (str): Euler sequence jointRange (list): flexion angle boundaries

fromKjcMarker(acq, leftKJC_label='LKJC', rightKJC_label='RKJC', side='both')

KJC positioned from a virtual KJC marker trajectory computed from an other process

Parameters
  • acq (btkAcquisition) – an acquisition with the virtual KJC marker trajectoriy

  • leftKJC_label (str,Optional[LKJC]) – left virtual KJC label

  • rightKJC_label (str,Optional[RKJC]) – right virtual KJC label

  • side (str,Optional[True]) – body side

midCondyles(acq, side='both', leftLateralKneeLabel='LKNE', leftMedialKneeLabel='LKNM', rightLateralKneeLabel='RKNE', rightMedialKneeLabel='RKNM', markerDiameter=14, widthFromMp=True)

Compute Knee joint centre from mid condyles.

Parameters
  • acq (btkAcquisition) – a btk acquisition instance of a static c3d

  • side (str,Optional[True]) – body side

  • leftLateralKneeLabel (str,Optional[LKNE]) – label of the left lateral knee marker

  • leftMedialKneeLabel (str,Optional[LKNM]) – label of the left medial knee marker

  • rightLateralKneeLabel (str,Optional[RKNE]) – label of the right lateral knee marker

  • rightMedialKneeLabel (str,Optional[RKNM]) – label of the right medial knee marker

  • markerDiameter (double,Optional[14]) – marker diameter

  • widthFromMp (bool,Optional[True]) – knee with from model anthropometric parameters

midCondyles_KAD(acq, side='both', leftLateralKneeLabel='LKNE', leftMedialKneeLabel='LKNM', rightLateralKneeLabel='RKNE', rightMedialKneeLabel='RKNM', markerDiameter=14)

Compute Knee joint centre from mid condyles and relocate AJC like KAD process.

Parameters
  • acq (btkAcquisition) – a btk acquisition instance of a static c3d

  • side (str,Optional[both]) – body side

  • leftLateralKneeLabel (str,Optional[LKNE]) – label of the left lateral knee marker

  • leftMedialKneeLabel (str,Optional[LKNM]) – label of the left medial knee marker

  • rightLateralKneeLabel (str,Optional[RKNE]) – label of the left lateral knee marker

  • rightMedialKneeLabel (str,Optional[RKNM]) – label of the left medial knee marker

  • markerDiameter (double,Optional[14]) – marker diameter

sara(side, **kwargs)

Compute Knee flexion axis, relocate knee joint centre from SARA functional calibration

Parameters

side (str) – body side

Kargs:

indexFirstFrame (int): start frame indexLastFrame (int): last frame

pyCGM2.Model.modelDecorator.VCMJointCentre(HalfJoint, JointMarker, TopJoint, StickMarker, beta=0)

Calculate the joint centre according the Vicon Clinical Manager method ( ie chord function )

Parameters
  • HalfJoint (double) – radius of the joint

  • JointMarker (array(1,3)) – joint marker trajectory at a specific frame

  • TopJoint (type) – proximal joint centre trajectory at a specific frame

  • StickMarker (type) – lateral marker trajectory at a specific frame

  • beta (double,Optional[0]) – rotation angle offset.

Reference

Kabada, M., Ramakrishan, H., & Wooten, M. (1990). Measurement of lower extremity kinematics during level walking. Journal of Orthopaedic Research, 8, 383–392.

pyCGM2.Model.modelDecorator.bellRegression(mp_input, mp_computed, markerDiameter=14.0, basePlate=2.0, cgmReferential=True)

Hip joint centre regression from Bell and Brand et al, 2007

Args

mp_input (dict): dictionary of the measured anthropometric parameters mp_computed (dict): dictionary of the cgm-computed anthropometric parameters markerDiameter (double,Optional[14.0]): diameter of the marker basePlate (double,Optional[2.0]): thickness of the base plate cgmReferential (bool,optional[True]) - flag indicating HJC position will be expressed in the CGM pelvis Coordinate system

Reference:

  • Bell AL, Pederson DR, and Brand RA (1989) Prediction of hip joint center location from external landmarks. Human Movement Science. 8:3-16:

  • Bell AL, Pedersen DR, Brand RA (1990) A Comparison of the Accuracy of Several hip Center Location Prediction Methods. J Biomech. 23, 617-621.

pyCGM2.Model.modelDecorator.calibration2Dof(proxMotionRef, distMotionRef, indexFirstFrame, indexLastFrame, jointRange, sequence='YXZ', index=1, flexInd=0)

Calibration 2DOF ( aka dynakad)

Parameters
  • proxMotionRef (pyCGM2.Model.Referential.motion) – motion attribute of the proximal referential

  • distMotionRef (pyCGM2.Model.Referential.motion) – motion attribute of the distal referential

  • indexFirstFrame (int) – start frame

  • indexLastFrame (int) – end frame

  • jointRange (list) – minimum and maximum joint angle to process

  • sequence (str,Optional[YXZ]) – Euler sequence

  • index (int,Optional[1]) – coronal plane index

  • flexInd (int,Optional[0]) – sagital plane index

pyCGM2.Model.modelDecorator.davisRegression(mp_input, mp_computed, markerDiameter=14.0, basePlate=2.0)

Hip joint centre regression according Davis et al, 1991

Args

mp_input (dict): dictionary of the measured anthropometric parameters mp_computed (dict): dictionary of the cgm-computed anthropometric parameters markerDiameter (double,Optional[14.0]): diameter of the marker basePlate (double,Optional[2.0]): thickness of the base plate

Reference:

Davis, R., Ounpuu, S., Tyburski, D., & Gage, J. (1991). A gait analysis data collection and reduction technique. Human Movement Science, 10, 575–587.

pyCGM2.Model.modelDecorator.footJointCentreFromMet(acq, side, frameInit, frameEnd, markerDiameter=14, offset=0)

calculate the foot centre from metatarsal markers.

Parameters
  • acq (btk.acquisition) – an acquisition

  • side (str) – body sideEnum

  • frameInit (int) – start frame

  • frameEnd (int) – end frame

  • markerDiameter (double,Optional[14]) – marker diameter.

  • offset (double,Optional[0]) – marker offset.

pyCGM2.Model.modelDecorator.haraRegression(mp_input, mp_computed, markerDiameter=14.0, basePlate=2.0)

Hip joint centre regression from Hara et al, 2016

Args

mp_input (dict): dictionary of the measured anthropometric parameters mp_computed (dict): dictionary of the cgm-computed anthropometric parameters markerDiameter (double,Optional[14.0]): diameter of the marker basePlate (double,Optional[2.0]): thickness of the base plate

Reference

Hara, R., Mcginley, J. L., C, B., Baker, R., & Sangeux, M. (2016). Generation of age and sex specific regression equations to locate the Hip Joint Centres. Gait & Posture

pyCGM2.Model.modelDecorator.harringtonRegression(mp_input, mp_computed, predictors, markerDiameter=14.0, basePlate=2.0, cgmReferential=True)

Hip joint centre regression from Harrington et al, 2007

Parameters
  • mp_input (dict) – dictionary of the measured anthropometric parameters

  • mp_computed (dict) – dictionary of the cgm-computed anthropometric parameters

  • predictors (str) – predictor choice of the regression (full,PWonly,LLonly)

  • markerDiameter (double,Optional[14.0]) – diameter of the marker

  • basePlate (double,Optional[2.0]) – thickness of the base plate

  • cgmReferential (boolOptional[True]) –

Notes

  • Predictor choice allows using modified Harrington’s regression from Sangeux 2015

  • pelvisDepth,`asisDistance` and meanlegLength are automaticaly computed from CGM calibration

References

  • Harrington, M., Zavatsky, A., Lawson, S., Yuan, Z., & Theologis, T. (2007). Prediction of the hip joint centre in adults, children, and patients with cerebral palsy based on magnetic resonance imaging. Journal of Biomechanics, 40(3), 595–602

  • Sangeux, M. (2015). On the implementation of predictive methods to locate the hip joint centres. Gait and Posture, 42(3), 402–405.

pyCGM2.Model.modelDecorator.midPoint(acq, lateralMarkerLabel, medialMarkerLabel, offset=0)

return the mid point trajectory

Parameters
  • acq (btk.Acquisition) – An acquisition

  • lateralMarkerLabel (str) – label of the lateral marker

  • medialMarkerLabel (str) – label of the medial marker

  • offset (double,Optional[0]) – offset

Note

if offset is different to 0, the mid point is computed from the statement:

lateral + offset*(Vector[medial->lateral])

pyCGM2.Model.modelDecorator.saraCalibration(proxMotionRef, distMotionRef, indexFirstFrame, indexLastFrame, offset=100, method='1')

Computation of a joint center position from SARA.

Parameters
  • proxMotionRef (pyCGM2.Model.Referential.motion) – motion attribute of the proximal referential

  • distMotionRef (pyCGM2.Model.Referential.motion) – motion attribute of the distal referential

  • offset (double,Optional[100]) – distance in mm for positionning axis boundaries

  • method (int,Optional[1]) – method index . Affect the objective function (see Ehrig et al.).

Reference

Ehrig, R., Taylor, W. R., Duda, G., & Heller, M. (2007). A survey of formal methods for determining functional joint axes. Journal of Biomechanics, 40(10), 2150–7.

modelFilters

This module contains filters and associated procedures which can be applied on a model

class pyCGM2.Model.modelFilters.CGMLowerlimbInverseDynamicProcedure

Procedure for calcualting Inverse dynamics of the CGM lower limbs

class pyCGM2.Model.modelFilters.CentreOfMassFilter(iMod, btkAcq)

Compute the centre of mass trajectory

Parameters
  • btkAcq (btk.Acquisition) – an acquisition instance of a dynamic trial

  • iMod (pyCGM2.Model.CGM2.model.Model) – a model instance

compute(pointLabelSuffix=None)

Run the filter. The centre of mass trajectoy is stored in the acquisition instance

Parameters

pointLabelSuffix (str,Optional[None]) – suffix added to the ouput label

class pyCGM2.Model.modelFilters.ForcePlateAssemblyFilter(iMod, btkAcq, mappedForcePlateLetters, leftSegmentLabel='Left Foot', rightSegmentLabel='Right Foot')

Assemble Force plate with the model

Parameters
  • btkAcq (btkAcquisition) – an acquisition instance of a dynamic trial

  • iMod (pyCGM2.Model.CGM2.model.Model) – a model instance

  • mappedForcePlateLetters (str) – string indicating body side of the segment in contact with the force plate

  • leftSegmentLabel (str,Optional[Left Foot]) – left segment label to assemble with force plates

  • rightSegmentLabel (str,Optional[Right Foot]) – right segment label to assemble with force plates

compute(pointLabelSuffix=None)

Run the filter. Ground reaction forces and moments are stored in the acquisition instance

Parameters

pointLabelSuffix (str,Optional[None]) – suffix ending ground reaction labels

class pyCGM2.Model.modelFilters.GeneralCalibrationProcedure

General Procedure to load from the Model Calibration Filter if you work with a custom model

setAnatomicalDefinition(segmentName, sequence='', nodeLabel1=0, nodeLabel2=0, nodeLabel3=0, nodeLabelOrigin=0)

Define rules for constructing the anatomical coordinate system.

nodeLabels are the labels of node (see Frame module ) used for constructing two axes ( v1 and v2) which eventually define the coordinate system.

Parameters
  • segmentName (str) – name of the segment

  • referentialLabel (str) – label of the referential

  • sequence (str) – construction sequence (XYZ,XYiZ,….)

  • nodeLabel1 (str) – node label used for constructing the axes v1 and v2

  • nodeLabel2 (str) – node label used for constructing the axis v1

  • nodeLabel3 (str) – node label used for construting the axis v2

  • nodeLabelOrigin (str) – node label used as origin of the coordinate system

setDefinition(segmentName, referentialLabel, sequence='', pointLabel1=0, pointLabel2=0, pointLabel3=0, pointLabelOrigin=0)

Define rules for constructing a technical coordinate system.

pointLabels are the labels of marker ( virtual or concrete markers) used for constructing two axes ( v1 and v2) which

eventually define the coordinate system.

Parameters
  • segmentName (str) – name of the segment

  • referentialLabel (str) – label of the referential

  • sequence (str) – construction sequence (XYZ,XYiZ,….)

  • pointLabel1 (str) – marker label used for constructing the axes v1 and v2

  • pointLabel2 (str) – marker label used for constructing the axis v1

  • pointLabel3 (str) – marker label used for construting the axis v2

  • pointLabelOrigin (str) – marker label used as origin of the coordinate system

class pyCGM2.Model.modelFilters.InverseDynamicFilter(iMod, btkAcq, procedure=None, gravityVector=array([0, 0, - 1]), scaleToMeter=0.001, projection=MomentProjection.Distal, globalFrameOrientation='XYZ', forwardProgression=True, exportMomentContributions=False, **options)

Compute joint Forces and moments from Inverse dynamics

Parameters
  • btkAcq (btk.Acquisition) – an acquisition instance of a dynamic trial

  • iMod (pyCGM2.Model.CGM2.model.Model) – a model instance

  • procedure (pyCGM2.Model.CGM2.modelFilters.(_Procedure)) – an inverse dynamic procedure

  • gravityVector (numpy.array(3,),Optional[numpy.array([0,0,-1]]) – the gravity vector

  • scaleToMeter (double,Optional[0.001]) – scale to meter

  • projection (pyCGM2.enums.MomentProjection,Optional[enums.MomentProjection.Distal]) – coordinate system in which joint moments and forces are expressed

  • exportMomentContributions (bool,Optional[false]) – export moment contributions

compute(pointLabelSuffix=None)

Run the filter. Joint forces and moments are stored in the acquisition instance

Parameters

pointLabelSuffix (str,Optional[None]) – suffix ending output labels

Kargs:

viconCGM1compatible(bool): replicate the Vicon Plugin-gait error related to the proximal and distal tibia

class pyCGM2.Model.modelFilters.JointPowerFilter(iMod, btkAcq, scaleToMeter=0.001)

Compute joint power

Parameters
  • btkAcq (btk.Acquisition) – an acquisition instance of a dynamic trial

  • iMod (pyCGM2.Model.CGM2.model.Model) – a model instance

  • scaleToMeter (double,Optional[0.001]) – scale to meter

compute(pointLabelSuffix=None)

Run the filter. Joint powers are stored in the acquisition instance

Parameters

pointLabelSuffix (str,Optional[None]) – suffix ending output labels

class pyCGM2.Model.modelFilters.ModelAbsoluteAnglesFilter(iMod, acq, segmentLabels=[], angleLabels=[], eulerSequences=[], globalFrameOrientation='XYZ', forwardProgression=True)

Compute the absolute joint angles

Args

acq (btk.Acquisition): an acquisition instance iMod (pyCGM2.Model.CGM2.model.Model): a model instance segmentLabels (list of str): segment labels angleLabels (list of str): absolute angles labels eulerSequences (str): Euler sequence to use. ( nomenclature TOR (ie Tilt-Obliquity-Rotation), ORT, ROT… ) globalFrameOrientation (str): global frame forwardProgression (bool): flag indicating subject moves in same direction than the global longitudinal axis

compute(description='absolute', pointLabelSuffix=None)

Run the filter. All ouputs are stored in the acquisition instance as btk.Point

Parameters
  • description (str,Optional[absolute]) – short description added to the btkPoint storing joint angles

  • pointLabelSuffix (str,Optional[None]) – suffix ending the angle label

class pyCGM2.Model.modelFilters.ModelCalibrationFilter(procedure, acq, iMod, **options)

Calibrate a model from a static acquisition.

The calibration consists in the construction of both technical and anatomical coordinate sytems of each segment constituting the model.

Args

procedure (pyCGM2.Model.CGM2.ModelFilters.(_Procedure)): a calibration procedure acq (btk.Acquisition): an acquisition instance iMod (pyCGM2.Model.CGM2.model.Model): a model instance

Kargs:

markerDiameter (double): marker diameter basePlate (double): base plate thickness viconCGM1compatible(bool): replicate the Vicon Plugin-gait error related to the proximal and distal tibia leftFlatFoot (bool) : left longitudinal foot axis parallel to the ground rightFlatFoot : right longitudinal foot axis parallel to the ground headFlat: longitudinal head axis parallel to the ground

compute(firstFrameOnly=True)

Run the Calibration filter

Parameters

firstFrameOnly (bool,optional[true]) – use the first frame only

class pyCGM2.Model.modelFilters.ModelJCSFilter(iMod, acq)

Compute the relative joint angles

Args

acq (btk.Acquisition): an acquisition instance iMod (pyCGM2.Model.CGM2.model.Model): a model instance

compute(description='', pointLabelSuffix=None)

run the filter. All ouputs are stored in the acquisition instance as btk.Point

Parameters
  • description (str,Optional[""]) – short description added to the btkPoint storing joint angles

  • pointLabelSuffix (str,Optional[None]) – suffix ending the angle label

class pyCGM2.Model.modelFilters.ModelMotionCorrectionFilter(procedure)

This filter correct the motion attributes (ie the segmental pose at each frame) of the anatomical coordinate systems.

The method implemented so far is the misaligment correction of Naaim et al (see Naim2019ThighMisaligmentCorrectionProcedure)

Parameters

procedure (pyCGM2.Model.CGM2.modelFilters.(Procedure)) – a CorrectionProcedure

correct()

Run the filter

class pyCGM2.Model.modelFilters.ModelMotionFilter(procedure, acq, iMod, method, **options)

This filter update the model with the pose of both technical and anatomical coordinate systems at each frame.

Args

procedure (pyCGM2.Model.CGM2.ModelFilters.(_Procedure)):a motion procedure acq (btk.Acquisition): an acquisition instance iMod (pyCGM2.Model.CGM2.model.Model): a model instance method (pyCGM2.enums.motionMethod): pose method

Kargs:

markerDiameter (double): marker diameter basePlate (double): base plate thickness viconCGM1compatible(bool): replicate the Vicon Plugin-gait error related to the proximal and distal tibia useLeftKJCmarker (str): label of the left knee joint centre, present in the c3d as virtual marker useLeftAJCmarker (str): label of the left ankle joint centre, present in the c3d as virtual marker useLeftSJCmarker (str): label of the left shoulder joint centre, present in the c3d as virtual marker useLeftEJCmarker (str): label of the left elbow joint centre, present in the c3d as virtual marker useLeftWJCmarker (str): label of the left wrist joint centre, present in the c3d as virtual marker useRightKJCmarker (str): label of the right knee joint centre, present in the c3d as virtual marker useRightAJCmarker (str): label of the right ankle joint centre, present in the c3d as virtual marker useRightSJCmarker (str): label of the right shoulder joint centre, present in the c3d as virtual marker useRightEJCmarker (str): label of the right elbow joint centre, present in the c3d as virtual marker useRightWJCmarker (str): label of the right wrist joint centre, present in the c3d as virtual marker

compute()

Run the filter

segmentalCompute(segments)

Compute motion for given segments

Parameters

segments (list) – segment labels

class pyCGM2.Model.modelFilters.Naim2019ThighMisaligmentCorrectionProcedure(model, side, threshold=20)

This function corrects the thigh anatomical frame in respect with the method detailed in Naim et al, 2019.

Parameters
  • iMod (pyCGM2.Model.CGM2.model.Model) – a model instance

  • side (str) – body side

  • threshold (double,Optional[20]) – only consider frames with a flexion angle above the given threshold

  • **Reference

    **

  • Naaim (2019) –

  • A. (2019) –

  • Bonnefoy-Mazure (2019) –

  • A.

  • Armand (2019) –

  • S. (2019) –

  • Dumas (&) –

  • R. (2019) –

  • analysis (Correcting lower limb segment axis misalignment in gait) – A simple geometrical method.

  • Posture (Gait and) –

  • 72 (May) –

class pyCGM2.Model.modelFilters.StaticCalibrationProcedure(model)

Procedure to load from the Model Calibration Filter if you work with a pyCGM2-embedded model instance (like the CGM#i)

This procedure internally calls the calibrationProcedure method of the model instance.

Parameters

model (pyCGM2.Model.Model) – a pyCGM2-embeded model instancel

modelQualityFilter

This module contains filters and associated procedures for assessing the quality of the model

class pyCGM2.Model.modelQualityFilter.GeneralScoreResidualProcedure(model)

Procedure for calculating SCORE residual on given segments of the model

The main goal of the procedure is to populate the attribute m_scoreDefinition which will be handle by the ScoreresidualFilter

Parameters

model (pyCGM2.Model.model.Model) –

setDefinition(nodeLabel, proxSegLabel, distSegLabel)

set the definition dictionary.

Parameters
  • nodeLabel (str) – node label.

  • proxSegLabel (str) – proximal segment label

  • distSegLabel (str) – distal segment label

class pyCGM2.Model.modelQualityFilter.ModelScoreResidualProcedure(model)

Procedure for calculating SCORE residual for all joints of the model

The procedure populates its attribute m_scoreDefinition from the geometric attributes of the model

Parameters

model (pyCGM2.Model.model.Model) –

class pyCGM2.Model.modelQualityFilter.ScoreResidualFilter(acq, scoreProcedure)

Calculate the SCORE residual

Args

acq (btk.Acquisition): an acquisition instance scoreProcedure (pyCGM2.Model.modelQualityFilter.(Procedure)): a score procedure instance

References

  • Ehrig, Rainald M.; Heller, Markus O.; Kratzenstein, Stefan; Duda, Georg N.; Trepczynski, Adam; Taylor, William R. (2011)

The SCoRE residual: a quality index to assess the accuracy of joint estimations. In : Journal of biomechanics, vol. 44, n° 7, p. 1400–1404. DOI: 10.1016/j.jbiomech.2010.12.009.

compute()

Run the filter

motion

This module contains pose algorithms

pyCGM2.Model.motion.segmentalLeastSquare(A, B)

Compute the transformation between two coordinate systems using SVD.

Parameters
  • A (numpy.array(n,3)) –

  • B (numpy.array(n,3)) –

CGM2

cgm

class pyCGM2.Model.CGM2.cgm.CGM

Abstract Class of the Conventional Gait Model

classmethod detectCalibrationMethods(acqStatic)

Class method to detect the method used to calibrate knee and ankle joint centres

Parameters

acqStatic (btk.Acquisition) – acquisition.

getStaticTrackingMarkers()

get tracking markers

classmethod get_markerLabelForPiGStatic(dcm)

Class method returning marker label of the knee and ankle joint centres

Parameters

dcm (dict) – dictionary returned from the function detectCalibrationMethods

setStaticTrackingMarkers(markers)

Set tracking markers

Parameters

markers (list) – tracking markers

class pyCGM2.Model.CGM2.cgm.CGM1

Conventional Gait Model 1 (aka Vicon Plugin Gait Clone)

calibrate(aquiStatic, dictRef, dictAnatomic, options=None)

calibrate the model

Parameters
  • aquiStatic (btk.acquisition) – acquisition

  • dictRef (dict) – markers and sequence used for building the technical coordinate system

  • dictAnatomic (dict) – markers and sequence used for building the anatomical coordinate system

  • options (dict, optional[None]) – passed arguments to embedded methods

calibrationProcedure()

Define the calibration Procedure

Returns

markers and sequence use for building Technical coordinate system dict: markers and sequence use for building Anatomical coordinate system

Return type

dict

computeMotion(aqui, dictRef, dictAnat, motionMethod, options=None)

Compute poses of both Technical and Anatomical coordinate systems

Parameters
  • aqui (btk.acquisition) – acquisition

  • dictRef (dict) – technical referential definitions

  • dictAnat (dict) – anatomical referential definitions

  • motionMethod (enums.motionMethod) – segmental motion method

  • options (dict,optional[None]) – passed arguments to embedded functions

options:
  • pigStatic (bool) : compute foot cordinate system according the Vicon Plugin-gait

  • forceFoot6DoF (bool): apply 6DOF pose optimisation on the foot

computeOptimizedSegmentMotion(aqui, segments, dictRef, dictAnat, motionMethod, options)

Compute poses of both Technical and Anatomical coordinate systems for specific segments of the model

Parameters
  • aqui (btk.Acquisition) – motion acquisitiuon

  • segments (list) – segments of the model

  • dictRef (dict) – technical referential definitions

  • dictAnat (dict) – anatomical referential definitions

  • motionMethod (enums.motionMethod) – segmental motion method to apply

  • options (dict) – passed known-arguments

configure(detectedCalibrationMethods=None)

” configure the model

Parameters

detectedCalibrationMethods (dict,optional[None]) – dictionary returned from the function detectCalibrationMethods

getAbdAddAnkleJointOffset(side='both')

return the Abd/Add ankle offset, ie angle in the frontal plan between the ankle marker and the ankle flexion axis

Parameters

side (string, Optional[both]) – lower limb side (both, left or right)

getFootOffset(side='both')

return the foot offsets, ie the plantar flexion offset and the rotation offset

Parameters

side (string, Optional[both]) – lower limb side (both, left or right)

getShankOffsets(side='both')

return the shank offset, ie the angle between the projection of the lateral shank marker and the ankle flexion axis

Parameters

side (string, Optional[both]) – lower limb side (both, left or right)

getStaticMarkers(dcm)

return static markers

Parameters

dcm (dict) – dictionary returned from the function detectCalibrationMethods

getThighOffset(side='both')

return the thigh offset. Angle between the projection of the lateral thigh marker and the knee flexion axis

Parameters

side (string, Optional[both]) – lower limb side (both, left or right)

getTibialTorsionOffset(side='both')

return the tibial torsion offsets :

Parameters

side (string, Optional[both]) – lower limb side (both, left or right)

getTrackingMarkers(acq)

return tracking markers

Parameters

acq (btk.Acquisition) – acquisition.

opensimGeometry()

return dict used to configure the osim file

opensimIkTask()

return marker weights used for IK

setVersion(string)

amend model vesion

viconExport(NEXUS, acq, vskName, pointSuffix, staticProcessingFlag)

method exporting model outputs to Nexus

Parameters
  • NEXUS (viconnexus) – Nexus handle

  • vskName (str) – vsk name

  • staticProcessingFlag (bool) – only static model ouputs will be exported

cgm2

class pyCGM2.Model.CGM2.cgm2.CGM2_1

Implementation of the CGM2.1

class pyCGM2.Model.CGM2.cgm2.CGM2_2

Implementation of the CGM2.2

getStaticIkTargets()

return markers used to fit the static

setStaticIkTargets(targetNames)

set markers used to fit the static with IK

Parameters

targetNames (list) – marker labels

class pyCGM2.Model.CGM2.cgm2.CGM2_3

Implementation of the CGM2.3

calibrate(aquiStatic, dictRef, dictAnatomic, options=None)

calibrate the model

Parameters
  • aquiStatic (btk.acquisition) – acquisition

  • dictRef (dict) – markers and sequence used for building the technical coordinate system

  • dictAnatomic (dict) – markers and sequence used for building the anatomical coordinate system

  • options (dict, optional[None]) – passed arguments to embedded methods

getStaticIkTargets()

return markers used to fit the static

opensimIkTask()

return marker weights used for IK

setStaticIkTargets(targetNames)

set markers used to fit the static with IK

Parameters

targetNames (list) – marker labels

class pyCGM2.Model.CGM2.cgm2.CGM2_4

Implementation of the CGM2.4

calibrate(aquiStatic, dictRef, dictAnatomic, options=None)

calibrate the model

Parameters
  • aquiStatic (btk.acquisition) – acquisition

  • dictRef (dict) – markers and sequence used for building the technical coordinate system

  • dictAnatomic (dict) – markers and sequence used for building the anatomical coordinate system

  • options (dict, optional[None]) – passed arguments to embedded methods

computeMotion(aqui, dictRef, dictAnat, motionMethod, options=None)

Compute poses of both Technical and Anatomical coordinate systems

Parameters
  • aqui (btk.acquisition) – acquisition

  • dictRef (dict) – technical referential definitions

  • dictAnat (dict) – anatomical referential definitions

  • motionMethod (enums.motionMethod) – segmental motion method

  • options (dict,optional[None]) – passed arguments to embedded functions

options:
  • pigStatic (bool) : compute foot cordinate system according the Vicon Plugin-gait

  • forceFoot6DoF (bool): apply 6DOF pose optimisation on the foot

computeOptimizedSegmentMotion(aqui, segments, dictRef, dictAnat, motionMethod, options)

Compute poses of both Technical and Anatomical coordinate systems for specific segments of the model

Parameters
  • aqui (btk.Acquisition) – motion acquisitiuon

  • segments (list) – segments of the model

  • dictRef (dict) – technical referential definitions

  • dictAnat (dict) – anatomical referential definitions

  • motionMethod (enums.motionMethod) – segmental motion method to apply

  • options (dict) – passed known-arguments

getHindFootOffset(side='Both')

return the hindfoot offsets, ie the plantar flexion offset and the rotation offset

Parameters

side (string, Optional[Both]) – lower limb side (Both, Left or Right)

opensimGeometry()

return dict used to configure the osim file

opensimIkTask()

return marker weights used for IK

viconExport(NEXUS, acq, vskName, pointSuffix, staticProcessingFlag)

Method exporting model outputs to Nexus

see [cgm.CGM1.viconExport](/Low level/Model/CGM2)

class pyCGM2.Model.CGM2.cgm2.CGM2_5

decorators

this module gathers decorators specific to the CGM

pyCGM2.Model.CGM2.decorators.applyBasicDecorators(dcm, model, acqStatic, optional_mp, markerDiameter, cgm1only=False)

Apply decorators from detected calibration method

Parameters
  • dcm (dict) – dictionary returned from the function detectCalibrationMethods

  • model (pyCGM2.Model.CGM2.cgm) – a CGM model instance

  • acqStatic (btk.acquisition) – a btk acquisition instance of a static file

  • optional_mp (dict) – optional anthropometric parameters of the CGM

  • markerDiameter (float) – marker diameter

  • cgm1only (bool, optional[False]) – enable computation for the CGM1 only

pyCGM2.Model.CGM2.decorators.applyHJCDecorators(model, method)

apply hip joint centre decorators

Parameters
  • model (pyCGM2.Model.CGM2.cgm) – a CGM model instance

  • method (dict) – dict indicating HJC method to use

Example:

`python method = {"Left": "Hara", "Right": [1,3,4]} # a string or a list (ie. position in the pelvic coordinate system) applyHJCDecorators(model, method) `

Opensim

opensimFilters

This module contains Filters and procedures used as interface for working with the opensim API

class pyCGM2.Model.Opensim.opensimFilters.CgmOpensimCalibrationProcedures(model)

Model-embedded Procedure for calibrating an opensim model

class pyCGM2.Model.Opensim.opensimFilters.CgmOpensimFittingProcedure(model)

Model-embedded Procedure for fitting an opensim model

updateMarkerWeight(markerLabel, weight)

Update weigth of a tracking marker

Parameters
  • markerLabel (str) – marker label

  • weight (double) – joint label of a pyCGM2 model

class pyCGM2.Model.Opensim.opensimFilters.GeneralOpensimCalibrationProcedure

General procedure for calibrating an opensim model

setGeometry(opensimJointLabel, jointLabel, proximalSegmentLabel, distalSegmentLabel)

Design the opensim model geometry

Parameters
  • opensimJointLabel (str) – joint label of the opensim model (see inside osim file)

  • jointLabel (str) – joint label of the pyCGM2 model

  • proximalSegmentLabel (str) – proximal segment label of LTHI_perturbTraj pyCGM2 model

  • distalSegmentLabel (str) – distal segment label of the pyCGM2 model

setMarkers(segmentLabel, trackingMarkers)

Add tracking markers to a pycgm2-model segment

Parameters
  • segmentLabel (str) – segment label of a pyCGM2 model

  • trackingMarkers (list) – traking markers

class pyCGM2.Model.Opensim.opensimFilters.GeneralOpensimFittingProcedure

General procedure for Fitting a motion on the osim file

setMarkerWeight(markerLabel, weight)

Set weigth of a tracking marker

Parameters
  • markerLabel (str) – marker label

  • weight (double) – joint label of a pyCGM2 model

osimProcessing

This module contains convenient functions and classes for working with opensim.

pyCGM2.Model.Opensim.osimProcessing.globalTransformationLabToOsim(acq, R_LAB_OSIM)

transform all markers into the the opensim global coordinate system

Parameters
  • acq (Btk.Acquisition) – an acquisition

  • R_LAB_OSIM (array(3,3)) – rotation matrix for passing from the lab to opensim coordinate sytem

pyCGM2.Model.Opensim.osimProcessing.mot2pointValues(motFilename, labels, orientation=[1, 1, 1])

convert an element of an opensim mot file into a btk-point values (ie array(n,3) with n: the number of frames)

Parameters
  • motFilename (str) – full filename of the mot file

  • label (str) – label to convert

  • orientation (list) – scales to apply before returning final values. Default is [1,1,1]

pyCGM2.Model.Opensim.osimProcessing.setGlobalTransormation_lab_osim(axis, forwardProgression)

return the rotation matrix expressing the opensim global coordinate system to the laboratory coordinate system

Parameters
  • axis (str) – defined progression axis (ie X or Y ).

  • forwardProgression (bool) – forward progression flag.

  • True ((if) –

  • of (the movement progression is along the positive value) –

  • ) (your progression axis) –

pyCGM2.Model.Opensim.osimProcessing.smartTrcExport(acq, filenameNoExt)

save as a trc file

Parameters
  • acq (Btk.Acquisition) – an acquisition

  • filenameNoExt (str) – filename without extension

pyCGM2.Model.Opensim.osimProcessing.sto2pointValues(storageObject, label, R_LAB_OSIM)

transform an element of a storage instance into the Laboratory coordinate system.

Parameters
  • storageObject (opensim.Storage) – an opensim storage instance.

  • label (str) – label to extract from the storage instance

  • R_LAB_OSIM (array(3,3)) – rotation matrix for passing from the lab to opensim coordinate sytem

QTM

qtmTools

Module contains convenient functions dealing with the session.xml file generated from QTM.

pyCGM2.QTM.qtmTools.SubjectMp(soup)

return the antropometric parameters

Parameters

soup (bs4.soup) – content of the session.xml

pyCGM2.QTM.qtmTools.detectMeasurementType(soup)

return the type of each measurement section

Parameters

soup (bs4.soup) – content of the session.xml

pyCGM2.QTM.qtmTools.findDynamic(soup)

return the dynamic files from the bs4.soup instance representing the content of the session.xml

Parameters

soup (bs4.soup) – content of the session.xml

pyCGM2.QTM.qtmTools.findKneeCalibration(soup, side)

return the knee functional calibration file from the bs4.soup instance representing the content of the session.xml

Parameters
  • soup (bs4.soup) – content of the session.xml

  • side (str) – lower limb side

pyCGM2.QTM.qtmTools.findStatic(soup)

return the static file from the bs4.soup instance representing the content of the session.xml

Parameters

soup (bs4.soup) – content of the session.xml

pyCGM2.QTM.qtmTools.getFilename(measurement)

return the filename of the measurement section

Parameters

measurement (bs4.soup) – a measurement section of the session.xml file.

pyCGM2.QTM.qtmTools.getForcePlateAssigment(measurement)

return the force plate assigment from the measurement section

Parameters

measurement (bs4.soup) – a measurement section of the session.xml file.

pyCGM2.QTM.qtmTools.getKneeFunctionCalibMethod(measurement)

return the method used for the knee calibration

Parameters

measurement (bs4.soup) – a measurement section of the session.xml file.

pyCGM2.QTM.qtmTools.isType(measurement, type)

check type of measurement section

Parameters
  • measurement (bs4.soup) – a measurement section of the session.xml file.

  • type (str) – type

Processing

analysis

The main goal of this module is to construct an Analysis instance. It’s a matlab-like structure with spatio temporal (stp), kinematics, kinetics and emg parameters as attributes.

The implementation is based on a Builder pattern . The AnalysisFilter calls a procedure and return the final Analysis instance

class pyCGM2.Processing.analysis.Analysis

Object built from AnalysisFilter.build().

Analysis work as class-container. Its attributes are:

  • stpStats (dict) - descritive statictics (mean,sd,median) of satiotemporal parameters

  • kinematicStats (AnalysisStructure) - descritive statictics of kinematics data.

  • kineticStats (AnalysisStructure) - descritive statictics of kinetics data.

  • emgStats (AnalysisStructure) - descritive statictics of emg data.

Two items constitute the AnalysisStructure returns by kinematicStats, kineticStats and emgStats

  • data is a a dict collecting descriptive statistics of kinematic, kinetic or emg output.

  • pst returns the spatiotemporal parameters of the cycles associated to kinematic, kinetics or emg outputs.

Examples

If you want to return the mean, sd, and median of the left hip angles, time normalized from left gait events

>>> analysis.kinematicStats.data["LHipAngles", "Left"]["mean"] #return array(101,3)
>>> analysis.kinematicStats.data["LHipAngles", "Left"]["sd"] #return array(101,3)
>>> analysis.kinematicStats.data["LHipAngles", "Left"]["median"] #return array(101,3)

You can also get all-cycle values from the below code.

>>> analysis.kinematicStats.data["LHipAngles", "Left"]["values"] #return list (length=number of cycle) of array(101,3)
class pyCGM2.Processing.analysis.AnalysisBuilder(cycles, kinematicLabelsDict=None, kineticLabelsDict=None, pointlabelSuffix=None, emgLabelList=None, modelInfos=None, subjectInfos=None, experimentalInfos=None, emgs=None)

Analysis builder

Unlike GaitAnalysisBuilder, this builder does not compute spatiotemporal parameters

Parameters
  • cycles (pyCGM2.Processing.cycle.Cycles) – Cycles instance built from CycleFilter

  • kinematicLabelsDict (dict) – dictionary with two items (Left and Right) grouping kinematic output label

  • kineticLabelsDict (dict) – dictionary with two items (Left and Right) grouping kinetic output label

  • pointlabelSuffix (dict) –

  • emgLabelList (list of str) – labels of used emg

  • subjectInfos (dict) – information about the subject

  • modelInfos (dict) – information about the model

  • experimentalInfos (dict) – information about the experimental conditions

Notes

modelInfos,`experimentalInfos`, subjectInfos are simple dictionaries used to store basic information. When the analysis is exported as speadsheet, these informations appear as columns.

computeEmgEnvelopes()

Compute descriptive stats of the emg envelops

computeKinematics()

Compute descriptive stats of the kinematic parameters

computeKinetics()

Compute descriptive stats of the kinetic parameters

class pyCGM2.Processing.analysis.AnalysisFilter

Filter building an Analysis instance.

build()

Run the filter and build the analysis

setBuilder(concreteBuilder)

Set a concrete builder

Parameters

concreteBuilder (Builder) –

setInfo(subject=None, experimental=None, model=None)

Set informations

Parameters
  • subject (dict,Optional[None]) – subject info

  • experimental (dict,Optional[None]) – xperimental info

  • model (dict,Optional[None]) – model info

class pyCGM2.Processing.analysis.GaitAnalysisBuilder(cycles, kinematicLabelsDict=None, kineticLabelsDict=None, pointlabelSuffix=None, emgLabelList=None, modelInfos=None, subjectInfos=None, experimentalInfos=None, emgs=None)

Gait analysis Builder.

Parameters
  • cycles (pyCGM2.Processing.cycle.Cycles) – Cycles instance built from CycleFilter

  • kinematicLabelsDict (dict) – dictionary with two items (Left and Right) grouping kinematic output label

  • kineticLabelsDict (dict) – dictionary with two items (Left and Right) grouping kinetic output label

  • pointlabelSuffix (dict) –

  • emgLabelList (list of str) – labels of used emg

  • subjectInfos (dict) – information about the subject

  • modelInfos (dict) – information about the model

  • experimentalInfos (dict) – information about the experimental conditions

Notes

modelInfos,`experimentalInfos`, subjectInfos are simple dictionaries used to store basic information. When the analysis is exported as speadsheet, these informations appear as columns.

computeEmgEnvelopes()

Compute descriptive stats of the emg envelops

computeKinematics()

Compute descriptive stats of the kinematic parameters

computeKinetics()

Compute descriptive stats of the kinetic parameters

computeSpatioTemporel()

compute descriptive stats of the spatio-temporal parameters

analysisHandler

pyCGM2.Processing.analysisHandler.getAnalysisSection(analysisInstance, label, context)

return the section ( ie kinematic, kinetic or emg) of a given label and its context

Parameters
pyCGM2.Processing.analysisHandler.getNumberOfCycle(analysisInstance, label, context)

return the number of cycle from a given ouput and its event context.

Parameters
pyCGM2.Processing.analysisHandler.getPhases(dataStats, context='Both')

get phases

Parameters
  • dataStats (pyCGM2.Processing.analysis.Analysis.kinematicStats.data) – data level

  • instance (of the kinematicStats or kineticStats attributes of an Analysis) –

  • context (str) – event context

pyCGM2.Processing.analysisHandler.getValues(analysisInstance, label, context)

return the values from a given ouput and its event context.

Parameters
pyCGM2.Processing.analysisHandler.isKeyExist(analysisInstance, label, context, exceptionMode=False)

check if the combinaison label/context exist in the analysis instance

Parameters
  • analysisInstance (pyCGM2.Processing.analysis.Analysis) – an analysis instance

  • label (str) – givel ouput label (eg LKneeAngles)

  • context (str) – event context

  • exceptionMode (bool) – enable exception raising

analysisProcessing

cycle

This module aims to construct a Cycles instance. Based on a builder pattern design, the Filter CyclesFilter calls a builder, ie CyclesBuilder or a GaitCyclesBuilder in the context of gait Analysis, then return a Cycles instance.

As attributes, the Cycles instance distinguished series of Cycle (or GaitCycle) instance according to computational objectives ( ie computation of spatio-temporal parameters, kinematics, kinetics or emg.)

class pyCGM2.Processing.cycle.Cycle(acq, startFrame, endFrame, context, enableFlag=True)

Generic Cycle

Parameters
  • acq (btk.Acquisituion) – an acquisition

  • startFrame (int) – start frame of the cycle

  • endFrame (double) – end frame of the cycle

  • enableFlag (bool) – flag to indicate the cycle will be use in further computation.

getAnalogTimeSequenceData(analogLabel)

Get analog data of the cycle

Parameters

analogLabel (str) – analog Label

getAnalogTimeSequenceDataNormalized(analogLabel)

Time-normalize an analog data

Parameters

analogLabel (str) – analog Label

getEvents(context='All')

Get all events of the cycle

Parameters

context (str) – event context (All, Left or Right)

getPointTimeSequenceData(pointLabel)

Get temporal point data of the cycle

Parameters

pointLabel (str) – point Label

getPointTimeSequenceDataNormalized(pointLabel)

Time-Normalise a point label

Parameters

pointLabel (str) – point Label

setEnableFlag(flag)

enable/disable the cycle

Parameters

flag (bool) – boolean flag

class pyCGM2.Processing.cycle.Cycles

Object to build from CycleFilter.

Cycles work as class-container. Its attribute members collect list of Cycle or GaitCycle according to computational objectives

Attributes are

  • spatioTemporalCycles: list of cycles uses for spatiotemporal parameter computation

  • kinematicCycles: list of cycles uses for kinematic computation

  • kineticCycles: list of cycles uses for kinetic computation

  • emgCycles: list of cycles uses for emg computation

class pyCGM2.Processing.cycle.CyclesBuilder(spatioTemporalAcqs=None, kinematicAcqs=None, kineticAcqs=None, emgAcqs=None)

Builder of generic cycles

Parameters
  • spatioTemporalAcqs (list) – acquisitions used for spatio-temporal parameter computation

  • kinematicAcqs (list) – acquisitions used for kinematics computation

  • kineticAcqs (list) – acquisitions used for kinetics computation

  • emgAcqs (list) – acquisitions used for emg computation

getEmg()

get the list of Cycle used for emg computation

getKinematics()

get the list of Cycle used for kinematic computation

getKinetics()

get the list of Cycle used for kinetic computation

getSpatioTemporal()

get the list of Cycle used for spatio-temporal parameter computation

class pyCGM2.Processing.cycle.CyclesFilter

Filter buiding a Cycles instance.

build()

Build a Cycles instance

setBuilder(builder)

Set the builder

Parameters

builder (pyCGM2.Processing.Cycle.(Builder)) – a concrete cycle builder

class pyCGM2.Processing.cycle.GaitCycle(gaitAcq, startFrame, endFrame, context, enableFlag=True)

Inherited class from Cycle defining a Gait cycle.

Parameters
  • acq (btk.Acquisituion) – an acquisition

  • startFrame (int) – start frame of the cycle

  • endFrame (double) – end frame of the cycle

  • enableFlag (bool) – flag to indicate the cycle will be use in further computation.

Notes

  • By default, X0 and Y0 are the longitudinal and lateral global axis respectively

  • GaitCycle construction computes spatio-temporal parameters automatically.

  • spatio-temporal parameters are :

    “duration”, “cadence”, “stanceDuration”, “stepDuration”, “doubleStance1Duration”, “doubleStance2Duration”, “simpleStanceDuration”, “stancePhase”, “swingDuration”, “swingPhase”, “doubleStance1”, “doubleStance2”, “simpleStance”, “stepPhase”, “strideLength”, “stepLength”, “strideWidth”, “speed”

getSpatioTemporalParameter(label)

Return a spatio-temporal parameter

Parameters

label (str) – label of the desired spatio-temporal parameter

class pyCGM2.Processing.cycle.GaitCyclesBuilder(spatioTemporalAcqs=None, kinematicAcqs=None, kineticAcqs=None, emgAcqs=None)

Builder of gait cycle

Parameters
  • spatioTemporalAcqs (list) – acquisitions used for spatio-temporal parameter computation

  • kinematicAcqs (list) – acquisitions used for kinematics computation

  • kineticAcqs (list) – acquisitions used for kinetics computation

  • emgAcqs (list) – acquisitions used for emg computation

getEmg()

get the list of Cycle used for emg computation

getKinematics()

get the list of Cycle used for kinematic computation

getKinetics()

get the list of Cycle used for kinetic computation

getSpatioTemporal()

get the list of Cycle used for spatio-temporal parameter computation

pyCGM2.Processing.cycle.analog_descriptiveStats(cycles, label, context)

Compute descriptive statistics of analog parameters from a cycles instance

Parameters
pyCGM2.Processing.cycle.construcGaitCycle(acq)

Construct gait cycle

Parameters

acq (btk.Acquisition) – an acquisition

pyCGM2.Processing.cycle.point_descriptiveStats(cycles, label, context)

Compute descriptive statistics of point parameters from a cycles instance

Parameters
pyCGM2.Processing.cycle.spatioTemporelParameter_descriptiveStats(cycles, label, context)

Compute descriptive statistics of spatio-temporal parameters from a cycles instance

Parameters

exporter

This module contains 2 classes (XlsAnalysisExportFilter and AnalysisExportFilter) for exporting an analysis instance in xls fomat and json respectively.

the class XlsExportDataFrameFilter is a generic filter for exporting Pandas.DataFrame in xls.

class pyCGM2.Processing.exporter.AnalysisExportFilter

Filter exporting an analysis instance as json.

export(outputName, path=None)

Export as json

Parameters
  • outputName (str) – filename without extension

  • path (str) – Path

setAnalysisInstance(analysisInstance)

set the analysis instance

Parameters

analysisInstance (pyCGM2.analysis.Analysis) – an analysis instance

class pyCGM2.Processing.exporter.XlsAnalysisExportFilter

Filter exporting an analysis instance as spreadheet.

Exported spreadsheet can organize either by row (Advanced mode) or column (basic mode). In Advanced mode, a row is made up of 101 columns representing a time normalized cycle.

export(outputName, path=None, excelFormat='xls', mode='Advanced')

Export spreadsheet

Parameters
  • outputName (str) – filename without extension

  • path (str) – Path

  • excelFormat (str) – format (xls,xlsx)

  • mode (str) – structure mode of the spreadsheet (Advanced,Basic)

setAnalysisInstance(analysisInstance)

set the analysis instance

Parameters

analysisInstance (pyCGM2.analysis.Analysis) – an analysis instance

class pyCGM2.Processing.exporter.XlsExportDataFrameFilter

Filter exporting a pandas.dataFrame or a list of pandas.dataFrame as xls spreadsheet(s)

export(outputName, path=None, excelFormat='xls')

Export spreadsheet

Parameters
  • outputName (str) – filename without extension

  • path (str) – Path

  • excelFormat (str) – format (xls,xlsx)

setDataFrames(dataframes)

Set the dataFrame

Parameters

dataframes (pandas.dataFrame or list) – dataframe or list of dataframe

c3dManager

c3dManagerFilters

This module aims to organize the c3d trials according to computational objectives, ie computation of spatio-temporal, kinematic, kinetics or emg parameters.

The implementation is based on a builder pattern. The filter C3dManagerFilter calls a procedure, then return a C3dManager instance, a ie , a structure listing both Btk.Acquisition instances and their associated filename according the computational objectives

c3dmanagerProcedure = c3dManagerProcedures.DistinctC3dSetProcedure(
    DATA_PATH, iPstFilenames, iKinematicFilenames, iKineticFilenames, iEmgFilenames)

cmf = c3dManagerFilters.C3dManagerFilter(c3dmanagerProcedure)
cmf.enableKinematic(True)
cmf.enableKinetic(True)
cmf.enableEmg(True)
trialManager = cmf.generate()
class pyCGM2.Processing.C3dManager.c3dManagerFilters.C3dManager

A c3d manager instance is a structure listing btk.Acquisition instances and the associated filenames for the 4 computational objectives (spatio-temporal, kinematic, kinetics or emg computation)

class pyCGM2.Processing.C3dManager.c3dManagerFilters.C3dManagerFilter(procedure)

pyCGM2 Filter used for disseminate c3d trial set(s)

Parameters

procedure (pyCGM2.Processing.C3dManager.c3dManagerProcedures.C3dManagerProcedure) – a C3dManagerProcedure instance

enableEmg(boolean)

enable emg computation

Parameters

boolean (bool) – boolean flag

enableKinematic(boolean)

enable kinematic computation

Parameters

boolean (bool) – boolean flag

enableKinetic(boolean)

enable kinetic computation

Parameters

boolean (bool) – boolean flag

enableSpatioTemporal(boolean)

enable spatio-temporal computation

Parameters

boolean (bool) – boolean flag

generate()

disseminate c3d trials according to the given Procedure

c3dManagerProcedures

This module gathers the procedures callable from the c3dManagerFilters

class pyCGM2.Processing.C3dManager.c3dManagerProcedures.DistinctC3dSetProcedure(data_path, stp_fileLst, kinematic_fileLst, kinetic_fileLst, emg_fileLst)

Distinct c3d sets are for each computational objectives

Parameters
  • data_path (str) – folder path

  • stp_fileLst (list) – c3d filenames for the spatioTemporal computation

  • kinematic_fileLst (list) – c3d filenames for the kinematic computation

  • kinetic_fileLst (list) – c3d filenames for the kinetics computation

  • emg_fileLst (list) – c3d filenames for the emg computation

generate(c3dManager, spatioTempFlag, kinematicFlag, kineticFlag, emgFlag)

disseminate c3d sets

Parameters
  • c3dManager (pyCGM2.Processing.c3dManager.C3dManager) – a c3dManager instance.

  • spatioTempFlag (bool) – enable populating the spatioTemporal attribute of the c3dManager instance

  • kinematicFlag (bool) – enable populating the kinematic attribute of the c3dManager instance

  • kineticFlag (bool) – enable populating the kinetic attribute of the c3dManager instance

  • emgFlag (bool) – enable populating the emg attribute of the c3dManager instance

class pyCGM2.Processing.C3dManager.c3dManagerProcedures.UniqueBtkAcqSetProcedure(data_path, fileLst, acqs)

the same combinaison (btk.Acquisition/c3d filenames) is used for all computational objectives

Parameters
  • data_path (str) – folder path

  • fileLst (list) – c3d filenames

  • acqs (list) – btk.Acquisition instances

Warning:

btk.Acquisition instances must match filenames. The first btk.acquisition instance must be the btk.acquisition from the first c3d filename.

generate(c3dManager, spatioTempFlag, kinematicFlag, kineticFlag, emgFlag)

disseminate the combinaison (btk.Acquisition/c3d filenames)

Parameters
  • c3dManager (pyCGM2.Processing.c3dManager.C3dManager) – a c3dManager instance.

  • spatioTempFlag (bool) – enable populating the spatioTemporal attribute of the c3dManager instance

  • kinematicFlag (bool) – enable populating the kinematic attribute of the c3dManager instance

  • kineticFlag (bool) – enable populating the kinetic attribute of the c3dManager instance

  • emgFlag (bool) – enable populating the emg attribute of the c3dManager instance

class pyCGM2.Processing.C3dManager.c3dManagerProcedures.UniqueC3dSetProcedure(data_path, fileLst)

the same c3d filenames is used for all computational objectives

Parameters
  • data_path (str) – folder path

  • fileLst (list) – c3d filenames

generate(c3dManager, spatioTempFlag, kinematicFlag, kineticFlag, emgFlag)

disseminate c3d filenames

Parameters
  • c3dManager (pyCGM2.Processing.c3dManager.C3dManager) – a c3dManager instance.

  • spatioTempFlag (bool) – enable populating the spatioTemporal attribute of the c3dManager instance

  • kinematicFlag (bool) – enable populating the kinematic attribute of the c3dManager instance

  • kineticFlag (bool) – enable populating the kinetic attribute of the c3dManager instance

  • emgFlag (bool) – enable populating the emg attribute of the c3dManager instance

Classification

classificationFilters

This module aims to classify the model ouputs according a gait pattern.

The implementation is based on a adapter pattern. The classication filter calls a procedure, then return the gait pattern for both limbs

example:

nds = normativeDatasets.NormativeData("Schwartz2008","Free")

procedure = classificationProcedures.PFKEprocedure(nds)
filt = classificationFilters.ClassificationFilter(analysisInstance, procedure)
sagClass = filt.run()
class pyCGM2.Processing.Classification.classificationFilters.ClassificationFilter(analysisInstance, procedure, pointSuffix=None)

Classification Filter

Parameters
  • analysis (pyCGM2.Processing.analysis.Analysis) – an analysis instance

  • procedure (pyCGM2.Processing.Classification.classificationProcedures.ClassificationProcedure) – a procedure instance

  • pointSuffix (str) – suffix added to model outputs.

run()

Run the filter

classificationProcedures

class pyCGM2.Processing.Classification.classificationProcedures.PFKEprocedure(normativeData, midStanceDefinition='PFKE', dataType='cycle', side='Both')

PlantarFlexor-KneeExtensor classification procedure defined by Sangeux et al 2015

Parameters
  • normativeData (pyCGM2.Report.normativeDatasets.NormativeData) – normative data instance

  • midStanceDefinition (str) – mid stance frame boundaries. Choice: PFKE (20,45), Perry (10,30) or Baker (10,50))

  • dataType (str) – chosen data type for classification. Choice cycle,mean,median.If cycle, knee and ankle scores are the median score from all cycle values with the normative mean value

  • side (str) – event context (Both,Left or Right)

Reference

  • Sangeux, Morgan; Rodda, Jill; Graham, H. Kerr (2015)

Sagittal gait patterns in cerebral palsy: the plantarflexor-knee extension couple index. In : Gait & posture, vol. 41, n° 2, p. 586–591. DOI: 10.1016/j.gaitpost.2014.12.019.

plot(analysis, title=None)

plot PFKE panels

Parameters

analysis (pyCGM2.Processing.analysis.Analysis) – an analysis instance

run(analysis, pointSuffix)

run the procedure

Parameters

DiscretePoints

discretePointFilters

A discrete point is a value at a specific frame of a cycle.

In this module, through the filter DiscretePointsFilter, the goal is to get series of discrete values extracted according a specific strategy (ie a procedure). For instance, the BenedettiProcedure extracts dicrete points recommanded in Benededdi et al (1998):

References:

Benedetti, M. G.; Catani, F.; Leardini, A.; Pignotti, E.; Giannini, S. (1998) Data management in gait analysis for clinical applications. In : Clinical biomechanics (Bristol, Avon), vol. 13, n° 3, p. 204–215. DOI: 10.1016/s0268-0033(97)00041-7.

class pyCGM2.Processing.DiscretePoints.discretePointFilters.DiscretePointsFilter(discretePointProcedure, analysis, modelInfo=None, subjInfo=None, condExpInfo=None)

Discrete point filter

Parameters
  • discretePointProcedure (pyCGM2.Processing.DiscrePoints.discretePointProcedures.DiscretePointProcedure) – a procedure

  • analysis (pyCGM2.Processing.analysis.Analysis) – an analysis instance

  • modelInfo (dict) – information about the model

  • subjInfo (dict) – information about the subject

  • condExpInfo (dict) – information about the experiment

getOutput()

get the output dataframe with all discrete values according to the procedure

setCondExpInf(condExpInfo)

Set experimental information

Parameters

condExpInfo (dict) – experimental information

setModelInfo(modelInfo)

Set model information

Parameters

modelInfo (dict) – model information

setSubjInfo(subjInfo)

Set subject information

Parameters

subjInfo (dict) – subject information

discretePointProcedures

class pyCGM2.Processing.DiscretePoints.discretePointProcedures.BenedettiProcedure(pointSuffix=None)

discrete points recommanded by benededdi et al(1998).

Parameters

pointSuffix (str) – suffix added to model ouputs

References:

Benedetti, M. G.; Catani, F.; Leardini, A.; Pignotti, E.; Giannini, S. (1998) Data management in gait analysis for clinical applications. In : Clinical biomechanics (Bristol, Avon), vol. 13, n° 3, p. 204–215. DOI: 10.1016/s0268-0033(97)00041-7.

detect(analysisInstance)

extract discrete points

Parameters

analysisInstance (pyCGM2.Processing.analysis.Analysis) – an analysis instance

class pyCGM2.Processing.DiscretePoints.discretePointProcedures.GoldbergProcedure(pointSuffix=None)

discrete points recommanded by Goldberg et al(1998).

Parameters

pointSuffix (str) – suffix added to model ouputs

References:

Goldberg, Saryn R.; Ounpuu, Sylvia; Arnold, Allison S.; Gage, James R.; Delp, Scott L. (2006) Kinematic and kinetic factors that correlate with improved knee flexion following treatment for stiff-knee gait. In : Journal of biomechanics, vol. 39, n° 4, p. 689–698. DOI: 10.1016/j.jbiomech.2005.01.015.

detect(analysisInstance)

extract discrete points

Parameters

analysisInstance (pyCGM2.Processing.analysis.Analysis) – an analysis instance

class pyCGM2.Processing.DiscretePoints.discretePointProcedures.MaxMinProcedure(pointSuffix=None)

extract extrema values.

Parameters

pointSuffix (str) – suffix added to model ouputs

detect(analysisInstance)

extract discrete points

Parameters

analysisInstance (pyCGM2.Processing.analysis.Analysis) – an analysis instance

JointPatterns

jointPatternFilters

class pyCGM2.Processing.JointPatterns.jointPatternFilters.JointPatternFilter(jointPatternProcedure, analysis)

jointPatternProcedures

ProgressionFrame

progressionFrameFilters

This module aims to detect the progression frame of a trial.

The filter ProgressionFrameFilter calls a procedure, and return the progression axis and a flag indicating the forward/backward progression.

class pyCGM2.Processing.ProgressionFrame.progressionFrameFilters.ProgressionFrameFilter(acq, progressionProcedure)

Progression Filter

Parameters
  • acq (btk.Acquisition) – an acquisition

  • progressionProcedure (pyCGM2.Processing.ProgressionFrame.progressionFrameProcedures.ProgressionFrameProcedure) – a procedure instance

compute()

run the filter

progressionFrameProcedures

class pyCGM2.Processing.ProgressionFrame.progressionFrameProcedures.PelvisProgressionFrameProcedure(marker='LASI', frontMarkers=['LASI', 'RASI'], backMarkers=['LPSI', 'RPSI'])

detect the progression from the trajectory of pelvic markers

Parameters
  • marker (str,Optional[LASI]) – marker label

  • frontMarkers (list,Optional["LASI","RASI"]) – anterior pelvic marker labels

  • backMarkers (list,Optional["LPSI","RPSI"]) – posterior pelvic markers labels

class pyCGM2.Processing.ProgressionFrame.progressionFrameProcedures.PointProgressionFrameProcedure(marker='LHEE')

detect the progression from the trajectory of a single marker

Parameters

marker (str,Optional[LHEE]) – marker label

class pyCGM2.Processing.ProgressionFrame.progressionFrameProcedures.ThoraxProgressionFrameProcedure(marker='CLAV', frontMarkers=['CLAV'], backMarkers=['C7'])

detect the progression from the trajectory of thoracic markers

Parameters
  • marker (str,Optional[CLAV]) – marker label

  • frontMarkers (list,Optional["CLAV"]) – anterior pelvic marker labels

  • backMarkers (list,Optional["C7"]) – posterior pelvic markers labels

Representative

representativeFilters

This module aims to detect a representative cycle

The filter RepresentativeCycleFilter calls a specific procedure, and return indexes of the representive cycle for the Left and right event contexts

class pyCGM2.Processing.Representative.representativeFilters.RepresentativeCycleFilter(analysisInstance, representativeProcedure)

Representative cycle filter

Parameters
  • analysisInstance (pyCGM2.Processing.analysis.Analysis) – an analysis instance.

  • representativeProcedure (pyCGM2.Processing.Representative.representativeProcedures.RepresentativeProcedure) – a procedure instance

run()

Run the filter

representativeProcedures

class pyCGM2.Processing.Representative.representativeProcedures.Sangeux2015Procedure

Representative detection method of Sangeux 2015

reference

Sangeux, Morgan A simple method to choose the most representative stride and detect outliers.

setData(EventContext, Label, indexes)

populate data

Parameters
  • EventContext (str) – event context

  • Label (str) – kinematic model output label

  • indexes (list) – axis indexes

```python

proc = Sangeux2015Procedure proc.setData(“Left”,”LHipAngles”,[0,2]) # 0:flexion and 2:transverse rotation

```

setDefaultData()

set default data according Sangeux 2015

Scores

scoreFilters

This module is dedicated to the quantification of a Score, i e a Global index caracterizing the movement performed

The filter ScoreFilter calls a specific procedure, and return scores values.

class pyCGM2.Processing.Scores.scoreFilters.ScoreFilter(scoreProcedure, analysis, normativeDataSet)

the score filter

Parameters

scoreProcedures

class pyCGM2.Processing.Scores.scoreProcedures.CGM1_GPS(pointSuffix=None)

Gait profile score accordin Baker et al. 2009

Parameters

pointSuffix (str,Optional[None]) – suffix added to model ouputs

Reference

Baker, Richard; McGinley, Jennifer L.; Schwartz, Michael H.; Beynon, Sarah; Rozumalski, Adam; Graham, H. Kerr; Tirosh, Oren (2009) The gait profile score and movement analysis profile. In : Gait & posture, vol. 30, n° 3, p. 265–269. DOI: 10.1016/j.gaitpost.2009.05.020.

Report

normativeDatasets

Module deals with normative datasets.

Normative datasets are embedded in pyCGM2. they are placed in the folder pyCGM2/Data as a json file.

The construction of a NormativeData instance automatically populate its attribute data, an intuitive dictionary with model ouput as key, reporting mean and standard deviation as sub-key.

The NormativeSTP class replicates the process for the spatio-temporal excel file (normal_stp.xlsx) placed in the folder pyCGM2/Data/stp

class pyCGM2.Report.normativeDatasets.NormalSTP

Normative spatio-temporal dataset.

The instance contruction populates the attribute data which reports normative data as a dictionary

class pyCGM2.Report.normativeDatasets.NormativeData(filenameNoExt, modality)

Normative dataset.

The instance contruction populates the attribute data which reports normative data as a dictionary

Parameters
  • filenameNoExt (str) – filename of the targeted json file.

  • modality (str) – modality.

plot

Module contains low-level plot functions

pyCGM2.Report.plot.addNormalActivationLayer(figAxis, normalActivationLabel, fo)

display normal muscle activation in the background of a time-normalized trace

Parameters
  • figAxis (matplotlib.pyplot.Axis) – a matplotlib figure axis

  • normalActivationLabel (str) – muscle label

  • fo (int) – time-normalized foot off frame

pyCGM2.Report.plot.addTemporalNormalActivationLayer(figAxis, acq, normalActivationLabel, context)

display normal muscle activation in the background of a temporal trace

Parameters
  • figAxis (matplotlib.pyplot.Axis) – a matplotlib figure axis

  • acq (btk.Acquisition) – an acquisition

  • normalActivationLabel (str) – muscle label

  • context (str) – event context

pyCGM2.Report.plot.consistencyPlot(figAxis, analysisStructureItem, pointLabel, contextPointLabel, axis, color=None, title=None, xlabel=None, ylabel=None, ylim=None, legendLabel=None, customLimits=None)

Plot all time-normalized traces from an attribute of an analysis instance

Parameters
  • figAxis (matplotlib.pyplot.Axis) – a matplotlib figure axis

  • analysisStructureItem (pyCGM2.Processing.analysis.Analysis.(attribute)) – an attribute of an analysis instance

  • pointLabel (str) – point label

  • contextPointLabel (str) – event context

  • axis (int) – column index of the point values

  • color (type,Optional[None]) – line color

  • title (type,Optional[None]) – plot title

  • xlabel (type,Optional[None]) – x-axis label

  • ylabel (type,Optional[None]) – y-axis label

  • ylim (list,Optional[None]) – y boundaries

  • legendLabel (type,Optional[None]) – legend

  • customLimits (list,Optional[None]) – horizontal lines

pyCGM2.Report.plot.descriptivePlot(figAxis, analysisStructureItem, pointLabel, contextPointLabel, axis, color=None, title=None, xlabel=None, ylabel=None, ylim=None, legendLabel=None, customLimits=None)

Plot descriptive (average and sd corridor) time-normalized traces from an attribute of an analysis instance

Parameters
  • figAxis (matplotlib.pyplot.Axis) – a matplotlib figure axis

  • analysisStructureItem (pyCGM2.Processing.analysis.Analysis.(attribute)) – an attribute of an analysis instance

  • pointLabel (str) – point label

  • contextPointLabel (str) – event context

  • axis (int) – column index of the point values

  • color (type,Optional[None]) – line color

  • title (type,Optional[None]) – plot title

  • xlabel (type,Optional[None]) – x-axis label

  • ylabel (type,Optional[None]) – y-axis label

  • ylim (list,Optional[None]) – y boundaries

  • legendLabel (type,Optional[None]) – legend

  • customLimits (list,Optional[None]) – horizontal lines

pyCGM2.Report.plot.gaitConsistencyPlot(figAxis, analysisStructureItem, pointLabel, contextPointLabel, axis, color=None, title=None, xlabel=None, ylabel=None, ylim=None, legendLabel=None, customLimits=None)

Plot all gait traces from an attribute of an analysis instance

Parameters
  • figAxis (matplotlib.pyplot.Axis) – a matplotlib figure axis

  • analysisStructureItem (pyCGM2.Processing.analysis.Analysis.(attribute)) – an attribute of an analysis instance

  • pointLabel (str) – point label

  • contextPointLabel (str) – event context

  • axis (int) – column index of the point values

  • color (type,Optional[None]) – line color

  • title (type,Optional[None]) – plot title

  • xlabel (type,Optional[None]) – x-axis label

  • ylabel (type,Optional[None]) – y-axis label

  • ylim (list,Optional[None]) – y boundaries

  • legendLabel (type,Optional[None]) – legend

  • customLimits (list,Optional[None]) – horizontal lines

pyCGM2.Report.plot.gaitDescriptivePlot(figAxis, analysisStructureItem, pointLabel, contextPointLabel, axis, color=None, title=None, xlabel=None, ylabel=None, ylim=None, legendLabel=None, customLimits=None)

Plot descriptive (average and sd corridor) gait traces from an attribute of an analysis instance

Parameters
  • figAxis (matplotlib.pyplot.Axis) – a matplotlib figure axis

  • analysisStructureItem (pyCGM2.Processing.analysis.Analysis.(attribute)) – an attribute of an analysis instance

  • pointLabel (str) – point label

  • contextPointLabel (str) – event context

  • axis (int) – column index of the point values

  • color (type,Optional[None]) – line color

  • title (type,Optional[None]) – plot title

  • xlabel (type,Optional[None]) – x-axis label

  • ylabel (type,Optional[None]) – y-axis label

  • ylim (list,Optional[None]) – y boundaries

  • legendLabel (type,Optional[None]) – legend

  • customLimits (list,Optional[None]) – horizontal lines

pyCGM2.Report.plot.gaitMeanPlot(figAxis, analysisStructureItem, pointLabel, contextPointLabel, axis, color=None, title=None, xlabel=None, ylabel=None, ylim=None, legendLabel=None, customLimits=None)

Plot average gait traces from an attribute of an analysis instance

Parameters
  • figAxis (matplotlib.pyplot.Axis) – a matplotlib figure axis

  • analysisStructureItem (pyCGM2.Processing.analysis.Analysis.(attribute)) – an attribute of an analysis instance

  • pointLabel (str) – point label

  • contextPointLabel (str) – event context

  • axis (int) – column index of the point values

  • color (type,Optional[None]) – line color

  • title (type,Optional[None]) – plot title

  • xlabel (type,Optional[None]) – x-axis label

  • ylabel (type,Optional[None]) – y-axis label

  • ylim (list,Optional[None]) – y boundaries

  • legendLabel (type,Optional[None]) – legend

  • customLimits (list,Optional[None]) – horizontal lines

pyCGM2.Report.plot.meanPlot(figAxis, analysisStructureItem, pointLabel, contextPointLabel, axis, color=None, title=None, xlabel=None, ylabel=None, ylim=None, legendLabel=None, customLimits=None)

Plot the average time-normalized traces from an attribute of an analysis instance

Parameters
  • figAxis (matplotlib.pyplot.Axis) – a matplotlib figure axis

  • analysisStructureItem (pyCGM2.Processing.analysis.Analysis.(attribute)) – an attribute of an analysis instance

  • pointLabel (str) – point label

  • contextPointLabel (str) – event context

  • axis (int) – column index of the point values

  • color (type,Optional[None]) – line color

  • title (type,Optional[None]) – plot title

  • xlabel (type,Optional[None]) – x-axis label

  • ylabel (type,Optional[None]) – y-axis label

  • ylim (list,Optional[None]) – y boundaries

  • legendLabel (type,Optional[None]) – legend

  • customLimits (list,Optional[None]) – horizontal lines

pyCGM2.Report.plot.stpHorizontalHistogram(figAxis, analysisStructureItem, stpLabel, overall=False, title=None, xlabel=None, xlim=None)

Plot spatio-temporal parameters as histogram from an attribute of an analysis instance

Parameters
  • figAxis (matplotlib.pyplot.Axis) – a matplotlib figure axis

  • analysisStructureItem (pyCGM2.Processing.analysis.Analysis.(attribute)) – an attribute of an analysis instance

  • stpLabel (str) – spatio-temporal label

  • title (type,Optional[None]) – plot title

  • xlabel (type,Optional[None]) – x-axis label

  • xlim (list,Optional[None]) – x boundaries

pyCGM2.Report.plot.temporalPlot(figAxis, acq, pointLabel, axis, pointLabelSuffix=None, color=None, linewidth=None, title=None, xlabel=None, ylabel=None, ylim=None, legendLabel=None, customLimits=None)

Plot temporal traces from an acquisition

Parameters
  • figAxis (matplotlib.pyplot.Axis) – a matplotlib figure axis

  • acq (btk.Acquisition) – an acquisition

  • pointLabel (str) – point label

  • axis (int) – column index of the point values

  • pointLabelSuffix (type,Optional[None]) – suffix added to the point label

  • color (type,Optional[None]) – line color

  • linewidth (type,Optional[None]) – line width

  • title (type,Optional[None]) – plot title

  • xlabel (type,Optional[None]) – x-axis label

  • ylabel (type,Optional[None]) – y-axis label

  • ylim (list,Optional[None]) – y boundaries

  • legendLabel (type,Optional[None]) – legend

  • customLimits (list,Optional[None]) – horizontal lines

plotFilters

This Module contains the pyCGM2 plot filter PlottingFilter.

This PlottingFilter requires a PlotViewer, then displays the plot panel

class pyCGM2.Report.plotFilters.PlottingFilter

The plot filter

plot()

generate plot panel

setAutomaticYlimits()

set Y-axis boundaries to default values

setExport(path, filename, format)

Set filename of the export file

Parameters
  • path (str) – folder path

  • filename (str) – filename

  • format (str) – file format

setHorizontalLine(axisIndex, value, color='black')

set horizontal lines

Parameters
  • axisIndex (int) – index of the matplotlib.figure.axis instance

  • value (double) – y-axis value

  • color (str,Optional[black]) – line color

setTitle(title)

Set the plot panel title

Parameters

title (str) – title

setViewer(concretePlotViewer)

set the plot viewer

Parameters

concretePlotViewer (pyCGM2.report.(Viewers)) – a plot viewer

setYlimits(axisIndex, min, max)

set the y-axis boundaries

Parameters
  • axisIndex (int) – index of the matplotlib.figure.axis instance

  • min (double) – minimum value

  • max (double) – maximum value

plotUtils

Viewers

plotViewers

Module contains plotViewers for displaying convenient gait plot

class pyCGM2.Report.Viewers.plotViewers.GpsMapPlotViewer(iAnalysis, pointLabelSuffix=None)

Plot viewer to display GPS and MAP panel

Parameters

iAnalysis (pyCGM2.Processing.analysis.Analysis) – an analysis instance

plotPanel()

plat the panel

class pyCGM2.Report.Viewers.plotViewers.NormalizedKinematicsPlotViewer(iAnalysis, pointLabelSuffix=None, bodyPart=BodyPartPlot.LowerLimb)

Plot time-Normalized Kinematics

Parameters
  • iAnalysis (pyCGM2.Processing.analysis.Analysis) – an analysis instance

  • pointLabelSuffix (str) – suffix added model outputs

  • bodyPart (enums.BodyPartPlot,Optional[enums.BodyPartPlot.LowerLimb]) – body part

plotPanel()

Plot the panel

setConcretePlotFunction(concreteplotFunction)

set a plot function ( see plot)

Parameters

concreteplotFunction (function) – plot function

setNormativeDataset(iNormativeDataSet)

Set the normative dataset

Parameters

iNormativeDataSet (pyCGM2.Report.normativeDatasets.NormativeData) – a normative dataset instance

class pyCGM2.Report.Viewers.plotViewers.NormalizedKineticsPlotViewer(iAnalysis, pointLabelSuffix=None, bodyPart=BodyPartPlot.LowerLimb)

Plot time-Normalized kinetics

Parameters
  • iAnalysis (pyCGM2.Processing.analysis.Analysis) – an analysis instance

  • pointLabelSuffix (str) – suffix added model outputs

  • bodyPart (enums.BodyPartPlot,Optional[enums.BodyPartPlot.LowerLimb]) – body part

plotPanel()

Plot the panel

setConcretePlotFunction(concreteplotFunction)

set a plot function ( see plot)

Parameters

concreteplotFunction (function) – plot function

setNormativeDataset(iNormativeDataSet)

Set the normative dataset

Parameters

iNormativeDataSet (pyCGM2.Report.normativeDatasets.NormativeData) – a normative dataset instance

class pyCGM2.Report.Viewers.plotViewers.SpatioTemporalPlotViewer(iAnalysis)

Plot viewer to display spatio-temporal parameters as histogram

Parameters

iAnalysis (pyCGM2.Processing.analysis.Analysis) – an analysis instance

plotPanel()

Plot the panel

setNormativeDataset(iNormativeDataSet)

Set the normative dataset

Parameters

iNormativeDataSet (pyCGM2.Report.normativeDatasets.NormalSTP) – a spatio-temporal normative dataset instance

class pyCGM2.Report.Viewers.plotViewers.TemporalKinematicsPlotViewer(iAcq, pointLabelSuffix=None, bodyPart=BodyPartPlot.LowerLimb)

Plot temporal Kinematics

Parameters
  • iAcq (btk.Acquisition) – an acquisition

  • pointLabelSuffix (str) – suffix added model outputs

  • bodyPart (enums.BodyPartPlot,Optional[enums.BodyPartPlot.LowerLimb]) – body part

plotPanel()

Plot the panel

class pyCGM2.Report.Viewers.plotViewers.TemporalKineticsPlotViewer(iAcq, pointLabelSuffix=None, bodyPart=BodyPartPlot.LowerLimb)

Plot temporal Kinetics

Parameters
  • iAcq (btk.Acquisition) – an acquisition

  • pointLabelSuffix (str) – suffix added model outputs

  • bodyPart (enums.BodyPartPlot,Optional[enums.BodyPartPlot.LowerLimb]) – body part

plotPanel()

plot the panel

emgPlotViewers

Module contains plotViewers for displaying emg data

class pyCGM2.Report.Viewers.emgPlotViewers.CoactivationEmgPlotViewer(iAnalysis, pointLabelSuffix=None)

plot coactivation plot

Parameters
plotPanel()

plot the panel

setConcretePlotFunction(concreteplotFunction)

set a concrete plot function

Parameters

concreteplotFunction (pyCGM2.Report.plot) – plot function

setContext(context)

set event context

Parameters

context (str) – event context

setEmgs(label1, label2)

set the 2 emg labels to plot

Parameters
  • label1 (str) – emg channel label

  • label2 (str) – emg channel label

setMuscles(label1, label2)

set the 2 measured muscle names

Parameters
  • label1 (str) – muscle name

  • label2 (str) – muscle name

class pyCGM2.Report.Viewers.emgPlotViewers.EnvEmgGaitPlotPanelViewer(iAnalysis, pointLabelSuffix=None)

plot emg envelops

Parameters
plotPanel()

plot the panel

selectEmgChannels(channelNames)

set the emg channels

Parameters

channelNames (str) – channel labels

setConcretePlotFunction(concreteplotFunction)

set a concrete plot function

Parameters

concreteplotFunction (pyCGM2.Report.plot) – plot function

setEmgManager(emgManager)

set the emgManager instance

Parameters

emgManager (pyCGM2.EMG.EmgManager) – emgManager instance

setNormalizedEmgFlag(flag)

Enable/Disable amplitude-normalized emg

Parameters

flag (bool) – boolean flag

class pyCGM2.Report.Viewers.emgPlotViewers.MultipleAnalysis_EnvEmgPlotPanelViewer(iAnalyses, legends, pointLabelSuffix=None)

plot emg envelops from multiple analysis instances

Parameters
  • iAnalyses (list) – analysis instances

  • legend (str) – label assoaciated to each instance

  • pointLabelSuffix (str,Optional[None]) – suffix added to emg outputs

plotPanel()

plot the panel

selectEmgChannels(channelNames)

set the emg channels

Parameters

channelNames (str) – channel labels

setConcretePlotFunction(concreteplotFunction)

set a concrete plot function

Parameters

concreteplotFunction (pyCGM2.Report.plot) – plot function

setEmgManager(emgManager)

set the emgManager instance

Parameters

emgManager (pyCGM2.EMG.EmgManager) – emgManager instance

setNormalizedEmgFlag(flag)

Enable/Disable amplitude-normalized emg

Parameters

flag (bool) – boolean flag

class pyCGM2.Report.Viewers.emgPlotViewers.TemporalEmgPlotViewer(iAcq, pointLabelSuffix=None)

plot temporal emg plot

Parameters
  • iAcq (btk.Acquisition) – an acquisition

  • pointLabelSuffix (str,Optional[None]) – suffix added to emg outputs

ignoreNormalActivty(bool)

Enable/disable normal actividy display

Parameters

bool (bool) – boolean flag

plotPanel()

plot the panel

selectEmgChannels(channelNames)

set the emg channels

Parameters

channelNames (str) – channel labels

setEmgManager(emgManager)

set the emgManager instance

Parameters

emgManager (pyCGM2.EMG.EmgManager) – emgManager instance

setEmgRectify(flag)

Enable/disable rectify mode

Parameters

flag (bool) – boolean flag

comparisonPlotViewers

Module contains plotViewers for comparing data from different analysis instances

class pyCGM2.Report.Viewers.comparisonPlotViewers.KinematicsPlotComparisonViewer(iAnalyses, context, legends, pointLabelSuffix_lst=None, bodyPart=BodyPartPlot.LowerLimb)

Compare kinematics

Parameters
  • iAnalyses (list) – pyCGM2.Processing.analysis.Analysis instances

  • context (str) – event context

  • pointLabelSuffix (str) –

  • legends (list) – labels caracterizing the analysis instances

  • pointLabelSuffix_lst (list,Optional[None]) – suffix added to model outputs of the analysis instances

  • bodyPart (pyCGM2.enums.BodyPartPlot,Optional[pyCGM2.enums.BodyPartPlot.LowerLimb]) – body part

plotPanel()

plot the panel

setConcretePlotFunction(concreteplotFunction)

set a plot function ( see plot)

Parameters

concreteplotFunction (function) – plot function

setNormativeDataset(iNormativeDataSet)

Set a normative dataset

Parameters

iNormativeDataSet (pyCGM2.Report.normativeDatasets.NormativeData) – normative data instance

class pyCGM2.Report.Viewers.comparisonPlotViewers.KineticsPlotComparisonViewer(iAnalyses, context, legends, pointLabelSuffix_lst=None, bodyPart=BodyPartPlot.LowerLimb)

Compare kinetics

Parameters
  • iAnalyses (list) – pyCGM2.Processing.analysis.Analysis instances

  • context (str) – event context

  • pointLabelSuffix (str) –

  • legends (list) – labels caracterizing the analysis instances

  • pointLabelSuffix_lst (list,Optional[None]) – suffix added to model outputs of the analysis instances

  • bodyPart (pyCGM2.enums.BodyPartPlot,Optional[pyCGM2.enums.BodyPartPlot.LowerLimb]) – body part

plotPanel()

plot the panel

setConcretePlotFunction(concreteplotFunction)

set a plot function ( see plot)

Parameters

concreteplotFunction (function) – plot function

setNormativeDataset(iNormativeDataSet)

Set a normative dataset

Parameters

iNormativeDataSet (pyCGM2.Report.normativeDatasets.NormativeData) – normative data instance

Signal

anomaly

pyCGM2.Signal.anomaly.anomaly_rolling(values, aprioriError=0, window=10, threshold=3, method='median', plot=False, label='Unknow', referenceValues=None)

anomaly detection from rolling windows

Parameters
  • values (np.array) – values

  • aprioriError (int,Optional[0]) – a priori error.

  • window (int,Optional[10]) – size of the window.

  • threshold (int,Optional[3]) – standard deviation factor

  • method (str,Optional[median]) – descriptive statistic method

  • plot (bool,Optional[False]) – enable plot

  • label (str,Optional[Unknown]) – Description of parameter label

  • referenceValues (np.array,Optional[None]) – values used as reference instead of the values computing from the rolling windows

detect_changes

The module only contains the function “detect_changes” implemenented by Marcos Duarte, available in [BMC](https://github.com/demotu/BMC)

see BMC documentation for details

pyCGM2.Signal.detect_changes.detect_cusum(x, threshold=1, drift=0, ending=False, show=True, ax=None)

Cumulative sum algorithm (CUSUM) to detect abrupt changes in data

detect_onset

The module only contains the function “detect_onset” implemenented by Marcos Duarte, available in [BMC](https://github.com/demotu/BMC)

see BMC documentation for details

pyCGM2.Signal.detect_onset.detect_onset(x, threshold=0, n_above=1, n_below=0, threshold2=None, n_above2=1, show=False, ax=None)

Detects onset in data based on amplitude threshold.

detect_peaks

The module only contains the function “detect_peaks” implemenented by Marcos Duarte, available in [BMC](https://github.com/demotu/BMC)

see BMC documentation for details

pyCGM2.Signal.detect_peaks.detect_peaks(x, mph=None, mpd=1, threshold=0, edge='rising', kpsh=False, valley=False, show=False, ax=None)

Detect peaks in data based on their amplitude and other features.

signal_processing

The module only contains functions for filtering data

pyCGM2.Signal.signal_processing.arrayLowPassFiltering(valuesArray, freq, order=2, fc=6)

Low-pass filtering of a numpy.array

Parameters
  • valuesArray (numpy.array(n,n)) –

  • fc (float,Optional) – cut-off frequency. Default set to 6 Hz

  • order (int,optional) – order of the low-pass filter, Default set to 2

pyCGM2.Signal.signal_processing.enveloppe(array, fc, fa)

Get signal enveloppe from a low pass filter

Parameters
  • array (numpy.array(n,n)) – array

  • fc (float) – cut-off frequency

  • fa (float) – sample frequency

pyCGM2.Signal.signal_processing.forcePlateFiltering(btkAcq, order=4, fc=5)

Low-pass filtering of Force plate outputs

Parameters
  • btkAcq (btk.Acquisition) – btk acquisition instance

  • fc (float,Optional) – cut-off frequency. Default set to 5 Hz

  • order (int,optional) – order of the low-pass filter, Default set to 4

pyCGM2.Signal.signal_processing.highPass(array, lowerFreq, upperFreq, fa)

butterworth bandpass filter.

Parameters
  • array (numpy.array(n,n)) – array

  • lowerFreq (float) – lower frequency

  • upperFreq (float) – upper frequency

  • fa (float) – sample frequency

pyCGM2.Signal.signal_processing.markerFiltering(btkAcq, markers, order=2, fc=6, zerosFiltering=True)

Low-pass filtering of all points in an acquisition

Parameters
  • btkAcq (btk.Acquisition) – btk acquisition instance

  • fc (float,Optional) – cut-off frequency. Default set to 6 Hz

  • order (int,optional) – order of the low-pass filter, Default set to 2

  • zerosFiltering (bool,optional) – enable zero filtering, Default set to True

pyCGM2.Signal.signal_processing.rectify(array)

rectify a signal ( i.e get absolute values)

Parameters

array (numpy.array(n,n)) – array

pyCGM2.Signal.signal_processing.remove50hz(array, fa)

Remove the 50Hz signal

Args

array (array(n,n): array fa (float): sample frequency

Tools

btkTools

This module contains convenient functions for working with btk

check out test_btkTools for examples

pyCGM2.Tools.btkTools.GetAnalogNames(acq)

return analog labels

Parameters

acq (btk.acquisition) – a btk acquisition instance

pyCGM2.Tools.btkTools.GetMarkerNames(acq)

return marker labels

Parameters

acq (btk.acquisition) – a btk acquisition instance

pyCGM2.Tools.btkTools.applyOnValidFrames(acq, validFrames)

set zeros to all points if the frame is not valid

Parameters
  • acq (btkAcquisition) – a btk acquisition inctance

  • validFrames (list) – list of n frames with 1 or 0 indicating if the frame is valid or not

pyCGM2.Tools.btkTools.applyRotation(acq, markers, globalFrameOrientation, forwardProgression)

apply a rotation to markers

Args

acq (btkAcquisition): a btk acquisition instance markers (list): marker labels globalFrameOrientation (str): orientation of the global frame ( eg XYZ stands for X:long, y: transversal, Z:normal) forwardProgression (bool): indicate progression along the positive axis of the progression frame

pyCGM2.Tools.btkTools.applyTranslators(acq, translators)

Rename marker from translators

Parameters
  • acq (btk.Acquisition) – a btk acquisition instance

  • translators (dict) – translators

pyCGM2.Tools.btkTools.applyValidFramesOnOutput(acq, validFrames)

set model outputs to zero if not a valid frame

Parameters
  • acq (btkAcquisition) – a btk acquisition inctance

  • validFrames (list) – valid frame flags

pyCGM2.Tools.btkTools.automaticKineticDetection(dataPath, filenames, acqs=None)

check presence of force plate events (ie Left-FP”, “Right-FP”) in a list of files

Args

dataPath (str): data folder dataPath filenames ([str..]): filenames acqs ([btk.acquisition,…],Optional): list of btk.acquisition instances. default set to None

pyCGM2.Tools.btkTools.buildTrials(dataPath, filenames)

build acquisitions

Args

dataPath (str): data folder dataPath filenames(list): c3d filenames

pyCGM2.Tools.btkTools.changeSubjectName(acq, subjectName)

change subject name in all section of the acquisition

Args

acq (btkAcquisition): a btk acquisition instance subjectName (str): subject name

pyCGM2.Tools.btkTools.checkForcePlateExist(acq)

check force plate presence

Args

acq (btkAcquisition): a btk acquisition instance

pyCGM2.Tools.btkTools.checkGap(acq, markerList, frameBounds=None)

check if there are any gaps from a list of markers

Parameters
  • acq (btkAcquisition) – a btk acquisition inctance

  • markerLabels ([str...]) – marker labels

  • frameBounds ([double,double]) – frame boundaries

pyCGM2.Tools.btkTools.checkMarkers(acq, markerList)

check marker presence. Raise an exception if fails

Parameters
  • acq (btk.Acquisition) – a btk acquisition instance

  • markerList (list) – marker labels

pyCGM2.Tools.btkTools.checkMetadata(acq, firstLevel, secondLevel)

check presence of a metadata

Args

acq (btkAcquisition): a btk acquisition instance firstLevel (str): metadata first-level label secondLevel (str): metadata second-level label

pyCGM2.Tools.btkTools.checkMultipleSubject(acq)

check if multiple subject detected in the acquisition

Parameters

acq (btkAcquisition) – a btk acquisition inctance

pyCGM2.Tools.btkTools.cleanAcq(acq)

clean an aquisition ( remove zero points)

Args

acq (btkAcquisition): a btk acquisition instance

pyCGM2.Tools.btkTools.clearEvents(acq, labels)

remove events from their label

Parameters
  • acq (btk.Acquisition) – a btk acquisition instance

  • label (list) – event labels

pyCGM2.Tools.btkTools.clearPoints(acq, pointlabelList)

Remove points

Parameters
  • acq (btk.acquisition) – a btk acquisition instance

  • pointlabelList (list) – point labels

pyCGM2.Tools.btkTools.constructMarker(acq, label, markers, numpyMethod=<function mean>, desc='')

construct a marker from others

Args

acq (btkAcquisition): a btk acquisition inctance label (str): marker label of the constructed marker markers ([str…]): markers labels numpyMethod (np.function, Optional): [default:np.mean]: numpy function used for handle markers desc (str,optional) - description

pyCGM2.Tools.btkTools.constructPhantom(acq, label, desc='')

construct a phantom

Args

acq (btkAcquisition): a btk acquisition inctance label (str): marker label of the constructed marker desc (str,optional) - description

pyCGM2.Tools.btkTools.createPhantoms(acq, markerLabels)

construct phantoms

Args

acq (btkAcquisition): a btk acquisition instance markerLabels (list): phantom marker labels

pyCGM2.Tools.btkTools.deleteContextEvents(acq, context)

remove events with the same context ( eg Left,Right, or General )

Parameters
  • acq (btk.Acquisition) – a btk acquisition instance

  • context (str) – event context

pyCGM2.Tools.btkTools.findMarkerGap(acq)

return markers with detected gap

Parameters

acq (btk.acquisition) – a btk acquisition instance

pyCGM2.Tools.btkTools.findValidFrames(acq, markerLabels)

find valid frames to process from markers

Parameters
  • acq (btkAcquisition) – a btk acquisition inctance

  • markerLabels (list) – marker labels

pyCGM2.Tools.btkTools.getAllParamAnalysis(acq)

get all analysis parameters

Args

acq (btkAcquisition): a btk acquisition instance

pyCGM2.Tools.btkTools.getForcePlateWrench(acq, fpIndex=None)

get force plate wrench

Args

acq (btkAcquisition): a btk acquisition instance

pyCGM2.Tools.btkTools.getFrameBoundaries(acq, markerLabels)

get frame boundaries from a list of markers

Parameters
  • acq (btkAcquisition) – a btk acquisition inctance

  • markerLabels (list) – marker labels

pyCGM2.Tools.btkTools.getNumberOfForcePlate(acq)

return number of force plate

Args

acq (btkAcquisition): a btk acquisition instance

pyCGM2.Tools.btkTools.getNumberOfModelOutputs(acq)

return the size of model outputs

Parameters

acq (btk.Acquisition) – a btk acquisition instance

pyCGM2.Tools.btkTools.getParamAnalysis(btkAcq, name, context, subject)

get an analysis parameter

Args

acq (btkAcquisition): a btk acquisition instance name (str): parameter labels context (str): event contexts subject (str): subject name

pyCGM2.Tools.btkTools.getStartEndEvents(acq, context, startLabel='Start', endLabel='End')

return frames of the start and end events.

Args

acq (btkAcquisition): a btk acquisition instance context (str): event context startLabel (str,optional). label of the start event. default set to Start endLabel (str,optional). label of the end event. default set to End

pyCGM2.Tools.btkTools.getValidFrames(acq, markerLabels, frameBounds=None)

get valid frames of markers

Parameters
  • acq (btkAcquisition) – a btk acquisition inctance

  • markerLabel (str) – marker label

  • frameBounds ([int,int],optional) – frame boundaries

pyCGM2.Tools.btkTools.getVisibleMarkersAtFrame(acq, markers, index)

return markers visible at a specific frame

Parameters

acq (btk.Acquisition) – a btk acquisition instance

pyCGM2.Tools.btkTools.isAnalogExist(acq, label)

Check if a point label exists inside an acquisition

Args

acq (btkAcquisition): a btk acquisition inctance label (str) - analog label

pyCGM2.Tools.btkTools.isGap(acq, markerLabel)

check gap

Parameters
  • acq (btk.acquisition) – a btk acquisition instance

  • markerLabel (list) – marker labels

pyCGM2.Tools.btkTools.isKineticFlag(acq)

check presence of force plate events (ie Left-FP”, “Right-FP”)

Args

acq (btkAcquisition): a btk acquisition instance

pyCGM2.Tools.btkTools.isPhantom(acq, label)

check if a point is a phantom ( ie zero point)

Parameters
  • acq (btkAcquisition) - a btk acquisition inctance

  • label (str) - point label

pyCGM2.Tools.btkTools.isPointExist(acq, label, ignorePhantom=True)

check if a point exist

Parameters
  • acq (btk.acquisition) – a btk acquisition instance

  • label (str) – marker label

  • ignorePhantom (bool,optional) –

pyCGM2.Tools.btkTools.isPointsExist(acq, labels, ignorePhantom=True)

check if a list of points exist

Parameters
  • acq (btk.acquisition) – a btk acquisition instance

  • label (list) – marker labels

  • ignorePhantom (bool,optional) –

pyCGM2.Tools.btkTools.keepAndDeleteOtherPoints(acq, pointToKeep)

Remove points except ones

Parameters
  • acq (btk.acquisition) – a btk acquisition instance

  • pointToKeep ([str) – points to keep

pyCGM2.Tools.btkTools.markerUnitConverter(acq, unitOffset)

apply an offset to convert marker in an other unit

Args

acq (btkAcquisition): a btk acquisition inctance unitOffset (float) - offset value

pyCGM2.Tools.btkTools.modifyEventSubject(acq, newSubjectlabel)

update the subject name of all events

Parameters
  • acq (btk.Acquisition) – a btk acquisition instance

  • newSubjectlabel (str) – new subject

pyCGM2.Tools.btkTools.modifySubject(acq, newSubjectlabel)

update the subject name inside c3d metadata

Parameters
  • acq (btk.Acquisition) – a btk acquisition instance

  • newSubjectlabel (str) – new subject

pyCGM2.Tools.btkTools.smartAppendAnalog(acq, label, values, desc='')

append an analog output

Args

acq (btkAcquisition): a btk acquisition inctance label (str) - analog label label (np.array) - values desc (str,optional) - description

pyCGM2.Tools.btkTools.smartAppendParamAnalysis(acq, name, eventcontext, value, description='', subject='', unit='')

set an analysis parameter

Args

acq (btkAcquisition): a btk acquisition instance name (str): parameter label eventcontext (str): event context value (float): value subject (str,optional ): name of the subject. Defaut set to “” description (str,optional ): description. Defaut set to “” unit (str,optional ): unit. Defaut set to “”

pyCGM2.Tools.btkTools.smartAppendPoint(acq, label, values, PointType='Marker', desc='', residuals=None)

Append or Update a point

Parameters
  • acq (btk.acquisition) – a btk acquisition instance

  • label (str) – marker label

  • values (np.array(n,3)) – point values

  • PointType (str) – point type (choice : Marker,Angle,Moment,Force,Power,Reaction,Scalar)

  • desc (str,optional) – point description. Default set to “”

  • residuals (np.array(n,1)) – point residual values

pyCGM2.Tools.btkTools.smartCreateEvent(acq, label, context, frame, type='Automatic', subject='', desc='')

set an event

Args

acq (btkAcquisition): a btk acquisition instance label (str): event labels context (str): event context frame (int) event frameEnd type (btk.btkEvent enum,optional ): btk event type. Default set to btk.btkEvent.Automatic subject (str,optional ): name of the subject. Defaut set to “” desc (str,optional ): description. Defaut set to “”

pyCGM2.Tools.btkTools.smartGetEvents(acq, label, context)

return an event

Args

acq (btkAcquisition): a btk acquisition instance label (str): event label context (str): event context

pyCGM2.Tools.btkTools.smartGetMetadata(acq, firstLevel, secondLevel, returnType='String')

return metadata

Args

acq (btkAcquisition): a btk acquisition instance firstLevel (str): metadata first-level label secondLevel (str): metadata second-level label returnType (str,optional) : returned type of the metadata. defalut set to String

pyCGM2.Tools.btkTools.smartReader(filename, translators=None)

Convenient function to read a c3d with Btk

Parameters
  • filename (str) – filename with its path

  • translators (dict) – marker translators

pyCGM2.Tools.btkTools.smartSetMetadata(acq, firstLevel, secondLevel, index, value)

set a metadata

Args

acq (btkAcquisition): a btk acquisition instance firstLevel (str): metadata first-level label secondLevel (str): metadata second-level label index (int) : index value (str,optional) : metadata value

pyCGM2.Tools.btkTools.smartWriter(acq, filename)

Convenient function to write a c3d with Btk

Parameters
  • acq (btk.acquisition) – a btk acquisition instance

  • filename (str) – filename with its path

pyCGM2.Tools.btkTools.sortedEvents(acq)

sort events

Args

acq (btkAcquisition): a btk acquisition instance

pythonTools

class pyCGM2.Tools.pythonTools.ordict(*args, **kwargs)

ordered dictionary

clear()

clear the dictionary

copy()

copy dict

items()

return items (key,value)

iteritems()

iterator returning tuples (key, value)

iterkeys()

iterator returning key

itervalues()

iterator returning value

keys()

get keys

pop(key, value=None)

remove a key and return its value

popitem()

remove a key an return the key an its value

setdefault(key, value=None)

set a default item

update(*args, **kwargs)

update the dictionary

values()

return values

Utils

files

pyCGM2.Utils.files.copyPaste(src, dst)

file copy/paste

Parameters
  • src (str) – source

  • dst (str) – destination

pyCGM2.Utils.files.copyPasteDirectory(src, dst)

folder copy/paste

Parameters
  • src (str) – source

  • dst (str) – destination

pyCGM2.Utils.files.copySessionFolder(folderPath, folder2copy, newFolder, selectedFiles=None)

copy a vicon-session folder

Parameters
  • folderPath (str) – new session folder path

  • folder2copy (str) – session folder path to copy

  • selectedFiles (str,Optional[none]) – selected files to copy

pyCGM2.Utils.files.createDir(fullPathName)

Create a folder

Parameters

fullPathName (str) – path

pyCGM2.Utils.files.deleteDirectory(dir)

Delete a folder

Parameters

dir (str) – folder path

pyCGM2.Utils.files.getC3dFiles(path, text='', ignore=None)

get all c3d files in a folder

Parameters
  • path (str) – folder path

  • text (str,Optional[""]) – included text in the filename

pyCGM2.Utils.files.getDirs(folderPath)

get all folders

Parameters

folderPath (str) – folder path

pyCGM2.Utils.files.getFileCreationDate(file)

return file creation date

Parameters

file (str) – full filename (path+filename)

pyCGM2.Utils.files.getFiles(path, extension, ignore=None, raiseFlag=False)

get all files in a folder

Parameters
  • path (str) – folder path

  • extension (str) – file extension

  • ignore (str,Optional[None]) – ignored filenames

  • raiseFlag (bool,Optional[False]) – raise exception

pyCGM2.Utils.files.getIKweightSet(DATA_PATH, ikwf)

get marker weights for kinematic fitting

Parameters
  • DATA_PATH (str) – data folder path

  • ikwf (str) – weights filename

pyCGM2.Utils.files.getMp(mpInfo, resetFlag=True)

return required and optional anthropometric parameters

Parameters
  • mpInfo (dict) – global mp dictionary

  • resetFlag (bool,Optional[True]) – reset optional parameters

pyCGM2.Utils.files.getMpFileContent(DATA_PATH, file, subject)

get anthropometric data

Parameters
  • DATA_PATH (str) – data folder path

  • file (str) – Filename

  • subject (str) – subject name

pyCGM2.Utils.files.getTranslators(DATA_PATH, translatorType='CGM1.translators')

get CGM marker translators

Parameters
  • DATA_PATH (str) – data folder path

  • translatorType (str,Optional[CGM1.translators]) – translator filename

pyCGM2.Utils.files.loadAnalysis(path, FilenameNoExt)

load an analysis instance

Parameters
  • path (str) – data folder path

  • FilenameNoExt (str) – analysis filename without extension

pyCGM2.Utils.files.loadModel(path, FilenameNoExt)

load a pyCGM2 model instance

Parameters
  • path (str) – data folder path

  • FilenameNoExt (str) – model filename wthout extension

pyCGM2.Utils.files.loadModelSettings(DATA_PATH, expertsettings_filename)

Load a pyCGM2 model settings.

Parameters
  • DATA_PATH (str) – data folder path

  • expertsettings_filename (str) – setting filename

pyCGM2.Utils.files.openFile(path, filename)

open a json/yaml file.

Parameters
  • path (str) – data folder path

  • filename (str) – filename with Extension

pyCGM2.Utils.files.openPickleFile(path, filename)

open a serialized file.

Parameters
  • path (str) – data folder path

  • filename (str) – filename with Extension

pyCGM2.Utils.files.readContent(stringContent)

read a json/yaml content

Parameters

stringContent (str) – json or yaml content

pyCGM2.Utils.files.readXml(DATA_PATH, filename)

Read a xml file

Parameters
  • DATA_PATH (str) – folder path

  • filename (str) – xlm filename

pyCGM2.Utils.files.saveAnalysis(analysisInstance, path, FilenameNoExt)

save a pyCGM2 analysis instance

Parameters
  • pyCGM2.Processing.analysis.Analysis) (model) – an analysis instance

  • path (str) – data folder path

  • FilenameNoExt (str) – model filename wthout extension

pyCGM2.Utils.files.saveJson(path, filename, content, ensure_ascii=False)

save as json file

Parameters
  • path (str) – data folder path

  • filename (str) – json filename

  • content (dict) – dictionary to save

pyCGM2.Utils.files.saveModel(model, path, FilenameNoExt)

save a pyCGM2 model instance

Parameters
  • pyCGM2.Model.model.Model) (model) – a model instance

  • path (str) – data folder path

  • FilenameNoExt (str) – model filename wthout extension

pyCGM2.Utils.files.saveMp(mpInfo, model, DATA_PATH, mpFilename)

Save anthropometric parameters as json

Parameters
  • mpInfo (dict) – global anthropometric parameters

  • model (pyCGM2.Model.model.Model) – a model instance

  • DATA_PATH (str) – data folder path

  • mpFilename (str) – filename

pyCGM2.Utils.files.savePickleFile(instance, path, filename)

serialized a pyCGM2 instance , then save it.

Parameters
  • instance (object) – a object instance

  • path (str) – data folder path

  • filename (str) – filename with Extension

utils

pyCGM2.Utils.utils.isInRange(val, min, max)

check if value is in range

Parameters
  • val (double) – value

  • min (double) – minimim value

  • max (double) – maximum value

pyCGM2.Utils.utils.toBool(text)

convert text to bool

Parameters

text (str) – text

Enums