예제 #1
0
def dataTest3():
    DATA_PATH1 = pyCGM2.TEST_DATA_PATH + "GaitData\\Patient\\session 1 - CGM1\\"
    modelledFilenames1 = ["20180706_CS_PONC_S_NNNN dyn 02.c3d",
                        "20180706_CS_PONC_S_NNNN dyn 03.c3d",
                        "20180706_CS_PONC_S_NNNN dyn 05.c3d"]

    analysisInstance1 = analysis.makeAnalysis(DATA_PATH1,
                        modelledFilenames1,
                        type="Gait",
                        emgChannels = emgChannels,
                        pointLabelSuffix=None,
                        subjectInfo=None, experimentalInfo=None,modelInfo=None,
                        )

    DATA_PATH2 = pyCGM2.TEST_DATA_PATH + "GaitData\\Patient\\session 2 - CGM23\\"
    modelledFilenames2 = ["20200729-SC-PONC-S-NNNN dyn 04.c3d",
                        "20200729-SC-PONC-S-NNNN dyn 06.c3d"]

    analysisInstance2 = analysis.makeAnalysis(DATA_PATH2,
                        modelledFilenames2,
                        type="Gait",
                        emgChannels = emgChannels,
                        pointLabelSuffix=None,
                        subjectInfo=None, experimentalInfo=None,modelInfo=None,
                        )

    return DATA_PATH1,modelledFilenames1,analysisInstance1,DATA_PATH2,modelledFilenames2,analysisInstance2
예제 #2
0
    def test_gaitMeanOnlyKineticPlotPanel(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"]



        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo=None
        subjectInfo=None
        experimentalInfo=None

        analysis1 = analysis.makeAnalysis(DATA_PATH,modelledFilenames)

        analysis2 = analysis.makeAnalysis(DATA_PATH,modelledFilenames)


        kv = ComparisonPlotViewers.KineticsPlotComparisonViewer([analysis1,analysis2],"Right",
                                                                    ["ana1","ana2"])
        kv.setConcretePlotFunction(plot.gaitMeanPlot)
        kv.setNormativeDataset(normativeDatasets.Schwartz2008("Free"))

        # filter
        pf = plotFilters.PlottingFilter()
        pf.setViewer(kv)
        pf.plot()
예제 #3
0
    def meanPlot_OneModelOutputPlot(cls):
        """
        Plot only one Model output
        """

        # ----DATA-----
        DATA_PATH = pyCGM2.TEST_DATA_PATH + "operations\\plot\\gaitPlot\\"
        modelledFilenames = ["gait Trial 03 - viconName.c3d"]

        #---- c3d manager
        #--------------------------------------------------------------------------
        c3dmanagerProcedure = c3dManager.UniqueC3dSetProcedure(
            DATA_PATH, modelledFilenames)
        cmf = c3dManager.C3dManagerFilter(c3dmanagerProcedure)
        cmf.enableEmg(False)
        trialManager = cmf.generate()

        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo = None
        subjectInfo = None
        experimentalInfo = None

        analysis1 = analysis.makeAnalysis("Gait", "CGM1.0", DATA_PATH,
                                          modelledFilenames, None, None, None)

        analysis2 = analysis.makeAnalysis("Gait", "CGM1.0", DATA_PATH,
                                          modelledFilenames, None, None, None)

        analyses = [analysis1, analysis2]
        fig = plt.figure()
        ax = plt.gca()
        colormap = plt.cm.Reds
        colormap_i = [colormap(i) for i in np.linspace(0.2, 1, len(analyses))]

        plot.gaitMeanPlot(ax,
                          analysis1.kinematicStats,
                          "LPelvisAngles",
                          "Left",
                          0,
                          color=colormap_i[0],
                          legendLabel="analysis1",
                          customLimits=None)

        plot.gaitMeanPlot(ax,
                          analysis2.kinematicStats,
                          "LKneeAngles",
                          "Left",
                          0,
                          color=colormap_i[1],
                          legendLabel="analysis2",
                          customLimits=None)
        ax.legend()
        plt.show()
예제 #4
0
    def test_consistencyPlot_OneModelOutputPlot(self):
        """
        Plot only one Model output
        """

        # ----DATA-----
        DATA_PATH = pyCGM2.TEST_DATA_PATH + "GaitData\CGM1-NormalGaitData-Events\Hånnibøl Lecter\\"
        modelledFilenames = ["gait Trial 01.c3d", "gait Trial 02.c3d"]

        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo = None
        subjectInfo = None
        experimentalInfo = None

        analysisInstance = analysis.makeAnalysis(DATA_PATH, modelledFilenames)

        fig = plt.figure()
        ax = plt.gca()
        plot.gaitConsistencyPlot(ax,
                                 analysisInstance.kinematicStats,
                                 "LPelvisAngles",
                                 "Left",
                                 0,
                                 color="blue",
                                 title="",
                                 xlabel="",
                                 ylabel="",
                                 ylim=None,
                                 customLimits=None)
예제 #5
0
    def singleAnalysis(cls):

        # ----DATA-----
        DATA_PATH = pyCGM2.TEST_DATA_PATH + "operations\\plot\\gaitPlot\\"
        modelledFilenames = ["gait Trial 03 - viconName.c3d"]

        #---- c3d manager
        #--------------------------------------------------------------------------
        c3dmanagerProcedure = c3dManager.UniqueC3dSetProcedure(
            DATA_PATH, modelledFilenames)
        cmf = c3dManager.C3dManagerFilter(c3dmanagerProcedure)
        cmf.enableEmg(False)
        trialManager = cmf.generate()

        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo = None
        subjectInfo = None
        experimentalInfo = None

        analysisInstance = analysis.makeAnalysis(DATA_PATH, modelledFilenames,
                                                 None, None, None)

        # viewer
        kv = plotViewers.SpatioTemporalPlotViewer(analysisInstance)
        kv.setNormativeDataset(normativeDatasets.NormalSTP())

        # filter
        pf = plotFilters.PlottingFilter()
        pf.setViewer(kv)
        pf.setExport(DATA_PATH, "stp", "pdf")
        pf.plot()

        plt.show()
예제 #6
0
    def gaitDescriptiveKinematicPlotPanel(cls):

        # ----DATA-----
        DATA_PATH = pyCGM2.TEST_DATA_PATH+"operations\\plot\\gaitPlot\\"
        modelledFilenames = ["gait Trial 03 - viconName.c3d"]


        #---- c3d manager
        #--------------------------------------------------------------------------
        c3dmanagerProcedure = c3dManager.UniqueC3dSetProcedure(DATA_PATH,modelledFilenames)
        cmf = c3dManager.C3dManagerFilter(c3dmanagerProcedure)
        cmf.enableEmg(False)
        trialManager = cmf.generate()

        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo=None
        subjectInfo=None
        experimentalInfo=None

        analysisInstance = analysis.makeAnalysis("Gait", "CGM1.0", DATA_PATH,modelledFilenames,None, None, None)

        # viewer
        kv = plotViewers.LowerLimbKinematicsPlotViewer(analysisInstance)
        kv.setConcretePlotFunction(plot.gaitDescriptivePlot)
        kv.setNormativeDataset(normativeDatasets.Schwartz2008("Free"))

        # filter
        pf = plotFilters.PlottingFilter()
        pf.setViewer(kv)
        pf.plot()

        plt.show()
예제 #7
0
    def test_gaitConsistencyKinematicPlotPanel(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"]


        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo=None
        subjectInfo=None
        experimentalInfo=None

        analysisInstance = analysis.makeAnalysis(DATA_PATH,modelledFilenames)

        # viewer
        kv = plotViewers.NormalizedKinematicsPlotViewer(analysisInstance)
        kv.setConcretePlotFunction(plot.gaitConsistencyPlot)
        kv.setNormativeDataset(normativeDatasets.Schwartz2008("Free"))

        # filter
        pf = plotFilters.PlottingFilter()
        pf.setViewer(kv)
        pf.plot()
예제 #8
0
    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()
예제 #9
0
    def test_singleAnalysis(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"]

        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo = None
        subjectInfo = None
        experimentalInfo = None

        analysisInstance = analysis.makeAnalysis(DATA_PATH, modelledFilenames)

        ndp = normativeDatasets.Schwartz2008("Free")
        gps = scores.CGM1_GPS()
        scf = scores.ScoreFilter(gps, analysisInstance, ndp)
        scf.compute()

        # viewer
        kv = plotViewers.GpsMapPlotViewer(analysisInstance)

        # filter
        pf = plotFilters.PlottingFilter()
        pf.setViewer(kv)
        pf.plot()
예제 #10
0
def dataTest1():
    DATA_PATH = pyCGM2.TEST_DATA_PATH + "GaitData//CGM1-NormalGaitData-Events//Hannibal Lecter\\"
    modelledFilenames = ["gait Trial 01.c3d", "gait Trial 02.c3d"]
    analysisInstance = analysis.makeAnalysis(DATA_PATH,
                        modelledFilenames,
                        type="Gait")
    return DATA_PATH,analysisInstance
예제 #11
0
    def __init__(self, workingDirectory):
        self.workingDirectory = workingDirectory
        self.null = None

        c3dValObj = c3dValidation.c3dValidation(workingDirectory)
        self.measurementNames = c3dValObj.getValidC3dList(True)
        self.fileNames = c3dValObj.getValidC3dList(False)
        self.perFilePyCGM2tspStats = {path.basename(name).replace(".c3d", ""): analysis.makeAnalysis(
            workingDirectory + "\\", [path.basename(name)]).stpStats for name in self.fileNames}
예제 #12
0
    def test_meanPlot_OneModelOutputPlot(self):
        """
        Plot only one Model output
        """

        # ----DATA-----
        DATA_PATH = pyCGM2.TEST_DATA_PATH + "GaitData\CGM1-NormalGaitData-Events\Hånnibøl Lecter\\"
        modelledFilenames1 = ["gait Trial 01.c3d"]
        modelledFilenames2 = ["gait Trial 02.c3d"]

        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo = None
        subjectInfo = None
        experimentalInfo = None

        analysis1 = analysis.makeAnalysis(DATA_PATH, modelledFilenames1)
        analysis2 = analysis.makeAnalysis(DATA_PATH, modelledFilenames2)

        analyses = [analysis1, analysis2]
        fig = plt.figure()
        ax = plt.gca()
        colormap = plt.cm.Reds
        colormap_i = [colormap(i) for i in np.linspace(0.2, 1, len(analyses))]

        plot.gaitMeanPlot(ax,
                          analysis1.kinematicStats,
                          "LPelvisAngles",
                          "Left",
                          0,
                          color=colormap_i[0],
                          legendLabel="analysis1",
                          customLimits=None)

        plot.gaitMeanPlot(ax,
                          analysis2.kinematicStats,
                          "LKneeAngles",
                          "Left",
                          0,
                          color=colormap_i[1],
                          legendLabel="analysis2",
                          customLimits=None)
        ax.legend()
예제 #13
0
def main():

    plt.close("all")

    parser = argparse.ArgumentParser(description='CGM plot stp')
    parser.add_argument('-ps',
                        '--pointSuffix',
                        type=str,
                        help='suffix added to pyCGM2 outputs')
    args = parser.parse_args()

    NEXUS = ViconNexus.ViconNexus()
    NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected()

    if NEXUS_PYTHON_CONNECTED:

        pointSuffix = args.pointSuffix
        # --------------------------INPUTS ------------------------------------
        DATA_PATH, modelledFilenameNoExt = NEXUS.GetTrialName()

        modelledFilename = modelledFilenameNoExt + ".c3d"

        logging.info("data Path: " + DATA_PATH)
        logging.info("file: " + modelledFilename)

        # ----- Subject -----
        # need subject to find input files
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.checkActivatedSubject(NEXUS, subjects)
        logging.info("Subject name : " + subject)

        # ----- construction of the openMA root instance  -----
        trialConstructorFilter = nexusFilters.NexusConstructTrialFilter(
            DATA_PATH, modelledFilenameNoExt, subject)
        openmaTrial = trialConstructorFilter.build()

        # --------------------pyCGM2 MODEL ------------------------------
        model = files.loadModel(DATA_PATH, subject)
        modelVersion = model.version

        # --------------------------PROCESSING --------------------------------
        analysisInstance = analysis.makeAnalysis(
            DATA_PATH, [modelledFilename],
            pointLabelSuffix=pointSuffix,
            openmaTrials=[openmaTrial]
        )  # analysis structure gathering Time-normalized Kinematic and kinetic CGM outputs
        plot.plot_spatioTemporal(DATA_PATH,
                                 analysisInstance,
                                 exportPdf=True,
                                 outputName=modelledFilename)

    else:
        raise Exception("NO Nexus connection. Turn on Nexus")
예제 #14
0
def main(args):
    DATA_PATH = os.getcwd()+"\\"
    userSettings = files.openFile(DATA_PATH,args.userFile)

    manager = ProcessingManager.GaitProcessingConfigManager(userSettings,modelVersion=None)

    modelledTrials = [str(trialFilename[:-4]+"-pyCGM2modelled.c3d") for trialFilename in manager.modelledTrials]

    analysisInstance = analysis.makeAnalysis(
            DATA_PATH,modelledTrials,
            subjectInfo=manager.subjectInfo,
            experimentalInfo=manager.experimentalInfo,
            modelInfo=None,
            pointLabelSuffix=manager.pointSuffix)

    plot.plot_spatioTemporal(DATA_PATH,analysisInstance,
        exportPdf=True,
        outputName=manager.title)

    for body in manager.bodyPart:
        if not manager.consistencyFlag:
            plot.plot_DescriptiveKinematic(DATA_PATH,analysisInstance,body,
                manager.normativeData,
                exportPdf=True,
                outputName=manager.title,
                pointLabelSuffix=manager.pointSuffix)
            try:
                plot.plot_DescriptiveKinetic(DATA_PATH,analysisInstance,body,
                    manager.normativeData,
                    exportPdf=True,outputName=manager.title,
                    pointLabelSuffix=manager.pointSuffix)
            except:
                pass

        else:

            plot.plot_ConsistencyKinematic(DATA_PATH,analysisInstance,body,
                manager.normativeData,
                exportPdf=True,
                outputName=manager.title,
                pointLabelSuffix=manager.pointSuffix)

            try:
                plot.plot_ConsistencyKinetic(DATA_PATH,analysisInstance,body,
                    manager.normativeData,
                    exportPdf=True,outputName=manager.title,
                    pointLabelSuffix=manager.pointSuffix)
            except:
                pass

    plot.plot_MAP(DATA_PATH,analysisInstance,manager.normativeData,exportPdf=True,outputName=manager.title,pointLabelSuffix=manager.pointSuffix)
예제 #15
0
def dataTest2():
    DATA_PATH = pyCGM2.TEST_DATA_PATH + "GaitData\\Patient\\session 1 - CGM1\\"
    modelledFilenames = ["20180706_CS_PONC_S_NNNN dyn 02.c3d",
                        "20180706_CS_PONC_S_NNNN dyn 03.c3d",
                        "20180706_CS_PONC_S_NNNN dyn 05.c3d"]


    analysisInstance = analysis.makeAnalysis(DATA_PATH,
                        modelledFilenames,
                        type="Gait",
                        emgChannels = emgChannels,
                        pointLabelSuffix=None,
                        subjectInfo=None, experimentalInfo=None,modelInfo=None,
                        )

    return DATA_PATH,modelledFilenames,analysisInstance
예제 #16
0
    def consistencyPlot_OneModelOutputPlot(cls):
        """
        Plot only one Model output
        """

        # ----DATA-----
        DATA_PATH = pyCGM2.TEST_DATA_PATH + "operations\\plot\\gaitPlot\\"
        modelledFilenames = ["gait Trial 03 - viconName.c3d"]

        #---- c3d manager
        #--------------------------------------------------------------------------
        c3dmanagerProcedure = c3dManager.UniqueC3dSetProcedure(
            DATA_PATH, modelledFilenames)
        cmf = c3dManager.C3dManagerFilter(c3dmanagerProcedure)
        cmf.enableEmg(False)
        trialManager = cmf.generate()

        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo = None
        subjectInfo = None
        experimentalInfo = None

        analysisInstance = analysis.makeAnalysis("Gait", "CGM1.0", DATA_PATH,
                                                 modelledFilenames, None, None,
                                                 None)

        fig = plt.figure()
        ax = plt.gca()
        plot.gaitConsistencyPlot(ax,
                                 analysisInstance.kinematicStats,
                                 "LPelvisAngles",
                                 "Left",
                                 0,
                                 color="blue",
                                 title="",
                                 xlabel="",
                                 ylabel="",
                                 ylim=None,
                                 customLimits=None)
        plt.show()
예제 #17
0
    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)
예제 #18
0
    def singleAnalysis(cls):

        # ----DATA-----
        DATA_PATH = pyCGM2.TEST_DATA_PATH + "operations\\plot\\gaitPlot\\"
        modelledFilenames = ["gait Trial 03 - viconName.c3d"]

        #---- c3d manager
        #--------------------------------------------------------------------------
        c3dmanagerProcedure = c3dManager.UniqueC3dSetProcedure(
            DATA_PATH, modelledFilenames)
        cmf = c3dManager.C3dManagerFilter(c3dmanagerProcedure)
        cmf.enableEmg(False)
        trialManager = cmf.generate()

        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo = None
        subjectInfo = None
        experimentalInfo = None

        analysisInstance = analysis.makeAnalysis("Gait", "CGM1.0", DATA_PATH,
                                                 modelledFilenames, None, None,
                                                 None)

        ndp = normativeDatasets.Schwartz2008("Free")
        gps = scores.CGM1_GPS()
        scf = scores.ScoreFilter(gps, analysisInstance, ndp)
        scf.compute()

        # viewer
        kv = plotViewers.GpsMapPlotViewer(analysisInstance)

        # filter
        pf = plotFilters.PlottingFilter()
        pf.setViewer(kv)
        pf.setPath(DATA_PATH)
        pf.setPdfName(str("map"))
        pf.plot()

        plt.show()
예제 #19
0
    def __init__(self, workingDirectory):
        self.workingDirectory = workingDirectory
        self.null = None

        c3dValObj = c3dValidation.c3dValidation(workingDirectory)
        self.measurementNames = c3dValObj.getValidC3dList(True)
        self.fileNames = c3dValObj.getValidC3dList(False)
        self.normative_dataset = normativeDatasets.NormativeData(
            "Schwartz2008", "Free")
        analysis_per_file = {
            path.basename(name).replace(".c3d", ""):
            analysis.makeAnalysis(workingDirectory + "\\",
                                  [path.basename(name)])
            for name in self.fileNames
        }
        self.scores = {}
        for filename, analysis_obj in analysis_per_file.items():
            gps = scores.CGM1_GPS(pointSuffix=None)
            scf = scores.ScoreFilter(gps, analysis_obj, self.normative_dataset)
            scf.compute()
            self.scores[filename] = analysis_obj
예제 #20
0
    def test_singleAnalysis(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"]

        #---- Analysis
        #--------------------------------------------------------------------------

        modelInfo = None
        subjectInfo = None
        experimentalInfo = None

        analysisInstance = analysis.makeAnalysis(DATA_PATH, modelledFilenames)

        # viewer
        kv = plotViewers.SpatioTemporalPlotViewer(analysisInstance)
        kv.setNormativeDataset(normativeDatasets.NormalSTP())

        # filter
        pf = plotFilters.PlottingFilter()
        pf.setViewer(kv)
        pf.plot()
예제 #21
0
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")
예제 #22
0
def main():

    plt.close("all")

    parser = argparse.ArgumentParser(
        description='CGM plot Normalized Kinematics')
    parser.add_argument(
        '-nd',
        '--normativeData',
        type=str,
        help='normative Data set (Schwartz2008 or Pinzone2014)',
        default="Schwartz2008")
    parser.add_argument(
        '-ndm',
        '--normativeDataModality',
        type=str,
        help=
        "if Schwartz2008 [VerySlow,SlowFree,Fast,VeryFast] - if Pinzone2014 [CentreOne,CentreTwo]",
        default="Free")
    parser.add_argument('-ps',
                        '--pointSuffix',
                        type=str,
                        help='suffix of model outputs')
    parser.add_argument('-c',
                        '--consistency',
                        action='store_true',
                        help='consistency plots')

    args = parser.parse_args()

    NEXUS = ViconNexus.ViconNexus()
    NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected()

    if NEXUS_PYTHON_CONNECTED:

        #-----------------------SETTINGS---------------------------------------
        normativeData = {
            "Author": args.normativeData,
            "Modality": args.normativeDataModality
        }

        if normativeData["Author"] == "Schwartz2008":
            chosenModality = normativeData["Modality"]
            nds = normativeDatasets.Schwartz2008(
                chosenModality
            )  # modalites : "Very Slow" ,"Slow", "Free", "Fast", "Very Fast"
        elif normativeData["Author"] == "Pinzone2014":
            chosenModality = normativeData["Modality"]
            nds = normativeDatasets.Pinzone2014(
                chosenModality)  # modalites : "Center One" ,"Center Two"

        consistencyFlag = True if args.consistency else False
        pointSuffix = args.pointSuffix

        # --------------------------INPUTS ------------------------------------
        DATA_PATH, modelledFilenameNoExt = NEXUS.GetTrialName()

        modelledFilename = modelledFilenameNoExt + ".c3d"

        logging.info("data Path: " + DATA_PATH)
        logging.info("file: " + modelledFilename)

        # ----- Subject -----
        # need subject to find input files
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.checkActivatedSubject(NEXUS, subjects)
        logging.info("Subject name : " + subject)

        # --------------------pyCGM2 MODEL ------------------------------
        model = files.loadModel(DATA_PATH, subject)
        modelVersion = model.version

        # ----- construction of the openMA root instance  -----
        trialConstructorFilter = nexusFilters.NexusConstructTrialFilter(
            DATA_PATH, modelledFilenameNoExt, subject)
        openmaTrial = trialConstructorFilter.build()

        # --------------------------PROCESSING --------------------------------
        analysisInstance = analysis.makeAnalysis(DATA_PATH, [modelledFilename],
                                                 pointLabelSuffix=pointSuffix,
                                                 openmaTrials=[openmaTrial])

        if not consistencyFlag:
            if model.m_bodypart in [
                    enums.BodyPart.LowerLimb, enums.BodyPart.LowerLimbTrunk,
                    enums.BodyPart.FullBody
            ]:
                plot.plot_DescriptiveKinematic(DATA_PATH,
                                               analysisInstance,
                                               "LowerLimb",
                                               nds,
                                               pointLabelSuffix=pointSuffix,
                                               exportPdf=True,
                                               outputName=modelledFilename)
                #plot_DescriptiveKinematic(DATA_PATH,analysis,bodyPart,normativeDataset,pointLabelSuffix=None,type="Gait",exportPdf=False,outputName=None):

            if model.m_bodypart in [
                    enums.BodyPart.LowerLimbTrunk, enums.BodyPart.FullBody
            ]:
                plot.plot_DescriptiveKinematic(DATA_PATH,
                                               analysisInstance,
                                               "Trunk",
                                               nds,
                                               pointLabelSuffix=pointSuffix,
                                               exportPdf=True,
                                               outputName=modelledFilename)
            if model.m_bodypart in [
                    enums.BodyPart.UpperLimb, enums.BodyPart.FullBody
            ]:
                pass  # TODO plot upperlimb panel

        else:
            if model.m_bodypart in [
                    enums.BodyPart.LowerLimb, enums.BodyPart.LowerLimbTrunk,
                    enums.BodyPart.FullBody
            ]:
                plot.plot_ConsistencyKinematic(DATA_PATH,
                                               analysisInstance,
                                               "LowerLimb",
                                               nds,
                                               pointLabelSuffix=pointSuffix,
                                               exportPdf=True,
                                               outputName=modelledFilename)
            if model.m_bodypart in [
                    enums.BodyPart.LowerLimbTrunk, enums.BodyPart.FullBody
            ]:
                plot.plot_ConsistencyKinematic(DATA_PATH,
                                               analysisInstance,
                                               "Trunk",
                                               nds,
                                               pointLabelSuffix=pointSuffix,
                                               exportPdf=True,
                                               outputName=modelledFilename)
            if model.m_bodypart in [
                    enums.BodyPart.UpperLimb, enums.BodyPart.FullBody
            ]:
                pass  # TODO plot upperlimb panel

    else:
        raise Exception("NO Nexus connection. Turn on Nexus")
예제 #23
0
def process_pdf_report(data_path,
                       modelled_trials,
                       title,
                       model,
                       normative_dataset,
                       point_suffix=None):
    analysisInstance = analysis.makeAnalysis(data_path + "\\",
                                             modelled_trials,
                                             subjectInfo=None,
                                             experimentalInfo=None,
                                             modelInfo=None,
                                             pointLabelSuffix=None)

    # 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",
                                       normative_dataset,
                                       exportPdf=True,
                                       outputName=title,
                                       pointLabelSuffix=point_suffix,
                                       show=False,
                                       title=title)

        plot.plot_ConsistencyKinematic(data_path,
                                       analysisInstance,
                                       "LowerLimb",
                                       normative_dataset,
                                       exportPdf=True,
                                       outputName=title,
                                       pointLabelSuffix=point_suffix,
                                       show=False,
                                       title=title)
    if model.m_bodypart in [
            enums.BodyPart.LowerLimbTrunk, enums.BodyPart.FullBody
    ]:
        plot.plot_DescriptiveKinematic(data_path,
                                       analysisInstance,
                                       "Trunk",
                                       normative_dataset,
                                       exportPdf=True,
                                       outputName=title,
                                       pointLabelSuffix=point_suffix,
                                       show=False,
                                       title=title)

        plot.plot_ConsistencyKinematic(data_path,
                                       analysisInstance,
                                       "Trunk",
                                       normative_dataset,
                                       exportPdf=True,
                                       outputName=title,
                                       pointLabelSuffix=point_suffix,
                                       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",
                                     normative_dataset,
                                     exportPdf=True,
                                     outputName=title,
                                     pointLabelSuffix=point_suffix,
                                     show=False,
                                     title=title)

        plot.plot_ConsistencyKinetic(data_path,
                                     analysisInstance,
                                     "LowerLimb",
                                     normative_dataset,
                                     exportPdf=True,
                                     outputName=title,
                                     pointLabelSuffix=point_suffix,
                                     show=False,
                                     title=title)

    # MAP
    plot.plot_MAP(data_path,
                  analysisInstance,
                  normative_dataset,
                  exportPdf=True,
                  outputName=title,
                  pointLabelSuffix=point_suffix,
                  show=False,
                  title=title)

    plt.show(False)
예제 #24
0
def main():

    plt.close("all")

    parser = argparse.ArgumentParser(description='CGM plotMAP')
    parser.add_argument(
        '-nd',
        '--normativeData',
        type=str,
        help='normative Data set (Schwartz2008 or Pinzone2014)',
        default="Schwartz2008")
    parser.add_argument(
        '-ndm',
        '--normativeDataModality',
        type=str,
        help=
        "if Schwartz2008 [VerySlow,SlowFree,Fast,VeryFast] - if Pinzone2014 [CentreOne,CentreTwo]",
        default="Free")
    parser.add_argument('-ps',
                        '--pointSuffix',
                        type=str,
                        help='suffix of model outputs')

    args = parser.parse_args()

    NEXUS = ViconNexus.ViconNexus()
    NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected()

    if not NEXUS_PYTHON_CONNECTED:
        raise Exception("Vicon Nexus is not running")

    #-----------------------SETTINGS---------------------------------------
    pointSuffix = args.pointSuffix

    #-----------------------SETTINGS---------------------------------------
    normativeData = {
        "Author": args.normativeData,
        "Modality": args.normativeDataModality
    }

    if normativeData["Author"] == "Schwartz2008":
        chosenModality = normativeData["Modality"]
    elif normativeData["Author"] == "Pinzone2014":
        chosenModality = normativeData["Modality"]
    nds = normativeDatasets.NormativeData(normativeData["Author"],
                                          chosenModality)

    #--------------------------Data Location and subject-------------------------------------
    if eclipse.getCurrentMarkedNodes() is not None:
        LOGGER.logger.info(
            "[pyCGM2] - Script worked with marked node of Vicon Eclipse")
        # --- acquisition file and path----
        DATA_PATH, modelledFilenames = eclipse.getCurrentMarkedNodes()
        ECLIPSE_MODE = True

    if not ECLIPSE_MODE:
        LOGGER.logger.info(
            "[pyCGM2] - Script works with the loaded c3d in vicon Nexus")
        # --- acquisition file and path----
        DATA_PATH, modelledFilenameNoExt = NEXUS.GetTrialName()
        modelledFilename = modelledFilenameNoExt + ".c3d"

        LOGGER.logger.info("data Path: " + DATA_PATH)
        LOGGER.logger.info("file: " + modelledFilename)

    # ----- Subject -----
    # need subject to find input files
    subject = nexusTools.getActiveSubject(NEXUS)
    LOGGER.logger.info("Subject name : " + subject)

    if not ECLIPSE_MODE:
        # btkAcq builder
        nacf = nexusFilters.NexusConstructAcquisitionFilter(
            DATA_PATH, modelledFilenameNoExt, subject)
        acq = nacf.build()

        # --------------------------PROCESSING --------------------------------
        analysisInstance = analysis.makeAnalysis(DATA_PATH, [modelledFilename],
                                                 type="Gait",
                                                 kineticLabelsDict=None,
                                                 emgChannels=None,
                                                 pointLabelSuffix=pointSuffix,
                                                 btkAcqs=[acq],
                                                 subjectInfo=None,
                                                 experimentalInfo=None,
                                                 modelInfo=None)

        outputName = modelledFilename
    else:
        analysisInstance = analysis.makeAnalysis(DATA_PATH,
                                                 type="Gait",
                                                 kineticLabelsDict=None,
                                                 emgChannels=None,
                                                 pointLabelSuffix=pointSuffix,
                                                 subjectInfo=None,
                                                 experimentalInfo=None,
                                                 modelInfo=None)

        outputName = "Eclipse-MAP"

    plot.plot_MAP(DATA_PATH,
                  analysisInstance,
                  nds,
                  exportPdf=True,
                  outputName=outputName,
                  pointLabelSuffix=pointSuffix)
예제 #25
0
def pdfGaitReport(DATA_PATH,
                  model,
                  modelledTrials,
                  normativeDataset,
                  pointSuffix,
                  title="gait report"):

    analysisInstance = analysis.makeAnalysis(DATA_PATH,
                                             modelledTrials,
                                             subjectInfo=None,
                                             experimentalInfo=None,
                                             modelInfo=None,
                                             pointLabelSuffix=None)

    with PdfPages(DATA_PATH + title + ".pdf") as pdf:
        # spatiotemporal
        plot.plot_spatioTemporal(DATA_PATH,
                                 analysisInstance,
                                 exportPdf=False,
                                 outputName=title,
                                 show=None,
                                 title=title)
        pdf.savefig()

        #Kinematics
        if model.m_bodypart in [
                enums.BodyPart.LowerLimb, enums.BodyPart.LowerLimbTrunk,
                enums.BodyPart.FullBody
        ]:
            plot.plot_DescriptiveKinematic(DATA_PATH,
                                           analysisInstance,
                                           "LowerLimb",
                                           normativeDataset,
                                           exportPdf=False,
                                           outputName=title,
                                           pointLabelSuffix=pointSuffix,
                                           show=False,
                                           title=title)
            pdf.savefig()

            plot.plot_ConsistencyKinematic(DATA_PATH,
                                           analysisInstance,
                                           "LowerLimb",
                                           normativeDataset,
                                           exportPdf=False,
                                           outputName=title,
                                           pointLabelSuffix=pointSuffix,
                                           show=False,
                                           title=title)
            pdf.savefig()

        if model.m_bodypart in [
                enums.BodyPart.LowerLimbTrunk, enums.BodyPart.FullBody
        ]:
            plot.plot_DescriptiveKinematic(DATA_PATH,
                                           analysisInstance,
                                           "Trunk",
                                           normativeDataset,
                                           exportPdf=False,
                                           outputName=title,
                                           pointLabelSuffix=pointSuffix,
                                           show=False,
                                           title=title)
            pdf.savefig()

            plot.plot_ConsistencyKinematic(DATA_PATH,
                                           analysisInstance,
                                           "Trunk",
                                           normativeDataset,
                                           exportPdf=False,
                                           outputName=title,
                                           pointLabelSuffix=pointSuffix,
                                           show=False,
                                           title=title)
            pdf.savefig()

        if model.m_bodypart in [
                enums.BodyPart.UpperLimb, enums.BodyPart.FullBody
        ]:
            plot.plot_DescriptiveKinematic(DATA_PATH,
                                           analysisInstance,
                                           "UpperLimb",
                                           normativeDataset,
                                           exportPdf=False,
                                           outputName=title,
                                           pointLabelSuffix=pointSuffix,
                                           show=False,
                                           title=title)
            pdf.savefig()

            plot.plot_ConsistencyKinematic(DATA_PATH,
                                           analysisInstance,
                                           "UpperLimb",
                                           normativeDataset,
                                           exportPdf=False,
                                           outputName=title,
                                           pointLabelSuffix=pointSuffix,
                                           show=False,
                                           title=title)
            pdf.savefig()

        #Kinetics
        if model.m_bodypart in [
                enums.BodyPart.LowerLimb, enums.BodyPart.LowerLimbTrunk,
                enums.BodyPart.FullBody
        ]:
            plot.plot_DescriptiveKinetic(DATA_PATH,
                                         analysisInstance,
                                         "LowerLimb",
                                         normativeDataset,
                                         exportPdf=False,
                                         outputName=title,
                                         pointLabelSuffix=pointSuffix,
                                         show=False,
                                         title=title)
            pdf.savefig()

            plot.plot_ConsistencyKinetic(DATA_PATH,
                                         analysisInstance,
                                         "LowerLimb",
                                         normativeDataset,
                                         exportPdf=False,
                                         outputName=title,
                                         pointLabelSuffix=pointSuffix,
                                         show=False,
                                         title=title)
            pdf.savefig()

        #MAP
        plot.plot_MAP(DATA_PATH,
                      analysisInstance,
                      normativeDataset,
                      exportPdf=False,
                      outputName=title,
                      pointLabelSuffix=pointSuffix,
                      show=False,
                      title=title)
        pdf.savefig()

        plt.show(False)
        logging.info("----- Gait Processing -----> DONE")
예제 #26
0
def main():

    plt.close("all")

    parser = argparse.ArgumentParser(description='CGM plot stp')
    parser.add_argument('-ps',
                        '--pointSuffix',
                        type=str,
                        help='suffix added to pyCGM2 outputs')
    args = parser.parse_args()

    NEXUS = ViconNexus.ViconNexus()
    NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected()
    ECLIPSE_MODE = False

    if not NEXUS_PYTHON_CONNECTED:
        raise Exception("Vicon Nexus is not running")

    pointSuffix = args.pointSuffix

    #--------------------------Data Location and subject-------------------------------------
    if eclipse.getCurrentMarkedNodes() is not None:
        LOGGER.logger.info(
            "[pyCGM2] - Script worked with marked node of Vicon Eclipse")
        # --- acquisition file and path----
        DATA_PATH, modelledFilenames = eclipse.getCurrentMarkedNodes()
        ECLIPSE_MODE = True

    if not ECLIPSE_MODE:
        LOGGER.logger.info(
            "[pyCGM2] - Script works with the loaded c3d in vicon Nexus")

        # --------------------------INPUTS ------------------------------------
        DATA_PATH, modelledFilenameNoExt = NEXUS.GetTrialName()

        modelledFilename = modelledFilenameNoExt + ".c3d"

        LOGGER.logger.info("data Path: " + DATA_PATH)
        LOGGER.logger.info("file: " + modelledFilename)

    # ----- Subject -----
    # need subject to find input files
    # subjects = NEXUS.GetSubjectNames()
    subject = nexusTools.getActiveSubject(NEXUS)
    LOGGER.logger.info("Subject name : " + subject)

    if not ECLIPSE_MODE:
        # btkAcq builder
        nacf = nexusFilters.NexusConstructAcquisitionFilter(
            DATA_PATH, modelledFilenameNoExt, subject)
        acq = nacf.build()

        # --------------------------PROCESSING --------------------------------
        analysisInstance = analysis.makeAnalysis(DATA_PATH, [modelledFilename],
                                                 type="Gait",
                                                 kineticLabelsDict=None,
                                                 emgChannels=None,
                                                 pointLabelSuffix=pointSuffix,
                                                 btkAcqs=[acq],
                                                 subjectInfo=None,
                                                 experimentalInfo=None,
                                                 modelInfo=None)

        outputName = modelledFilename
    else:
        # --------------------------PROCESSING --------------------------------
        analysisInstance = analysis.makeAnalysis(DATA_PATH,
                                                 modelledFilenames,
                                                 type="Gait",
                                                 kineticLabelsDict=None,
                                                 emgChannels=None,
                                                 pointLabelSuffix=pointSuffix,
                                                 subjectInfo=None,
                                                 experimentalInfo=None,
                                                 modelInfo=None)
        outputName = "Eclipse - SpatioTemporal parameters"

    plot.plot_spatioTemporal(DATA_PATH,
                             analysisInstance,
                             exportPdf=True,
                             outputName=outputName)
예제 #27
0
파일: report.py 프로젝트: sremm/pyCGM2
def pdfGaitReport(DATA_PATH,
                  model,
                  modelledTrials,
                  normativeDataset,
                  pointSuffix,
                  title="gait report"):

    analysisInstance = analysis.makeAnalysis(
        DATA_PATH,
        modelledTrials,
        type="Gait",
        emgChannels=None,
        pointLabelSuffix=None,
        subjectInfo=None,
        experimentalInfo=None,
        modelInfo=None,
    )

    analysis.exportAnalysis(analysisInstance,
                            DATA_PATH,
                            title,
                            mode="Advanced")

    with PdfPages(DATA_PATH + title + ".pdf") as pdf:
        # spatiotemporal
        plot.plot_spatioTemporal(DATA_PATH,
                                 analysisInstance,
                                 exportPdf=False,
                                 outputName=title,
                                 show=None,
                                 title=title)
        pdf.savefig()

        #Kinematics
        plot.plot_DescriptiveKinematic(DATA_PATH,
                                       analysisInstance,
                                       "LowerLimb",
                                       normativeDataset,
                                       exportPdf=False,
                                       outputName=title,
                                       pointLabelSuffix=pointSuffix,
                                       show=False,
                                       title=title)
        pdf.savefig()

        plot.plot_ConsistencyKinematic(DATA_PATH,
                                       analysisInstance,
                                       "LowerLimb",
                                       normativeDataset,
                                       exportPdf=False,
                                       outputName=title,
                                       pointLabelSuffix=pointSuffix,
                                       show=False,
                                       title=title)
        pdf.savefig()

        plot.plot_DescriptiveKinematic(DATA_PATH,
                                       analysisInstance,
                                       "Trunk",
                                       normativeDataset,
                                       exportPdf=False,
                                       outputName=title,
                                       pointLabelSuffix=pointSuffix,
                                       show=False,
                                       title=title)
        pdf.savefig()

        plot.plot_ConsistencyKinematic(DATA_PATH,
                                       analysisInstance,
                                       "Trunk",
                                       normativeDataset,
                                       exportPdf=False,
                                       outputName=title,
                                       pointLabelSuffix=pointSuffix,
                                       show=False,
                                       title=title)
        pdf.savefig()

        plot.plot_DescriptiveKinematic(DATA_PATH,
                                       analysisInstance,
                                       "UpperLimb",
                                       normativeDataset,
                                       exportPdf=False,
                                       outputName=title,
                                       pointLabelSuffix=pointSuffix,
                                       show=False,
                                       title=title)
        pdf.savefig()

        plot.plot_ConsistencyKinematic(DATA_PATH,
                                       analysisInstance,
                                       "UpperLimb",
                                       normativeDataset,
                                       exportPdf=False,
                                       outputName=title,
                                       pointLabelSuffix=pointSuffix,
                                       show=False,
                                       title=title)
        pdf.savefig()

        #Kinetics
        plot.plot_DescriptiveKinetic(DATA_PATH,
                                     analysisInstance,
                                     "LowerLimb",
                                     normativeDataset,
                                     exportPdf=False,
                                     outputName=title,
                                     pointLabelSuffix=pointSuffix,
                                     show=False,
                                     title=title)
        pdf.savefig()

        plot.plot_ConsistencyKinetic(DATA_PATH,
                                     analysisInstance,
                                     "LowerLimb",
                                     normativeDataset,
                                     exportPdf=False,
                                     outputName=title,
                                     pointLabelSuffix=pointSuffix,
                                     show=False,
                                     title=title)
        pdf.savefig()

        #MAP
        plot.plot_MAP(DATA_PATH,
                      analysisInstance,
                      normativeDataset,
                      exportPdf=False,
                      outputName=title,
                      pointLabelSuffix=pointSuffix,
                      show=False,
                      title=title)
        pdf.savefig()
예제 #28
0
def main():

    parser = argparse.ArgumentParser(description='EMG-plot_temporalEMG')
    parser.add_argument('-bpf', '--BandpassFrequencies', nargs='+',help='bandpass filter')
    parser.add_argument('-elf','--EnvelopLowpassFrequency', type=int, help='cutoff frequency for emg envelops')
    parser.add_argument('-c','--consistency', action='store_true', help='consistency plots')
    args = parser.parse_args()


    NEXUS = ViconNexus.ViconNexus()
    NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected()
    ECLIPSE_MODE = False

    if not NEXUS_PYTHON_CONNECTED:
        raise Exception("Vicon Nexus is not running")

    #--------------------------Data Location-------------------------------------
    if eclipse.getCurrentMarkedNodes() is not None:
        LOGGER.logger.info("[pyCGM2] - Script worked with marked node of Vicon Eclipse")
        # --- acquisition file and path----
        DATA_PATH, inputFiles =eclipse.getCurrentMarkedNodes()
        ECLIPSE_MODE = True

    if not ECLIPSE_MODE:
        LOGGER.logger.info("[pyCGM2] - Script works with the loaded c3d in vicon Nexus")
        # --- acquisition file and path----
        DATA_PATH, inputFileNoExt = NEXUS.GetTrialName()
        inputFile = inputFileNoExt+".c3d"

    LOGGER.set_file_handler(DATA_PATH+"pyCGM2.log")
    #--------------------------settings-------------------------------------
    if os.path.isfile(DATA_PATH + "emg.settings"):
        emgSettings = files.openFile(DATA_PATH,"emg.settings")
        LOGGER.logger.warning("[pyCGM2]: emg.settings detected in the data folder")
    else:
        emgSettings = None

    manager = EmgManager.EmgConfigManager(None,localInternalSettings=emgSettings)
    manager.contruct()


    # ----------------------INPUTS-------------------------------------------
    bandPassFilterFrequencies = manager.BandpassFrequencies#emgSettings["Processing"]["BandpassFrequencies"]
    if args.BandpassFrequencies is not None:
        if len(args.BandpassFrequencies) != 2:
            raise Exception("[pyCGM2] - bad configuration of the bandpass frequencies ... set 2 frequencies only")
        else:
            bandPassFilterFrequencies = [float(args.BandpassFrequencies[0]),float(args.BandpassFrequencies[1])]
            LOGGER.logger.info("Band pass frequency set to %i - %i instead of 20-200Hz",bandPassFilterFrequencies[0],bandPassFilterFrequencies[1])

    envelopCutOffFrequency = manager.EnvelopLowpassFrequency#emgSettings["Processing"]["EnvelopLowpassFrequency"]
    if args.EnvelopLowpassFrequency is not None:
        envelopCutOffFrequency =  args.EnvelopLowpassFrequency
        LOGGER.logger.info("Cut-off frequency set to %i instead of 6Hz ",envelopCutOffFrequency)

    consistencyFlag = True if args.consistency else False

    # --------------emg Processing--------------
    EMG_LABELS,EMG_MUSCLES,EMG_CONTEXT,NORMAL_ACTIVITIES  =  manager.getEmgConfiguration()

    if not ECLIPSE_MODE:
        # --------------------------SUBJECT ------------------------------------
        subject = nexusTools.getActiveSubject(NEXUS)

        # btkAcq builder
        nacf = nexusFilters.NexusConstructAcquisitionFilter(DATA_PATH,inputFileNoExt,subject)
        acq = nacf.build()

        emg.processEMG_fromBtkAcq(acq, EMG_LABELS,
            highPassFrequencies=bandPassFilterFrequencies,
            envelopFrequency=envelopCutOffFrequency) # high pass then low pass for all c3ds

        # emgAnalysis = analysis.makeEmgAnalysis(DATA_PATH, [inputFile], EMG_LABELS,btkAcqs = [acq])

        emgAnalysis = analysis.makeAnalysis(DATA_PATH,
                            [inputFile],
                            type="Gait",
                            kinematicLabelsDict=None,
                            kineticLabelsDict=None,
                            emgChannels = EMG_LABELS,
                            pointLabelSuffix=None,
                            btkAcqs=[acq],
                            subjectInfo=None, experimentalInfo=None,modelInfo=None,
                            )

        outputName = inputFile
    else:

        emg.processEMG(DATA_PATH, inputFiles, EMG_LABELS, highPassFrequencies=bandPassFilterFrequencies,
            envelopFrequency=envelopCutOffFrequency)

        emgAnalysis = analysis.makeAnalysis(DATA_PATH,
                            [inputFile],
                            type="Gait",
                            kinematicLabelsDict=None,
                            kineticLabelsDict=None,
                            emgChannels = EMG_LABELS,
                            pointLabelSuffix=None,
                            subjectInfo=None, experimentalInfo=None,modelInfo=None,
                            )

        outputName = "Eclipse -  NormalizedEMG"


    if not consistencyFlag:
        plot.plotDescriptiveEnvelopEMGpanel(DATA_PATH,emgAnalysis, EMG_LABELS,EMG_MUSCLES,EMG_CONTEXT, NORMAL_ACTIVITIES, normalized=False,exportPdf=True,outputName=outputName)
    else:
        plot.plotConsistencyEnvelopEMGpanel(DATA_PATH,emgAnalysis, EMG_LABELS,EMG_MUSCLES,EMG_CONTEXT, NORMAL_ACTIVITIES, normalized=False,exportPdf=True,outputName=outputName)
예제 #29
0
def main(args):

    NEXUS = ViconNexus.ViconNexus()
    NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected()

    if NEXUS_PYTHON_CONNECTED:

        #-----------------------SETTINGS---------------------------------------
        pointSuffix = args.pointSuffix
        normativeData = {
            "Author": args.normativeData,
            "Modality": args.normativeDataModality
        }

        if normativeData["Author"] == "Schwartz2008":
            chosenModality = normativeData["Modality"]
            nds = normativeDatasets.Schwartz2008(
                chosenModality
            )  # modalites : "Very Slow" ,"Slow", "Free", "Fast", "Very Fast"
        elif normativeData["Author"] == "Pinzone2014":
            chosenModality = normativeData["Modality"]
            nds = normativeDatasets.Pinzone2014(
                chosenModality)  # modalites : "Center One" ,"Center Two"

        consistencyFlag = True if args.consistency else False

        # --------------------------INPUTS ------------------------------------
        DATA_PATH, modelledFilenameNoExt = NEXUS.GetTrialName()

        modelledFilename = modelledFilenameNoExt + ".c3d"

        logging.info("data Path: " + DATA_PATH)
        logging.info("file: " + modelledFilename)

        # ----- Subject -----
        # need subject to find input files
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.checkActivatedSubject(NEXUS, subjects)
        logging.info("Subject name : " + subject)

        # ----- construction of the openMA root instance  -----
        trialConstructorFilter = nexusFilters.NexusConstructTrialFilter(
            DATA_PATH, modelledFilenameNoExt, subject)
        openmaTrial = trialConstructorFilter.build()

        # --------------------pyCGM2 MODEL ------------------------------
        model = files.loadModel(DATA_PATH, subject)
        modelVersion = model.version

        # --------------------------PROCESSING --------------------------------
        analysisInstance = analysis.makeAnalysis(
            DATA_PATH, [modelledFilename],
            pointLabelSuffix=pointSuffix,
            openmaTrials=[openmaTrial]
        )  # analysis structure gathering Time-normalized Kinematic and kinetic CGM outputs

        if not consistencyFlag:
            if model.m_bodypart in [
                    enums.BodyPart.LowerLimb, enums.BodyPart.LowerLimbTrunk,
                    enums.BodyPart.FullBody
            ]:
                plot.plot_DescriptiveKinetic(DATA_PATH,
                                             analysisInstance,
                                             "LowerLimb",
                                             nds,
                                             pointLabelSuffix=pointSuffix,
                                             exportPdf=True,
                                             outputName=modelledFilename)
        else:
            if model.m_bodypart in [
                    enums.BodyPart.LowerLimb, enums.BodyPart.LowerLimbTrunk,
                    enums.BodyPart.FullBody
            ]:
                plot.plot_ConsistencyKinetic(DATA_PATH,
                                             analysisInstance,
                                             "LowerLimb",
                                             nds,
                                             pointLabelSuffix=pointSuffix,
                                             exportPdf=True,
                                             outputName=modelledFilename)
    else:
        raise Exception("NO Nexus connection. Turn on Nexus")
예제 #30
0
def main():

    plt.close("all")

    parser = argparse.ArgumentParser(description='CGM plotMAP')
    parser.add_argument(
        '-nd',
        '--normativeData',
        type=str,
        help='normative Data set (Schwartz2008 or Pinzone2014)',
        default="Schwartz2008")
    parser.add_argument(
        '-ndm',
        '--normativeDataModality',
        type=str,
        help=
        "if Schwartz2008 [VerySlow,SlowFree,Fast,VeryFast] - if Pinzone2014 [CentreOne,CentreTwo]",
        default="Free")
    parser.add_argument('-ps',
                        '--pointSuffix',
                        type=str,
                        help='suffix of model outputs')

    args = parser.parse_args()

    NEXUS = ViconNexus.ViconNexus()
    NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected()

    if NEXUS_PYTHON_CONNECTED:

        #-----------------------SETTINGS---------------------------------------
        pointSuffix = args.pointSuffix

        normativeData = {
            "Author": args.normativeData,
            "Modality": args.normativeDataModality
        }

        if normativeData["Author"] == "Schwartz2008":
            chosenModality = normativeData["Modality"]
            nds = normativeDatasets.Schwartz2008(
                chosenModality
            )  # modalites : "Very Slow" ,"Slow", "Free", "Fast", "Very Fast"
        elif normativeData["Author"] == "Pinzone2014":
            chosenModality = normativeData["Modality"]
            nds = normativeDatasets.Pinzone2014(
                chosenModality)  # modalites : "Center One" ,"Center Two"

        # --------------------------INPUTS ------------------------------------
        DATA_PATH, modelledFilenameNoExt = NEXUS.GetTrialName()

        modelledFilename = modelledFilenameNoExt + ".c3d"

        logging.info("data Path: " + DATA_PATH)
        logging.info("file: " + modelledFilename)

        # ----- Subject -----
        # need subject to find input files
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.checkActivatedSubject(NEXUS, subjects)
        logging.info("Subject name : " + subject)

        # ----- construction of the openMA root instance  -----
        trialConstructorFilter = nexusFilters.NexusConstructTrialFilter(
            DATA_PATH, modelledFilenameNoExt, subject)
        openmaTrial = trialConstructorFilter.build()

        # --------------------pyCGM2 MODEL ------------------------------
        model = files.loadModel(DATA_PATH, subject)
        modelVersion = model.version

        # --------------------------PROCESSING --------------------------------
        analysisInstance = analysis.makeAnalysis(
            DATA_PATH, [modelledFilename],
            None,
            None,
            None,
            pointLabelSuffix=pointSuffix,
            openmaTrials=[openmaTrial]
        )  # analysis structure gathering Time-normalized Kinematic and kinetic CGM outputs
        plot.plot_MAP(DATA_PATH,
                      analysisInstance,
                      nds,
                      exportPdf=True,
                      outputName=modelledFilename,
                      pointLabelSuffix=pointSuffix)

    else:
        raise Exception("NO Nexus connection. Turn on Nexus")