def main(): logging.info("------------------------------------------------") logging.info("------------QTM - pyCGM2 Workflow---------------") logging.info("------------------------------------------------") file = "session.xml" sessionXML = files.readXml(os.getcwd() + "\\", file) sessionDate = files.getFileCreationDate(os.getcwd() + "\\" + file) # --------------------------------------------------------------------------- # management of the Processed folder DATA_PATH = os.getcwd() + "\\" + "processed\\" files.createDir(DATA_PATH) staticMeasurement = utils.find_static(sessionXML) calibrateFilenameLabelled = qtmTools.getFilename(staticMeasurement) if not os.path.isfile(DATA_PATH + calibrateFilenameLabelled): shutil.copyfile(os.getcwd() + "\\" + calibrateFilenameLabelled, DATA_PATH + calibrateFilenameLabelled) logging.info( "qualisys exported c3d file [%s] copied to processed folder" % (calibrateFilenameLabelled)) dynamicMeasurements = qtmTools.findDynamic(sessionXML) for dynamicMeasurement in dynamicMeasurements: reconstructFilenameLabelled = qtmTools.getFilename(dynamicMeasurement) if not os.path.isfile(DATA_PATH + reconstructFilenameLabelled): shutil.copyfile(os.getcwd() + "\\" + reconstructFilenameLabelled, DATA_PATH + reconstructFilenameLabelled) logging.info( "qualisys exported c3d file [%s] copied to processed folder" % (reconstructFilenameLabelled)) acq = btkTools.smartReader( str(DATA_PATH + reconstructFilenameLabelled)) if btkTools.checkForcePlateExist(acq): if "5" in btkTools.smartGetMetadata(acq, "FORCE_PLATFORM", "TYPE"): forceplates.correctForcePlateType5(acq) acq, zeniState = eventDetector.zeni(acq) if zeniState: btkTools.smartWriter( acq, str(DATA_PATH + reconstructFilenameLabelled)) cmd = "Mokka.exe \"%s\"" % (str(DATA_PATH + reconstructFilenameLabelled)) os.system(cmd) # --------------------------GLOBAL SETTINGS ------------------------------------ # global setting ( in user/AppData) if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_2-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH, "CGM2_2-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER, "CGM2_2-pyCGM2.settings") # --------------------------MP ------------------------------------ required_mp, optional_mp = qtmTools.SubjectMp(sessionXML) # --Check MP inspectprocedure = inspectProcedures.AnthropometricDataQualityProcedure( required_mp) inspector = inspectFilters.QualityFilter(inspectprocedure) inspector.run() # translators management translators = files.getTranslators(os.getcwd() + "\\", "CGM2_2.translators") if not translators: translators = settings["Translators"] # ikweight ikWeight = files.getIKweightSet(DATA_PATH, "CGM2_2.ikw") if not ikWeight: ikWeight = settings["Fitting"]["Weight"] # --------------------------MODEL CALIBRATION ----------------------- logging.info( "--------------------------MODEL CALIBRATION -----------------------") staticMeasurement = utils.find_static(sessionXML) calibrateFilenameLabelled = qtmTools.getFilename(staticMeasurement) logging.info("----- CALIBRATION- static file [%s]--" % (calibrateFilenameLabelled)) leftFlatFoot = toBool( staticMeasurement.Left_foot_normalised_to_static_trial.text) rightFlatFoot = toBool( staticMeasurement.Right_foot_normalised_to_static_trial.text) headFlat = toBool(staticMeasurement.Head_normalised_to_static_trial.text) markerDiameter = float(staticMeasurement.Marker_diameter.text) * 1000.0 hjcMethod = settings["Calibration"]["HJC"] pointSuffix = None # Calibration checking # -------------------- acqStatic = btkTools.smartReader(DATA_PATH + calibrateFilenameLabelled) for key in MARKERSETS.keys(): logging.info("[pyCGM2] Checking of the %s" % (key)) # presence ip_presence = inspectProcedures.MarkerPresenceQualityProcedure( acqStatic, markers=MARKERSETS[key]) inspector = inspectFilters.QualityFilter(ip_presence) inspector.run() if ip_presence.markersIn != []: ip_gap = inspectProcedures.GapQualityProcedure( acqStatic, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_gap) inspector.run() ip_swap = inspectProcedures.SwappingMarkerQualityProcedure( acqStatic, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_swap) inspector.run() ip_pos = inspectProcedures.MarkerPositionQualityProcedure( acqStatic, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_pos) # Calibration operation # -------------------- logging.info("[pyCGM2] --- calibration operation ---") model, acqStatic = cgm2_2.calibrate(DATA_PATH, calibrateFilenameLabelled, translators, settings, required_mp, optional_mp, False, leftFlatFoot, rightFlatFoot, headFlat, markerDiameter, hjcMethod, pointSuffix) logging.info("----- CALIBRATION- static file [%s]-----> DONE" % (calibrateFilenameLabelled)) # --------------------------MODEL FITTING ---------------------------------- logging.info( "--------------------------MODEL FITTING ----------------------------------" ) dynamicMeasurements = qtmTools.findDynamic(sessionXML) modelledC3ds = list() eventInspectorStates = list() for dynamicMeasurement in dynamicMeasurements: reconstructFilenameLabelled = qtmTools.getFilename(dynamicMeasurement) logging.info("----Processing of [%s]-----" % (reconstructFilenameLabelled)) mfpa = qtmTools.getForcePlateAssigment(dynamicMeasurement) momentProjection_text = dynamicMeasurement.Moment_Projection.text if momentProjection_text == "Default": momentProjection_text = settings["Fitting"]["Moment Projection"] if momentProjection_text == "Distal": momentProjection = enums.MomentProjection.Distal elif momentProjection_text == "Proximal": momentProjection = enums.MomentProjection.Proximal elif momentProjection_text == "Global": momentProjection = enums.MomentProjection.Global elif momentProjection_text == "JCS": momentProjection = enums.MomentProjection.JCS acq = btkTools.smartReader(DATA_PATH + reconstructFilenameLabelled) # Fitting checking # -------------------- for key in MARKERSETS.keys(): if key != "Calibration markers": logging.info("[pyCGM2] Checking of the %s" % (key)) # presence ip_presence = inspectProcedures.MarkerPresenceQualityProcedure( acq, markers=MARKERSETS[key]) inspector = inspectFilters.QualityFilter(ip_presence) inspector.run() if ip_presence.markersIn != []: ip_gap = inspectProcedures.GapQualityProcedure( acq, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_gap) inspector.run() ip_swap = inspectProcedures.SwappingMarkerQualityProcedure( acq, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_swap) inspector.run() ip_pos = inspectProcedures.MarkerPositionQualityProcedure( acq, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_pos) # filtering # ----------------------- # marker order = int(float(dynamicMeasurement.Marker_lowpass_filter_order.text)) fc = float(dynamicMeasurement.Marker_lowpass_filter_frequency.text) signal_processing.markerFiltering(acq, order=order, fc=fc) # management of force plate type 5 and force plate filtering order = int( float(dynamicMeasurement.Forceplate_lowpass_filter_order.text)) fc = float(dynamicMeasurement.Forceplate_lowpass_filter_frequency.text) if order != 0 and fc != 0: acq = btkTools.smartReader(DATA_PATH + reconstructFilenameLabelled) if btkTools.checkForcePlateExist(acq): if "5" in btkTools.smartGetMetadata(acq, "FORCE_PLATFORM", "TYPE"): forceplates.correctForcePlateType5(acq) signal_processing.markerFiltering(acq, order=order, fc=fc) else: if btkTools.checkForcePlateExist(acq): if "5" in btkTools.smartGetMetadata(acq, "FORCE_PLATFORM", "TYPE"): forceplates.correctForcePlateType5(acq) btkTools.smartWriter(acq, DATA_PATH + reconstructFilenameLabelled) # event checking # ----------------------- inspectprocedureEvents = inspectProcedures.GaitEventQualityProcedure( acq) inspector = inspectFilters.QualityFilter(inspectprocedureEvents) inspector.run() eventInspectorStates.append(inspectprocedureEvents.state) # fitting operation # ----------------------- logging.info("[pyCGM2] --- Fitting operation ---") acqGait = cgm2_2.fitting(model, DATA_PATH, reconstructFilenameLabelled, translators, settings, markerDiameter, pointSuffix, mfpa, momentProjection) outFilename = reconstructFilenameLabelled # [:-4] + "_CGM1.c3d" btkTools.smartWriter(acqGait, str(DATA_PATH + outFilename)) modelledC3ds.append(outFilename) logging.info("----Processing of [%s]-----> DONE" % (reconstructFilenameLabelled)) # --------------------------GAIT PROCESSING ----------------------- if not all(eventInspectorStates): raise Exception( "[pyCGM2] Impossible to run Gait processing. Badly gait event detection. check the log file" ) logging.info( "---------------------GAIT PROCESSING -----------------------") return model
def fitting(model,DATA_PATH, reconstructFilenameLabelled, translators,weights, ik_flag,markerDiameter, pointSuffix, mfpa, momentProjection,**kwargs): """ Fitting of the CGM2.3 :param model [str]: pyCGM2 model previously calibrated :param DATA_PATH [str]: path to your data :param reconstructFilenameLabelled [string list]: c3d files :param translators [dict]: translators to apply :param ik_flag [bool]: enable the inverse kinematic solver :param mfpa [str]: manual force plate assignement :param markerDiameter [double]: marker diameter (mm) :param pointSuffix [str]: suffix to add to model outputs :param momentProjection [str]: Coordinate system in which joint moment is expressed """ if "Fitting" in weights.keys(): weights = weights["Fitting"]["Weight"] # --------------------------ACQ WITH TRANSLATORS -------------------------------------- # --- btk acquisition ---- if "forceBtkAcq" in kwargs.keys(): acqGait = kwargs["forceBtkAcq"] else: acqGait = btkTools.smartReader((DATA_PATH + reconstructFilenameLabelled)) btkTools.checkMultipleSubject(acqGait) if btkTools.isPointExist(acqGait,"SACR"): translators["LPSI"] = "SACR" translators["RPSI"] = "SACR" logging.info("[pyCGM2] Sacrum marker detected") acqGait = btkTools.applyTranslators(acqGait,translators) trackingMarkers = model.getTrackingMarkers(acqGait) validFrames,vff,vlf = btkTools.findValidFrames(acqGait,trackingMarkers) # filtering # ----------------------- if "fc_lowPass_marker" in kwargs.keys() and kwargs["fc_lowPass_marker"]!=0 : fc = kwargs["fc_lowPass_marker"] order = 4 if "order_lowPass_marker" in kwargs.keys(): order = kwargs["order_lowPass_marker"] signal_processing.markerFiltering(acqGait,trackingMarkers,order=order, fc =fc) if "fc_lowPass_forcePlate" in kwargs.keys() and kwargs["fc_lowPass_forcePlate"]!=0 : fc = kwargs["fc_lowPass_forcePlate"] order = 4 if "order_lowPass_forcePlate" in kwargs.keys(): order = kwargs["order_lowPass_forcePlate"] signal_processing.forcePlateFiltering(acqGait,order=order, fc =fc) # --- initial motion Filter --- scp=modelFilters.StaticCalibrationProcedure(model) # section to remove : - copy motion of ProximalShank from Shank with Sodervisk modMotion=modelFilters.ModelMotionFilter(scp,acqGait,model,enums.motionMethod.Sodervisk) modMotion.compute() # /section to remove if model.getBodyPart() == enums.BodyPart.UpperLimb: ik_flag = False logging.warning("[pyCGM2] Fitting only applied for the upper limb") if ik_flag: # ---OPENSIM IK--- # --- opensim calibration Filter --- osimfile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + "models\\osim\\lowerLimb_ballsJoints.osim" # osimfile markersetFile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + "models\\settings\\cgm2_3\\cgm2_3-markerset.xml" # markerset cgmCalibrationprocedure = opensimFilters.CgmOpensimCalibrationProcedures(model) # procedure oscf = opensimFilters.opensimCalibrationFilter(osimfile, model, cgmCalibrationprocedure, (DATA_PATH)) oscf.addMarkerSet(markersetFile) scalingOsim = oscf.build() # --- opensim Fitting Filter --- iksetupFile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + "models\\settings\\cgm2_3\\cgm2_3-ikSetUp_template.xml" # ik tl file cgmFittingProcedure = opensimFilters.CgmOpensimFittingProcedure(model) # procedure cgmFittingProcedure.updateMarkerWeight("LASI",weights["LASI"]) cgmFittingProcedure.updateMarkerWeight("RASI",weights["RASI"]) cgmFittingProcedure.updateMarkerWeight("LPSI",weights["LPSI"]) cgmFittingProcedure.updateMarkerWeight("RPSI",weights["RPSI"]) cgmFittingProcedure.updateMarkerWeight("RTHI",weights["RTHI"]) cgmFittingProcedure.updateMarkerWeight("RKNE",weights["RKNE"]) cgmFittingProcedure.updateMarkerWeight("RTIB",weights["RTIB"]) cgmFittingProcedure.updateMarkerWeight("RANK",weights["RANK"]) cgmFittingProcedure.updateMarkerWeight("RHEE",weights["RHEE"]) cgmFittingProcedure.updateMarkerWeight("RTOE",weights["RTOE"]) cgmFittingProcedure.updateMarkerWeight("LTHI",weights["LTHI"]) cgmFittingProcedure.updateMarkerWeight("LKNE",weights["LKNE"]) cgmFittingProcedure.updateMarkerWeight("LTIB",weights["LTIB"]) cgmFittingProcedure.updateMarkerWeight("LANK",weights["LANK"]) cgmFittingProcedure.updateMarkerWeight("LHEE",weights["LHEE"]) cgmFittingProcedure.updateMarkerWeight("LTOE",weights["LTOE"]) cgmFittingProcedure.updateMarkerWeight("LTHAP",weights["LTHAP"]) cgmFittingProcedure.updateMarkerWeight("LTHAD",weights["LTHAD"]) cgmFittingProcedure.updateMarkerWeight("LTIAP",weights["LTIAP"]) cgmFittingProcedure.updateMarkerWeight("LTIAD",weights["LTIAD"]) cgmFittingProcedure.updateMarkerWeight("RTHAP",weights["RTHAP"]) cgmFittingProcedure.updateMarkerWeight("RTHAD",weights["RTHAD"]) cgmFittingProcedure.updateMarkerWeight("RTIAP",weights["RTIAP"]) cgmFittingProcedure.updateMarkerWeight("RTIAD",weights["RTIAD"]) osrf = opensimFilters.opensimFittingFilter(iksetupFile, scalingOsim, cgmFittingProcedure, (DATA_PATH) ) logging.info("-------INVERSE KINEMATICS IN PROGRESS----------") acqIK = osrf.run(acqGait,(DATA_PATH + reconstructFilenameLabelled )) logging.info("-------INVERSE KINEMATICS DONE-----------------") # eventual gait acquisition to consider for joint kinematics finalAcqGait = acqIK if ik_flag else acqGait # --- final pyCGM2 model motion Filter --- # use fitted markers modMotionFitted=modelFilters.ModelMotionFilter(scp,finalAcqGait,model,enums.motionMethod.Sodervisk , markerDiameter=markerDiameter) modMotionFitted.compute() if "displayCoordinateSystem" in kwargs.keys() and kwargs["displayCoordinateSystem"]: csp = modelFilters.ModelCoordinateSystemProcedure(model) csdf = modelFilters.CoordinateSystemDisplayFilter(csp,model,finalAcqGait) csdf.setStatic(False) csdf.display() #---- Joint kinematics---- # relative angles modelFilters.ModelJCSFilter(model,finalAcqGait).compute(description="vectoriel", pointLabelSuffix=pointSuffix) # detection of traveling axis + absolute angle if model.m_bodypart != enums.BodyPart.UpperLimb: pfp = progressionFrame.PelvisProgressionFrameProcedure() else: pfp = progressionFrame.ThoraxProgressionFrameProcedure() pff = progressionFrame.ProgressionFrameFilter(finalAcqGait,pfp) pff.compute() globalFrame = pff.outputs["globalFrame"] forwardProgression = pff.outputs["forwardProgression"] if model.m_bodypart != enums.BodyPart.UpperLimb: modelFilters.ModelAbsoluteAnglesFilter(model,finalAcqGait, segmentLabels=["Left Foot","Right Foot","Pelvis"], angleLabels=["LFootProgress", "RFootProgress","Pelvis"], eulerSequences=["TOR","TOR", "ROT"], globalFrameOrientation = globalFrame, forwardProgression = forwardProgression).compute(pointLabelSuffix=pointSuffix) if model.m_bodypart == enums.BodyPart.LowerLimbTrunk: modelFilters.ModelAbsoluteAnglesFilter(model,finalAcqGait, segmentLabels=["Thorax"], angleLabels=["Thorax"], eulerSequences=["YXZ"], globalFrameOrientation = globalFrame, forwardProgression = forwardProgression).compute(pointLabelSuffix=pointSuffix) if model.m_bodypart == enums.BodyPart.UpperLimb or model.m_bodypart == enums.BodyPart.FullBody: modelFilters.ModelAbsoluteAnglesFilter(model,finalAcqGait, segmentLabels=["Thorax","Head"], angleLabels=["Thorax", "Head"], eulerSequences=["YXZ","TOR"], globalFrameOrientation = globalFrame, forwardProgression = forwardProgression).compute(pointLabelSuffix=pointSuffix) #---- Body segment parameters---- bspModel = bodySegmentParameters.Bsp(model) bspModel.compute() if model.m_bodypart == enums.BodyPart.FullBody: modelFilters.CentreOfMassFilter(model,finalAcqGait).compute(pointLabelSuffix=pointSuffix) # Inverse dynamics if btkTools.checkForcePlateExist(acqGait): if model.m_bodypart != enums.BodyPart.UpperLimb: # --- force plate handling---- # find foot in contact mappedForcePlate = forceplates.matchingFootSideOnForceplate(finalAcqGait,mfpa=mfpa) forceplates.addForcePlateGeneralEvents(finalAcqGait,mappedForcePlate) logging.warning("Manual Force plate assignment : %s" %mappedForcePlate) # assembly foot and force plate modelFilters.ForcePlateAssemblyFilter(model,finalAcqGait,mappedForcePlate, leftSegmentLabel="Left Foot", rightSegmentLabel="Right Foot").compute(pointLabelSuffix=pointSuffix) #---- Joint kinetics---- idp = modelFilters.CGMLowerlimbInverseDynamicProcedure() modelFilters.InverseDynamicFilter(model, finalAcqGait, procedure = idp, projection = momentProjection, globalFrameOrientation = globalFrame, forwardProgression = forwardProgression ).compute(pointLabelSuffix=pointSuffix) #---- Joint energetics---- modelFilters.JointPowerFilter(model,finalAcqGait).compute(pointLabelSuffix=pointSuffix) #---- zero unvalid frames --- btkTools.applyValidFramesOnOutput(finalAcqGait,validFrames) return finalAcqGait
def fitting(model, DATA_PATH, reconstructFilenameLabelled, translators, markerDiameter, pointSuffix, mfpa, momentProjection, **kwargs): """ Fitting of the CGM1.1 :param model [str]: pyCGM2 model previously calibrated :param DATA_PATH [str]: path to your data :param reconstructFilenameLabelled [string list]: c3d files :param translators [dict]: translators to apply :param mfpa [str]: manual force plate assignement :param markerDiameter [double]: marker diameter (mm) :param pointSuffix [str]: suffix to add to model outputs :param momentProjection [str]: Coordinate system in which joint moment is expressed """ # --------------------------ACQUISITION ------------------------------------ # --- btk acquisition ---- if "forceBtkAcq" in kwargs.keys(): acqGait = kwargs["forceBtkAcq"] else: acqGait = btkTools.smartReader( (DATA_PATH + reconstructFilenameLabelled)) btkTools.checkMultipleSubject(acqGait) if btkTools.isPointExist(acqGait, "SACR"): translators["LPSI"] = "SACR" translators["RPSI"] = "SACR" logging.info("[pyCGM2] Sacrum marker detected") acqGait = btkTools.applyTranslators(acqGait, translators) trackingMarkers = model.getTrackingMarkers(acqGait) validFrames, vff, vlf = btkTools.findValidFrames(acqGait, trackingMarkers) # filtering # ----------------------- if "fc_lowPass_marker" in kwargs.keys( ) and kwargs["fc_lowPass_marker"] != 0: fc = kwargs["fc_lowPass_marker"] order = 4 if "order_lowPass_marker" in kwargs.keys(): order = kwargs["order_lowPass_marker"] signal_processing.markerFiltering(acqGait, trackingMarkers, order=order, fc=fc) if "fc_lowPass_forcePlate" in kwargs.keys( ) and kwargs["fc_lowPass_forcePlate"] != 0: fc = kwargs["fc_lowPass_forcePlate"] order = 4 if "order_lowPass_forcePlate" in kwargs.keys(): order = kwargs["order_lowPass_forcePlate"] signal_processing.forcePlateFiltering(acqGait, order=order, fc=fc) scp = modelFilters.StaticCalibrationProcedure(model) # procedure # ---Motion filter---- modMotion = modelFilters.ModelMotionFilter(scp, acqGait, model, enums.motionMethod.Determinist, markerDiameter=markerDiameter) modMotion.compute() if "displayCoordinateSystem" in kwargs.keys( ) and kwargs["displayCoordinateSystem"]: csp = modelFilters.ModelCoordinateSystemProcedure(model) csdf = modelFilters.CoordinateSystemDisplayFilter(csp, model, acqGait) csdf.setStatic(False) csdf.display() if "NaimKneeCorrection" in kwargs.keys() and kwargs["NaimKneeCorrection"]: # Apply Naim 2019 method if type(kwargs["NaimKneeCorrection"]) is float: nmacp = modelFilters.Naim2019ThighMisaligmentCorrectionProcedure( model, "Both", threshold=(kwargs["NaimKneeCorrection"])) else: nmacp = modelFilters.Naim2019ThighMisaligmentCorrectionProcedure( model, "Both") mmcf = modelFilters.ModelMotionCorrectionFilter(nmacp) mmcf.correct() # btkTools.smartAppendPoint(acqGait,"LNaim",mmcf.m_procedure.m_virtual["Left"]) # btkTools.smartAppendPoint(acqGait,"RNaim",mmcf.m_procedure.m_virtual["Right"]) #---- Joint kinematics---- # relative angles modelFilters.ModelJCSFilter(model, acqGait).compute(description="vectoriel", pointLabelSuffix=pointSuffix) # detection of traveling axis + absolute angle if model.m_bodypart != enums.BodyPart.UpperLimb: pfp = progressionFrame.PelvisProgressionFrameProcedure() else: pfp = progressionFrame.ThoraxProgressionFrameProcedure() pff = progressionFrame.ProgressionFrameFilter(acqGait, pfp) pff.compute() globalFrame = pff.outputs["globalFrame"] forwardProgression = pff.outputs["forwardProgression"] if model.m_bodypart != enums.BodyPart.UpperLimb: modelFilters.ModelAbsoluteAnglesFilter( model, acqGait, segmentLabels=["Left Foot", "Right Foot", "Pelvis"], angleLabels=["LFootProgress", "RFootProgress", "Pelvis"], eulerSequences=["TOR", "TOR", "ROT"], globalFrameOrientation=globalFrame, forwardProgression=forwardProgression).compute( pointLabelSuffix=pointSuffix) if model.m_bodypart == enums.BodyPart.LowerLimbTrunk: modelFilters.ModelAbsoluteAnglesFilter( model, acqGait, segmentLabels=["Thorax"], angleLabels=["Thorax"], eulerSequences=["YXZ"], globalFrameOrientation=globalFrame, forwardProgression=forwardProgression).compute( pointLabelSuffix=pointSuffix) if model.m_bodypart == enums.BodyPart.UpperLimb or model.m_bodypart == enums.BodyPart.FullBody: modelFilters.ModelAbsoluteAnglesFilter( model, acqGait, segmentLabels=["Thorax", "Head"], angleLabels=["Thorax", "Head"], eulerSequences=["YXZ", "TOR"], globalFrameOrientation=globalFrame, forwardProgression=forwardProgression).compute( pointLabelSuffix=pointSuffix) #---- Body segment parameters---- bspModel = bodySegmentParameters.Bsp(model) bspModel.compute() if model.m_bodypart == enums.BodyPart.FullBody: modelFilters.CentreOfMassFilter( model, acqGait).compute(pointLabelSuffix=pointSuffix) # Inverse dynamics if btkTools.checkForcePlateExist(acqGait): if model.m_bodypart != enums.BodyPart.UpperLimb: # --- force plate handling---- # find foot in contact mappedForcePlate = forceplates.matchingFootSideOnForceplate( acqGait, mfpa=mfpa) forceplates.addForcePlateGeneralEvents(acqGait, mappedForcePlate) logging.warning("Manual Force plate assignment : %s" % mappedForcePlate) # assembly foot and force plate modelFilters.ForcePlateAssemblyFilter( model, acqGait, mappedForcePlate, leftSegmentLabel="Left Foot", rightSegmentLabel="Right Foot").compute( pointLabelSuffix=pointSuffix) #---- Joint kinetics---- idp = modelFilters.CGMLowerlimbInverseDynamicProcedure() modelFilters.InverseDynamicFilter( model, acqGait, procedure=idp, projection=momentProjection, globalFrameOrientation=globalFrame, forwardProgression=forwardProgression).compute( pointLabelSuffix=pointSuffix) #---- Joint energetics---- modelFilters.JointPowerFilter( model, acqGait).compute(pointLabelSuffix=pointSuffix) #---- zero unvalid frames --- btkTools.applyValidFramesOnOutput(acqGait, validFrames) return acqGait
def main(): logging.info("------------------------------------------------") logging.info("------------QTM - pyCGM2 Workflow---------------") logging.info("------------------------------------------------") file = "session.xml" sessionXML = files.readXml(os.getcwd() + "\\", file) sessionDate = files.getFileCreationDate(os.getcwd() + "\\" + file) #--------------------------------------------------------------------------- #management of the Processed folder DATA_PATH = os.getcwd() + "\\" + "processed\\" files.createDir(DATA_PATH) staticMeasurement = qtmTools.findStatic(sessionXML) calibrateFilenameLabelled = qtmTools.getFilename(staticMeasurement) if not os.path.isfile(DATA_PATH + calibrateFilenameLabelled): shutil.copyfile(os.getcwd() + "\\" + calibrateFilenameLabelled, DATA_PATH + calibrateFilenameLabelled) logging.info( "qualisys exported c3d file [%s] copied to processed folder" % (calibrateFilenameLabelled)) dynamicMeasurements = qtmTools.findDynamic(sessionXML) for dynamicMeasurement in dynamicMeasurements: reconstructFilenameLabelled = qtmTools.getFilename(dynamicMeasurement) if not os.path.isfile(DATA_PATH + reconstructFilenameLabelled): shutil.copyfile(os.getcwd() + "\\" + reconstructFilenameLabelled, DATA_PATH + reconstructFilenameLabelled) logging.info( "qualisys exported c3d file [%s] copied to processed folder" % (reconstructFilenameLabelled)) acq = btkTools.smartReader( str(DATA_PATH + reconstructFilenameLabelled)) if btkTools.checkForcePlateExist(acq): if "5" in btkTools.smartGetMetadata(acq, "FORCE_PLATFORM", "TYPE"): forceplates.correctForcePlateType5(acq) acq, zeniState = eventDetector.zeni(acq) if zeniState: btkTools.smartWriter( acq, str(DATA_PATH + reconstructFilenameLabelled)) cmd = "Mokka.exe \"%s\"" % (str(DATA_PATH + reconstructFilenameLabelled)) os.system(cmd) # --------------------------GLOBAL SETTINGS ------------------------------------ # global setting ( in user/AppData) if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_2-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH, "CGM2_2-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER, "CGM2_2-pyCGM2.settings") # --------------------------MP ------------------------------------ required_mp, optional_mp = qtmTools.SubjectMp(sessionXML) # --Check MP inspectprocedure = inspectProcedures.AnthropometricDataQualityProcedure( required_mp) inspector = inspectFilters.QualityFilter(inspectprocedure) inspector.run() # translators management translators = files.getTranslators(os.getcwd() + "\\", "CGM2_2.translators") if not translators: translators = settings["Translators"] # ikweight ikWeight = files.getIKweightSet(DATA_PATH, "CGM2_2.ikw") if not ikWeight: ikWeight = settings["Fitting"]["Weight"] # --------------------------MODEL CALIBRATION ----------------------- logging.info( "--------------------------MODEL CALIBRATION -----------------------") staticMeasurement = qtmTools.findStatic(sessionXML) calibrateFilenameLabelled = qtmTools.getFilename(staticMeasurement) logging.info("----- CALIBRATION- static file [%s]--" % (calibrateFilenameLabelled)) leftFlatFoot = toBool( staticMeasurement.Left_foot_normalised_to_static_trial.text) rightFlatFoot = toBool( staticMeasurement.Right_foot_normalised_to_static_trial.text) headFlat = toBool(staticMeasurement.Head_normalised_to_static_trial.text) markerDiameter = float(staticMeasurement.Marker_diameter.text) * 1000.0 hjcMethod = settings["Calibration"]["HJC"] pointSuffix = None # Calibration checking # -------------------- acqStatic = btkTools.smartReader(DATA_PATH + calibrateFilenameLabelled) for key in MARKERSETS.keys(): logging.info("[pyCGM2] Checking of the %s" % (key)) # presence ip_presence = inspectProcedures.MarkerPresenceQualityProcedure( acqStatic, markers=MARKERSETS[key]) inspector = inspectFilters.QualityFilter(ip_presence) inspector.run() if ip_presence.markersIn != []: ip_gap = inspectProcedures.GapQualityProcedure( acqStatic, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_gap) inspector.run() ip_swap = inspectProcedures.SwappingMarkerQualityProcedure( acqStatic, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_swap) inspector.run() ip_pos = inspectProcedures.MarkerPositionQualityProcedure( acqStatic, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_pos) # Calibration operation # -------------------- logging.info("[pyCGM2] --- calibration operation ---") model, acqStatic = cgm2_2.calibrate(DATA_PATH, calibrateFilenameLabelled, translators, settings, required_mp, optional_mp, False, leftFlatFoot, rightFlatFoot, headFlat, markerDiameter, hjcMethod, pointSuffix) logging.info("----- CALIBRATION- static file [%s]-----> DONE" % (calibrateFilenameLabelled)) # --------------------------MODEL FITTING ---------------------------------- logging.info( "--------------------------MODEL FITTING ----------------------------------" ) dynamicMeasurements = qtmTools.findDynamic(sessionXML) modelledC3ds = list() eventInspectorStates = list() for dynamicMeasurement in dynamicMeasurements: reconstructFilenameLabelled = qtmTools.getFilename(dynamicMeasurement) logging.info("----Processing of [%s]-----" % (reconstructFilenameLabelled)) mfpa = qtmTools.getForcePlateAssigment(dynamicMeasurement) momentProjection_text = dynamicMeasurement.Moment_Projection.text if momentProjection_text == "Default": momentProjection_text = settings["Fitting"]["Moment Projection"] if momentProjection_text == "Distal": momentProjection = enums.MomentProjection.Distal elif momentProjection_text == "Proximal": momentProjection = enums.MomentProjection.Proximal elif momentProjection_text == "Global": momentProjection = enums.MomentProjection.Global elif momentProjection_text == "JCS": momentProjection = enums.MomentProjection.JCS acq = btkTools.smartReader(DATA_PATH + reconstructFilenameLabelled) # Fitting checking # -------------------- for key in MARKERSETS.keys(): if key != "Calibration markers": logging.info("[pyCGM2] Checking of the %s" % (key)) # presence ip_presence = inspectProcedures.MarkerPresenceQualityProcedure( acq, markers=MARKERSETS[key]) inspector = inspectFilters.QualityFilter(ip_presence) inspector.run() if ip_presence.markersIn != []: ip_gap = inspectProcedures.GapQualityProcedure( acq, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_gap) inspector.run() ip_swap = inspectProcedures.SwappingMarkerQualityProcedure( acq, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_swap) inspector.run() ip_pos = inspectProcedures.MarkerPositionQualityProcedure( acq, markers=ip_presence.markersIn) inspector = inspectFilters.QualityFilter(ip_pos) # filtering # ----------------------- # marker order = int(float(dynamicMeasurement.Marker_lowpass_filter_order.text)) fc = float(dynamicMeasurement.Marker_lowpass_filter_frequency.text) signal_processing.markerFiltering(acq, order=order, fc=fc) # management of force plate type 5 and force plate filtering order = int( float(dynamicMeasurement.Forceplate_lowpass_filter_order.text)) fc = float(dynamicMeasurement.Forceplate_lowpass_filter_frequency.text) if order != 0 and fc != 0: acq = btkTools.smartReader(DATA_PATH + reconstructFilenameLabelled) if btkTools.checkForcePlateExist(acq): if "5" in btkTools.smartGetMetadata(acq, "FORCE_PLATFORM", "TYPE"): forceplates.correctForcePlateType5(acq) signal_processing.markerFiltering(acq, order=order, fc=fc) else: if btkTools.checkForcePlateExist(acq): if "5" in btkTools.smartGetMetadata(acq, "FORCE_PLATFORM", "TYPE"): forceplates.correctForcePlateType5(acq) btkTools.smartWriter(acq, DATA_PATH + reconstructFilenameLabelled) # event checking # ----------------------- inspectprocedureEvents = inspectProcedures.GaitEventQualityProcedure( acq) inspector = inspectFilters.QualityFilter(inspectprocedureEvents) inspector.run() eventInspectorStates.append(inspectprocedureEvents.state) # fitting operation # ----------------------- logging.info("[pyCGM2] --- Fitting operation ---") acqGait = cgm2_2.fitting(model, DATA_PATH, reconstructFilenameLabelled, translators, settings, markerDiameter, pointSuffix, mfpa, momentProjection) outFilename = reconstructFilenameLabelled #[:-4] + "_CGM1.c3d" btkTools.smartWriter(acqGait, str(DATA_PATH + outFilename)) modelledC3ds.append(outFilename) logging.info("----Processing of [%s]-----> DONE" % (reconstructFilenameLabelled)) # --------------------------GAIT PROCESSING ----------------------- if not all(eventInspectorStates): raise Exception( "[pyCGM2] Impossible to run Gait processing. Badly gait event detection. check the log file" ) logging.info( "---------------------GAIT PROCESSING -----------------------") nds = normativeDatasets.Schwartz2008("Free") types = qtmTools.detectMeasurementType(sessionXML) for type in types: modelledTrials = list() for dynamicMeasurement in dynamicMeasurements: if qtmTools.isType(dynamicMeasurement, type): filename = qtmTools.getFilename(dynamicMeasurement) modelledTrials.append(filename) #.replace(".c3d","_CGM1.c3d")) subjectMd = { "patientName": sessionXML.find("Last_name").text + " " + sessionXML.find("First_name").text, "bodyHeight": sessionXML.find("Height").text, "bodyWeight": sessionXML.find("Weight").text, "diagnosis": sessionXML.find("Diagnosis").text, "dob": sessionXML.find("Date_of_birth").text, "sex": sessionXML.find("Sex").text, "test condition": type, "gmfcs": sessionXML.find("Gross_Motor_Function_Classification").text, "fms": sessionXML.find("Functional_Mobility_Scale").text } analysisInstance = analysis.makeAnalysis(DATA_PATH, modelledTrials, subjectInfo=None, experimentalInfo=None, modelInfo=None, pointLabelSuffix=None) title = type # spatiotemporal plot.plot_spatioTemporal(DATA_PATH, analysisInstance, exportPdf=True, outputName=title, show=None, title=title) #Kinematics if model.m_bodypart in [ enums.BodyPart.LowerLimb, enums.BodyPart.LowerLimbTrunk, enums.BodyPart.FullBody ]: plot.plot_DescriptiveKinematic(DATA_PATH, analysisInstance, "LowerLimb", nds, exportPdf=True, outputName=title, pointLabelSuffix=pointSuffix, show=False, title=title) plot.plot_ConsistencyKinematic(DATA_PATH, analysisInstance, "LowerLimb", nds, exportPdf=True, outputName=title, pointLabelSuffix=pointSuffix, show=False, title=title) if model.m_bodypart in [ enums.BodyPart.LowerLimbTrunk, enums.BodyPart.FullBody ]: plot.plot_DescriptiveKinematic(DATA_PATH, analysisInstance, "Trunk", nds, exportPdf=True, outputName=title, pointLabelSuffix=pointSuffix, show=False, title=title) plot.plot_ConsistencyKinematic(DATA_PATH, analysisInstance, "Trunk", nds, exportPdf=True, outputName=title, pointLabelSuffix=pointSuffix, show=False, title=title) if model.m_bodypart in [ enums.BodyPart.UpperLimb, enums.BodyPart.FullBody ]: pass # TODO plot upperlimb panel #Kinetics if model.m_bodypart in [ enums.BodyPart.LowerLimb, enums.BodyPart.LowerLimbTrunk, enums.BodyPart.FullBody ]: plot.plot_DescriptiveKinetic(DATA_PATH, analysisInstance, "LowerLimb", nds, exportPdf=True, outputName=title, pointLabelSuffix=pointSuffix, show=False, title=title) plot.plot_ConsistencyKinetic(DATA_PATH, analysisInstance, "LowerLimb", nds, exportPdf=True, outputName=title, pointLabelSuffix=pointSuffix, show=False, title=title) #MAP plot.plot_MAP(DATA_PATH, analysisInstance, nds, exportPdf=True, outputName=title, pointLabelSuffix=pointSuffix, show=False, title=title) plt.show(False) logging.info("----- Gait Processing -----> DONE")
def fitting(model,DATA_PATH, reconstructFilenameLabelled, translators, markerDiameter, pointSuffix, mfpa, momentProjection,**kwargs): """ Fitting of the CGM2.1 :param model [str]: pyCGM2 model previously calibrated :param DATA_PATH [str]: path to your data :param reconstructFilenameLabelled [string list]: c3d files :param translators [dict]: translators to apply :param mfpa [str]: manual force plate assignement :param markerDiameter [double]: marker diameter (mm) :param pointSuffix [str]: suffix to add to model outputs :param momentProjection [str]: Coordinate system in which joint moment is expressed """ detectAnomaly = False if "anomalyException" in kwargs.keys(): anomalyException = kwargs["anomalyException"] else: anomalyException=False # --------------------------ACQUISITION ------------------------------------ # --- btk acquisition ---- if "forceBtkAcq" in kwargs.keys(): acqGait = kwargs["forceBtkAcq"] else: acqGait = btkTools.smartReader((DATA_PATH + reconstructFilenameLabelled)) btkTools.checkMultipleSubject(acqGait) if btkTools.isPointExist(acqGait,"SACR"): translators["LPSI"] = "SACR" translators["RPSI"] = "SACR" LOGGER.logger.info("[pyCGM2] Sacrum marker detected") acqGait = btkTools.applyTranslators(acqGait,translators) trackingMarkers = cgm.CGM1.LOWERLIMB_TRACKING_MARKERS + cgm.CGM1.THORAX_TRACKING_MARKERS+ cgm.CGM1.UPPERLIMB_TRACKING_MARKERS actual_trackingMarkers,phatoms_trackingMarkers = btkTools.createPhantoms(acqGait, trackingMarkers) vff,vlf = btkTools.getFrameBoundaries(acqGait,actual_trackingMarkers) if "frameInit" in kwargs.keys() and kwargs["frameInit"] is not None: vff = kwargs["frameInit"] LOGGER.logger.info("[pyCGM2] first frame forced to frame [%s]"%(vff)) if "frameEnd" in kwargs.keys() and kwargs["frameEnd"] is not None: vlf = kwargs["frameEnd"] LOGGER.logger.info("[pyCGM2] end frame forced to frame [%s]"%(vlf)) flag = btkTools.getValidFrames(acqGait,actual_trackingMarkers,frameBounds=[vff,vlf]) LOGGER.logger.info("[pyCGM2] Computation from frame [%s] to frame [%s]"%(vff,vlf)) # --------------------ANOMALY------------------------------ for marker in actual_trackingMarkers: if marker not in model.getStaticTrackingMarkers(): LOGGER.logger.warning("[pyCGM2-Anomaly] marker [%s] - not used during static calibration - wrong kinematic for the segment attached to this marker. "%(marker)) # --marker presence markersets = [cgm.CGM1.LOWERLIMB_TRACKING_MARKERS, cgm.CGM1.THORAX_TRACKING_MARKERS, cgm.CGM1.UPPERLIMB_TRACKING_MARKERS] for markerset in markersets: ipdp = InspectorProcedure.MarkerPresenceDetectionProcedure( markerset) idf = InspectorFilter.InspectorFilter(acqGait,reconstructFilenameLabelled,ipdp) inspector = idf.run() # --marker outliers if inspector["In"] !=[]: madp = AnomalyDetectionProcedure.MarkerAnomalyDetectionRollingProcedure( inspector["In"], plot=False, window=5,threshold = 3) adf = AnomalyFilter.AnomalyDetectionFilter(acqGait,reconstructFilenameLabelled,madp, frameRange=[vff,vlf]) anomaly = adf.run() anomalyIndexes = anomaly["Output"] if anomaly["ErrorState"]: detectAnomaly = True if btkTools.checkForcePlateExist(acqGait): afpp = AnomalyDetectionProcedure.ForcePlateAnomalyProcedure() adf = AnomalyFilter.AnomalyDetectionFilter(acqGait,reconstructFilenameLabelled,afpp, frameRange=[vff,vlf]) anomaly = adf.run() if anomaly["ErrorState"]: detectAnomaly = True if detectAnomaly and anomalyException: raise Exception ("Anomalies has been detected - Check Warning message of the log file") # --------------------MODELLING------------------------------ # filtering # ----------------------- if "fc_lowPass_marker" in kwargs.keys() and kwargs["fc_lowPass_marker"]!=0 : fc = kwargs["fc_lowPass_marker"] order = 4 if "order_lowPass_marker" in kwargs.keys(): order = kwargs["order_lowPass_marker"] signal_processing.markerFiltering(acqGait,trackingMarkers,order=order, fc =fc) if "fc_lowPass_forcePlate" in kwargs.keys() and kwargs["fc_lowPass_forcePlate"]!=0 : fc = kwargs["fc_lowPass_forcePlate"] order = 4 if "order_lowPass_forcePlate" in kwargs.keys(): order = kwargs["order_lowPass_forcePlate"] signal_processing.forcePlateFiltering(acqGait,order=order, fc =fc) scp=modelFilters.StaticCalibrationProcedure(model) # ---Motion filter---- modMotion=modelFilters.ModelMotionFilter(scp,acqGait,model,enums.motionMethod.Determinist, markerDiameter=markerDiameter) modMotion.compute() progressionFlag = False if btkTools.isPointExist(acqGait, 'LHEE',ignorePhantom=False) or btkTools.isPointExist(acqGait, 'RHEE',ignorePhantom=False): pfp = progressionFrame.PointProgressionFrameProcedure(marker="LHEE") \ if btkTools.isPointExist(acqGait, 'LHEE',ignorePhantom=False) \ else progressionFrame.PointProgressionFrameProcedure(marker="RHEE") pff = progressionFrame.ProgressionFrameFilter(acqGait,pfp) pff.compute() progressionAxis = pff.outputs["progressionAxis"] globalFrame = pff.outputs["globalFrame"] forwardProgression = pff.outputs["forwardProgression"] progressionFlag = True elif btkTools.isPointsExist(acqGait, ['LASI', 'RASI', 'RPSI', 'LPSI'],ignorePhantom=False) and not progressionFlag: LOGGER.logger.info("[pyCGM2] - progression axis detected from Pelvic markers ") pfp = progressionFrame.PelvisProgressionFrameProcedure() pff = progressionFrame.ProgressionFrameFilter(acqGait,pfp) pff.compute() globalFrame = pff.outputs["globalFrame"] forwardProgression = pff.outputs["forwardProgression"] progressionFlag = True elif btkTools.isPointsExist(acqGait, ['C7', 'T10', 'CLAV', 'STRN'],ignorePhantom=False) and not progressionFlag: LOGGER.logger.info("[pyCGM2] - progression axis detected from Thoracic markers ") pfp = progressionFrame.ThoraxProgressionFrameProcedure() pff = progressionFrame.ProgressionFrameFilter(acqGait,pfp) pff.compute() progressionAxis = pff.outputs["progressionAxis"] globalFrame = pff.outputs["globalFrame"] forwardProgression = pff.outputs["forwardProgression"] else: globalFrame = "XYZ" progressionAxis = "X" forwardProgression = True LOGGER.logger.error("[pyCGM2] - impossible to detect progression axis - neither pelvic nor thoracic markers are present. Progression set to +X by default ") if "displayCoordinateSystem" in kwargs.keys() and kwargs["displayCoordinateSystem"]: csp = modelFilters.ModelCoordinateSystemProcedure(model) csdf = modelFilters.CoordinateSystemDisplayFilter(csp,model,acqGait) csdf.setStatic(False) csdf.display() #---- Joint kinematics---- # relative angles modelFilters.ModelJCSFilter(model,acqGait).compute(description="vectoriel", pointLabelSuffix=pointSuffix) modelFilters.ModelAbsoluteAnglesFilter(model,acqGait, segmentLabels=["Left Foot","Right Foot","Pelvis","Thorax","Head"], angleLabels=["LFootProgress", "RFootProgress","Pelvis","Thorax", "Head"], eulerSequences=["TOR","TOR", "ROT","YXZ","TOR"], globalFrameOrientation = globalFrame, forwardProgression = forwardProgression).compute(pointLabelSuffix=pointSuffix) #---- Body segment parameters---- bspModel = bodySegmentParameters.Bsp(model) bspModel.compute() modelFilters.CentreOfMassFilter(model,acqGait).compute(pointLabelSuffix=pointSuffix) # Inverse dynamics if btkTools.checkForcePlateExist(acqGait): if model.m_bodypart != enums.BodyPart.UpperLimb: # --- force plate handling---- # find foot in contact mappedForcePlate = forceplates.matchingFootSideOnForceplate(acqGait,mfpa=mfpa) forceplates.addForcePlateGeneralEvents(acqGait,mappedForcePlate) LOGGER.logger.info("Manual Force plate assignment : %s" %mappedForcePlate) # assembly foot and force plate modelFilters.ForcePlateAssemblyFilter(model,acqGait,mappedForcePlate, leftSegmentLabel="Left Foot", rightSegmentLabel="Right Foot").compute(pointLabelSuffix=pointSuffix) #---- Joint kinetics---- idp = modelFilters.CGMLowerlimbInverseDynamicProcedure() modelFilters.InverseDynamicFilter(model, acqGait, procedure = idp, projection = momentProjection, globalFrameOrientation = globalFrame, forwardProgression = forwardProgression ).compute(pointLabelSuffix=pointSuffix) #---- Joint energetics---- modelFilters.JointPowerFilter(model,acqGait).compute(pointLabelSuffix=pointSuffix) btkTools.cleanAcq(acqGait) btkTools.applyOnValidFrames(acqGait,flag) if detectAnomaly and not anomalyException: LOGGER.logger.error("Anomalies has been detected - Check Warning messages of the log file") return acqGait,detectAnomaly
def fitting(model, DATA_PATH, reconstructFilenameLabelled, translators, weights, ik_flag, markerDiameter, pointSuffix, mfpa, momentProjection, **kwargs): """ Fitting of the CGM2.5 :param model [str]: pyCGM2 model previously calibrated :param DATA_PATH [str]: path to your data :param reconstructFilenameLabelled [string list]: c3d files :param translators [dict]: translators to apply :param ik_flag [bool]: enable the inverse kinematic solver :param mfpa [str]: manual force plate assignement :param markerDiameter [double]: marker diameter (mm) :param pointSuffix [str]: suffix to add to model outputs :param momentProjection [str]: Coordinate system in which joint moment is expressed """ detectAnomaly = False if "anomalyException" in kwargs.keys(): anomalyException = kwargs["anomalyException"] else: anomalyException = False if "forceFoot6DoF" in kwargs.keys() and kwargs["forceFoot6DoF"]: forceFoot6DoF_flag = True else: forceFoot6DoF_flag = False if "Fitting" in weights.keys(): weights = weights["Fitting"]["Weight"] # --- btk acquisition ---- if "forceBtkAcq" in kwargs.keys(): acqGait = kwargs["forceBtkAcq"] else: acqGait = btkTools.smartReader( (DATA_PATH + reconstructFilenameLabelled)) btkTools.checkMultipleSubject(acqGait) if btkTools.isPointExist(acqGait, "SACR"): translators["LPSI"] = "SACR" translators["RPSI"] = "SACR" LOGGER.logger.info("[pyCGM2] Sacrum marker detected") acqGait = btkTools.applyTranslators(acqGait, translators) trackingMarkers = cgm2.CGM2_5.LOWERLIMB_TRACKING_MARKERS + cgm2.CGM2_5.THORAX_TRACKING_MARKERS + cgm2.CGM2_5.UPPERLIMB_TRACKING_MARKERS actual_trackingMarkers, phatoms_trackingMarkers = btkTools.createPhantoms( acqGait, trackingMarkers) vff, vlf = btkTools.getFrameBoundaries(acqGait, actual_trackingMarkers) if "frameInit" in kwargs.keys() and kwargs["frameInit"] is not None: vff = kwargs["frameInit"] LOGGER.logger.info("[pyCGM2] first frame forced to frame [%s]" % (vff)) if "frameEnd" in kwargs.keys() and kwargs["frameEnd"] is not None: vlf = kwargs["frameEnd"] LOGGER.logger.info("[pyCGM2] end frame forced to frame [%s]" % (vlf)) flag = btkTools.getValidFrames(acqGait, actual_trackingMarkers, frameBounds=[vff, vlf]) LOGGER.logger.info("[pyCGM2] Computation from frame [%s] to frame [%s]" % (vff, vlf)) # --------------------ANOMALY------------------------------ for marker in actual_trackingMarkers: if marker not in model.getStaticTrackingMarkers(): LOGGER.logger.warning( "[pyCGM2-Anomaly] marker [%s] - not used during static calibration - wrong kinematic for the segment attached to this marker. " % (marker)) # --marker presence markersets = [ cgm2.CGM2_5.LOWERLIMB_TRACKING_MARKERS, cgm2.CGM2_5.THORAX_TRACKING_MARKERS, cgm2.CGM2_5.UPPERLIMB_TRACKING_MARKERS ] for markerset in markersets: ipdp = InspectorProcedure.MarkerPresenceDetectionProcedure(markerset) idf = InspectorFilter.InspectorFilter(acqGait, reconstructFilenameLabelled, ipdp) inspector = idf.run() # --marker outliers if inspector["In"] != []: madp = AnomalyDetectionProcedure.MarkerAnomalyDetectionRollingProcedure( inspector["In"], plot=False, window=5, threshold=3) adf = AnomalyFilter.AnomalyDetectionFilter( acqGait, reconstructFilenameLabelled, madp, frameRange=[vff, vlf]) anomaly = adf.run() anomalyIndexes = anomaly["Output"] if anomaly["ErrorState"]: detectAnomaly = True if btkTools.checkForcePlateExist(acqGait): afpp = AnomalyDetectionProcedure.ForcePlateAnomalyProcedure() adf = AnomalyFilter.AnomalyDetectionFilter(acqGait, reconstructFilenameLabelled, afpp, frameRange=[vff, vlf]) anomaly = adf.run() if anomaly["ErrorState"]: detectAnomaly = True if detectAnomaly and anomalyException: raise Exception( "Anomalies has been detected - Check Warning message of the log file" ) # --------------------MODELLING------------------------------ # filtering # ----------------------- if "fc_lowPass_marker" in kwargs.keys( ) and kwargs["fc_lowPass_marker"] != 0: fc = kwargs["fc_lowPass_marker"] order = 4 if "order_lowPass_marker" in kwargs.keys(): order = kwargs["order_lowPass_marker"] signal_processing.markerFiltering(acqGait, trackingMarkers, order=order, fc=fc) if "fc_lowPass_forcePlate" in kwargs.keys( ) and kwargs["fc_lowPass_forcePlate"] != 0: fc = kwargs["fc_lowPass_forcePlate"] order = 4 if "order_lowPass_forcePlate" in kwargs.keys(): order = kwargs["order_lowPass_forcePlate"] signal_processing.forcePlateFiltering(acqGait, order=order, fc=fc) # --- initial motion Filter --- scp = modelFilters.StaticCalibrationProcedure(model) modMotion = modelFilters.ModelMotionFilter(scp, acqGait, model, enums.motionMethod.Sodervisk) modMotion.compute() progressionFlag = False if btkTools.isPointExist(acqGait, 'LHEE', ignorePhantom=False) or btkTools.isPointExist( acqGait, 'RHEE', ignorePhantom=False): pfp = progressionFrame.PointProgressionFrameProcedure(marker="LHEE") \ if btkTools.isPointExist(acqGait, 'LHEE',ignorePhantom=False) \ else progressionFrame.PointProgressionFrameProcedure(marker="RHEE") pff = progressionFrame.ProgressionFrameFilter(acqGait, pfp) pff.compute() progressionAxis = pff.outputs["progressionAxis"] globalFrame = pff.outputs["globalFrame"] forwardProgression = pff.outputs["forwardProgression"] progressionFlag = True elif btkTools.isPointsExist(acqGait, ['LASI', 'RASI', 'RPSI', 'LPSI'], ignorePhantom=False) and not progressionFlag: LOGGER.logger.info( "[pyCGM2] - progression axis detected from Pelvic markers ") pfp = progressionFrame.PelvisProgressionFrameProcedure() pff = progressionFrame.ProgressionFrameFilter(acqGait, pfp) pff.compute() globalFrame = pff.outputs["globalFrame"] forwardProgression = pff.outputs["forwardProgression"] progressionFlag = True elif btkTools.isPointsExist(acqGait, ['C7', 'T10', 'CLAV', 'STRN'], ignorePhantom=False) and not progressionFlag: LOGGER.logger.info( "[pyCGM2] - progression axis detected from Thoracic markers ") pfp = progressionFrame.ThoraxProgressionFrameProcedure() pff = progressionFrame.ProgressionFrameFilter(acqGait, pfp) pff.compute() progressionAxis = pff.outputs["progressionAxis"] globalFrame = pff.outputs["globalFrame"] forwardProgression = pff.outputs["forwardProgression"] else: globalFrame = "XYZ" progressionAxis = "X" forwardProgression = True LOGGER.logger.error( "[pyCGM2] - impossible to detect progression axis - neither pelvic nor thoracic markers are present. Progression set to +X by default " ) for target in weights.keys(): if target not in actual_trackingMarkers or target not in model.getStaticIkTargets( ): weights[target] = 0 LOGGER.logger.warning( "[pyCGM2] - the IK targeted marker [%s] is not labelled in the acquisition [%s]" % (target, reconstructFilenameLabelled)) if ik_flag: # ---OPENSIM IK--- # --- opensim calibration Filter --- osimfile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + "models\\osim\\lowerLimb_ballsJoints.osim" # osimfile markersetFile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + "models\\settings\\cgm2_4\\cgm2_4-markerset.xml" # markerset cgmCalibrationprocedure = opensimFilters.CgmOpensimCalibrationProcedures( model) # procedure oscf = opensimFilters.opensimCalibrationFilter( osimfile, model, cgmCalibrationprocedure, DATA_PATH) oscf.addMarkerSet(markersetFile) scalingOsim = oscf.build() # --- opensim Fitting Filter --- iksetupFile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + "models\\settings\\cgm2_4\\cgm2_4-ikSetUp_template.xml" # ik tl file cgmFittingProcedure = opensimFilters.CgmOpensimFittingProcedure( model) # procedure cgmFittingProcedure.updateMarkerWeight("LASI", weights["LASI"]) cgmFittingProcedure.updateMarkerWeight("RASI", weights["RASI"]) cgmFittingProcedure.updateMarkerWeight("LPSI", weights["LPSI"]) cgmFittingProcedure.updateMarkerWeight("RPSI", weights["RPSI"]) cgmFittingProcedure.updateMarkerWeight("RTHI", weights["RTHI"]) cgmFittingProcedure.updateMarkerWeight("RKNE", weights["RKNE"]) cgmFittingProcedure.updateMarkerWeight("RTIB", weights["RTIB"]) cgmFittingProcedure.updateMarkerWeight("RANK", weights["RANK"]) cgmFittingProcedure.updateMarkerWeight("RHEE", weights["RHEE"]) cgmFittingProcedure.updateMarkerWeight("RTOE", weights["RTOE"]) cgmFittingProcedure.updateMarkerWeight("LTHI", weights["LTHI"]) cgmFittingProcedure.updateMarkerWeight("LKNE", weights["LKNE"]) cgmFittingProcedure.updateMarkerWeight("LTIB", weights["LTIB"]) cgmFittingProcedure.updateMarkerWeight("LANK", weights["LANK"]) cgmFittingProcedure.updateMarkerWeight("LHEE", weights["LHEE"]) cgmFittingProcedure.updateMarkerWeight("LTOE", weights["LTOE"]) cgmFittingProcedure.updateMarkerWeight("LTHAP", weights["LTHAP"]) cgmFittingProcedure.updateMarkerWeight("LTHAD", weights["LTHAD"]) cgmFittingProcedure.updateMarkerWeight("LTIAP", weights["LTIAP"]) cgmFittingProcedure.updateMarkerWeight("LTIAD", weights["LTIAD"]) cgmFittingProcedure.updateMarkerWeight("RTHAP", weights["RTHAP"]) cgmFittingProcedure.updateMarkerWeight("RTHAD", weights["RTHAD"]) cgmFittingProcedure.updateMarkerWeight("RTIAP", weights["RTIAP"]) cgmFittingProcedure.updateMarkerWeight("RTIAD", weights["RTIAD"]) cgmFittingProcedure.updateMarkerWeight("LSMH", weights["LSMH"]) cgmFittingProcedure.updateMarkerWeight("LFMH", weights["LFMH"]) cgmFittingProcedure.updateMarkerWeight("LVMH", weights["LVMH"]) cgmFittingProcedure.updateMarkerWeight("RSMH", weights["RSMH"]) cgmFittingProcedure.updateMarkerWeight("RFMH", weights["RFMH"]) cgmFittingProcedure.updateMarkerWeight("RVMH", weights["RVMH"]) # cgmFittingProcedure.updateMarkerWeight("LTHL",weights["LTHL"]) # cgmFittingProcedure.updateMarkerWeight("LTHLD",weights["LTHLD"]) # cgmFittingProcedure.updateMarkerWeight("LPAT",weights["LPAT"]) # cgmFittingProcedure.updateMarkerWeight("LTIBL",weights["LTIBL"]) # cgmFittingProcedure.updateMarkerWeight("RTHL",weights["RTHL"]) # cgmFittingProcedure.updateMarkerWeight("RTHLD",weights["RTHLD"]) # cgmFittingProcedure.updateMarkerWeight("RPAT",weights["RPAT"]) # cgmFittingProcedure.updateMarkerWeight("RTIBL",weights["RTIBL"]) osrf = opensimFilters.opensimFittingFilter(iksetupFile, scalingOsim, cgmFittingProcedure, DATA_PATH, acqGait) osrf.setTimeRange(acqGait, beginFrame=vff, lastFrame=vlf) if "ikAccuracy" in kwargs.keys(): osrf.setAccuracy(kwargs["ikAccuracy"]) LOGGER.logger.info("-------INVERSE KINEMATICS IN PROGRESS----------") try: acqIK = osrf.run(DATA_PATH + reconstructFilenameLabelled, progressionAxis=progressionAxis, forwardProgression=forwardProgression) LOGGER.logger.info("[pyCGM2] - IK solver complete") except: LOGGER.logger.error("[pyCGM2] - IK solver fails") acqIK = acqGait detectAnomaly = True LOGGER.logger.info( "---------------------------------------------------") # eventual gait acquisition to consider for joint kinematics finalAcqGait = acqIK if ik_flag else acqGait if "displayCoordinateSystem" in kwargs.keys( ) and kwargs["displayCoordinateSystem"]: csp = modelFilters.ModelCoordinateSystemProcedure(model) csdf = modelFilters.CoordinateSystemDisplayFilter( csp, model, finalAcqGait) csdf.setStatic(False) csdf.display() # --- final pyCGM2 model motion Filter --- # use fitted markers modMotionFitted = modelFilters.ModelMotionFilter( scp, finalAcqGait, model, enums.motionMethod.Sodervisk, markerDiameter=markerDiameter, forceFoot6DoF=forceFoot6DoF_flag) modMotionFitted.compute() #---- Joint kinematics---- # relative angles modelFilters.ModelJCSFilter(model, finalAcqGait).compute( description="vectoriel", pointLabelSuffix=pointSuffix) modelFilters.ModelAbsoluteAnglesFilter( model, finalAcqGait, segmentLabels=["Left Foot", "Right Foot", "Pelvis", "Thorax", "Head"], angleLabels=[ "LFootProgress", "RFootProgress", "Pelvis", "Thorax", "Head" ], eulerSequences=["TOR", "TOR", "ROT", "YXZ", "TOR"], globalFrameOrientation=globalFrame, forwardProgression=forwardProgression).compute( pointLabelSuffix=pointSuffix) #---- Body segment parameters---- bspModel = bodySegmentParameters.Bsp(model) bspModel.compute() modelFilters.CentreOfMassFilter( model, finalAcqGait).compute(pointLabelSuffix=pointSuffix) # Inverse dynamics if btkTools.checkForcePlateExist(acqGait): # --- force plate handling---- # find foot in contact mappedForcePlate = forceplates.matchingFootSideOnForceplate( finalAcqGait, mfpa=mfpa) forceplates.addForcePlateGeneralEvents(finalAcqGait, mappedForcePlate) LOGGER.logger.warning("Manual Force plate assignment : %s" % mappedForcePlate) # assembly foot and force plate modelFilters.ForcePlateAssemblyFilter( model, finalAcqGait, mappedForcePlate, leftSegmentLabel="Left Foot", rightSegmentLabel="Right Foot").compute( pointLabelSuffix=pointSuffix) #---- Joint kinetics---- idp = modelFilters.CGMLowerlimbInverseDynamicProcedure() modelFilters.InverseDynamicFilter( model, finalAcqGait, procedure=idp, projection=momentProjection, globalFrameOrientation=globalFrame, forwardProgression=forwardProgression).compute( pointLabelSuffix=pointSuffix) #---- Joint energetics---- modelFilters.JointPowerFilter( model, finalAcqGait).compute(pointLabelSuffix=pointSuffix) #---- zero unvalid frames --- btkTools.cleanAcq(finalAcqGait) btkTools.applyOnValidFrames(finalAcqGait, flag) if detectAnomaly and not anomalyException: LOGGER.logger.error( "Anomalies has been detected - Check Warning messages of the log file" ) return finalAcqGait, detectAnomaly