Beispiel #1
0
    def calculateRawEMG(self):
        origEMGNames = list()
        emgData = {}

        noSignals = 0
        for filename in self.fileNames:
            acq = qtools.fileOpen(filename)
            noSignals = acq.GetAnalogNumber()

        for number in range(
                noSignals):  # it is assumed same signals are in all trials
            signal = acq.GetAnalog(number)
            signalLabel = signal.GetLabel()

            if "Moment" not in signalLabel and "Force" not in signalLabel:
                origEMGNames.append(signal.GetLabel())

        for origSigName, ourSigName in signalMapping.emgNameMap.iteritems():
            if origSigName in origEMGNames and ourSigName is not "":
                emgData[ourSigName] = {}

                for filename in self.fileNames:
                    acq = qtools.fileOpen(filename)
                    measurementName = path.basename(filename)
                    measurementName = measurementName.replace('.c3d', '')

                    signal = acq.GetAnalog(origSigName)
                    values = np.array(signal.GetValues()[:, 0])

                    emgData[ourSigName][measurementName] = {}
                    emgData[ourSigName][measurementName] = values

        return emgData
    def getForceData(self, acq, frame, noFrames):
        pfe = btk.btkForcePlatformsExtractor()
        grwf = btk.btkGroundReactionWrenchFilter()
        pfe.SetInput(acq)
        pfc = pfe.GetOutput()
        grwf.SetInput(pfc)
        grwc = grwf.GetOutput()
        grwc.Update()

        for filename in self.fileNames:
            forceData = []
            acq = qtools.fileOpen(filename)

            for forceNumber in range(grwc.GetItemNumber()):
                forceData.append({
                    "id": forceNumber + 1,
                    "forceCount": 1,
                    "forcenumber": 2951,
                    "data": {
                        "force":
                        list(
                            self.resampleForceData(grwc, forceNumber, 0,
                                                   noFrames)[frame, :]),
                        "moment":
                        list(
                            self.resampleForceData(grwc, forceNumber, 1,
                                                   noFrames)[frame, :]),
                        "position":
                        list(
                            self.resampleForceData(grwc, forceNumber, 2,
                                                   noFrames)[frame, :])
                    }
                })
        return forceData
Beispiel #3
0
    def getValidC3dList(self, basenameOnly):
        measurementNames = []
        fileNames = []
        # check that pluginGait model calculations exist
        # check that events exist

        for filename in self.c3dFileList:
            origLabelNames = []
            acq = qtools.fileOpen(filename)
            noMarkers = range(acq.GetPointNumber())

            measurementName = path.basename(filename)
            measurementName = measurementName.replace('.c3d', '')

            for number in noMarkers:  # it is assumed that same signals are in all trials
                marker = acq.GetPoint(number)
                origLabelNames.append(marker.GetLabel())

            if "LAnkleAngles" in origLabelNames and acq.GetEventNumber() > 0:
                measurementNames.append(measurementName)
                fileNames.append(filename)

            if basenameOnly == True:
                out = measurementNames
            else:
                out = fileNames
        return out
Beispiel #4
0
    def getMetaValue(self, measurementName, groupLabelName, scalarName):
        acq = qtools.fileOpen(self.workingDirectory + measurementName + ".c3d")
        md = acq.GetMetaData()
        fieldFormat = md.FindChild(groupLabelName).value().FindChild(
            scalarName).value().GetInfo().GetFormatAsString()
        scalarValue = list()

        if fieldFormat == "Char":
            sValue = md.FindChild(groupLabelName).value().FindChild(
                scalarName).value().GetInfo().ToString()
            sValue = list(sValue)
            scalarValue = [i.rstrip() for i in sValue]
        else:
            scalarValue = md.FindChild(groupLabelName).value().FindChild(
                scalarName).value().GetInfo().ToDouble()
        return scalarValue
    def getSegAngles(self):
        for filename in self.fileNames:
            measurementName = os.path.basename(filename)
            measurementName = measurementName.replace('.c3d', '')
            if '1' in measurementName:  #temporaty
                acq = qtools.fileOpen(filename)
                noFrames = acq.GetLastFrame() - acq.GetFirstFrame()
                sig = {}

                for sigName in self.segmentRotList:
                    if qtools.isPointExist(acq, sigName + 'O'):
                        sig[sigName] = np.array([0, 0, 0])
                        for frame in range(noFrames):
                            sig[sigName] = np.vstack(
                                (sig[sigName],
                                 self.combineCardanSeqPerFrame(
                                     acq, sigName.split(), frame)))
        return sig
Beispiel #6
0
    def calculateEvents(self, forceThreshold):
        self.forceThreshold = forceThreshold
        eventLabels = dict()
        eventsGroupped = dict()
        eventData = dict()
        null = None

        for filename in self.fileNames:
            acq = qtools.fileOpen(filename)

            measurementName = path.basename(filename)
            measurementName = measurementName.replace('.c3d', '')

            eventLabels[measurementName] = []

            frameRate = acq.GetPointFrequency()

            noEvents = range(acq.GetEventNumber())
            eventTimesLHS = list()
            eventTimesRHS = list()
            eventTimesLTO = list()
            eventTimesRTO = list()

            for number in noEvents:
                firstFrame = acq.GetFirstFrame()
                lastFrame = acq.GetLastFrame()
                # extract the event of the aquisition
                event = acq.GetEvent(number)
                eventFrame = event.GetFrame() - firstFrame
                eventTime = eventFrame / frameRate
                eventName = event.GetLabel()
                eventSide = event.GetContext(
                )  # return a string representing the Context
                eventLabelOrig = eventSide + " " + eventName
                eventLabel = qtools.renameSignal(signalMapping.eventNameMap,
                                                 eventLabelOrig)

                if eventLabel not in eventLabels[
                        measurementName] and eventLabel != 'None':
                    eventLabels[measurementName].append(eventLabel)

                if eventLabel == "LHS":
                    eventTimesLHS.append(eventTime)
                    eventsGroupped[measurementName + "_" +
                                   eventLabel] = eventTimesLHS
                    if self.checkSignalExists(acq, measurementName,
                                              'LGroundReactionForce'):
                        eventTimeLON = self.getOnOffEvent(
                            acq, measurementName, 'LGroundReactionForce',
                            frameRate, firstFrame, lastFrame, eventFrame,
                            eventTime, 'on')
                        if eventTimeLON:
                            eventsGroupped[measurementName +
                                           "_LON"] = eventTimeLON
                            eventLabels[measurementName].append('LON')
                elif eventLabel == "RHS":
                    eventTimesRHS.append(eventTime)
                    eventsGroupped[measurementName + "_" +
                                   eventLabel] = eventTimesRHS
                    if self.checkSignalExists(acq, measurementName,
                                              'RGroundReactionForce'):
                        eventTimeRON = self.getOnOffEvent(
                            acq, measurementName, 'RGroundReactionForce',
                            frameRate, firstFrame, lastFrame, eventFrame,
                            eventTime, 'on')
                        if eventTimeRON:
                            eventsGroupped[measurementName +
                                           "_RON"] = eventTimeRON
                            eventLabels[measurementName].append('RON')
                elif eventLabel == "LTO":
                    eventTimesLTO.append(eventTime)
                    eventsGroupped[measurementName + "_" +
                                   eventLabel] = eventTimesLTO
                    if self.checkSignalExists(acq, measurementName,
                                              'LGroundReactionForce'):
                        eventTimeLOFF = self.getOnOffEvent(
                            acq, measurementName, 'LGroundReactionForce',
                            frameRate, firstFrame, lastFrame, eventFrame,
                            eventTime, 'off')
                        if eventTimeLOFF:
                            eventsGroupped[measurementName +
                                           "_LOFF"] = eventTimeLOFF
                            eventLabels[measurementName].append('LOFF')
                elif eventLabel == "RTO":
                    eventTimesRTO.append(eventTime)
                    eventsGroupped[measurementName + "_" +
                                   eventLabel] = eventTimesRTO
                    if self.checkSignalExists(acq, measurementName,
                                              'RGroundReactionForce'):
                        eventTimeROFF = self.getOnOffEvent(
                            acq, measurementName, 'RGroundReactionForce',
                            frameRate, firstFrame, lastFrame, eventFrame,
                            eventTime, 'off')
                        if eventTimeROFF:
                            eventsGroupped[measurementName +
                                           "_ROFF"] = eventTimeROFF
                            eventLabels[measurementName].append('ROFF')

            for eventLabel in eventLabels[measurementName]:
                eventData[measurementName + "_" + eventLabel] = {
                    "measurement": measurementName,
                    "values":
                    eventsGroupped[measurementName + "_" + eventLabel],
                    "rate": null
                }
        return (eventData, eventLabels)
def getFrameAndAnalogRateFromC3D(filePath):
    acq = qtools.fileOpen(filePath)

    frameRate = acq.GetPointFrequency()
    analogRate = acq.GetAnalogFrequency()
    return frameRate, analogRate
    def createJson(self):
        sig = {}
        for filename in self.fileNames:
            measurementName = os.path.basename(filename)
            measurementName = measurementName.replace('.c3d', '')
            if '1' in measurementName:  #temporaty
                acq = qtools.fileOpen(filename)
                noFrames = acq.GetLastFrame() - acq.GetFirstFrame()

                frames = []
                sig[measurementName] = {}
                for frame in range(noFrames):
                    fr = frame + 1
                    frames.append({
                        "frame":
                        fr,
                        "markers":
                        self.getMarkersPerFrame(acq, self.markerList, frame),
                        "segmentPos":
                        self.getMarkersPerFrame(acq, self.segmentList, frame),
                        "segmentRot":
                        self.combineCardanSeqPerFrame(acq, self.segmentRotList,
                                                      frame),
                        "force":
                        self.getForceData(acq, frame, noFrames)
                    })
                    sig[measurementName] = self.combineCardanSeqPerFrame(
                        acq, self.segmentRotList, frame)

                root = {
                    "startTime":
                    acq.GetFirstFrame() / acq.GetPointFrequency(),
                    "endTime": (acq.GetLastFrame() - acq.GetFirstFrame()) /
                    acq.GetPointFrequency(),
                    "frameRate":
                    acq.GetPointFrequency(),
                    "uncroppedLength":
                    acq.GetLastFrame() / acq.GetPointFrequency(),
                    "labels": [self.labels(acq, self.markerList)],
                    "bones":
                    self.bones(acq),
                    "segments":
                    self.segments(acq),
                    "frames":
                    frames,
                    "force": {
                        "lengthUnit": "mm",
                        "forceUnit": "F",
                        "plates": self.calculateForcePlateInfo(acq)
                    }
                }

                #            with open(self.workingDirectory + measurementName + '-3d-data.json', 'w') as f:
                #                json.dump(root, f, indent=4,sort_keys=True)
                with open(
                        'E:\\Qualisys_repository\\q3dv\\examples\\data\\plugingait.js',
                        'w') as f:  #temporaty
                    f.write('var plugingait = ')  #temporaty
                with open(
                        'E:\\Qualisys_repository\\q3dv\\examples\\data\\plugingait.js',
                        'a') as f:  #temporaty
                    json.dump(root, f, indent=4, sort_keys=True)  #temporaty
        return root
Beispiel #9
0
    def getAllGVS(self):

        mapSignalNames = [
            "Left Pelvic Angles", "Left Hip Angles", "Left Knee Angles",
            "Left Ankle Angles", "Left Foot Progression",
            "Right Pelvic Angles", "Right Hip Angles", "Right Knee Angles",
            "Right Ankle Angles", "Right Foot Progression"
        ]
        components = {'X', 'Y', 'Z'}
        measuredValuesNormalized = {}
        gvs = {}
        gvsLn = {}

        tree = ET.parse(
            path.join(qtmWebGaitReport.GAIT_WEB_REPORT_PATH,
                      "qtmWebGaitReport", "Normatives", "normatives.xml"))
        xmlRoot = tree.getroot()

        for sigName in mapSignalNames:
            measuredValuesNormalized[sigName] = {}

            for component in components:
                gvs[sigName + "_" + component + "_gvs"] = {}
                gvsLn[sigName + "_" + component + "_gvs_ln_mean"] = {}

                normValues = self.getNormValuesFromV3DXml(
                    xmlRoot, sigName + "_" + component)

                if normValues is not "":
                    if component == "X":
                        i = 0
                    elif component == "Y":
                        i = 1
                    elif component == "Z":
                        i = 2

                    for filename in self.fileNames:
                        acq = qtools.fileOpen(filename)
                        measurementName = path.basename(filename)
                        measurementName = measurementName.replace('.c3d', '')

                        measuredValuesNormalized[sigName][measurementName] = {}
                        gvs[sigName + "_" + component +
                            "_gvs"][measurementName] = {}
                        gvsLn[sigName + "_" + component +
                              "_gvs_ln_mean"][measurementName] = {}

                        for origSigName, ourSigName in signalMapping.sigNameMap.iteritems(
                        ):
                            if ourSigName == sigName:
                                pigSigName = origSigName

                        signal = acq.GetPoint(pigSigName)
                        measuredValues = scipy.signal.resample(
                            signal.GetValues(), 101)  # normalize to 101 points
                        measuredValuesNormalized[sigName][
                            measurementName] = measuredValues

                        sub = measuredValuesNormalized[sigName][
                            measurementName][:, i] - normValues
                        gvs[sigName + "_" + component +
                            "_gvs"][measurementName] = qtools.rootMeanSquared(
                                sub)
                        gvsLn[sigName + "_" + component +
                              "_gvs_ln_mean"][measurementName] = np.log(
                                  gvs[sigName + "_" + component +
                                      "_gvs"][measurementName])

        return (gvs, gvsLn)
    def measurementInfo(self, extra_settings={}):
        info = []

        for filename in self.fileNames:
            acq = qtools.fileOpen(filename)
            measurementName = path.basename(filename)
            measurementName = measurementName.replace('.c3d', '')

            val = acq.GetDuration()
            startOffset = acq.GetFirstFrame() / acq.GetPointFrequency()
            frameRate = acq.GetPointFrequency()
            originalDuration = acq.GetDuration()
            creation_date = datetime.fromtimestamp(get_creation_date(filename))
            creationDate = str(creation_date.date())
            creationTime = str(creation_date.time())

            diagnosis = ""

            patientName = "UNSPECIFIED"
            bodyHeight = 0
            bodyWeight = 0

            video_filenames = get_mp4_filenames(
                get_parent_folder_absolute_path(self.workingDirectory))
            resources = create_resources(video_filenames, extra_settings)

            fields = [
                {
                    "id": "Creation date",
                    "value": creationDate,
                    "type": "text"
                },
                {
                    "id": "Creation time",
                    "value": creationTime,
                    "type": "text"
                },
                {
                    "id": "Diagnosis",
                    "value": diagnosis,
                    "type": "text"
                },
                {
                    "id": "Last name",
                    "value": patientName,
                    "type": "text"
                },
                {
                    "id": "Height",
                    "value": bodyHeight,
                    "type": "text"
                },
                {
                    "id": "Weight",
                    "value": bodyWeight,
                    "type": "text"
                },
            ]

            info.append({
                "duration": val,
                "startOffset": startOffset,
                "originalDuration": originalDuration,
                "rate": frameRate,
                "id": measurementName,
                "fields": fields,
                "resources": resources
            })
        return info
Beispiel #11
0
    def calculateTimeseries(self):
        #metaObj = metadata.Metadata(self.workingDirectory)
        timeseries = dict()
        components = {'X', 'Y', 'Z'}
        origLabelNames = list()
        origLabels = {}

        for filename in self.fileNames:  # create list of signals. Make sure that missing signal in one of trial will not break it
            measurementName = path.basename(filename)
            measurementName = measurementName.replace('.c3d', '')
            origLabels[measurementName] = {}
            origLabelNamesSelected = list()

            acq = qtools.fileOpen(filename)
            md = acq.GetMetaData()

            if "PROCESSING" in _getSectionFromMd(md):
                processingMd = acq.GetMetaData().FindChild(
                    "PROCESSING").value()

                if "Weight" in _getSectionFromMd(processingMd):
                    mass = processingMd.FindChild(
                        "Weight").value().GetInfo().ToString()

                elif "Bodymass" in _getSectionFromMd(processingMd):
                    mass = processingMd.FindChild(
                        "Bodymass").value().GetInfo().ToString()

            noMarkers = range(acq.GetPointNumber())

            for number in noMarkers:
                marker = acq.GetPoint(number)
                origLabelNames.append(marker.GetLabel())

            for origLabelName in origLabelNames:
                if origLabelName in signalMapping.sigNameMap and signalMapping.sigNameMap.get(
                        origLabelName) is not "":
                    origLabelNamesSelected.append(origLabelName)

            origLabels[measurementName] = origLabelNamesSelected

        for origLabelNameSelected in origLabelNamesSelected:
            if signalMapping.sigNameMap.get(origLabelNameSelected) is not "":
                ourSigName = signalMapping.sigNameMap.get(
                    origLabelNameSelected)

                for component in components:
                    timeseries[ourSigName + "_" + component] = {}

                    for filename in self.fileNames:
                        acq = qtools.fileOpen(filename)
                        measurementName = path.basename(filename)
                        measurementName = measurementName.replace('.c3d', '')

                        if component == "X":
                            i = 0
                        elif component == "Y":
                            i = 1
                        elif component == "Z":
                            i = 2
                        bodyMass = float(mass[0])
                        constant2 = 0
                        if "Moment" in ourSigName:
                            constant1 = 1000  # converts from mm to m
                        elif "GRF" in ourSigName:
                            if component == "X":
                                i = 1
                                constant1 = bodyMass * 9.81 * -1
                            elif component == "Y":
                                i = 0
                                constant1 = bodyMass * 9.81 * -1
                            else:
                                constant1 = bodyMass * 9.81
                        elif "Ankle Angles" in ourSigName and component == "Y":
                            constant1 = -1
                        elif "Prog" in ourSigName and component == "X":
                            constant1 = -1
                            constant2 = -90
                        else:
                            constant1 = 1

                        if "Power" in ourSigName:
                            i = 2

                        if origLabelNameSelected in origLabels[
                                measurementName]:
                            marker = acq.GetPoint(origLabelNameSelected)
                            values = (np.array(marker.GetValues()[:, i]) /
                                      constant1) + constant2
                            timeseries[ourSigName + "_" +
                                       component][measurementName] = {}
                            timeseries[ourSigName + "_" +
                                       component][measurementName] = values
        return timeseries