Exemple #1
0
 def __internalsettings(self):
     if self._localInternalSettings is None:
         if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "emg.settings"):
             self._internSettings = files.openFile(
                 pyCGM2.PYCGM2_APPDATA_PATH, "emg.settings")
         else:
             self._internSettings = files.openFile(
                 pyCGM2.PYCGM2_SETTINGS_FOLDER, "emg.settings")
     else:
         LOGGER.logger.info("Local internal setting found")
         self._internSettings = self._localInternalSettings
Exemple #2
0
 def __internalsettings(self):
     if self._localInternalSettings is None:
         if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH +
                           "CGM2_5-pyCGM2.settings"):
             self._internSettings = files.openFile(
                 pyCGM2.PYCGM2_APPDATA_PATH, "CGM2_5-pyCGM2.settings")
         else:
             self._internSettings = files.openFile(
                 pyCGM2.PYCGM2_SETTINGS_FOLDER, "CGM2_5-pyCGM2.settings")
     else:
         self._internSettings = self._localInternalSettings
Exemple #3
0
    def customTranslators(cls):

        DATA_PATH = pyCGM2.TEST_DATA_PATH + "Configurator\\CGM1\\customTranslators\\"

        #internalSettings = files.openFile(pyCGM2_GLOBAL_SETTINGS_PATH,"CGM1-pyCGM2.settings")

        userSettings = files.openFile(DATA_PATH, "CGM1.userSettings")
        translators = files.openFile(DATA_PATH, "CGM1.translators")

        manager = ModelManager.CGM1ConfigManager(userSettings,
                                                 localTranslators=translators)
        manager.contruct()
        manager.getFinalSettings()
Exemple #4
0
    def test_openFile(self):

        contentYaml = files.openFile(
            pyCGM2.TEST_DATA_PATH + "\\LowLevel\\IO\\Hanibal_files\\",
            "file.yaml")
        contentJson = files.openFile(
            pyCGM2.TEST_DATA_PATH + "\\LowLevel\\IO\\Hanibal_files\\",
            "file.json")

        assert contentYaml != False
        assert contentJson != False

        files.saveJson(
            pyCGM2.TEST_DATA_PATH + "\\LowLevel\\IO\\Hanibal_files\\",
            "testJsonOut", contentJson)
Exemple #5
0
    def test_temporalEmgPlot(self):

        # ----DATA-----
        DATA_PATH = pyCGM2.TEST_DATA_PATH+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\"
        gaitTrial = "PRE-gait trial 01.c3d"
        restTrial = "PRE-repos.c3d"

        DATA_PATH_OUT = pyCGM2.TEST_DATA_PATH_OUT+"GaitData\\EMG\\Hånnibøl Lecter-nerve block\\"
        files.createDir(DATA_PATH_OUT)

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


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

        EMG_LABELS,EMG_MUSCLES,EMG_CONTEXT,NORMAL_ACTIVITIES  =  manager.getEmgConfiguration()

        rectifyBool=True

        acq = btkTools.smartReader(DATA_PATH+gaitTrial)


        analysis.processEMG_fromBtkAcq(acq, EMG_LABELS,
            highPassFrequencies=[20,200],
            envelopFrequency=6.0)

        openmaTrial = trialTools.convertBtkAcquisition(acq)

        plot.plotTemporalEMG(DATA_PATH,gaitTrial, EMG_LABELS,EMG_MUSCLES, EMG_CONTEXT, NORMAL_ACTIVITIES,exportPdf=False,rectify=rectifyBool,openmaTrial=openmaTrial)
    def test_CGM24_FullBody_noOptions_uncorrectLowerLimbMarker(self):
        DATA_PATH = pyCGM2.TEST_DATA_PATH + "Scenarii\\different static and dynamic marker set\\CGM24-fullBody\\"
        staticFilename = "static.c3d"

        acqStatic = btkTools.smartReader(DATA_PATH +  staticFilename)


        markerDiameter=14
        leftFlatFoot = False
        rightFlatFoot = False
        headStraight = False
        pointSuffix = "test"

        vskFile = vskTools.getVskFiles(DATA_PATH)
        vsk = vskTools.Vsk(DATA_PATH + "PN07.vsk")
        required_mp,optional_mp = vskTools.getFromVskSubjectMp(vsk, resetFlag=True)

        settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,"CGM2_4-pyCGM2.settings")
        hjcMethod = settings["Calibration"]["HJC"]

        translators = files.getTranslators(DATA_PATH,"CGM2_4.translators")
        # if not translators:  translators = settings["Translators"]


        model,finalAcqStatic = cgm2_4.calibrate(DATA_PATH,
            staticFilename,
            translators,
            settings,
            required_mp,
            optional_mp,
            False,
            leftFlatFoot,
            rightFlatFoot,
            headStraight,
            markerDiameter,
            hjcMethod,
            pointSuffix,
            displayCoordinateSystem=True)

        # btkTools.smartWriter(finalAcqStatic, str( staticFilename[:-4]+"-pyCGM2modelled.c3d"))
        logging.info("Static Calibration -----> Done")

        gaitFilename="gait1_noLASI.c3d"

        mfpa = None
        reconstructFilenameLabelled = gaitFilename

        acqGait = cgm2_4.fitting(model,DATA_PATH, reconstructFilenameLabelled,
            translators,
            settings,
            False,
            markerDiameter,
            pointSuffix,
            mfpa,
            enums.MomentProjection.Proximal,
            displayCoordinateSystem=True)

        assert model.m_bodypart  == enums.BodyPart.UpperLimb
Exemple #7
0
    def __init__(self, filenameNoExt, modality):

        fullJsonDict = files.openFile(pyCGM2.NORMATIVE_DATABASE_PATH,
                                      filenameNoExt + ".json")
        keys = list(fullJsonDict.keys())
        self._jsonDict = fullJsonDict[keys[0]][modality]

        self.data = dict()
        self.construct()
Exemple #8
0
    def allCustom(cls):

        DATA_PATH = pyCGM2.TEST_DATA_PATH + "Configurator\\CGM1\\allCustom\\"

        #internalSettings = files.openFile(pyCGM2_GLOBAL_SETTINGS_PATH,"CGM1-pyCGM2.settings")

        userSettings = files.openFile(DATA_PATH, "CGM1.userSettings")
        translators = files.openFile(DATA_PATH, "CGM1.translators")
        customAdvancedSettings = files.openFile(DATA_PATH,
                                                "CGM1-pyCGM2.settings")
        vsk = vskTools.Vsk(str(DATA_PATH + "CGM1.vsk"))

        manager = ModelManager.CGM1ConfigManager(
            userSettings,
            localInternalSettings=customAdvancedSettings,
            localTranslators=translators,
            vsk=vsk)
        manager.contruct()
        manager.getFinalSettings()
Exemple #9
0
    def testCGM1(cls):

        DATA_PATH = "C:\\Users\\HLS501\\Documents\\Programming\\API\\pyCGM2\\pyCGM2\\Tests\\configurator\\localsettings\\"

        #internalSettings = files.openFile(pyCGM2_GLOBAL_SETTINGS_PATH,"CGM1-pyCGM2.settings")

        userSettings = files.openFile(DATA_PATH, "altered_CGM1.userSettings")

        manager = Manager.CGM1ConfigManager(userSettings)
        manager.contruct()
        manager.getFinalSettings()
Exemple #10
0
    def userSettingsOnly(cls):

        DATA_PATH = pyCGM2.TEST_DATA_PATH + "Configurator\\CGM1\\onlyUserSettings\\"

        #internalSettings = files.openFile(pyCGM2_GLOBAL_SETTINGS_PATH,"CGM1-pyCGM2.settings")

        userSettings = files.openFile(DATA_PATH, "CGM1.userSettings")

        manager = ModelManager.CGM1ConfigManager(userSettings)
        manager.contruct()
        manager.getFinalSettings()
Exemple #11
0
    def mpFromVsk(cls):

        DATA_PATH = pyCGM2.TEST_DATA_PATH + "Configurator\\CGM1\\vskIn\\"

        #internalSettings = files.openFile(pyCGM2_GLOBAL_SETTINGS_PATH,"CGM1-pyCGM2.settings")

        userSettings = files.openFile(DATA_PATH, "CGM1.userSettings")

        vsk = vskTools.Vsk(str(DATA_PATH + "CGM1.vsk"))

        manager = ModelManager.CGM1ConfigManager(userSettings, vsk=vsk)
        manager.contruct()
        manager.getFinalSettings()
Exemple #12
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)
Exemple #13
0
    def testCGM1_localSettings(cls):

        DATA_PATH = "C:\\Users\\HLS501\\Documents\\Programming\\API\\pyCGM2\\pyCGM2\\Tests\\configurator\\localsettings\\"

        internalSettings = files.openFile(pyCGM2_GLOBAL_SETTINGS_PATH,
                                          "CGM1-pyCGM2.settings")

        userSettings = files.openFile(DATA_PATH, "altered_CGM1.userSettings")

        manager = Manager.CGM1ConfigManager(
            userSettings, localInternalSettings=internalSettings)
        manager.contruct()
        finalSettings = manager.getFinalSettings()

        #files.prettyDictPrint(finalSettings)

        np.testing.assert_equal(finalSettings["Global"]["Marker diameter"], 28)
        np.testing.assert_equal(finalSettings["Global"]["Point suffix"],
                                "TEST")
        np.testing.assert_equal(finalSettings["Calibration"]["Left flat foot"],
                                0)
        np.testing.assert_equal(
            finalSettings["Calibration"]["Right flat foot"], 0)
        np.testing.assert_equal(finalSettings["Translators"]["LASI"], "None")
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")
Exemple #15
0
def main(sessionFilename, createPDFReport=True):
    logging.info("------------------------------------------------")
    logging.info("------------QTM - pyCGM2 Workflow---------------")
    logging.info("------------------------------------------------")

    sessionXML = files.readXml(os.getcwd() + "\\", sessionFilename)
    sessionDate = files.getFileCreationDate(os.getcwd() + "\\" +
                                            sessionFilename)

    #---------------------------------------------------------------------------
    #management of the Processed folder
    DATA_PATH = os.getcwd() + "\\" + "processed\\"
    files.createDir(DATA_PATH)

    staticMeasurement = qtmTools.findStatic(sessionXML)
    calibrateFilenameLabelled = qtmTools.getFilename(staticMeasurement)
    if not os.path.isfile(DATA_PATH + calibrateFilenameLabelled):
        shutil.copyfile(os.getcwd() + "\\" + calibrateFilenameLabelled,
                        DATA_PATH + calibrateFilenameLabelled)
        logging.info(
            "qualisys exported c3d file [%s] copied to processed folder" %
            (calibrateFilenameLabelled))

    dynamicMeasurements = qtmTools.findDynamic(sessionXML)
    for dynamicMeasurement in dynamicMeasurements:
        reconstructFilenameLabelled = qtmTools.getFilename(dynamicMeasurement)
        if not os.path.isfile(DATA_PATH + reconstructFilenameLabelled):
            shutil.copyfile(os.getcwd() + "\\" + reconstructFilenameLabelled,
                            DATA_PATH + reconstructFilenameLabelled)
            logging.info(
                "qualisys exported c3d file [%s] copied to processed folder" %
                (reconstructFilenameLabelled))

            acq = btkTools.smartReader(
                str(DATA_PATH + reconstructFilenameLabelled))

            acq, zeniState = eventDetector.zeni(acq)

            if zeniState:
                btkTools.smartWriter(
                    acq, str(DATA_PATH + reconstructFilenameLabelled))

                cmd = "Mokka.exe \"%s\"" % (str(DATA_PATH +
                                                reconstructFilenameLabelled))
                os.system(cmd)

    # --------------------------GLOBAL SETTINGS ------------------------------------
    # global setting ( in user/AppData)

    if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM1_1-pyCGM2.settings"):
        settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,
                                  "CGM1_1-pyCGM2.settings")
    else:
        settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,
                                  "CGM1_1-pyCGM2.settings")
    # --------------------------MP ------------------------------------
    required_mp, optional_mp = qtmTools.SubjectMp(sessionXML)

    # --Check MP
    inspectprocedure = inspectProcedures.AnthropometricDataQualityProcedure(
        required_mp)
    inspector = inspectFilters.QualityFilter(inspectprocedure)
    inspector.run()

    #  translators management
    translators = files.getTranslators(os.getcwd() + "\\",
                                       "CGM1_1.translators")
    if not translators: translators = settings["Translators"]

    # --------------------------MODEL CALIBRATION -----------------------
    logging.info(
        "--------------------------MODEL CALIBRATION -----------------------")
    staticMeasurement = qtmTools.findStatic(sessionXML)
    calibrateFilenameLabelled = qtmTools.getFilename(staticMeasurement)

    logging.info("----- CALIBRATION-  static file [%s]--" %
                 (calibrateFilenameLabelled))

    leftFlatFoot = utils.toBool(
        sessionXML.Left_foot_normalised_to_static_trial.text)
    rightFlatFoot = utils.toBool(
        sessionXML.Right_foot_normalised_to_static_trial.text)
    headFlat = utils.toBool(sessionXML.Head_normalised_to_static_trial.text)
    markerDiameter = float(sessionXML.Marker_diameter.text) * 1000.0
    pointSuffix = None

    # Calibration checking
    # --------------------
    acqStatic = btkTools.smartReader(DATA_PATH + calibrateFilenameLabelled)
    for key in MARKERSETS.keys():
        logging.info("[pyCGM2] Checking of the %s" % (key))

        # presence
        ip_presence = inspectProcedures.MarkerPresenceQualityProcedure(
            acqStatic, markers=MARKERSETS[key])
        inspector = inspectFilters.QualityFilter(ip_presence)
        inspector.run()

        if ip_presence.markersIn != []:

            ip_gap = inspectProcedures.GapQualityProcedure(
                acqStatic, markers=ip_presence.markersIn)
            inspector = inspectFilters.QualityFilter(ip_gap)
            inspector.run()

            ip_swap = inspectProcedures.SwappingMarkerQualityProcedure(
                acqStatic, markers=ip_presence.markersIn)
            inspector = inspectFilters.QualityFilter(ip_swap)
            inspector.run()

            ip_pos = inspectProcedures.MarkerPositionQualityProcedure(
                acqStatic, markers=ip_presence.markersIn)
            inspector = inspectFilters.QualityFilter(ip_pos)

    # Calibration operation
    # --------------------
    logging.info("[pyCGM2] --- calibration operation ---")
    model, acqStatic = cgm1_1.calibrate(DATA_PATH, calibrateFilenameLabelled,
                                        translators, required_mp, optional_mp,
                                        leftFlatFoot, rightFlatFoot, headFlat,
                                        markerDiameter, pointSuffix)
    logging.info("----- CALIBRATION-  static file [%s]-----> DONE" %
                 (calibrateFilenameLabelled))

    # --------------------------MODEL FITTING ----------------------------------
    logging.info(
        "--------------------------MODEL FITTING ----------------------------------"
    )
    dynamicMeasurements = qtmTools.findDynamic(sessionXML)

    modelledC3ds = list()
    eventInspectorStates = list()
    for dynamicMeasurement in dynamicMeasurements:

        reconstructFilenameLabelled = qtmTools.getFilename(dynamicMeasurement)

        logging.info("----Processing of [%s]-----" %
                     (reconstructFilenameLabelled))
        mfpa = qtmTools.getForcePlateAssigment(dynamicMeasurement)
        momentProjection_text = sessionXML.Moment_Projection.text
        if momentProjection_text == "Default":
            momentProjection_text = settings["Fitting"]["Moment Projection"]
        if momentProjection_text == "Distal":
            momentProjection = enums.MomentProjection.Distal
        elif momentProjection_text == "Proximal":
            momentProjection = enums.MomentProjection.Proximal
        elif momentProjection_text == "Global":
            momentProjection = enums.MomentProjection.Global
        elif momentProjection_text == "JCS":
            momentProjection = enums.MomentProjection.JCS

        acq = btkTools.smartReader(DATA_PATH + reconstructFilenameLabelled)

        # Fitting checking
        # --------------------
        for key in MARKERSETS.keys():
            if key != "Calibration markers":

                logging.info("[pyCGM2] Checking of the %s" % (key))
                # presence
                ip_presence = inspectProcedures.MarkerPresenceQualityProcedure(
                    acq, markers=MARKERSETS[key])
                inspector = inspectFilters.QualityFilter(ip_presence)
                inspector.run()

                if ip_presence.markersIn != []:

                    ip_gap = inspectProcedures.GapQualityProcedure(
                        acq, markers=ip_presence.markersIn)
                    inspector = inspectFilters.QualityFilter(ip_gap)
                    inspector.run()

                    ip_swap = inspectProcedures.SwappingMarkerQualityProcedure(
                        acq, markers=ip_presence.markersIn)
                    inspector = inspectFilters.QualityFilter(ip_swap)
                    inspector.run()

                    ip_pos = inspectProcedures.MarkerPositionQualityProcedure(
                        acq, markers=ip_presence.markersIn)
                    inspector = inspectFilters.QualityFilter(ip_pos)

        # filtering
        # -----------------------

        # marker
        order_marker = int(
            float(dynamicMeasurement.Marker_lowpass_filter_order.text))
        fc_marker = float(
            dynamicMeasurement.Marker_lowpass_filter_frequency.text)

        # force plate
        order_fp = int(
            float(dynamicMeasurement.Forceplate_lowpass_filter_order.text))
        fc_fp = float(
            dynamicMeasurement.Forceplate_lowpass_filter_frequency.text)

        # event checking
        # -----------------------
        inspectprocedureEvents = inspectProcedures.GaitEventQualityProcedure(
            acq)
        inspector = inspectFilters.QualityFilter(inspectprocedureEvents)
        inspector.run()
        eventInspectorStates.append(inspectprocedureEvents.state)

        # fitting operation
        # -----------------------
        logging.info("[pyCGM2] --- Fitting operation ---")
        acqGait = cgm1_1.fitting(model,
                                 DATA_PATH,
                                 reconstructFilenameLabelled,
                                 translators,
                                 markerDiameter,
                                 pointSuffix,
                                 mfpa,
                                 momentProjection,
                                 fc_lowPass_marker=fc_marker,
                                 order_lowPass_marker=order_marker,
                                 fc_lowPass_forcePlate=fc_fp,
                                 order_lowPass_forcePlate=order_fp)

        outFilename = reconstructFilenameLabelled
        btkTools.smartWriter(acqGait, str(DATA_PATH + outFilename))
        modelledC3ds.append(outFilename)

        logging.info("----Processing of [%s]-----> DONE" %
                     (reconstructFilenameLabelled))

    # --------------------------GAIT PROCESSING -----------------------
    if not all(eventInspectorStates):
        raise Exception(
            "[pyCGM2] Impossible to run Gait processing. Badly gait event detection. check the log file"
        )
    logging.info(
        "---------------------GAIT PROCESSING -----------------------")

    if createPDFReport:
        nds = normativeDatasets.Schwartz2008("Free")

        types = qtmTools.detectMeasurementType(sessionXML)
        for type in types:

            modelledTrials = list()
            for dynamicMeasurement in dynamicMeasurements:
                if qtmTools.isType(dynamicMeasurement, type):
                    filename = qtmTools.getFilename(dynamicMeasurement)
                    modelledTrials.append(filename)

            report.pdfGaitReport(DATA_PATH,
                                 model,
                                 modelledTrials,
                                 nds,
                                 pointSuffix,
                                 title=type)
            logging.info("----- Gait Processing -----> DONE")
Exemple #16
0
def main(args):

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

    if NEXUS_PYTHON_CONNECTED:  # run Operation
        # --------------------------GLOBAL SETTINGS ------------------------------------
        # global setting ( in user/AppData)
        if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH +
                          "CGM1_1-pyCGM2.settings"):
            settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,
                                      "CGM1_1-pyCGM2.settings")
        else:
            settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,
                                      "CGM1_1-pyCGM2.settings")

        # --------------------------CONFIG ------------------------------------
        argsManager = CgmArgsManager.argsManager_cgm(settings, args)
        markerDiameter = argsManager.getMarkerDiameter()
        pointSuffix = argsManager.getPointSuffix("cgm1_1")
        momentProjection = argsManager.getMomentProjection()

        DATA_PATH, reconstructFilenameLabelledNoExt = NEXUS.GetTrialName()

        reconstructFilenameLabelled = reconstructFilenameLabelledNoExt + ".c3d"
        logging.info("data Path: " + DATA_PATH)
        logging.info("calibration file: " + reconstructFilenameLabelled)

        # --------------------------SUBJECT ------------------------------------
        # Notice : Work with ONE subject by session
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.checkActivatedSubject(NEXUS, subjects)
        logging.info("Subject name : " + subject)

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

        # --------------------------CHECKING -----------------------------------
        # check model is the CGM1
        logging.info("loaded model : %s" % (model.version))
        if model.version != "CGM1.1":
            raise Exception(
                "%s-pyCGM2.model file was not calibrated from the CGM1.1 calibration pipeline"
                % model.version)

        # --------------------------SESSION INFOS ------------------------------------

        #  translators management
        translators = files.getTranslators(DATA_PATH, "CGM1_1.translators")
        if not translators: translators = settings["Translators"]

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

        #force plate assignement from Nexus
        mfpa = nexusTools.getForcePlateAssignment(NEXUS)

        # --------------------------MODELLING PROCESSING -----------------------
        acqGait = cgm1_1.fitting(model,
                                 DATA_PATH,
                                 reconstructFilenameLabelled,
                                 translators,
                                 markerDiameter,
                                 pointSuffix,
                                 mfpa,
                                 momentProjection,
                                 forceBtkAcq=acq)

        # ----------------------SAVE-------------------------------------------
        # Todo: pyCGM2 model :  cpickle doesn t work. Incompatibility with Swig. ( see about BTK wrench)

        # ----------------------DISPLAY ON VICON-------------------------------
        nexusFilters.NexusModelFilter(NEXUS, model, acqGait, subject,
                                      pointSuffix).run()
        nexusTools.createGeneralEvents(NEXUS, subject, acqGait,
                                       ["Left-FP", "Right-FP"])

        # ========END of the nexus OPERATION if run from Nexus  =========

    else:
        raise Exception("NO Nexus connection. Turn on Nexus")
Exemple #17
0
def main(args):
    DATA_PATH = os.getcwd() + "\\"

    # User Settings
    if os.path.isfile(DATA_PATH + args.userFile):
        userSettings = files.openFile(DATA_PATH, args.userFile)
    else:
        raise Exception("user setting file not found")

    # internal (expert) Settings
    if args.expertFile:
        if os.path.isfile(DATA_PATH + args.expertFile):
            internalSettings = files.openFile(DATA_PATH, args.expertFile)
        else:
            raise Exception("expert setting file not found")
    else:
        internalSettings = None

    # translators
    if os.path.isfile(DATA_PATH + "CGM1_1.translators"):
        translators = files.openFile(DATA_PATH, "CGM1_1.translators")
    else:
        translators = None

    # --- Manager ----
    manager = ModelManager.CGM1_1ConfigManager(
        userSettings,
        localInternalSettings=internalSettings,
        localTranslators=translators)
    manager.contruct()
    finalSettings = manager.getFinalSettings()
    #    files.prettyDictPrint(finalSettings)

    #    logging.info("=============Calibration=============")
    model, finalAcqStatic = cgm1_1.calibrate(DATA_PATH,
                                             manager.staticTrial,
                                             manager.translators,
                                             manager.requiredMp,
                                             manager.optionalMp,
                                             manager.leftFlatFoot,
                                             manager.rightFlatFoot,
                                             manager.headFlat,
                                             manager.markerDiameter,
                                             manager.pointSuffix,
                                             displayCoordinateSystem=True)

    btkTools.smartWriter(
        finalAcqStatic,
        str(DATA_PATH + finalSettings["Calibration"]["StaticTrial"][:-4]) +
        '.C3D')  #+"-pyCGM2modelled.c3d"
    #    logging.info("Static Calibration -----> Done")

    manager.updateMp(model)
    #files.prettyDictPrint(manager.finalSettings)

    #    logging.info("=============Fitting=============")
    for trial in manager.dynamicTrials:
        mfpa = None if trial["Mfpa"] == "Auto" else trial["Mfpa"]
        reconstructFilenameLabelled = trial["File"]

        acqGait = cgm1_1.fitting(model,
                                 DATA_PATH,
                                 reconstructFilenameLabelled,
                                 manager.translators,
                                 manager.markerDiameter,
                                 manager.pointSuffix,
                                 mfpa,
                                 manager.momentProjection,
                                 displayCoordinateSystem=True)

        btkTools.smartWriter(
            acqGait,
            str(DATA_PATH + reconstructFilenameLabelled[:-4]) +
            '.C3D')  #+"-pyCGM2modelled.c3d"
Exemple #18
0
def main(args):

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

    if NEXUS_PYTHON_CONNECTED:  # run Operation

        # --------------------GLOBAL SETTINGS ------------------------------

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

        argsManager = CgmArgsManager.argsManager_cgm(settings, args)
        leftFlatFoot = argsManager.getLeftFlatFoot()
        rightFlatFoot = argsManager.getRightFlatFoot()
        headFlat = argsManager.getHeadFlat()
        markerDiameter = argsManager.getMarkerDiameter()
        pointSuffix = argsManager.getPointSuffix("cgm2.5")
        ik_flag = argsManager.enableIKflag()

        hjcMethod = settings["Calibration"]["HJC"]
        lhjc = argsManager.forceHjc("left")
        rhjc = argsManager.forceHjc("right")
        if lhjc is not None:
            hjcMethod["Left"] = lhjc
        if rhjc is not None:
            hjcMethod["Right"] = rhjc

        # --------------------------LOADING------------------------------
        DATA_PATH, calibrateFilenameLabelledNoExt = NEXUS.GetTrialName()

        calibrateFilenameLabelled = calibrateFilenameLabelledNoExt + ".c3d"

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

        # --------------------------SUBJECT -----------------------------------
        # Notice : Work with ONE subject by session
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.checkActivatedSubject(NEXUS, subjects)
        Parameters = NEXUS.GetSubjectParamNames(subject)

        required_mp, optional_mp = nexusUtils.getNexusSubjectMp(
            NEXUS, subject, resetFlag=args.resetMP)

        # --------------------------SESSION INFOS -----------------------------
        # --------------------------SESSIONS INFOS -----------------------------------
        mpInfo, mpFilename = files.getMpFileContent(DATA_PATH, "mp.pyCGM2",
                                                    subject)

        #  translators management
        translators = files.getTranslators(DATA_PATH, "CGM2_5.translators")
        if not translators: translators = settings["Translators"]

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

        # --------------------------CONFIG ------------------------------------
        model, finalAcqStatic = cgm2_5.calibrate(DATA_PATH,
                                                 calibrateFilenameLabelled,
                                                 translators,
                                                 settings,
                                                 required_mp,
                                                 optional_mp,
                                                 ik_flag,
                                                 leftFlatFoot,
                                                 rightFlatFoot,
                                                 headFlat,
                                                 markerDiameter,
                                                 hjcMethod,
                                                 pointSuffix,
                                                 forceBtkAcq=acq)

        # ----------------------SAVE-------------------------------------------
        files.saveModel(model, DATA_PATH, subject)

        # save mp
        files.saveMp(mpInfo, model, DATA_PATH, mpFilename)

        # ----------------------DISPLAY ON VICON-------------------------------
        nexusUtils.updateNexusSubjectMp(NEXUS, model, subject)
        nexusFilters.NexusModelFilter(NEXUS,
                                      model,
                                      finalAcqStatic,
                                      subject,
                                      pointSuffix,
                                      staticProcessing=True).run()

        # ========END of the nexus OPERATION if run from Nexus  =========

    else:
        raise Exception("NO Nexus connection. Turn on Nexus")
Exemple #19
0
def main():

    parser = argparse.ArgumentParser(description='CGM2-3 Fitting')
    parser.add_argument(
        '--proj',
        type=str,
        help='Moment Projection. Choice : Distal, Proximal, Global')
    parser.add_argument('-md',
                        '--markerDiameter',
                        type=float,
                        help='marker diameter')
    parser.add_argument('--noIk',
                        action='store_true',
                        help='cancel inverse kinematic')
    parser.add_argument('-ps',
                        '--pointSuffix',
                        type=str,
                        help='suffix of model outputs')
    parser.add_argument('--check',
                        action='store_true',
                        help='force model output suffix')
    parser.add_argument('-a',
                        '--accuracy',
                        type=float,
                        help='Inverse Kinematics accuracy')
    parser.add_argument('-ae',
                        '--anomalyException',
                        action='store_true',
                        help='stop if anomaly detected ')
    parser.add_argument('-fi',
                        '--frameInit',
                        type=int,
                        help='first frame to process')
    parser.add_argument('-fe',
                        '--frameEnd',
                        type=int,
                        help='last frame to process')
    args = parser.parse_args()

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

    if NEXUS_PYTHON_CONNECTED:  # run Operation

        # --------------------GLOBAL SETTINGS ------------------------------
        # global setting ( in user/AppData)
        if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH +
                          "CGM2_3-pyCGM2.settings"):
            settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,
                                      "CGM2_3-pyCGM2.settings")
        else:
            settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,
                                      "CGM2_3-pyCGM2.settings")

        # --------------------------CONFIG ------------------------------------
        argsManager = CgmArgsManager.argsManager_cgm(settings, args)
        markerDiameter = argsManager.getMarkerDiameter()
        pointSuffix = argsManager.getPointSuffix("cgm2.3")
        momentProjection = argsManager.getMomentProjection()
        ik_flag = argsManager.enableIKflag
        ikAccuracy = argsManager.getIkAccuracy()

        # ----------------------LOADING-------------------------------------------
        DATA_PATH, reconstructFilenameLabelledNoExt = NEXUS.GetTrialName()

        reconstructFilenameLabelled = reconstructFilenameLabelledNoExt + ".c3d"

        LOGGER.logger.info("data Path: " + DATA_PATH)
        LOGGER.set_file_handler(DATA_PATH + "pyCGM2-Fitting.log")
        LOGGER.logger.info("calibration file: " + reconstructFilenameLabelled)

        # --------------------------SUBJECT -----------------------------------
        # Notice : Work with ONE subject by session
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.getActiveSubject(NEXUS)
        LOGGER.logger.info("Subject name : " + subject)

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

        # -------------------------- MP ------------------------------------
        # allow alteration of thigh offset
        model.mp_computed[
            "LeftThighRotationOffset"] = NEXUS.GetSubjectParamDetails(
                subject, "LeftThighRotation")[0]
        model.mp_computed[
            "RightThighRotationOffset"] = NEXUS.GetSubjectParamDetails(
                subject, "RightThighRotation")[0]

        # --------------------------CHECKING -----------------------------------
        # check model
        LOGGER.logger.info("loaded model : %s" % (model.version))
        if model.version != "CGM2.3":
            raise Exception(
                "%s-pyCGM2.model file was not calibrated from the CGM2.3 calibration pipeline"
                % subject)

        # --------------------------SESSION INFOS ------------------------------------
        #  translators management
        translators = files.getTranslators(DATA_PATH, "CGM2_3.translators")
        if not translators: translators = settings["Translators"]

        #  ikweight
        ikWeight = files.getIKweightSet(DATA_PATH, "CGM2_3.ikw")
        if not ikWeight: ikWeight = settings["Fitting"]["Weight"]

        #force plate assignement from Nexus
        mfpa = nexusTools.getForcePlateAssignment(NEXUS)

        # btkAcquisition
        nacf = nexusFilters.NexusConstructAcquisitionFilter(
            DATA_PATH, reconstructFilenameLabelledNoExt, subject)
        acq = nacf.build()

        # --------------------------MODELLING PROCESSING -----------------------
        finalAcqGait, detectAnomaly = cgm2_3.fitting(
            model,
            DATA_PATH,
            reconstructFilenameLabelled,
            translators,
            settings,
            ik_flag,
            markerDiameter,
            pointSuffix,
            mfpa,
            momentProjection,
            forceBtkAcq=acq,
            ikAccuracy=ikAccuracy,
            anomalyException=args.anomalyException,
            frameInit=args.frameInit,
            frameEnd=args.frameEnd)

        # ----------------------DISPLAY ON VICON-------------------------------
        nexusFilters.NexusModelFilter(NEXUS, model, finalAcqGait, subject,
                                      pointSuffix).run()
        nexusTools.createGeneralEvents(NEXUS, subject, finalAcqGait,
                                       ["Left-FP", "Right-FP"])

        # ========END of the nexus OPERATION if run from Nexus  =========

    else:
        raise Exception("NO Nexus connection. Turn on Nexus")
Exemple #20
0
def main():


    parser = argparse.ArgumentParser(description='CGM2.4 Calibration')
    parser.add_argument('-l','--leftFlatFoot', type=int, help='left flat foot option')
    parser.add_argument('-r','--rightFlatFoot',type=int,  help='right flat foot option')
    parser.add_argument('-hf','--headFlat',type=int,  help='head flat option')
    parser.add_argument('-md','--markerDiameter', type=float, help='marker diameter')
    parser.add_argument('-ps','--pointSuffix', type=str, help='suffix of model outputs')
    parser.add_argument('--check', action='store_true', help='force model output suffix')
    parser.add_argument('--noIk', action='store_true', help='cancel inverse kinematic')
    parser.add_argument('--resetMP', action='store_true', help='reset optional mass parameters')
    parser.add_argument('--forceLHJC', nargs='+')
    parser.add_argument('--forceRHJC', nargs='+')
    parser.add_argument('-ae','--anomalyException', action='store_true', help='stop if anomaly detected ')
    args = parser.parse_args()


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


    if NEXUS_PYTHON_CONNECTED: # run Operation

        # --------------------GLOBAL SETTINGS ------------------------------

        # ( in user/AppData)
        if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_4-pyCGM2.settings"):
            settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,"CGM2_4-pyCGM2.settings")
        else:
            settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,"CGM2_4-pyCGM2.settings")


        argsManager = CgmArgsManager.argsManager_cgm(settings,args)
        leftFlatFoot = argsManager.getLeftFlatFoot()
        rightFlatFoot = argsManager.getRightFlatFoot()
        headFlat = argsManager.getHeadFlat()
        markerDiameter = argsManager.getMarkerDiameter()
        pointSuffix = argsManager.getPointSuffix("cgm2.4")
        ik_flag = argsManager.enableIKflag()

        hjcMethod = settings["Calibration"]["HJC"]
        lhjc = argsManager.forceHjc("left")
        rhjc = argsManager.forceHjc("right")
        if  lhjc is not None:
            hjcMethod["Left"] = lhjc
        if  rhjc is not None:
            hjcMethod["Right"] = rhjc


        # --------------------------LOADING------------------------------
        DATA_PATH, calibrateFilenameLabelledNoExt = NEXUS.GetTrialName()

        calibrateFilenameLabelled = calibrateFilenameLabelledNoExt+".c3d"

        LOGGER.logger.info( "data Path: "+ DATA_PATH )
        LOGGER.set_file_handler(DATA_PATH+"pyCGM2-Calibration.log")
        LOGGER.logger.info( "calibration file: "+ calibrateFilenameLabelled)


        # --------------------------SUBJECT -----------------------------------
        # Notice : Work with ONE subject by session
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.getActiveSubject(NEXUS)
        Parameters = NEXUS.GetSubjectParamNames(subject)

        required_mp,optional_mp = nexusUtils.getNexusSubjectMp(NEXUS,subject,resetFlag=args.resetMP)

        # --------------------------SESSION INFOS -----------------------------
         # --------------------------SESSIONS INFOS -----------------------------------
        mpInfo,mpFilename = files.getMpFileContent(DATA_PATH,"mp.pyCGM2",subject)

        #  translators management
        translators = files.getTranslators(DATA_PATH,"CGM2_4.translators")
        if not translators:  translators = settings["Translators"]

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

        # --------------------------CONFIG ------------------------------------
        model,finalAcqStatic,detectAnomaly = cgm2_4.calibrate(DATA_PATH,calibrateFilenameLabelled,translators,settings,
                      required_mp,optional_mp,
                      ik_flag,leftFlatFoot,rightFlatFoot,headFlat,
                      markerDiameter,
                      hjcMethod,
                      pointSuffix,forceBtkAcq=acq, anomalyException=args.anomalyException)



        # ----------------------SAVE-------------------------------------------
        files.saveModel(model,DATA_PATH,subject)

        # save mp
        files.saveMp(mpInfo,model,DATA_PATH,mpFilename)

        # ----------------------DISPLAY ON VICON-------------------------------
        nexusUtils.updateNexusSubjectMp(NEXUS,model,subject)
        nexusFilters.NexusModelFilter(NEXUS,
                                      model,finalAcqStatic,subject,
                                      pointSuffix,
                                      staticProcessing=True).run()

        # ========END of the nexus OPERATION if run from Nexus  =========


    else:
        raise Exception("NO Nexus connection. Turn on Nexus")
def main(args):
    DATA_PATH = os.getcwd()+"\\"

    # User Settings
    if os.path.isfile(DATA_PATH + args.userFile):
        userSettings = files.openFile(DATA_PATH,args.userFile)
    else:
        raise Exception ("user setting file not found")

    # internal (expert) Settings
    if args.expertFile:
        if os.path.isfile(DATA_PATH + args.expertFile):
            internalSettings = files.openFile(DATA_PATH,args.expertFile)
        else:
            raise Exception ("expert setting file not found")
    else:
        internalSettings = None

    # translators
    if os.path.isfile(DATA_PATH + "CGM1_1.translators"):
        translators = files.openFile(DATA_PATH,"CGM1_1.translators")
    else:
        translators = None


    # --- Manager ----
    manager = ModelManager.CGM1_1ConfigManager(userSettings,localInternalSettings=internalSettings,localTranslators=translators)
    manager.contruct()
    finalSettings = manager.getFinalSettings()
    files.prettyDictPrint(finalSettings)


    logging.info("=============Calibration=============")
    model,finalAcqStatic = cgm1_1.calibrate(DATA_PATH,
        manager.staticTrial,
        manager.translators,
        manager.requiredMp,
        manager.optionalMp,
        manager.leftFlatFoot,
        manager.rightFlatFoot,
        manager.markerDiameter,
        manager.pointSuffix,
        displayCoordinateSystem=True)



    btkTools.smartWriter(finalAcqStatic, str(DATA_PATH+finalSettings["Calibration"]["StaticTrial"]))#[:-4]+"-pyCGM2modelled.c3d"))
    logging.info("Static Calibration -----> Done")

    manager.updateMp(model)
    #files.prettyDictPrint(manager.finalSettings)

    logging.info("=============Fitting=============")
    for trial in manager.dynamicTrials:
        mfpa = None if trial["Mfpa"] == "Auto" else trial["Mfpa"]
        reconstructFilenameLabelled = trial["File"]

        acqGait = cgm1_1.fitting(model,DATA_PATH, reconstructFilenameLabelled,
            manager.translators,
            manager.markerDiameter,
            manager.pointSuffix,
            mfpa,
            manager.momentProjection,
            displayCoordinateSystem=True)

        btkTools.smartWriter(acqGait, str(DATA_PATH+reconstructFilenameLabelled))#[:-4]+"-pyCGM2modelled.c3d"))
        logging.info("---->dynamic trial (%s) processed" %(reconstructFilenameLabelled))

    logging.info("=============Writing of final Settings=============")
    i = 0
    while os.path.exists("CGM1.1 [%s].completeSettings" % i):
        i += 1
    filename = "CGM1.1 [" + str(i)+"].completeSettings"
    files.saveJson(DATA_PATH, filename, finalSettings)
    logging.info("---->complete settings (%s) exported" %(filename))


    raw_input("Press return to exit..")
Exemple #22
0
def main(args):


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

    if NEXUS_PYTHON_CONNECTED: # run Operation


        # --- acquisition file and path----
        DATA_PATH, inputFileNoExt = NEXUS.GetTrialName()
        inputFile = inputFileNoExt+".c3d"

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

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


        # ----------------------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])]
                logging.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
            logging.info("Cut-off frequency set to %i instead of 6Hz ",envelopCutOffFrequency)

        consistencyFlag = True if args.consistency else False


        # --------------------------SUBJECT ------------------------------------
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.checkActivatedSubject(NEXUS,subjects)

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


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

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



        openmaTrial = trialTools.convertBtkAcquisition(acq)
        emgAnalysis = analysis.makeEmgAnalysis(DATA_PATH, [inputFile], EMG_LABELS,openmaTrials = [openmaTrial])


        if not consistencyFlag:
            plot.plotDescriptiveEnvelopEMGpanel(DATA_PATH,emgAnalysis, EMG_LABELS,EMG_MUSCLES,EMG_CONTEXT, NORMAL_ACTIVITIES, normalized=False,exportPdf=True,outputName=inputFile)
        else:
            plot.plotConsistencyEnvelopEMGpanel(DATA_PATH,emgAnalysis, EMG_LABELS,EMG_MUSCLES,EMG_CONTEXT, NORMAL_ACTIVITIES, normalized=False,exportPdf=True,outputName=inputFile)


    else:
        raise Exception("NO Nexus connection. Turn on Nexus")
Exemple #23
0
def main():

    parser = argparse.ArgumentParser(description='CGM2-1 Fitting')
    parser.add_argument(
        '--proj',
        type=str,
        help='Moment Projection. Choice : Distal, Proximal, Global')
    parser.add_argument('-md',
                        '--markerDiameter',
                        type=float,
                        help='marker diameter')
    parser.add_argument('-ps',
                        '--pointSuffix',
                        type=str,
                        help='suffix of model outputs')
    parser.add_argument('--check',
                        action='store_true',
                        help='force model output suffix')
    args = parser.parse_args()

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

    if NEXUS_PYTHON_CONNECTED:  # run Operation

        # --------------------------GLOBAL SETTINGS ------------------------------------
        # global setting ( in user/AppData)
        if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH +
                          "CGM2_1-pyCGM2.settings"):
            settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,
                                      "CGM2_1-pyCGM2.settings")
        else:
            settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,
                                      "CGM2_1-pyCGM2.settings")

        # --------------------------CONFIG ------------------------------------
        argsManager = CgmArgsManager.argsManager_cgm(settings, args)
        markerDiameter = argsManager.getMarkerDiameter()
        pointSuffix = argsManager.getPointSuffix("cgm2.1")
        momentProjection = argsManager.getMomentProjection()

        # --------------------------LOADING ------------------------------------
        DATA_PATH, reconstructFilenameLabelledNoExt = NEXUS.GetTrialName()

        reconstructFilenameLabelled = reconstructFilenameLabelledNoExt + ".c3d"

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

        # --------------------------SUBJECT ------------------------------------
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.checkActivatedSubject(NEXUS, subjects)
        logging.info("Subject name : " + subject)

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

        # check model
        logging.info("loaded model : %s" % (model.version))
        if model.version != "CGM2.1":
            raise Exception(
                "%s-pyCGM2.model file was not calibrated from the CGM2.1 calibration pipeline"
                % subject)

        # --------------------------SESSION INFOS ------------------------------------

        #  translators management
        translators = files.getTranslators(DATA_PATH, "CGM2_1.translators")
        if not translators: translators = settings["Translators"]

        #force plate assignement from Nexus
        mfpa = nexusTools.getForcePlateAssignment(NEXUS)

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

        # --------------------------MODELLING PROCESSING -----------------------
        acqGait = cgm2_1.fitting(model,
                                 DATA_PATH,
                                 reconstructFilenameLabelled,
                                 translators,
                                 markerDiameter,
                                 pointSuffix,
                                 mfpa,
                                 momentProjection,
                                 forceBtkAcq=acq)

        # ----------------------DISPLAY ON VICON-------------------------------
        nexusFilters.NexusModelFilter(NEXUS, model, acqGait, subject,
                                      pointSuffix).run()
        nexusTools.createGeneralEvents(NEXUS, subject, acqGait,
                                       ["Left-FP", "Right-FP"])

        # ========END of the nexus OPERATION if run from Nexus  =========

    else:
        raise Exception("NO Nexus connection. Turn on Nexus")
Exemple #24
0
    def test_issue_jointForce_CGM24(self):
        """
        synopsis : inverted sign of the x-component of the joint force with CGM1.1 to CGM2.4
        """

        DATA_PATH = MAIN_PATH = pyCGM2.TEST_DATA_PATH + "Issues\\StephenM\\sign_jointForce_CGM24\\"
        staticFilename = "FullBody CGM2 data Cal 01.c3d"

        acqStatic = btkTools.smartReader(DATA_PATH + staticFilename)

        markerDiameter = 14
        leftFlatFoot = False
        rightFlatFoot = False
        headStraight = False
        pointSuffix = "test"

        vskFile = vskTools.getVskFiles(DATA_PATH)
        vsk = vskTools.Vsk(DATA_PATH + "Nick.vsk")
        required_mp, optional_mp = vskTools.getFromVskSubjectMp(vsk,
                                                                resetFlag=True)

        settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,
                                  "CGM2_4-pyCGM2.settings")

        model, finalAcqStatic = cgm2_4.calibrate(DATA_PATH,
                                                 staticFilename,
                                                 None,
                                                 settings,
                                                 required_mp,
                                                 optional_mp,
                                                 True,
                                                 leftFlatFoot,
                                                 rightFlatFoot,
                                                 headStraight,
                                                 markerDiameter, {
                                                     "Left": "Hara",
                                                     "Right": "Hara"
                                                 },
                                                 pointSuffix,
                                                 displayCoordinateSystem=True)

        # btkTools.smartWriter(finalAcqStatic, str( staticFilename[:-4]+"-pyCGM2modelled.c3d"))
        # logging.info("Static Calibration -----> Done")

        gaitFilename = "Capture 02.Distal.c3d"

        mfpa = "R"
        reconstructFilenameLabelled = gaitFilename

        acqGait = cgm2_4.fitting(model,
                                 DATA_PATH,
                                 reconstructFilenameLabelled,
                                 None,
                                 settings,
                                 True,
                                 markerDiameter,
                                 pointSuffix,
                                 mfpa,
                                 enums.MomentProjection.Distal,
                                 displayCoordinateSystem=True)

        testingUtils.plotComparisonOfPoint(acqGait,
                                           "RAnkleForce",
                                           "test",
                                           title="RAnkleForce PiG - CGM24")
        testingUtils.plotComparisonOfPoint(acqGait,
                                           "RKneeForce",
                                           "test",
                                           title="RKneeForce PiG - CGM24")
        testingUtils.plotComparisonOfPoint(acqGait,
                                           "RHipForce",
                                           "test",
                                           title="RHipForce PiG - CGM24")
Exemple #25
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")
def main(args):
    DATA_PATH = os.getcwd() + "\\"

    # User Settings
    if os.path.isfile(DATA_PATH + args.userFile):
        userSettings = files.openFile(DATA_PATH, args.userFile)
    else:
        raise Exception("user setting file not found")

    # internal (expert) Settings
    if args.expertFile:
        if os.path.isfile(DATA_PATH + args.expertFile):
            internalSettings = files.openFile(DATA_PATH, args.expertFile)
        else:
            raise Exception("expert setting file not found")
    else:
        internalSettings = None

    # --- Manager ----
    manager = EmgManager.EmgConfigManager(
        userSettings, localInternalSettings=internalSettings)
    manager.contruct()
    finalSettings = manager.getFinalSettings()
    files.prettyDictPrint(finalSettings)

    # reconfiguration of emg settings as lists
    EMG_LABELS, EMG_MUSCLES, EMG_CONTEXT, NORMAL_ACTIVITIES = manager.getEmgConfiguration(
    )

    #----- rectified view -------
    rectTrials = manager.temporal_trials
    analysis.processEMG(
        DATA_PATH,
        rectTrials,
        EMG_LABELS,
        highPassFrequencies=manager.BandpassFrequencies,
        envelopFrequency=manager.EnvelopLowpassFrequency,
        fileSuffix=None)  # high pass then low pass for all c3ds

    for trial in rectTrials:
        plot.plotTemporalEMG(DATA_PATH,
                             trial,
                             EMG_LABELS,
                             EMG_MUSCLES,
                             EMG_CONTEXT,
                             NORMAL_ACTIVITIES,
                             exportPdf=True,
                             rectify=manager.rectifyFlag)

    #----- Gait normalized envelop -------
    envTrials = manager.gaitNormalized_trials
    analysis.processEMG(
        DATA_PATH,
        envTrials,
        EMG_LABELS,
        highPassFrequencies=manager.BandpassFrequencies,
        envelopFrequency=manager.EnvelopLowpassFrequency,
        fileSuffix=None)  # high pass then low pass for all c3ds

    emgAnalysisInstance = analysis.makeEmgAnalysis(DATA_PATH, envTrials,
                                                   EMG_LABELS, None, None)

    filename = manager.title

    if not manager.consistencyFlag:
        plot.plotDescriptiveEnvelopEMGpanel(DATA_PATH,
                                            emgAnalysisInstance,
                                            EMG_LABELS,
                                            EMG_MUSCLES,
                                            EMG_CONTEXT,
                                            NORMAL_ACTIVITIES,
                                            normalized=False,
                                            exportPdf=True,
                                            outputName=filename)
    else:
        plot.plotConsistencyEnvelopEMGpanel(DATA_PATH,
                                            emgAnalysisInstance,
                                            EMG_LABELS,
                                            EMG_MUSCLES,
                                            EMG_CONTEXT,
                                            NORMAL_ACTIVITIES,
                                            normalized=False,
                                            exportPdf=True,
                                            outputName=filename)

    logging.info("=============Writing of final Settings=============")
    files.saveJson(DATA_PATH, str(filename + "-EMG.completeSettings"),
                   finalSettings)
    logging.info("---->complete settings (%s) exported" %
                 (str(filename + "-EMG.completeSettings")))

    raw_input("Press return to exit..")
Exemple #27
0
def main(args):

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

    if NEXUS_PYTHON_CONNECTED:  # run Operation

        # --------------------------PATH + FILE ------------------------------------
        DATA_PATH, reconstructedFilenameLabelledNoExt = NEXUS.GetTrialName()

        reconstructFilenameLabelled = reconstructedFilenameLabelledNoExt + ".c3d"

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

        # --------------------------SUBJECT -----------------------------------
        # Notice : Work with ONE subject by session
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.checkActivatedSubject(NEXUS, subjects)
        logging.info("Subject name : " + subject)

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

        logging.info("loaded model : %s" % (model.version))
        # --------------------------CONFIG ------------------------------------

        # --------------------CHECKING ------------------------------
        if model.version in ["CGM1.0", "CGM1.1", "CGM2.1", "CGM2.2"]:
            raise Exception(
                "Can t use SARA method with your model %s [minimal version : CGM2.3]"
                % (model.version))
        elif model.version == "CGM2.3":
            if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH +
                              "CGM2_3-pyCGM2.settings"):
                settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,
                                          "CGM2_3-pyCGM2.settings")
            else:
                settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,
                                          "CGM2_3-pyCGM2.settings")
        elif model.version in ["CGM2.4"]:
            if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH +
                              "CGM2_4-pyCGM2.settings"):
                settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,
                                          "CGM2_4-pyCGM2.settings")
            else:
                settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,
                                          "CGM2_4-pyCGM2.settings")
        elif model.version in ["CGM2.5"]:
            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")
        else:
            raise Exception("model version not found [contact admin]")

        # --------------------------SESSION INFOS ------------------------------------
        mpInfo, mpFilename = files.getMpFileContent(DATA_PATH, "mp.pyCGM2",
                                                    subject)

        #  translators management
        if model.version in ["CGM2.3"]:
            translators = files.getTranslators(DATA_PATH, "CGM2-3.translators")
        elif model.version in ["CGM2.4"]:
            translators = files.getTranslators(DATA_PATH, "CGM2-4.translators")
        elif model.version in ["CGM2.5"]:
            translators = files.getTranslators(DATA_PATH, "CGM2-5.translators")
        if not translators:
            translators = settings["Translators"]

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

        # --------------------------MODEL PROCESSING----------------------------
        model, acqFunc, side = kneeCalibration.sara(
            model,
            DATA_PATH,
            reconstructFilenameLabelled,
            translators,
            args.side,
            args.beginFrame,
            args.endFrame,
            forceBtkAcq=acq)

        # ----------------------SAVE-------------------------------------------
        files.saveModel(model, DATA_PATH, subject)
        logging.warning(
            "model updated with a  %s knee calibrated with SARA method" %
            (side))

        # save mp
        files.saveMp(mpInfo, model, DATA_PATH, mpFilename)
        # ----------------------VICON INTERFACE-------------------------------------------
        #--- update mp
        nexusUtils.updateNexusSubjectMp(NEXUS, model, subject)

        # -- add nexus Bones
        if side == "Left":
            nexusTools.appendBones(
                NEXUS,
                subject,
                acqFunc,
                "LFE0",
                model.getSegment("Left Thigh"),
                OriginValues=acqFunc.GetPoint("LKJC").GetValues())
        elif side == "Right":
            nexusTools.appendBones(
                NEXUS,
                subject,
                acqFunc,
                "RFE0",
                model.getSegment("Right Thigh"),
                OriginValues=acqFunc.GetPoint("RKJC").GetValues())

        proximalSegmentLabel = str(side + " Thigh")
        distalSegmentLabel = str(side + " Shank")

        # add modelled markers
        meanOr_inThigh = model.getSegment(proximalSegmentLabel).getReferential(
            "TF").getNodeTrajectory("KJC_Sara")
        meanAxis_inThigh = model.getSegment(
            proximalSegmentLabel).getReferential("TF").getNodeTrajectory(
                "KJC_SaraAxis")
        btkTools.smartAppendPoint(acqFunc, side + "_KJC_Sara", meanOr_inThigh)
        btkTools.smartAppendPoint(acqFunc, side + "_KJC_SaraAxis",
                                  meanAxis_inThigh)

        nexusTools.appendModelledMarkerFromAcq(NEXUS, subject,
                                               side + "_KJC_Sara", acqFunc)
        nexusTools.appendModelledMarkerFromAcq(NEXUS, subject,
                                               side + "_KJC_SaraAxis", acqFunc)

        #---Second model motion filter

        # consider new anatomical frame
        scp = modelFilters.StaticCalibrationProcedure(model)
        modMotion = modelFilters.ModelMotionFilter(
            scp, acqFunc, model, enums.motionMethod.Sodervisk)
        modMotion.segmentalCompute([proximalSegmentLabel, distalSegmentLabel])

        # projection of the Sara axis in the transversale plane
        # -- add nexus Bones
        if side == "Left":
            nexusTools.appendBones(
                NEXUS,
                subject,
                acqFunc,
                "LFE1",
                model.getSegment("Left Thigh"),
                OriginValues=acqFunc.GetPoint("LKJC").GetValues())
            print model.mp_computed["LeftKneeFuncCalibrationOffset"]
            logging.warning(
                "offset %s" %
                (str(model.mp_computed["LeftKneeFuncCalibrationOffset"])))
        elif side == "Right":
            nexusTools.appendBones(
                NEXUS,
                subject,
                acqFunc,
                "RFE1",
                model.getSegment("Right Thigh"),
                OriginValues=acqFunc.GetPoint("RKJC").GetValues())
            logging.warning(
                "offset %s" %
                (str(model.mp_computed["RightKneeFuncCalibrationOffset"])))
            print model.mp_computed["RightKneeFuncCalibrationOffset"]

    else:
        raise Exception("NO Nexus connection. Turn on Nexus")
Exemple #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)
def main():

    logging.info("------------------------------------------------")
    logging.info("------------QTM - pyCGM2 Workflow---------------")
    logging.info("------------------------------------------------")
    file = "session.xml"
    sessionXML = files.readXml(os.getcwd() + "\\", file)
    sessionDate = files.getFileCreationDate(os.getcwd() + "\\" + file)

    # ---------------------------------------------------------------------------
    # management of the Processed folder
    DATA_PATH = os.getcwd() + "\\" + "processed\\"
    files.createDir(DATA_PATH)

    staticMeasurement = utils.find_static(sessionXML)
    calibrateFilenameLabelled = qtmTools.getFilename(staticMeasurement)
    if not os.path.isfile(DATA_PATH + calibrateFilenameLabelled):
        shutil.copyfile(os.getcwd() + "\\" + calibrateFilenameLabelled,
                        DATA_PATH + calibrateFilenameLabelled)
        logging.info(
            "qualisys exported c3d file [%s] copied to processed folder" %
            (calibrateFilenameLabelled))

    dynamicMeasurements = qtmTools.findDynamic(sessionXML)
    for dynamicMeasurement in dynamicMeasurements:
        reconstructFilenameLabelled = qtmTools.getFilename(dynamicMeasurement)
        if not os.path.isfile(DATA_PATH + reconstructFilenameLabelled):
            shutil.copyfile(os.getcwd() + "\\" + reconstructFilenameLabelled,
                            DATA_PATH + reconstructFilenameLabelled)
            logging.info(
                "qualisys exported c3d file [%s] copied to processed folder" %
                (reconstructFilenameLabelled))

            acq = btkTools.smartReader(
                str(DATA_PATH + reconstructFilenameLabelled))

            if btkTools.checkForcePlateExist(acq):
                if "5" in btkTools.smartGetMetadata(acq, "FORCE_PLATFORM",
                                                    "TYPE"):
                    forceplates.correctForcePlateType5(acq)

            acq, zeniState = eventDetector.zeni(acq)

            if zeniState:
                btkTools.smartWriter(
                    acq, str(DATA_PATH + reconstructFilenameLabelled))

                cmd = "Mokka.exe \"%s\"" % (str(DATA_PATH +
                                                reconstructFilenameLabelled))
                os.system(cmd)

    # --------------------------GLOBAL SETTINGS ------------------------------------
    # global setting ( in user/AppData)

    if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_2-pyCGM2.settings"):
        settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,
                                  "CGM2_2-pyCGM2.settings")
    else:
        settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,
                                  "CGM2_2-pyCGM2.settings")
    # --------------------------MP ------------------------------------
    required_mp, optional_mp = qtmTools.SubjectMp(sessionXML)

    # --Check MP
    inspectprocedure = inspectProcedures.AnthropometricDataQualityProcedure(
        required_mp)
    inspector = inspectFilters.QualityFilter(inspectprocedure)
    inspector.run()

    #  translators management
    translators = files.getTranslators(os.getcwd() + "\\",
                                       "CGM2_2.translators")
    if not translators:
        translators = settings["Translators"]

    #  ikweight
    ikWeight = files.getIKweightSet(DATA_PATH, "CGM2_2.ikw")
    if not ikWeight:
        ikWeight = settings["Fitting"]["Weight"]

    # --------------------------MODEL CALIBRATION -----------------------
    logging.info(
        "--------------------------MODEL CALIBRATION -----------------------")
    staticMeasurement = utils.find_static(sessionXML)
    calibrateFilenameLabelled = qtmTools.getFilename(staticMeasurement)

    logging.info("----- CALIBRATION-  static file [%s]--" %
                 (calibrateFilenameLabelled))

    leftFlatFoot = toBool(
        staticMeasurement.Left_foot_normalised_to_static_trial.text)
    rightFlatFoot = toBool(
        staticMeasurement.Right_foot_normalised_to_static_trial.text)
    headFlat = toBool(staticMeasurement.Head_normalised_to_static_trial.text)

    markerDiameter = float(staticMeasurement.Marker_diameter.text) * 1000.0
    hjcMethod = settings["Calibration"]["HJC"]
    pointSuffix = None

    # Calibration checking
    # --------------------
    acqStatic = btkTools.smartReader(DATA_PATH + calibrateFilenameLabelled)
    for key in MARKERSETS.keys():
        logging.info("[pyCGM2] Checking of the %s" % (key))

        # presence
        ip_presence = inspectProcedures.MarkerPresenceQualityProcedure(
            acqStatic, markers=MARKERSETS[key])
        inspector = inspectFilters.QualityFilter(ip_presence)
        inspector.run()

        if ip_presence.markersIn != []:

            ip_gap = inspectProcedures.GapQualityProcedure(
                acqStatic, markers=ip_presence.markersIn)
            inspector = inspectFilters.QualityFilter(ip_gap)
            inspector.run()

            ip_swap = inspectProcedures.SwappingMarkerQualityProcedure(
                acqStatic, markers=ip_presence.markersIn)
            inspector = inspectFilters.QualityFilter(ip_swap)
            inspector.run()

            ip_pos = inspectProcedures.MarkerPositionQualityProcedure(
                acqStatic, markers=ip_presence.markersIn)
            inspector = inspectFilters.QualityFilter(ip_pos)

    # Calibration operation
    # --------------------
    logging.info("[pyCGM2] --- calibration operation ---")
    model, acqStatic = cgm2_2.calibrate(DATA_PATH, calibrateFilenameLabelled,
                                        translators, settings, required_mp,
                                        optional_mp, False, leftFlatFoot,
                                        rightFlatFoot, headFlat,
                                        markerDiameter, hjcMethod, pointSuffix)

    logging.info("----- CALIBRATION-  static file [%s]-----> DONE" %
                 (calibrateFilenameLabelled))

    # --------------------------MODEL FITTING ----------------------------------
    logging.info(
        "--------------------------MODEL FITTING ----------------------------------"
    )
    dynamicMeasurements = qtmTools.findDynamic(sessionXML)

    modelledC3ds = list()
    eventInspectorStates = list()
    for dynamicMeasurement in dynamicMeasurements:

        reconstructFilenameLabelled = qtmTools.getFilename(dynamicMeasurement)

        logging.info("----Processing of [%s]-----" %
                     (reconstructFilenameLabelled))
        mfpa = qtmTools.getForcePlateAssigment(dynamicMeasurement)
        momentProjection_text = dynamicMeasurement.Moment_Projection.text
        if momentProjection_text == "Default":
            momentProjection_text = settings["Fitting"]["Moment Projection"]
        if momentProjection_text == "Distal":
            momentProjection = enums.MomentProjection.Distal
        elif momentProjection_text == "Proximal":
            momentProjection = enums.MomentProjection.Proximal
        elif momentProjection_text == "Global":
            momentProjection = enums.MomentProjection.Global
        elif momentProjection_text == "JCS":
            momentProjection = enums.MomentProjection.JCS

        acq = btkTools.smartReader(DATA_PATH + reconstructFilenameLabelled)

        # Fitting checking
        # --------------------
        for key in MARKERSETS.keys():
            if key != "Calibration markers":

                logging.info("[pyCGM2] Checking of the %s" % (key))
                # presence
                ip_presence = inspectProcedures.MarkerPresenceQualityProcedure(
                    acq, markers=MARKERSETS[key])
                inspector = inspectFilters.QualityFilter(ip_presence)
                inspector.run()

                if ip_presence.markersIn != []:

                    ip_gap = inspectProcedures.GapQualityProcedure(
                        acq, markers=ip_presence.markersIn)
                    inspector = inspectFilters.QualityFilter(ip_gap)
                    inspector.run()

                    ip_swap = inspectProcedures.SwappingMarkerQualityProcedure(
                        acq, markers=ip_presence.markersIn)
                    inspector = inspectFilters.QualityFilter(ip_swap)
                    inspector.run()

                    ip_pos = inspectProcedures.MarkerPositionQualityProcedure(
                        acq, markers=ip_presence.markersIn)
                    inspector = inspectFilters.QualityFilter(ip_pos)

        # filtering
        # -----------------------

        # marker
        order = int(float(dynamicMeasurement.Marker_lowpass_filter_order.text))
        fc = float(dynamicMeasurement.Marker_lowpass_filter_frequency.text)

        signal_processing.markerFiltering(acq, order=order, fc=fc)

        # management of force plate type 5 and force plate filtering
        order = int(
            float(dynamicMeasurement.Forceplate_lowpass_filter_order.text))
        fc = float(dynamicMeasurement.Forceplate_lowpass_filter_frequency.text)

        if order != 0 and fc != 0:
            acq = btkTools.smartReader(DATA_PATH + reconstructFilenameLabelled)
            if btkTools.checkForcePlateExist(acq):
                if "5" in btkTools.smartGetMetadata(acq, "FORCE_PLATFORM",
                                                    "TYPE"):
                    forceplates.correctForcePlateType5(acq)
            signal_processing.markerFiltering(acq, order=order, fc=fc)
        else:
            if btkTools.checkForcePlateExist(acq):
                if "5" in btkTools.smartGetMetadata(acq, "FORCE_PLATFORM",
                                                    "TYPE"):
                    forceplates.correctForcePlateType5(acq)

        btkTools.smartWriter(acq, DATA_PATH + reconstructFilenameLabelled)

        # event checking
        # -----------------------
        inspectprocedureEvents = inspectProcedures.GaitEventQualityProcedure(
            acq)
        inspector = inspectFilters.QualityFilter(inspectprocedureEvents)
        inspector.run()
        eventInspectorStates.append(inspectprocedureEvents.state)

        # fitting operation
        # -----------------------
        logging.info("[pyCGM2] --- Fitting operation ---")
        acqGait = cgm2_2.fitting(model, DATA_PATH, reconstructFilenameLabelled,
                                 translators, settings, markerDiameter,
                                 pointSuffix, mfpa, momentProjection)

        outFilename = reconstructFilenameLabelled  # [:-4] + "_CGM1.c3d"
        btkTools.smartWriter(acqGait, str(DATA_PATH + outFilename))
        modelledC3ds.append(outFilename)

        logging.info("----Processing of [%s]-----> DONE" %
                     (reconstructFilenameLabelled))

    # --------------------------GAIT PROCESSING -----------------------
    if not all(eventInspectorStates):
        raise Exception(
            "[pyCGM2] Impossible to run Gait processing. Badly gait event detection. check the log file"
        )
    logging.info(
        "---------------------GAIT PROCESSING -----------------------")
    return model
Exemple #30
0
def main():

    parser = argparse.ArgumentParser(description='EMG-plot_temporalEMG')
    parser.add_argument('-bpf', '--BandpassFrequencies', nargs='+',help='bandpass filter')
    parser.add_argument('-ecf','--EnvelopLowpassFrequency', type=int, help='cutoff frequency for emg envelops')
    parser.add_argument('-r','--raw', action='store_true', help='rectified data')
    args = parser.parse_args()

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


    if NEXUS_PYTHON_CONNECTED: # run Operation


        # --- acquisition file and path----
        DATA_PATH, inputFileNoExt = NEXUS.GetTrialName()
        inputFile = inputFileNoExt+".c3d"


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

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

        # ----------------------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])]
                logging.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
            logging.info("Cut-off frequency set to %i instead of 6Hz ",envelopCutOffFrequency)

        rectifyBool = False if args.raw else True




        # --------------------------SUBJECT ------------------------------------
        subjects = NEXUS.GetSubjectNames()
        subject = nexusTools.checkActivatedSubject(NEXUS,subjects)


        # btk Acquisition
        nacf = nexusFilters.NexusConstructAcquisitionFilter(DATA_PATH,inputFileNoExt,subject)
        acq = nacf.build()

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


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

        openmaTrial = trialTools.convertBtkAcquisition(acq)



        plot.plotTemporalEMG(DATA_PATH,inputFile, EMG_LABELS,EMG_MUSCLES, EMG_CONTEXT, NORMAL_ACTIVITIES,exportPdf=True,rectify=rectifyBool,
                            openmaTrial=openmaTrial)

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