예제 #1
0
    def test__highLevel_customNormative_plot_MAP(self):
        DATA_PATH, modelledFilenames, analysisInstance = dataTest2()
        normativeDataset = normativeDatasets.NormativeData("CGM23", "Spont")

        fig = plot.plot_MAP(DATA_PATH,
                            analysisInstance,
                            normativeDataset,
                            exportPdf=False,
                            outputName=None,
                            pointLabelSuffix=None,
                            show=False,
                            title=None)

        if SHOW: plt.show()
        return fig
예제 #2
0
    def test_lowLevel_NormalizedKinematicsPlotViewer(self):

        DATA_PATH, analysisInstance = dataTest1()
        normativeDataset = normativeDatasets.NormativeData(
            "Schwartz2008", "Free")
        # viewer
        kv = plotViewers.NormalizedKinematicsPlotViewer(analysisInstance)
        kv.setConcretePlotFunction(reportPlot.gaitDescriptivePlot)
        kv.setNormativeDataset(normativeDataset)

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

        if SHOW: plt.show()
        return fig
예제 #3
0
    def test_highLevel_customNormative_gaitPanel_descriptiveKinetics(self):

        DATA_PATH, analysisInstance = dataTest1()
        normativeDataset = normativeDatasets.NormativeData("CGM23", "Spont")

        fig = plot.plot_DescriptiveKinetic(DATA_PATH,
                                           analysisInstance,
                                           "LowerLimb",
                                           normativeDataset,
                                           pointLabelSuffix=None,
                                           type="Gait",
                                           exportPdf=False,
                                           outputName=None,
                                           show=False,
                                           title=None)

        if SHOW: plt.show()
        return fig
예제 #4
0
    def test_highLevel_gaitPanel_consistencyKinetics(self):
        DATA_PATH, analysisInstance = dataTest1()
        normativeDataset = normativeDatasets.NormativeData(
            "Schwartz2008", "Free")

        fig = plot.plot_ConsistencyKinetic(DATA_PATH,
                                           analysisInstance,
                                           "LowerLimb",
                                           normativeDataset,
                                           pointLabelSuffix=None,
                                           type="Gait",
                                           exportPdf=False,
                                           outputName=None,
                                           show=False,
                                           title=None)

        if SHOW: plt.show()
        return fig
예제 #5
0
    def test_Schwartz2008(self):

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

        nds2 = normativeDatasets.Schwartz2008("Free")
        nds2.constructNormativeData()

        np.testing.assert_almost_equal(nds.data["PelvisAngles"]["mean"],
                                       nds2.data["Pelvis.Angles"]["mean"],
                                       decimal=3)
        np.testing.assert_almost_equal(nds.data["HipAngles"]["mean"],
                                       nds2.data["Hip.Angles"]["mean"],
                                       decimal=3)
        np.testing.assert_almost_equal(nds.data["KneeAngles"]["mean"],
                                       nds2.data["Knee.Angles"]["mean"],
                                       decimal=3)
        np.testing.assert_almost_equal(nds.data["AnkleAngles"]["mean"],
                                       nds2.data["Ankle.Angles"]["mean"],
                                       decimal=3)
        np.testing.assert_almost_equal(nds.data["FootProgressAngles"]["mean"],
                                       nds2.data["Foot.Angles"]["mean"],
                                       decimal=3)

        np.testing.assert_almost_equal(nds.data["HipMoment"]["mean"],
                                       nds2.data["Hip.Moment"]["mean"],
                                       decimal=3)
        np.testing.assert_almost_equal(nds.data["KneeMoment"]["mean"],
                                       nds2.data["Knee.Moment"]["mean"],
                                       decimal=3)
        np.testing.assert_almost_equal(nds.data["AnkleMoment"]["mean"],
                                       nds2.data["Ankle.Moment"]["mean"],
                                       decimal=3)

        np.testing.assert_almost_equal(nds.data["HipPower"]["mean"],
                                       nds2.data["Hip.Power"]["mean"],
                                       decimal=3)
        np.testing.assert_almost_equal(nds.data["KneePower"]["mean"],
                                       nds2.data["Knee.Power"]["mean"],
                                       decimal=3)
        np.testing.assert_almost_equal(nds.data["AnklePower"]["mean"],
                                       nds2.data["Ankle.Power"]["mean"],
                                       decimal=3)
예제 #6
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
예제 #7
0
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")
예제 #8
0
# coding: utf-8
#pytest -s --disable-pytest-warnings  test_GPS.py::Test_GPS::test_CGM1
# from __future__ import unicode_literals

import pyCGM2
from pyCGM2.Lib import analysis
from pyCGM2.Processing import scores

from pyCGM2.Report import normativeDatasets


normativeDataset = normativeDatasets.Schwartz2008("Free")
newNormativeDataset = normativeDatasets.NormativeData("Schwartz2008","Free")

emgChannels=['Voltage.EMG1','Voltage.EMG2','Voltage.EMG3','Voltage.EMG4','Voltage.EMG5',
            'Voltage.EMG6','Voltage.EMG7','Voltage.EMG8','Voltage.EMG9','Voltage.EMG10']

muscles=['RF','RF','VL','VL','HAM',
            'HAM','TI','TI','SOL','SOL']

contexts=['Left','Right','Left','Right','Left',
            'Right','Left','Right','Left','Right']

normalActivityEmgs=['RECFEM','RECFEM', None,None,None,
            None,None,None,None,None]


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,
예제 #9
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)
예제 #10
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()
    ECLIPSE_MODE = False

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


    #--------------------------Data Location and subject-------------------------------------
    if eclipse.getCurrentMarkedNodes() is None:
        raise Exception("No nodes marked")
    else:
        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 len(modelledFilenames)== 1:   raise Exception("Only one node marked")


    subject = nexusTools.getActiveSubject(NEXUS)
    LOGGER.logger.info(  "Subject name : " + subject  )

    #-----------------------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)

    consistencyFlag = True if args.consistency else False
    plotType = "Consistency" if consistencyFlag else "Descriptive"

    pointSuffix = args.pointSuffix

    if  ECLIPSE_MODE:

        if len(modelledFilenames) == 2:

            analysisInstance1 = analysis.makeAnalysis(DATA_PATH,
                                [modelledFilenames[0]],
                                type="Gait",
                                kinematicLabelsDict=None,
                                emgChannels = None,
                                pointLabelSuffix=pointSuffix,
                                subjectInfo=None, experimentalInfo=None,modelInfo=None,
                                )

            analysisInstance2 = analysisInstance1 = analysis.makeAnalysis(DATA_PATH,
                                [modelledFilenames[1]],
                                type="Gait",
                                kinematicLabelsDict=None,
                                emgChannels = None,
                                pointLabelSuffix=pointSuffix,
                                subjectInfo=None, experimentalInfo=None,modelInfo=None,
                                )

            # outputName = "Eclipse - CompareNormalizedKinematics"
        #
        analysesToCompare = [analysisInstance1, analysisInstance2]
        comparisonDetails =  modelledFilenames[0] + " Vs " + modelledFilenames[1]
        legends =[modelledFilenames[0],modelledFilenames[1]]

        plot.compareKinetic(DATA_PATH,analysesToCompare,legends,"Left","LowerLimb",nds,plotType=plotType,type="Gait",pointSuffixes=None,
                show=False, outputName=comparisonDetails,exportPdf=True)

        plot.compareKinetic(DATA_PATH,analysesToCompare,legends,"Right","LowerLimb",nds,plotType=plotType,type="Gait",pointSuffixes=None,
                show=False, outputName=comparisonDetails,exportPdf=True)

        plt.show()