def sortedEvents(acq): evs = acq.GetEvents() contextLst = [] # recuperation de tous les contextes for it in btk.Iterate(evs): if it.GetContext() not in contextLst: contextLst.append(it.GetContext()) valueFrame = [] # recuperation de toutes les frames SANS doublons for it in btk.Iterate(evs): if it.GetFrame() not in valueFrame: valueFrame.append(it.GetFrame()) valueFrame.sort() # trie events = [] for frame in valueFrame: for it in btk.Iterate(evs): if it.GetFrame() == frame: events.append(it) newEvents = btk.btkEventCollection() for ev in events: newEvents.InsertItem(ev) acq.ClearEvents() acq.SetEvents(newEvents)
def sortedEvents(acq): evs = acq.GetEvents() contextLst=[] # recuperation de tous les contextes for it in btk.Iterate(evs): if it.GetContext() not in contextLst: contextLst.append(it.GetContext()) valueFrame=[] # recuperation de toutes les frames SANS doublons for it in btk.Iterate(evs): if it.GetFrame() not in valueFrame: valueFrame.append(it.GetFrame()) valueFrame.sort() # trie events =[] for frame in valueFrame: for it in btk.Iterate(evs): if it.GetFrame()==frame: events.append(it) # # import ipdb; ipdb.set_trace() # events =[] # for contextLst_it in contextLst: # for frameSort in valueFrame: # for it in btk.Iterate(evs): # if it.GetFrame()==frameSort and it.GetContext()==contextLst_it: # events.append(it) return events
def applyTranslators(acq, translators): """ Rename marker from translators :Parameters: - `acq` (btkAcquisition) - a btk acquisition instance - `translators` (dict) - translators """ acqClone = btk.btkAcquisition.Clone(acq) if translators is not None: modifiedMarkerList = list() # gather all labels for it in translators.items(): wantedLabel,initialLabel = it[0],it[1] if wantedLabel != initialLabel and initialLabel !="None": modifiedMarkerList.append(it[0]) modifiedMarkerList.append(it[1]) # Remove Modified Markers from Clone for point in btk.Iterate(acq.GetPoints()): if point.GetType() == btk.btkPoint.Marker: label = point.GetLabel() if label in modifiedMarkerList: acqClone.RemovePoint(utils.str(label)) logging.debug("point (%s) remove in the clone acq " %((label))) # Add Modify markers to clone for it in translators.items(): wantedLabel,initialLabel = it[0],it[1] if initialLabel !="None": if isPointExist(acq,wantedLabel): smartAppendPoint(acqClone,(wantedLabel+"_origin"),acq.GetPoint(utils.str(wantedLabel)).GetValues(),PointType=btk.btkPoint.Marker) # modified marker logging.warning("wantedLabel (%s)_origin created" %((wantedLabel))) if isPointExist(acq,initialLabel): if initialLabel in translators.keys(): if translators[initialLabel] == "None": logging.warning("Initial point (%s)and (%s) point to similar values" %((initialLabel), (wantedLabel))) smartAppendPoint(acqClone,(wantedLabel),acq.GetPoint(utils.str(initialLabel)).GetValues(),PointType=btk.btkPoint.Marker) smartAppendPoint(acqClone,(initialLabel),acq.GetPoint(utils.str(initialLabel)).GetValues(),PointType=btk.btkPoint.Marker) # keep initial marker elif translators[initialLabel] == wantedLabel: logging.warning("Initial point (%s) swaped with (%s)" %((initialLabel), (wantedLabel))) initialValue = acq.GetPoint(utils.str(initialLabel)).GetValues() wantedlValue = acq.GetPoint(utils.str(wantedLabel)).GetValues() smartAppendPoint(acqClone,(wantedLabel),initialValue,PointType=btk.btkPoint.Marker) smartAppendPoint(acqClone,("TMP"),wantedlValue,PointType=btk.btkPoint.Marker) acqClone.GetPoint(utils.str("TMP")).SetLabel(initialLabel) acqClone.RemovePoint(utils.str(wantedLabel+"_origin")) acqClone.RemovePoint(utils.str(initialLabel+"_origin")) else: logging.warning("Initial point (%s) renamed (%s) added into the c3d" %((initialLabel), (wantedLabel))) smartAppendPoint(acqClone,(wantedLabel),acq.GetPoint(utils.str(initialLabel)).GetValues(),PointType=btk.btkPoint.Marker) smartAppendPoint(acqClone,(initialLabel),acq.GetPoint(utils.str(initialLabel)).GetValues(),PointType=btk.btkPoint.Marker) else: logging.warning("initialLabel (%s) doesn t exist " %((initialLabel))) #raise Exception ("your translators are badly configured") return acqClone
def createEvents(NEXUS,subject,acq,labels): freq = acq.GetPointFrequency() events= acq.GetEvents() for ev in btk.Iterate(events): if ev.GetLabel() in labels: NEXUS.CreateAnEvent( subject, ev.GetContext(), ev.GetLabel(), int(ev.GetTime()*freq), 0.0 )
def changeSubjectName(btkAcq,subjectName): # change subject name in the metadata md = btkAcq.GetMetaData() if "SUBJECTS" in _getSectionFromMd(md): subjectMd = btkAcq.GetMetaData().FindChild(utils.str("SUBJECTS")).value() if "NAMES" in _getSectionFromMd(subjectMd): subjectMd.FindChild(utils.str("NAMES")).value().GetInfo().SetValue(0,utils.str(subjectName)) if "USES_PREFIXES" not in _getSectionFromMd(subjectMd): btk.btkMetaDataCreateChild(subjectMd, utils.str("USES_PREFIXES"), 0) if "ANALYSIS" in _getSectionFromMd(md): analysisMd = btkAcq.GetMetaData().FindChild(utils.str("ANALYSIS")).value() if "SUBJECTS" in _getSectionFromMd(analysisMd): anaSubMdi = analysisMd.FindChild(utils.str("SUBJECTS")).value().GetInfo() for i in range(0,anaSubMdi.GetDimension(1) ): anaSubMdi.SetValue(i,utils.str(subjectName)) events = btkAcq.GetEvents() for ev in btk.Iterate(events): ev.SetSubject(utils.str(subjectName)) # Do not work # eventMd = btkAcq.GetMetaData().FindChild("EVENT").value() # eventMdi = eventMd.FindChild("SUBJECTS").value().GetInfo() # for i in range(0,eventMdi.GetDimension(1) ): # eventMdi.SetValue(i,"TEST") return btkAcq
def run(self): fa = self.m_acq.GetAnalogFrequency() for analog in btk.Iterate(self.m_acq.GetAnalogs()): for label in self.m_labels: if analog.GetLabel() == label: values = analog.GetValues() # stop 50hz value50 = signal_processing.remove50hz(values, fa) # high pass and compensation with mean hpLower = self.m_hpf_low hpUpper = self.m_hpf_up valuesHp = signal_processing.highPass( value50, hpLower, hpUpper, fa) btkTools.smartAppendAnalog(self.m_acq, label + "_HPF", valuesHp, desc="high Pass filter") # rectification btkTools.smartAppendAnalog(self.m_acq, label + "_Rectify", np.abs(valuesHp), desc="rectify")
def isKineticFlag(acq): """ Flag up if correct kinetics available :Parameters: - `trial` (openma.trial) - an openma trial instance :Return: - `` (bool) - flag if kinetic available - `kineticEvent_times` (lst) - time of maximal Normal reaction Forces for both context - `kineticEvent_times_left` (lst) - time of maximal Normal reaction Forces for the Left context - `kineticEvent_times_right` (lst) - time of maximal Normal reaction Forces for the Right context """ kineticEvent_frames = [] kineticEvent_frames_left = [] kineticEvent_frames_right = [] events = acq.GetEvents() for ev in btk.Iterate(events): if ev.GetContext() == "General": if ev.GetLabel() in ["Left-FP", "Right-FP"]: kineticEvent_frames.append(ev.GetFrame()) if ev.GetLabel() in ["Left-FP"]: kineticEvent_frames_left.append(ev.GetFrame()) if ev.GetLabel() in ["Right-FP"]: kineticEvent_frames_right.append(ev.GetFrame()) if kineticEvent_frames == []: return False, 0, 0, 0 else: return True, kineticEvent_frames, kineticEvent_frames_left, kineticEvent_frames_right
def markerFiltering(btkAcq, order=2, fc=6): """ Low-pass filtering of all points in an acquisition :Parameters: - `btkAcq` (btkAcquisition) - btk acquisition instance - `fc` (double) - cut-off frequency - `order` (double) - order of the low-pass filter """ fp = btkAcq.GetPointFrequency() bPoint, aPoint = signal.butter(order, fc / (fp * 0.5), btype='lowpass') for pointIt in btk.Iterate(btkAcq.GetPoints()): if pointIt.GetType() == btk.btkPoint.Marker: x = signal.filtfilt(bPoint, aPoint, pointIt.GetValues()[:, 0], axis=0) y = signal.filtfilt(bPoint, aPoint, pointIt.GetValues()[:, 1], axis=0) z = signal.filtfilt(bPoint, aPoint, pointIt.GetValues()[:, 2], axis=0) pointIt.SetValues(np.array([x, y, z]).transpose())
def isPointExist(acq, label, ignorePhantom=True): """ Check if a point label exists inside an acquisition :Parameters: - `acq` (btkAcquisition) - a btk acquisition inctance - `label` (str) - point label """ try: acq.GetPoint(label) except RuntimeError: return False else: frameNumber = acq.GetPointFrameNumber() for it in btk.Iterate(acq.GetPoints()): if it.GetLabel() == label: LOGGER.logger.debug("[pyCGM2] marker (%s) is a phantom " % label) values = it.GetValues() residuals = it.GetResiduals() if not ignorePhantom: if all(residuals == -1): return False else: return True else: return True
def GetMarkerNames(acq): """ """ markerNames=[] for it in btk.Iterate(acq.GetPoints()): if it.GetType() == btk.btkPoint.Marker and it.GetLabel()[0] !="*": markerNames.append(it.GetLabel()) return markerNames
def createGeneralEvents(NEXUS, subject, acq, labels): freq = acq.GetPointFrequency() events = acq.GetEvents() for ev in btk.Iterate(events): if ev.GetLabel() in labels: #print ev.GetTime()*freq NEXUS.CreateAnEvent(str(subject), "General", str(ev.GetLabel()), int(ev.GetTime() * freq), 0.0)
def smartGetEvents(acq, label, context): evs = acq.GetEvents() out = list() for it in btk.Iterate(evs): if it.GetContext() == context and it.GetLabel() == label: out.append(it.GetFrame()) return out
def globalTransformationLabToOsim(acq, R_LAB_OSIM): points = acq.GetPoints() for it in btk.Iterate(points): if it.GetType() == btk.btkPoint.Marker: values = np.zeros(it.GetValues().shape) for i in range(0, it.GetValues().shape[0]): values[i, :] = np.dot(R_LAB_OSIM, it.GetValues()[i, :]) it.SetValues(values)
def applyValidFramesOnOutput(acq,validFrames): validFrames = np.asarray(validFrames) for it in btk.Iterate(acq.GetPoints()): if it.GetType() in [btk.btkPoint.Angle, btk.btkPoint.Force, btk.btkPoint.Moment,btk.btkPoint.Power]: values = it.GetValues() for i in range(0,3): values[:,i] = values[:,i] * validFrames it.SetValues(values)
def clearEvents(acq,labels): events= acq.GetEvents() newEvents=btk.btkEventCollection() for ev in btk.Iterate(events): if ev.GetLabel() not in labels: newEvents.InsertItem(ev) acq.ClearEvents() acq.SetEvents(newEvents)
def applyTranslators(acq, translators,keepInitial=False): """ Rename marker from translators :Parameters: - `acq` (btkAcquisition) - a btk acquisition instance - `translators` (dict) - translators - `keepInitial` (bool) - flag for avoiding to remove initial markers example of translators : "Translators" : { "LASI":"L_ASIS", "RASI":"", } 2nd line means RASI is with the acq """ acqClone = btk.btkAcquisition.Clone(acq) modifiedMarkerList = list() # gather all labels for it in translators.items(): wantedLabel,initialLabel = it[0],it[1] if wantedLabel != initialLabel and initialLabel !="": modifiedMarkerList.append(it[0]) modifiedMarkerList.append(it[1]) # Remove Modified Markers from Clone for point in btk.Iterate(acq.GetPoints()): if point.GetType() == btk.btkPoint.Marker: label = point.GetLabel() if label in modifiedMarkerList: acqClone.RemovePoint(label) # Add Modify markers to clone for it in translators.items(): wantedLabel,initialLabel = it[0],it[1] logging.debug("wantedLabel (%s) initialLabel (%s) " %(str(wantedLabel), str(initialLabel))) if wantedLabel != initialLabel and initialLabel !="": if isPointExist(acq,initialLabel): logging.debug("Initial point (%s) renamed (%s) added into the c3d" %(str(initialLabel), str(wantedLabel))) smartAppendPoint(acqClone,str(wantedLabel),acq.GetPoint(str(initialLabel)).GetValues(),PointType=btk.btkPoint.Marker) # modified marker if keepInitial: smartAppendPoint(acqClone,str(initialLabel),acq.GetPoint(str(initialLabel)).GetValues(),PointType=btk.btkPoint.Marker) # keep initial marker else : logging.debug("initialLabel (%s) doesn t exist " %(str(initialLabel))) return acqClone
def applyOnValidFrames(acq, validFrames): frameNumber = acq.GetPointFrameNumber() for it in btk.Iterate(acq.GetPoints()): if it.GetType() in [ btk.btkPoint.Angle, btk.btkPoint.Force, btk.btkPoint.Moment, btk.btkPoint.Power ]: for i in range(0, frameNumber): if not validFrames[i]: it.SetResidual(i, -1) it.SetValue(i, 0, 0) it.SetValue(i, 1, 0) it.SetValue(i, 2, 0)
def run(self): fa = self.m_acq.GetAnalogFrequency() for analog in btk.Iterate(self.m_acq.GetAnalogs()): for label in self.m_labels: if analog.GetLabel() == label: values = analog.GetValues() valuesFilt = signal_processing.enveloppe( values, self.m_fc, fa) btkTools.smartAppendAnalog(self.m_acq, label + "_Env", valuesFilt, desc="fc(" + str(self.m_fc) + ")")
def cleanAcq(acq): nframes = acq.GetPointFrameNumber() for it in btk.Iterate(acq.GetPoints()): if it.GetType() in [ btk.btkPoint.Marker, btk.btkPoint.Scalar, btk.btkPoint.Angle, btk.btkPoint.Force, btk.btkPoint.Moment, btk.btkPoint.Power ]: values = it.GetValues() if np.all(values == np.zeros(3)) or np.all( values == np.array([180, 0, 180])): LOGGER.logger.debug("point %s remove from acquisition" % (it.GetLabel())) acq.RemovePoint(it.GetLabel())
def getStartEndEvents(btkAcq,context,startLabel="Start", endLabel="End"): events= btkAcq.GetEvents() start=[] end=[] for ev in btk.Iterate(events): if ev.GetContext()== utils.str(context) and ev.GetLabel()==utils.str(startLabel) : start.append(ev.GetFrame()) if ev.GetContext()==utils.str(context) and ev.GetLabel()==utils.str(endLabel) : end.append(ev.GetFrame()) if start==[] or end==[]: return None,None if len(start)>1 or len(end)>1: raise("[pyCGM2]: You can t have multiple Start and End events" ) elif end<start: raise("[pyCGM2]: wrong order ( start<end)" ) else: return start[0],end[0]
def hasChild(md,mdLabel): """ Check if a label is within metadata .. note:: btk has a HasChildren method. HasChild doesn t exist, you have to use MetadataIterator to loop metadata :Parameters: - `md` (btkMetadata) - a btk metadata instance - `mdLabel` (str) - label of the metadata you want to check """ outMd = None for itMd in btk.Iterate(md): if itMd.GetLabel() == utils.str(mdLabel): outMd = itMd break return outMd
def run(self, acq, filename, options): ff = acq.GetFirstFrame() lf = acq.GetLastFrame() if "frameRange" in options.keys(): frameInit = options["frameRange"][0] - ff frameEnd = options["frameRange"][1] - ff + 1 else: frameInit = ff - ff frameEnd = lf - ff + 1 errorState = False indexes = [] # --- ground reaction force wrench --- pfe = btk.btkForcePlatformsExtractor() grwf = btk.btkGroundReactionWrenchFilter() pfe.SetInput(acq) pfc = pfe.GetOutput() grwf.SetInput(pfc) grwc = grwf.GetOutput() grwc.Update() fp_counter = 1 for fpIt in btk.Iterate(grwc): force_Z = fpIt.GetForce().GetValues()[frameInit:frameEnd, 2] max = np.max(force_Z) if max != 0: indexes = np.where(force_Z == max) if indexes[0].shape[0] > 1: LOGGER.logger.warning( "[pyCGM2-Anomaly] - check Force plate (%s) of file [%s] - signal Fz seems saturated" % (str(fp_counter), filename)) errorState = True fp_counter += 1 self.anomaly["Output"] = indexes self.anomaly["ErrorState"] = errorState
def getNumberOfModelOutputs(acq): n_angles = 0 n_forces = 0 n_moments = 0 n_powers = 0 for it in btk.Iterate(acq.GetPoints()): if it.GetType() == btk.btkPoint.Angle: n_angles += 1 if it.GetType() == btk.btkPoint.Force: n_forces += 1 if it.GetType() == btk.btkPoint.Moment: n_moments += 1 if it.GetType() == btk.btkPoint.Power: n_powers += 1 return n_angles, n_forces, n_moments, n_powers
def findNearestMarker(acq,i,marker,markerNames=None): values = acq.GetPoint(utils.str(marker)).GetValues()[i,:] if markerNames is None: markerNames=[] for it in btk.Iterate(acq.GetPoints()): if it.GetType() == btk.btkPoint.Marker and it.GetLabel()[0] !="*" and it.GetLabel() != utils.str(marker): markerNames.append(it.GetLabel()) j=0 out = np.zeros((len(markerNames),3)) for name in markerNames : out[j,:] = acq.GetPoint(name).GetValues()[i,:] j+=1 tree = spatial.KDTree(out) dist,index = tree.query(values) return markerNames[index],dist
def temporalPlot(figAxis, acq, pointLabel, axis, pointLabelSuffix=None, color=None, title=None, xlabel=None, ylabel=None, ylim=None, legendLabel=None, customLimits=None): ''' **Description :** plot descriptive statistical (average and sd corridor) gait traces from a pyCGM2.Processing.analysis.Analysis instance :Parameters: - `figAxis` (matplotlib::Axis ) - `acq` (ma.Trial) - a Structure item of an Analysis instance built from AnalysisFilter :Return: - matplotlib figure **Usage** .. code:: python ''' pointLabel = pointLabel + "_" + pointLabelSuffix if pointLabelSuffix is not None else pointLabel flag = btkTools.isPointExist(acq, pointLabel) if flag: point = acq.GetPoint(pointLabel) lines = figAxis.plot(point.GetValues()[:, axis], '-', color=color) appf = 1 else: flag = btkTools.isAnalogExist(acq, pointLabel) if flag: analog = acq.GetAnalog(pointLabel) lines = figAxis.plot(analog.GetValues()[:, axis], '-', color=color) appf = acq.GetNumberAnalogSamplePerFrame() if legendLabel is not None and flag: lines[0].set_label(legendLabel) if title is not None: figAxis.set_title(title, size=8) figAxis.tick_params(axis='x', which='major', labelsize=6) figAxis.tick_params(axis='y', which='major', labelsize=6) if xlabel is not None: figAxis.set_xlabel(xlabel, size=8) if ylabel is not None: figAxis.set_ylabel(ylabel, size=8) if ylim is not None: figAxis.set_ylim(ylim) if flag: for ev in btk.Iterate(acq.GetEvents()): colorContext = plotUtils.colorContext(ev.GetContext()) if ev.GetLabel() == "Foot Strike": figAxis.axvline(x=(ev.GetFrame() - acq.GetFirstFrame()) * appf, color=colorContext, linestyle="-") if ev.GetLabel() == "Foot Off": figAxis.axvline(x=(ev.GetFrame() - acq.GetFirstFrame()) * appf, color=colorContext, linestyle="--")
def markerFiltering(btkAcq, markers, order=2, fc=6, zerosFiltering=True): """ Low-pass filtering of all points in an acquisition :Parameters: - `btkAcq` (btkAcquisition) - btk acquisition instance - `fc` (double) - cut-off frequency - `order` (double) - order of the low-pass filter """ def filterZeros(array, b, a): N = len(array) indexes = list(range(0, N)) for i in range(0, N): if array[i] == 0: indexes[i] = -1 splitdata = [ x[x != 0] for x in np.split(array, np.where(array == 0)[0]) if len(x[x != 0]) ] splitIndexes = [ x[x != -1] for x in np.split(indexes, np.where(indexes == -1)[0]) if len(x[x != -1]) ] filtValues_section = list() for data in splitdata: padlen = 3 * max( len(a), len(b) ) # default as defined in https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.filtfilt.html if len(data) <= padlen: padlen = len(data) - 1 filtValues_section.append( signal.filtfilt(b, a, data, padlen=padlen, axis=0)) indexes = np.concatenate(splitIndexes) if splitIndexes != [] else [] values = np.concatenate( filtValues_section) if filtValues_section != [] else [] out = np.zeros((N)) j = 0 for i in indexes: out[i] = values[j] j += 1 return out fp = btkAcq.GetPointFrequency() bPoint, aPoint = signal.butter(order, fc / (fp * 0.5), btype='lowpass') for pointIt in btk.Iterate(btkAcq.GetPoints()): if pointIt.GetType() == btk.btkPoint.Marker and pointIt.GetLabel( ) in markers: label = pointIt.GetLabel() if zerosFiltering: x = filterZeros(pointIt.GetValues()[:, 0], bPoint, aPoint) y = filterZeros(pointIt.GetValues()[:, 1], bPoint, aPoint) z = filterZeros(pointIt.GetValues()[:, 2], bPoint, aPoint) else: x = signal.filtfilt(bPoint, aPoint, pointIt.GetValues()[:, 0], axis=0) y = signal.filtfilt(bPoint, aPoint, pointIt.GetValues()[:, 1], axis=0) z = signal.filtfilt(bPoint, aPoint, pointIt.GetValues()[:, 2], axis=0) btkAcq.GetPoint(label).SetValues(np.array([x, y, z]).transpose())
def GetAnalogNames(acq): analogNames=[] for it in btk.Iterate(acq.GetAnalogs()): analogNames.append(it.GetLabel()) return analogNames
def check(self): events = self.acq.GetEvents() if events != []: events_L = list() events_R = list() for ev in btk.Iterate(events): if ev.GetContext() == "Left": events_L.append(ev) if ev.GetContext() == "Right": events_R.append(ev) if events_L != [] and events_R != []: labels = [ it.GetLabel() for it in btk.Iterate(events) if it.GetLabel() in ["Foot Strike", "Foot Off"] ] frames = [ it.GetFrame() for it in btk.Iterate(events) if it.GetLabel() in ["Foot Strike", "Foot Off"] ] init = labels[0] for i in range(1, len(labels)): label = labels[i] frame = frames[i] if label == init: LOGGER.logger.error( "[pyCGM2-Checking] two consecutive (%s) detected at frame (%i)" % ((label), frame)) if self.exceptionMode: raise Exception( "[pyCGM2-Checking] two consecutive (%s) detected at frame (%i)" % ((label), frame)) self.state = False init = label if events_L != []: init = events_L[0].GetLabel() if len(events_L) > 1: for i in range(1, len(events_L)): label = events_L[i].GetLabel() if label == init: LOGGER.logger.error( "[pyCGM2-Checking] Wrong Left Event - two consecutive (%s) detected at frane (%i)" % ((label), events_L[i].GetFrame())) if self.exceptionMode: raise Exception( "[pyCGM2-Checking] Wrong Left Event - two consecutive (%s) detected at frane (%i)" % ((label), events_L[i].GetFrame())) self.state = False init = label else: LOGGER.logger.warning("Only one left events") self.state = False if events_R != []: init = events_R[0].GetLabel() if len(events_R) > 1: for i in range(1, len(events_R)): label = events_R[i].GetLabel() if label == init: LOGGER.logger.error( "[pyCGM2-Checking] Wrong Right Event - two consecutive (%s) detected at frane (%i)" % ((label), events_R[i].GetFrame())) if self.exceptionMode: raise Exception( "[pyCGM2-Checking] Wrong Right Event - two consecutive (%s) detected at frane (%i)" % ((label), events_R[i].GetFrame())) self.state = False init = label else: LOGGER.logger.warning("Only one right events ") self.state = False else: LOGGER.logger.error("[pyCGM2-Checking] No events are in trial") if self.exceptionMode: raise Exception( "[pyCGM2-Checking] No events are in the trials") self.state = False
def markerUnitConverter(acq,unitOffset): for it in btk.Iterate(acq.GetPoints()): if it.GetType() == btk.btkPoint.Marker: values = it.GetValues() it.SetValues(values*unitOffset)
def convertBtkAcquisition(acq, returnType="Trial"): root = ma.Node('root') trial = ma.Trial("Trial", root) framerate = acq.GetPointFrequency() firstFrame = acq.GetFirstFrame() numberAnalogSamplePerFrame = acq.GetNumberAnalogSamplePerFrame() analogFramerate = acq.GetAnalogFrequency() if firstFrame == 1: time_init = 0.0 else: time_init = firstFrame / framerate for it in btk.Iterate(acq.GetPoints()): label = it.GetLabel() values = it.GetValues() residuals = it.GetResiduals() desc = it.GetDescription() data = np.zeros((values.shape[0], 4)) data[:, 0:3] = values data[:, 3] = residuals[:, 0] if it.GetType() == btk.btkPoint.Marker: ts = ma.TimeSequence(str(label), 4, data.shape[0], framerate, time_init, ma.TimeSequence.Type_Marker, "mm", trial.timeSequences()) elif it.GetType() == btk.btkPoint.Angle: ts = ma.TimeSequence(str(label), 4, data.shape[0], framerate, time_init, ma.TimeSequence.Type_Angle, "Deg", trial.timeSequences()) elif it.GetType() == btk.btkPoint.Force: ts = ma.TimeSequence(str(label), 4, data.shape[0], framerate, time_init, ma.TimeSequence.Type_Force, "N.Kg-1", trial.timeSequences()) elif it.GetType() == btk.btkPoint.Moment: ts = ma.TimeSequence(str(label), 4, data.shape[0], framerate, time_init, ma.TimeSequence.Type_Moment, "Nmm.Kg-1", trial.timeSequences()) elif it.GetType() == btk.btkPoint.Power: ts = ma.TimeSequence(str(label), 4, data.shape[0], framerate, time_init, ma.TimeSequence.Type_Power, "Watt.Kg-1", trial.timeSequences()) else: logging.warning( "[pyCGM2] point [%s] not copied into openma trial" % (label)) ts.setData(data) ts.setDescription(desc) for it in btk.Iterate(acq.GetAnalogs()): label = it.GetLabel() values = it.GetValues() desc = it.GetDescription() data = values ts = ma.TimeSequence(str(label), 1, data.shape[0], analogFramerate, time_init, ma.TimeSequence.Type_Analog, "V", 1.0, 0.0, [-10.0, 10.0], trial.timeSequences()) ts.setData(data) ts.setDescription(desc) for it in btk.Iterate(acq.GetEvents()): label = it.GetLabel() time = it.GetTime() context = it.GetContext() subject = it.GetSubject() ev = ma.Event(label, time, context, str(subject), trial.events()) sortedEvents(trial) if returnType == "Trial": return trial else: return root