def test_temporalPlotSingleEmg(self): # ----DATA----- DATA_PATH = pyCGM2.TEST_DATA_PATH+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\" gaitTrial = "PRE-gait trial 01.c3d" restTrial = "PRE-repos.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\" files.createDir(DATA_PATH_OUT) EMG_LABELS=['EMG1'] acq = btkTools.smartReader(DATA_PATH +gaitTrial) bf = emgFilters.BasicEmgProcessingFilter(acq,EMG_LABELS) bf.setHighPassFrequencies(20.0,200.0) bf.run() btkTools.smartWriter(acq,DATA_PATH_OUT+"test_temporalPlotSingleEmg.c3d") trial =trialTools.smartTrialReader(DATA_PATH_OUT,"test_temporalPlotSingleEmg.c3d") fig = plt.figure() ax = plt.gca() plot.temporalPlot(ax,trial,"EMG1_Rectify",0, color="blue", title="test", xlabel="frame", ylabel="emg",ylim=None,legendLabel=None, customLimits=None) plot.addTemporalNormalActivationLayer(ax,trial,"RECFEM","Left")
def test_descriptiveKinematicPlotPanel_savePngAndPdf(self): # ----DATA----- DATA_PATH = pyCGM2.TEST_DATA_PATH+"GaitData\CGM1-NormalGaitData-Events\Hånnibøl Lecter\\" modelledFilenames = ["gait Trial 01.c3d","gait Trial 02.c3d"] DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT+"GaitData\CGM1-NormalGaitData-Events\Hånnibøl Lecter\\" files.createDir(DATA_PATH_OUT) modelInfo=None subjectInfo=None experimentalInfo=None analysisInstance = analysis.makeAnalysis(DATA_PATH,modelledFilenames) # viewer kv = plotViewers.NormalizedKinematicsPlotViewer(analysisInstance) kv.setConcretePlotFunction(plot.descriptivePlot) kv.setNormativeDataset(normativeDatasets.Schwartz2008("Free")) # filter pf = plotFilters.PlottingFilter() pf.setViewer(kv) pf.setExport(DATA_PATH_OUT,"test_descriptiveKinematicPlotPanel","png") pf.plot() # filter pf = plotFilters.PlottingFilter() pf.setViewer(kv) pf.setExport(DATA_PATH_OUT,"test_descriptiveKinematicPlotPanel","pdf") pf.plot()
def test_temporalEmgPlot(self): # ----DATA----- DATA_PATH = pyCGM2.TEST_DATA_PATH+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\" gaitTrial = "PRE-gait trial 01.c3d" restTrial = "PRE-repos.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\" files.createDir(DATA_PATH_OUT) #--------------------------settings------------------------------------- if os.path.isfile(DATA_PATH + "emg.settings"): emgSettings = files.openFile(DATA_PATH,"emg.settings") logging.warning("[pyCGM2]: emg.settings detected in the data folder") else: emgSettings = None manager = EmgManager.EmgConfigManager(None,localInternalSettings=emgSettings) manager.contruct() EMG_LABELS,EMG_MUSCLES,EMG_CONTEXT,NORMAL_ACTIVITIES = manager.getEmgConfiguration() rectifyBool=True acq = btkTools.smartReader(DATA_PATH+gaitTrial) analysis.processEMG_fromBtkAcq(acq, EMG_LABELS, highPassFrequencies=[20,200], envelopFrequency=6.0) openmaTrial = trialTools.convertBtkAcquisition(acq) plot.plotTemporalEMG(DATA_PATH,gaitTrial, EMG_LABELS,EMG_MUSCLES, EMG_CONTEXT, NORMAL_ACTIVITIES,exportPdf=False,rectify=rectifyBool,openmaTrial=openmaTrial)
def test_temporalPlotPanel(self): # ----DATA----- DATA_PATH = pyCGM2.TEST_DATA_PATH+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\" gaitTrial = "PRE-gait trial 01.c3d" restTrial = "PRE-repos.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\" files.createDir(DATA_PATH_OUT) EMG_LABELS=['EMG1','EMG2','EMG3','EMG4'] acq = btkTools.smartReader(DATA_PATH +gaitTrial) bf = emgFilters.BasicEmgProcessingFilter(acq,EMG_LABELS) bf.setHighPassFrequencies(20.0,200.0) bf.run() btkTools.smartWriter(acq,DATA_PATH_OUT+"test_temporalPlotPanel.c3d") trial =trialTools.smartTrialReader(DATA_PATH_OUT,"test_temporalPlotPanel.c3d") # # viewer kv = emgPlotViewers.TemporalEmgPlotViewer(trial) kv.setEmgs([["EMG1","Left","RF"],["EMG2","Right","RF"],["EMG3","Left","vaste"],["EMG4","Right","vaste"]]) kv.setNormalActivationLabels(["RECFEM","RECFEM",None,"VASLAT"]) kv. setEmgRectify(True) # # filter pf = plotFilters.PlottingFilter() pf.setViewer(kv) pf.setExport(DATA_PATH_OUT,"hän-test_temporalPlotPanel","png") pf.plot()
def test_btkWriter(self): filename = pyCGM2.TEST_DATA_PATH + "LowLevel\\IO\\Hånnibøl_c3d\\static.c3d" acq = btkTools.smartReader(filename, translators=None) filenameOUT = pyCGM2.TEST_DATA_PATH_OUT + "LowLevel\\IO\\Hånnibøl_c3d\\static.c3d" files.createDir(pyCGM2.TEST_DATA_PATH_OUT + "LowLevel\\IO\\Hånnibøl_c3d") btkTools.smartWriter(acq, filenameOUT)
def test_correctForcePlateType5(self): MAIN_PATH = pyCGM2.TEST_DATA_PATH + "LowLevel\\ForcePlate\\ForcePlateTypeManagement\\" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT + "LowLevel\\ForcePlate\\ForcePlateTypeManagement\\" files.createDir(DATA_PATH_OUT) btkAcq = btkTools.smartReader(MAIN_PATH + "HUG_gait_type5.c3d") forceplates.correctForcePlateType5(btkAcq) btkTools.smartWriter(btkAcq, DATA_PATH_OUT + "HUG_gait_type5.c3d")
def test_FullBody_noOptions(self): DATA_PATH = MAIN_PATH = pyCGM2.TEST_DATA_PATH + "LowLevel\\uncropped data\\cgm1\\" staticFilename = "static.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT+"LowLevel\\uncropped data\\cgm1\\" files.createDir(DATA_PATH_OUT) markerDiameter=14 leftFlatFoot = True rightFlatFoot = True headStraight = True pointSuffix = "" vskFile = vskTools.getVskFiles(DATA_PATH) vsk = vskTools.Vsk(DATA_PATH + "New Subject.vsk") required_mp,optional_mp = vskTools.getFromVskSubjectMp(vsk, resetFlag=True) model,finalAcqStatic = cgm1.calibrate(DATA_PATH, staticFilename, None, required_mp, optional_mp, leftFlatFoot, rightFlatFoot, headStraight, markerDiameter, pointSuffix, displayCoordinateSystem=True) # btkTools.smartWriter(finalAcqStatic, str( staticFilename[:-4]+"-pyCGM2modelled.c3d")) # logging.info("Static Calibration -----> Done") gaitFilename="gait1.c3d" acqGait0 = btkTools.smartReader(DATA_PATH + gaitFilename) trackingMarkers = model.getTrackingMarkers(acqGait0) validFrames,vff,vlf = btkTools.findValidFrames(acqGait0,trackingMarkers) mfpa = None reconstructFilenameLabelled = gaitFilename acqGait = cgm1.fitting(model,DATA_PATH, reconstructFilenameLabelled, None, markerDiameter, pointSuffix, mfpa, enums.MomentProjection.Proximal, displayCoordinateSystem=True) btkTools.smartWriter(acqGait, DATA_PATH_OUT+"//gait1-processed.c3d")
def test_fullBody(self): # ----DATA----- DATA_PATH = pyCGM2.TEST_DATA_PATH+"GaitData\\CGM1-NormalGaitData-Events\\cgm1-fullbody\\" modelledFilenames = ["gait1.c3d","gait2.c3d"] DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT+"GaitData\\CGM1-NormalGaitData-Events\\cgm1-fullbody\\" files.createDir(DATA_PATH_OUT) nds = normativeDatasets.Schwartz2008("Free") analysisInstance = analysis.makeAnalysis(DATA_PATH,modelledFilenames) plot.plot_DescriptiveKinematic(DATA_PATH,analysisInstance,"LowerLimb", nds, pointLabelSuffix=None, type="Gait", exportPdf=False, outputName=None, show=True, title=None) plot.plot_DescriptiveKinematic(DATA_PATH,analysisInstance,"Trunk", nds, pointLabelSuffix=None, type="Gait", exportPdf=False, outputName=None, show=True, title=None) plot.plot_DescriptiveKinematic(DATA_PATH,analysisInstance,"UpperLimb", nds, pointLabelSuffix=None, type="Gait", exportPdf=False, outputName=None, show=True, title=None)
def test_cgm1_sacrum(self): MAIN_PATH = pyCGM2.TEST_DATA_PATH + "LowLevel\\translators\\cgm1-sacr\\" staticFilename = "static.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT + "LowLevel\\translators\\cgm1-sacr\\" files.createDir(DATA_PATH_OUT) translators = files.getTranslators(MAIN_PATH, translatorType="CGM1.translators") acqStatic = btkTools.smartReader(str(MAIN_PATH + staticFilename)) acqStatic2 = btkTools.applyTranslators(acqStatic, translators) btkTools.smartWriter(acqStatic2, DATA_PATH_OUT + "staticCGM1Sacrum.c3d") np.testing.assert_equal( acqStatic2.GetPoint(utils.str("LPSI")).GetValues(), acqStatic.GetPoint(utils.str("SACR")).GetValues()) np.testing.assert_equal( acqStatic2.GetPoint(utils.str("RPSI")).GetValues(), acqStatic.GetPoint(utils.str("SACR")).GetValues())
def test_markerFiltering_noGap(self): PATH = pyCGM2.TEST_DATA_PATH + "LowLevel\\filtering\\" acq = btkTools.smartReader(PATH + "verif0.c3d") import ipdb ipdb.set_trace() DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT + "LowLevel\\filtering\\" files.createDir(DATA_PATH_OUT) markers = [ 'LASI', 'RASI', 'RPSI', 'LPSI', 'LTHI', 'LKNE', 'LTHAP', 'LTHAD', 'LTIB', 'LANK', 'LTIAP', 'LTIAD', 'LHEE', 'LTOE', 'RTHI', 'RKNE', 'RTHAP', 'RTHAD', 'RTIB', 'RANK', 'RTIAP', 'RTIAD', 'RHEE', 'RTOE', 'C7', 'T10', 'CLAV', 'STRN', 'LSHO', 'LELB', 'LWRA', 'LWRB', 'LFIN', 'RSHO', 'RELB', 'RWRA', 'RWRB', 'RFIN', 'LFHD', 'LBHD', 'RFHD', 'RBHD' ] marker = "LFHD" array0 = acq.GetPoint(marker).GetValues()[:, 1] signal_processing.markerFiltering(acq, markers, zerosFiltering=True, order=4, fc=6.0) btkTools.smartWriter(acq, DATA_PATH_OUT + "test_markerFilteringCGM23.c3d") array1 = acq.GetPoint(marker).GetValues()[:, 1] plt.plot(array0, '-b') plt.plot(array1, '-r') plt.show()
def test_envelopGaitPlotPanel(self): # ----DATA----- DATA_PATH = pyCGM2.TEST_DATA_PATH+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\" gaitTrial = "PRE-gait trial 01.c3d" restTrial = "PRE-repos.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\" files.createDir(DATA_PATH_OUT) EMG_LABELS=['EMG1','EMG2'] acq = btkTools.smartReader(DATA_PATH +gaitTrial) bf = emgFilters.BasicEmgProcessingFilter(acq,EMG_LABELS) bf.setHighPassFrequencies(20.0,200.0) bf.run() envf = emgFilters.EmgEnvelopProcessingFilter(acq,EMG_LABELS) envf.setCutoffFrequency(180.0) envf.run() btkTools.smartWriter(acq,DATA_PATH_OUT+"test_envelopGaitPlotPanel.c3d") modelledFilenames = ["test_envelopGaitPlotPanel.c3d"] c3dmanagerProcedure = c3dManager.UniqueC3dSetProcedure(DATA_PATH_OUT,modelledFilenames) cmf = c3dManager.C3dManagerFilter(c3dmanagerProcedure) cmf.enableSpatioTemporal(False) cmf.enableKinematic(False) cmf.enableKinetic(False) cmf.enableEmg(True) trialManager = cmf.generate() #---- GAIT CYCLES FILTER #-------------------------------------------------------------------------- cycleBuilder = cycle.GaitCyclesBuilder(spatioTemporalTrials=trialManager.spatioTemporal["Trials"], kinematicTrials = trialManager.kinematic["Trials"], kineticTrials = trialManager.kinetic["Trials"], emgTrials=trialManager.emg["Trials"]) cyclefilter = cycle.CyclesFilter() cyclefilter.setBuilder(cycleBuilder) cycles = cyclefilter.build() modelInfo=None subjectInfo=None experimentalInfo=None analysisBuilder = analysis.GaitAnalysisBuilder(cycles, kinematicLabelsDict = None, kineticLabelsDict = None, emgLabelList = ['EMG1_Rectify_Env','EMG2_Rectify_Env'], subjectInfos=subjectInfo, modelInfos=modelInfo, experimentalInfos=experimentalInfo) analysisFilter = analysis.AnalysisFilter() analysisFilter.setBuilder(analysisBuilder) analysisFilter.setInfo(model = modelInfo) analysisFilter.build() analysisInstance = analysisFilter.analysis envnf = emgFilters.EmgNormalisationProcessingFilter(analysisInstance,"EMG1","Right") envnf.setMaxMethod(enums.EmgAmplitudeNormalization.MeanMax) envnf.run() envnf = emgFilters.EmgNormalisationProcessingFilter(analysisInstance,"EMG2","Right") envnf.setMaxMethod(enums.EmgAmplitudeNormalization.MeanMax) envnf.run() data = analysisInstance.emgStats.data # viewer kv = emgPlotViewers.EnvEmgGaitPlotPanelViewer (analysisInstance) kv.setEmgs([["EMG1","Right","rf"],["EMG2","Right","rf"]]) kv.setNormalActivationLabels(["RECFEM","RECFEM"]) kv.setConcretePlotFunction(plot.gaitDescriptivePlot) # # filter pf = plotFilters.PlottingFilter() pf.setViewer(kv) pf.plot()
def main(sessionFilename, createPDFReport=True): logging.info("------------------------------------------------") logging.info("------------QTM - pyCGM2 Workflow---------------") logging.info("------------------------------------------------") sessionXML = files.readXml(os.getcwd() + "\\", sessionFilename) sessionDate = files.getFileCreationDate(os.getcwd() + "\\" + sessionFilename) #--------------------------------------------------------------------------- #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)) 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 + "CGM1_1-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH, "CGM1_1-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER, "CGM1_1-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() + "\\", "CGM1_1.translators") if not translators: translators = settings["Translators"] # --------------------------MODEL CALIBRATION ----------------------- logging.info( "--------------------------MODEL CALIBRATION -----------------------") staticMeasurement = qtmTools.findStatic(sessionXML) calibrateFilenameLabelled = qtmTools.getFilename(staticMeasurement) logging.info("----- CALIBRATION- static file [%s]--" % (calibrateFilenameLabelled)) leftFlatFoot = utils.toBool( sessionXML.Left_foot_normalised_to_static_trial.text) rightFlatFoot = utils.toBool( sessionXML.Right_foot_normalised_to_static_trial.text) headFlat = utils.toBool(sessionXML.Head_normalised_to_static_trial.text) markerDiameter = float(sessionXML.Marker_diameter.text) * 1000.0 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 = cgm1_1.calibrate(DATA_PATH, calibrateFilenameLabelled, translators, required_mp, optional_mp, leftFlatFoot, rightFlatFoot, headFlat, markerDiameter, 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 = sessionXML.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_marker = int( float(dynamicMeasurement.Marker_lowpass_filter_order.text)) fc_marker = float( dynamicMeasurement.Marker_lowpass_filter_frequency.text) # force plate order_fp = int( float(dynamicMeasurement.Forceplate_lowpass_filter_order.text)) fc_fp = float( dynamicMeasurement.Forceplate_lowpass_filter_frequency.text) # event checking # ----------------------- inspectprocedureEvents = inspectProcedures.GaitEventQualityProcedure( acq) inspector = inspectFilters.QualityFilter(inspectprocedureEvents) inspector.run() eventInspectorStates.append(inspectprocedureEvents.state) # fitting operation # ----------------------- logging.info("[pyCGM2] --- Fitting operation ---") acqGait = cgm1_1.fitting(model, DATA_PATH, reconstructFilenameLabelled, translators, markerDiameter, pointSuffix, mfpa, momentProjection, fc_lowPass_marker=fc_marker, order_lowPass_marker=order_marker, fc_lowPass_forcePlate=fc_fp, order_lowPass_forcePlate=order_fp) outFilename = reconstructFilenameLabelled 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 -----------------------") if createPDFReport: 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) report.pdfGaitReport(DATA_PATH, model, modelledTrials, nds, pointSuffix, title=type) logging.info("----- Gait Processing -----> DONE")
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 test_scenario3Test(self): """ the pyCGM2 marker is IN the c3d. it points to another pyCGM2 marker which is IN c3d ( e.g : LTHI points to LTHAP) return: the translator and your own markers point to similar values (e.g LTHI amd LTAP point same values) a new marker suffixed with _origin for keeping a trace of the translator found in the c3d ( eg LTHi renamed LTHI_origin ) """ contents24 = """ Translators: LASI: None RASI: None LPSI: None RPSI: None RTHI: None RKNE: None RTIAP: None RTIAD: None RTIB: None RANK: None RTIAP: None RTIAD: None RHEE: None RSMH: None RTOE: None RFMH: None RVMH: None LTHI: LTHAD LKNE: None LTHAP: None LTHAD: None LTIB: None LANK: None LTIAP: None LTIAD: None LHEE: None LSMH: None LTOE: None LFMH: None LVMH: None RKNM: None LKNM: None RMED: None LMED: None C7: None T10: None CLAV: None STRN: None LFHD: None LBHD: None RFHD: None RBHD: None LSHO: None LELB: None LWRB: None LWRA: None LFIN: None RSHO: None RELB: None RWRB: None RWRA: None RFIN: None """ translators = files.readContent(contents24) MAIN_PATH = pyCGM2.TEST_DATA_PATH + "LowLevel\\translators\\scenario3\\" staticFilename = "staticAlana.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT + "LowLevel\\translators\\scenario3\\" files.createDir(DATA_PATH_OUT) acqStatic = btkTools.smartReader(str(MAIN_PATH + staticFilename)) acqStatic2 = btkTools.applyTranslators(acqStatic, translators["Translators"]) btkTools.smartWriter(acqStatic2, DATA_PATH_OUT + "scenario3Test.c3d") np.testing.assert_equal( acqStatic2.GetPoint(utils.str("LTHI")).GetValues(), acqStatic2.GetPoint(utils.str("LTHAD")).GetValues()) np.testing.assert_equal( acqStatic2.GetPoint(utils.str("LTHI_origin")).GetValues(), acqStatic.GetPoint(utils.str("LTHI")).GetValues())
def test_createDir(self): files.createDir(pyCGM2.TEST_DATA_PATH + "-OUT\\LowLevel\\IO\\Hanibal_files\\latin1_iæøå_test")
def test_scenario1Test(self): """ basic test. the pyCGM2 marker is not in the c3d. it points to you own label which is not a pyCGM2 marker ( e.g : LASI points to LeftASI) return: => own markers and pyGM2 markers are both IN the final c3d """ contents24 = """ Translators: LASI: LeftASI RASI: RightASI LPSI: LeftPSI RPSI: RightPSI RTHI: None RKNE: None RTIAP: None RTIAD: None RTIB: None RANK: None RTIAP: None RTIAD: None RHEE: None RSMH: None RTOE: None RFMH: None RVMH: None LTHI: None LKNE: None LTHAP: None LTHAD: None LTIB: None LANK: None LTIAP: None LTIAD: None LHEE: None LSMH: None LTOE: None LFMH: None LVMH: None RKNM: None LKNM: None RMED: None LMED: None C7: None T10: None CLAV: None STRN: None LFHD: None LBHD: None RFHD: None RBHD: None LSHO: None LELB: None LWRB: None LWRA: None LFIN: None RSHO: None RELB: None RWRB: None RWRA: None RFIN: None """ translators = files.readContent(contents24) MAIN_PATH = pyCGM2.TEST_DATA_PATH + "LowLevel\\translators\\scenario1\\" staticFilename = "static.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT + "LowLevel\\translators\\scenario1\\" files.createDir(DATA_PATH_OUT) acqStatic = btkTools.smartReader(str(MAIN_PATH + staticFilename)) acqStatic2 = btkTools.applyTranslators(acqStatic, translators["Translators"]) btkTools.smartWriter(acqStatic2, DATA_PATH_OUT + "scenario1Test.c3d") np.testing.assert_equal( acqStatic2.GetPoint(utils.str("LeftASI")).GetValues(), acqStatic2.GetPoint(utils.str("LASI")).GetValues()) np.testing.assert_equal( acqStatic2.GetPoint(utils.str("RightASI")).GetValues(), acqStatic2.GetPoint(utils.str("RASI")).GetValues()) np.testing.assert_equal( acqStatic2.GetPoint(utils.str("LeftPSI")).GetValues(), acqStatic2.GetPoint(utils.str("LPSI")).GetValues()) np.testing.assert_equal( acqStatic2.GetPoint(utils.str("RightPSI")).GetValues(), acqStatic2.GetPoint(utils.str("RPSI")).GetValues())
def main(sessionFilename, createPDFReport=True, checkEventsInMokka=True, anomalyException=False): detectAnomaly = False LOGGER.set_file_handler("pyCGM2-QTM-Workflow.log") LOGGER.logger.info("------------QTM - pyCGM2 Workflow---------------") sessionXML = files.readXml(os.getcwd() + "\\", sessionFilename) sessionDate = files.getFileCreationDate(os.getcwd() + "\\" + sessionFilename) #--------------------------------------------------------------------------- #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) LOGGER.logger.info( "qualisys exported c3d file [%s] copied to processed folder" % (calibrateFilenameLabelled)) if qtmTools.findKneeCalibration( sessionXML, "Left") is not None or qtmTools.findKneeCalibration( sessionXML, "Right") is not None: LOGGER.logger.info( " the %s not accept functional knee calibration !!" % (MODEL)) dynamicMeasurements = qtmTools.findDynamic(sessionXML) for dynamicMeasurement in dynamicMeasurements: reconstructFilenameLabelled = qtmTools.getFilename(dynamicMeasurement) # marker order_marker = int( float(dynamicMeasurement.Marker_lowpass_filter_order.text)) fc_marker = float( dynamicMeasurement.Marker_lowpass_filter_frequency.text) if not os.path.isfile(DATA_PATH + reconstructFilenameLabelled): shutil.copyfile(os.getcwd() + "\\" + reconstructFilenameLabelled, DATA_PATH + reconstructFilenameLabelled) LOGGER.logger.info( "qualisys exported c3d file [%s] copied to processed folder" % (reconstructFilenameLabelled)) acq = btkTools.smartReader( str(DATA_PATH + reconstructFilenameLabelled)) acq, zeniState = eventDetector.zeni( acq, fc_lowPass_marker=fc_marker, order_lowPass_marker=order_marker) if zeniState: btkTools.smartWriter( acq, str(DATA_PATH + reconstructFilenameLabelled)) if checkEventsInMokka: 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_5-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH, "CGM2_5-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER, "CGM2_5-pyCGM2.settings") # --------------------------MP ------------------------------------ required_mp, optional_mp = qtmTools.SubjectMp(sessionXML) # translators management translators = files.getTranslators(os.getcwd() + "\\", "CGM2_5.translators") if not translators: translators = settings["Translators"] # ikweight ikWeight = files.getIKweightSet(DATA_PATH, "CGM2_5.ikw") if not ikWeight: ikWeight = settings["Fitting"]["Weight"] # --------------------------MODEL CALIBRATION ----------------------- LOGGER.logger.info( "--------------------------MODEL CALIBRATION -----------------------") staticMeasurement = qtmTools.findStatic(sessionXML) calibrateFilenameLabelled = qtmTools.getFilename(staticMeasurement) LOGGER.logger.info("----- CALIBRATION- static file [%s]--" % (calibrateFilenameLabelled)) leftFlatFoot = utils.toBool( sessionXML.Left_foot_normalised_to_static_trial.text) rightFlatFoot = utils.toBool( sessionXML.Right_foot_normalised_to_static_trial.text) headFlat = utils.toBool(sessionXML.Head_normalised_to_static_trial.text) markerDiameter = float(sessionXML.Marker_diameter.text) * 1000.0 hjcMethod = settings["Calibration"]["HJC"] pointSuffix = None # Calibration checking # -------------------- acqStatic = btkTools.smartReader(DATA_PATH + calibrateFilenameLabelled) # Calibration operation # -------------------- model, acqStatic, detectAnomaly = cgm2_5.calibrate( DATA_PATH, calibrateFilenameLabelled, translators, settings, required_mp, optional_mp, False, leftFlatFoot, rightFlatFoot, headFlat, markerDiameter, hjcMethod, pointSuffix, anomalyException=anomalyException) LOGGER.logger.info("----- CALIBRATION- static file [%s]-----> DONE" % (calibrateFilenameLabelled)) # --------------------------MODEL FITTING ---------------------------------- LOGGER.logger.info( "--------------------------MODEL FITTING ----------------------------------" ) dynamicMeasurements = qtmTools.findDynamic(sessionXML) ik_flag = True modelledC3ds = list() eventInspectorStates = list() for dynamicMeasurement in dynamicMeasurements: reconstructFilenameLabelled = qtmTools.getFilename(dynamicMeasurement) LOGGER.logger.info("----Processing of [%s]-----" % (reconstructFilenameLabelled)) mfpa = qtmTools.getForcePlateAssigment(dynamicMeasurement) momentProjection_text = sessionXML.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) # filtering # ----------------------- # marker order_marker = int( float(dynamicMeasurement.Marker_lowpass_filter_order.text)) fc_marker = float( dynamicMeasurement.Marker_lowpass_filter_frequency.text) # force plate order_fp = int( float(dynamicMeasurement.Forceplate_lowpass_filter_order.text)) fc_fp = float( dynamicMeasurement.Forceplate_lowpass_filter_frequency.text) # ik accuracy ikAccuracy = float(dynamicMeasurement.IkAccuracy.text) if dynamicMeasurement.First_frame_to_process.text != "": vff = int(dynamicMeasurement.First_frame_to_process.text) else: vff = None if dynamicMeasurement.Last_frame_to_process.text != "": vlf = int(dynamicMeasurement.Last_frame_to_process.text) else: vlf = None # fitting operation # ----------------------- LOGGER.logger.info("[pyCGM2] --- Fitting operation ---") acqGait, detectAnomaly = cgm2_5.fitting( model, DATA_PATH, reconstructFilenameLabelled, translators, settings, ik_flag, markerDiameter, pointSuffix, mfpa, momentProjection, fc_lowPass_marker=fc_marker, order_lowPass_marker=order_marker, fc_lowPass_forcePlate=fc_fp, order_lowPass_forcePlate=order_fp, anomalyException=anomalyException, ikAccuracy=ikAccuracy, frameInit=vff, frameEnd=vlf) outFilename = reconstructFilenameLabelled btkTools.smartWriter(acqGait, str(DATA_PATH + outFilename)) modelledC3ds.append(outFilename) LOGGER.logger.info("----Processing of [%s]-----> DONE" % (reconstructFilenameLabelled)) LOGGER.logger.info( "---------------------GAIT PROCESSING -----------------------") if createPDFReport: nds = normativeDatasets.NormativeData("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) # event checking # ----------------------- acq = btkTools.smartReader(DATA_PATH + filename) geap = AnomalyDetectionProcedure.GaitEventAnomalyProcedure( ) adf = AnomalyFilter.AnomalyDetectionFilter( acq, filename, geap) anomaly_events = adf.run() if anomaly_events["ErrorState"]: detectAnomaly = True LOGGER.logger.warning( "file [%s] not used for generating the gait report. bad gait event detected" % (filename)) else: modelledTrials.append(filename) try: report.pdfGaitReport(DATA_PATH, model, modelledTrials, nds, pointSuffix, title=type) LOGGER.logger.error("Generation of Gait report complete") except: LOGGER.logger.error("Generation of Gait report failed") LOGGER.logger.info( "-------------------------------------------------------") if detectAnomaly: LOGGER.logger.error( "Anomalies has been detected - Find Error messages, then check warning message in the log file" ) else: LOGGER.logger.info("workflow return with no detected anomalies")
def test_scenario4Test(self): """ you want to swp to markers ( e.g : LTHI swap with LTHAD) return: in the final c3d, both markers are swapped. there are no _origin markers """ contents24 = """ Translators: LASI: None RASI: None LPSI: None RPSI: None RTHI: None RKNE: None RTIAP: None RTIAD: None RTIB: None RANK: None RTIAP: None RTIAD: None RHEE: None RSMH: None RTOE: None RFMH: None RVMH: None LTHI: LTHAD LKNE: None LTHAP: None LTHAD: LTHI LTIB: None LANK: None LTIAP: None LTIAD: None LHEE: None LSMH: None LTOE: None LFMH: None LVMH: None RKNM: None LKNM: None RMED: None LMED: None C7: None T10: None CLAV: None STRN: None LFHD: None LBHD: None RFHD: None RBHD: None LSHO: None LELB: None LWRB: None LWRA: None LFIN: None RSHO: None RELB: None RWRB: None RWRA: None RFIN: None """ translators = files.readContent(contents24) MAIN_PATH = pyCGM2.TEST_DATA_PATH + "LowLevel\\translators\\scenario4\\" staticFilename = "staticAlana.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT + "LowLevel\\translators\\scenario4\\" files.createDir(DATA_PATH_OUT) acqStatic = btkTools.smartReader(str(MAIN_PATH + staticFilename)) acqStatic2 = btkTools.applyTranslators(acqStatic, translators["Translators"]) btkTools.smartWriter(acqStatic2, DATA_PATH_OUT + "scenario4Test.c3d") np.testing.assert_equal( acqStatic2.GetPoint(utils.str("LTHI")).GetValues(), acqStatic.GetPoint(utils.str("LTHAD")).GetValues()) np.testing.assert_equal( acqStatic2.GetPoint(utils.str("LTHAD")).GetValues(), acqStatic.GetPoint(utils.str("LTHI")).GetValues())
def test_envelopPlotSingleEmg(self): # ----DATA----- DATA_PATH = pyCGM2.TEST_DATA_PATH+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\" gaitTrial = "PRE-gait trial 01.c3d" restTrial = "PRE-repos.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\" files.createDir(DATA_PATH_OUT) EMG_LABELS=['EMG1','EMG2'] acq = btkTools.smartReader(DATA_PATH +gaitTrial) bf = emgFilters.BasicEmgProcessingFilter(acq,EMG_LABELS) bf.setHighPassFrequencies(20.0,200.0) bf.run() envf = emgFilters.EmgEnvelopProcessingFilter(acq,EMG_LABELS) envf.setCutoffFrequency(180.0) envf.run() btkTools.smartWriter(acq,DATA_PATH_OUT+"test_envelopPlotSingleEmg.c3d") modelledFilenames = ["test_envelopPlotSingleEmg.c3d"] c3dmanagerProcedure = c3dManager.UniqueC3dSetProcedure(DATA_PATH_OUT,modelledFilenames) cmf = c3dManager.C3dManagerFilter(c3dmanagerProcedure) cmf.enableSpatioTemporal(False) cmf.enableKinematic(False) cmf.enableKinetic(False) cmf.enableEmg(True) trialManager = cmf.generate() #---- GAIT CYCLES FILTER #-------------------------------------------------------------------------- cycleBuilder = cycle.GaitCyclesBuilder(spatioTemporalTrials=trialManager.spatioTemporal["Trials"], kinematicTrials = trialManager.kinematic["Trials"], kineticTrials = trialManager.kinetic["Trials"], emgTrials=trialManager.emg["Trials"]) cyclefilter = cycle.CyclesFilter() cyclefilter.setBuilder(cycleBuilder) cycles = cyclefilter.build() modelInfo=None subjectInfo=None experimentalInfo=None analysisBuilder = analysis.GaitAnalysisBuilder(cycles, kinematicLabelsDict = None, kineticLabelsDict = None, emgLabelList = ['EMG1_Rectify_Env','EMG2_Rectify_Env'], subjectInfos=subjectInfo, modelInfos=modelInfo, experimentalInfos=experimentalInfo) analysisFilter = analysis.AnalysisFilter() analysisFilter.setBuilder(analysisBuilder) analysisFilter.setInfo(model = modelInfo) analysisFilter.build() analysisInstance = analysisFilter.analysis envnf = emgFilters.EmgNormalisationProcessingFilter(analysisInstance,"EMG1","Left") envnf.setMaxMethod(enums.EmgAmplitudeNormalization.MeanMax) envnf.run() fig = plt.figure() ax = plt.gca() plot.gaitDescriptivePlot(ax,analysisInstance.emgStats, "EMG1_Rectify_Env","Left",0, color=None, title="title", xlabel=None, ylabel=None,ylim=None,legendLabel=None, customLimits=None) footOff = analysisInstance.emgStats.pst['stancePhase', "Left"]["mean"] plot.addNormalActivationLayer(ax,"RECFEM", footOff)
def test_translators24_initiateWith_25markerset(self): contents24 = """ Translators: LASI: None RASI: None LPSI: None RPSI: None RTHI: None RKNE: None RTIAP: None RTIAD: None RTIB: None RANK: None RTIAP: None RTIAD: None RHEE: None RSMH: None RTOE: None RFMH: None RVMH: None LTHI: None LKNE: None LTHAP: None LTHAD: None LTIB: None LANK: None LTIAP: None LTIAD: None LHEE: None LSMH: None LTOE: None LFMH: None LVMH: None RKNM: None LKNM: None RMED: None LMED: None C7: T2 T10: None CLAV: None STRN: CLAV LFHD: GLAB LBHD: LMAS RFHD: GLAB RBHD: RMAS LSHO: None LELB: None LWRB: None LWRA: None LFIN: None RSHO: None RELB: None RWRB: None RWRA: None RFIN: None """ translators = files.readContent(contents24) MAIN_PATH = pyCGM2.TEST_DATA_PATH + "LowLevel\\translators\\cgm2.5\\" staticFilename = "static.c3d" DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT + "LowLevel\\translators\\cgm2.5\\" files.createDir(DATA_PATH_OUT) acqStatic = btkTools.smartReader(str(MAIN_PATH + staticFilename)) acqStatic2 = btkTools.applyTranslators(acqStatic, translators["Translators"]) btkTools.smartWriter( acqStatic2, DATA_PATH_OUT + "translators24_initiateWith_25markerset.c3d") np.testing.assert_equal( acqStatic2.GetPoint(utils.str("C7")).GetValues(), acqStatic.GetPoint(utils.str("T2")).GetValues()) np.testing.assert_equal( acqStatic2.GetPoint(utils.str("LFHD")).GetValues(), acqStatic.GetPoint(utils.str("GLAB")).GetValues()) np.testing.assert_equal( acqStatic2.GetPoint(utils.str("RFHD")).GetValues(), acqStatic.GetPoint(utils.str("GLAB")).GetValues()) np.testing.assert_equal( acqStatic2.GetPoint(utils.str("LBHD")).GetValues(), acqStatic.GetPoint(utils.str("LMAS")).GetValues()) np.testing.assert_equal( acqStatic2.GetPoint(utils.str("RBHD")).GetValues(), acqStatic.GetPoint(utils.str("RMAS")).GetValues())
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
#DATA_PATH = pyCGM2.TEST_DATA_PATH + "CGM1\\CGM1\\pipeline\\" #DATA_PATH = pyCGM2.TEST_DATA_PATH + "CGM2\\cgm2.3\\medialPipeline\\" DATA_PATH = "C:\\Users\\HLS501\\Documents\\VICON DATA\\pyCGM2-Data\\Datasets Tests\\didier\\08_02_18_Vincent Pere\\" pipelineFile = "pipeline.pyCGM2" xlsExport_flag = True plotFlag= True wd= DATA_PATH else: wd = os.getcwd()+"\\" # ----------------setting manager---------------- manager = pipManager.PipelineFileManager(wd,pipelineFile) # data path configurations if not args.DEBUG: DATA_PATH = wd if manager.getDataPath() is None else manager.getDataPath() print DATA_PATH DATA_PATH_OUT = DATA_PATH if manager.getOutDataPath() is None else manager.getOutDataPath() if manager.getOutDataPath() is not None: files.createDir(DATA_PATH_OUT) #----------------Modelling ----------------------- if modellingFlag: modelling(manager,DATA_PATH,DATA_PATH_OUT,vskFile=vskFile) #----------------Processing ----------------------- if processingFlag: processing(manager,DATA_PATH,DATA_PATH_OUT,plotFlag=plotFlag, exportFlag = xlsExport_flag)