def compute_difference(file1, file2, angle_name1, angle_name2): '''Check difference between 2 angles on c3d file''' reader = btk.btkAcquisitionFileReader() reader.SetFilename(file1) reader.Update() acq1 = reader.GetOutput() reader = btk.btkAcquisitionFileReader() reader.SetFilename(file2) reader.Update() acq2 = reader.GetOutput() angle1 = acq1.GetPoint(angle_name1).GetValues() angle2 = acq2.GetPoint(angle_name2).GetValues() nf = min(acq1.GetPointFrameNumber(), acq2.GetPointFrameNumber()) diffx = 0 diffy = 0 diffz = 0 for f in range(nf): dx = angle1[f, 0] - angle2[f, 0] dy = angle1[f, 1] - angle2[f, 1] dz = angle1[f, 2] - angle2[f, 2] if np.abs(dx) > np.abs(diffx): diffx = dx if np.abs(dy) > np.abs(diffy): diffy = dy if np.abs(dz) > np.abs(diffz): diffz = dz return (diffx, diffy, diffz)
def _get_c3dacq(c3dfile): """Get a btk c3dacq object. Object is returned from cache if filename and digest match. """ reader = btk.btkAcquisitionFileReader() c3dfile = str(c3dfile) # accept Path objects too (btk won't eat those) reader.SetFilename(c3dfile) try: reader.Update() except RuntimeError as e: # this is a workaround for an unresolved BTK Python 3 bug, where # filenames containing extended characters cannot be read # this is somehow related to Windows character set handling, since # it only manifests on some machines if not _is_ascii(c3dfile) and sys.version_info.major == 3: logger.warning( 'trying to work around possible btk extended chars bug') # just copy the file into another directory temp_path = _named_tempfile(suffix='.c3d') shutil.copy2(c3dfile, temp_path) logger.warning(f'using {temp_path}') # we need to create a new reader here # (the previous update call screws it up somehow) reader = btk.btkAcquisitionFileReader() reader.SetFilename(str(temp_path)) reader.Update() # we should be able to remove the temp file now temp_path.unlink() else: # something else went wrong during read raise e return reader.GetOutput()
def test_FileSample10Type2(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + "sample10/TYPE-2.C3D") pfe = btk.btkForcePlatformsExtractor() pfe.SetInput(reader.GetOutput()) pfc = pfe.GetOutput() pfe.Update() self.assertEqual(pfc.GetItemNumber(), 1) pf1 = pfc.GetItem(0) self.assertEqual(pf1.GetType(), 2) self.assertEqual(pf1.GetChannelNumber(), 6) self.assertEqual(pf1.GetChannel(0).GetLabel(), "FX1") self.assertEqual(pf1.GetChannel(1).GetLabel(), "FY1") self.assertEqual(pf1.GetChannel(2).GetLabel(), "FZ1") self.assertEqual(pf1.GetChannel(3).GetLabel(), "MX1") self.assertEqual(pf1.GetChannel(4).GetLabel(), "MY1") self.assertEqual(pf1.GetChannel(5).GetLabel(), "MZ1") o1 = numpy.array([[-1.6] , [0.7], [37.5]]) numpy.testing.assert_array_almost_equal(pf1.GetOrigin(), o1, 4) self.assertAlmostEqual(pf1.GetChannel(0).GetValues()[1], 0.08843, 5) self.assertAlmostEqual(pf1.GetChannel(0).GetValues()[3], -0.08843, 5) self.assertAlmostEqual(pf1.GetChannel(0).GetValues()[1020], -69.59441, 5) self.assertAlmostEqual(pf1.GetChannel(0).GetValues()[1021], -72.24731, 5) self.assertAlmostEqual(pf1.GetChannel(1).GetValues()[0], 0.17762, 5) self.assertAlmostEqual(pf1.GetChannel(3).GetValues()[2], 36.83129, 4) self.assertAlmostEqual(pf1.GetChannel(3).GetValues()[560], 73.66259, 4) self.assertAlmostEqual(pf1.GetChannel(3).GetValues()[561], 0.0, 5)
def open_c3d_data(self, path): ''' Receives c3d file path Returns: Aquisition in btk format Numpy array where: shape = (markers, frames, 3 (x, y, z)) Headers list ''' reader = btk.btkAcquisitionFileReader() reader.SetFilename(path) acq = reader.GetOutput() acq.Update() # array numpy headers = [] data = np.empty((3, acq.GetPointFrameNumber())) data.fill(np.nan) for i in range(0, acq.GetPoints().GetItemNumber()): label = acq.GetPoint(i).GetLabel() headers.append(label) data = np.dstack((data, acq.GetPoint(label).GetValues().T)) data = data.T data = np.delete(data, 0, axis=0) # deletando primeira linha feita na criacao do array return acq, data, headers
def test_Sample01_Eb015vi(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample01/Eb015vi.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetMaxInterpolationGap(), 10) self.assertEqual(acq.GetPointFrequency(), 50) self.assertEqual(acq.GetPointNumber(), 26) self.assertEqual(acq.GetAnalogFrequency(), 200) self.assertEqual(acq.GetAnalogNumber(), 16) self.assertEqual(acq.GetPoint(0).GetLabel(), 'RFT1') self.assertAlmostEqual(acq.GetPoint(0).GetValues()[8,0], 250.4166, 3) self.assertAlmostEqual(acq.GetPoint(17).GetValues()[16,0], 285, 3) self.assertAlmostEqual(acq.GetPoint(17).GetValues()[16,1], 222.4166, 3) self.assertAlmostEqual(acq.GetPoint(17).GetValues()[16,2], 564.4166, 3) self.assertAlmostEqual(acq.GetPoint(0).GetResiduals()[0], 1.3333, 3) self.assertAlmostEqual(acq.GetPoint(14).GetResiduals()[20], 1.91667, 3) self.assertAlmostEqual(acq.GetAnalog(0).GetValues()[0], -26.6599, 3) self.assertAlmostEqual(acq.GetAnalog(0).GetValues()[1], -25.8, 3) self.assertEqual(acq.GetEventNumber(), 3) self.assertEqual(acq.GetEvent(0).GetLabel(), 'RIC') self.assertAlmostEqual(acq.GetEvent(0).GetTime(), 2.72, 3) self.assertEqual(acq.GetEvent(1).GetLabel(), 'RHS') self.assertAlmostEqual(acq.GetEvent(1).GetTime(), 5.40, 3) self.assertEqual(acq.GetEvent(2).GetLabel(), 'RTO') self.assertAlmostEqual(acq.GetEvent(2).GetTime(), 7.32, 3)
def convert_and_write(from_c3d_filename, to_c3d_filename): # Makes reader from filename reader = btk.btkAcquisitionFileReader() reader.SetFilename(from_c3d_filename) reader.Update() acq=reader.GetOutput() points=acq.GetPoints() n_points=points.GetItemNumber() print '\n \n Updating values in c3d object' n=0 for f in xrange(acq.GetPointFrameNumber()): for i in xrange(n_points): point=acq.GetPoint(i) data=point.GetValues()[f,:] point.SetDataSlice(f, *[1000*x for x in data]) if not f%5000: n=n+1 print '\n So far updated {} frames'.format(n*5000) writer = btk.btkAcquisitionFileWriter() writer.SetInput(acq) writer.SetFilename(to_c3d_filename) writer.Update() print '\n Converted c3d file from: \n {}'.format(from_c3d_filename) print '\n Wrote converted c3d file to: \n {}'.format(to_c3d_filename)
def test_FileSample10Type4(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + "sample10/TYPE-4.C3D") pfe = btk.btkForcePlatformsExtractor() pfe.SetInput(reader.GetOutput()) pfc = pfe.GetOutput() pfe.Update() self.assertEqual(pfc.GetItemNumber(), 1) pf1 = pfc.GetItem(0) self.assertEqual(pf1.GetType(), 4) self.assertEqual(pf1.GetChannelNumber(), 6) self.assertEqual(pf1.GetChannel(0).GetFrameNumber(), 3980) self.assertEqual(pf1.GetChannel(0).GetLabel(), "FX1") self.assertEqual(pf1.GetChannel(1).GetLabel(), "FY1") self.assertEqual(pf1.GetChannel(2).GetLabel(), "FZ1") self.assertEqual(pf1.GetChannel(3).GetLabel(), "MX1") self.assertEqual(pf1.GetChannel(4).GetLabel(), "MY1") self.assertEqual(pf1.GetChannel(5).GetLabel(), "MZ1") cal = numpy.array([[ 1.5270, 0.0140, 0.0460,-4.2840, -5.4940, 2.8560 ], [-0.0050, 1.5390,-0.0190, 17.1600, 5.6680, -9.6390 ], [ 0.0000,-0.0090, 5.9880, 13.2330, 13.2500, 4.6090 ], [ 0.0000, 0.0020, 0.0000,741.8710, -0.5390, -0.5970 ], [ 0.0020,-0.0010, 0.000, -1.6820,739.6310, 2.0420 ], [-0.0020,-0.0050,-0.0020, -3.2500, -0.5940,391.8790 ]]) numpy.testing.assert_array_almost_equal(pf1.GetCalMatrix(), cal.transpose(), 4) o1 = numpy.array([[-1.6] , [0.7], [37.5]]) numpy.testing.assert_array_almost_equal(pf1.GetOrigin(), o1)
def extractintoDict(filename, TrialNum): reader = btk.btkAcquisitionFileReader() reader.SetFilename(filename) # set a filename to the reader reader.Update() trialacq = reader.GetOutput() # is the btk aquisition object patient["StepUp"][TrialNum] ={} patient["StepUp"][TrialNum].update({"Left": extractvalues(trialacq)}) patient["StepUp"][TrialNum].update({"Right": extractvalues(trialacq)}) patient["StepUp"][TrialNum].update({"startframe":trialacq.GetFirstFrame()})#first frame of data patient["StepUp"][TrialNum].update({"Filename":filename}) # #instantiate the nested dict to input in the footstrike etc for LR in ['Right','Left']: for key in patient["StepUp"][TrialNum][LR].keys(): arr = patient["StepUp"][TrialNum][LR][key] patient["StepUp"][TrialNum][LR][key] = { 'x':arr[:,0].tolist(), 'y':arr[:,1].tolist(), 'z':arr[:,2].tolist() } #call other function"returnvalues" to extract rest of data #returnvalues(trialacq) global ID try: ID = trialacq.GetEvent().GetSubject() vID.set(ID) except: pass
def test_Sample01_Eb015vi(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample01/Eb015vi.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetMaxInterpolationGap(), 10) self.assertEqual(acq.GetPointFrequency(), 50) self.assertEqual(acq.GetPointNumber(), 26) self.assertEqual(acq.GetAnalogFrequency(), 200) self.assertEqual(acq.GetAnalogNumber(), 16) self.assertEqual(acq.GetPoint(0).GetLabel(), 'RFT1') self.assertAlmostEqual(acq.GetPoint(0).GetValues()[8, 0], 250.4166, 3) self.assertAlmostEqual(acq.GetPoint(17).GetValues()[16, 0], 285, 3) self.assertAlmostEqual( acq.GetPoint(17).GetValues()[16, 1], 222.4166, 3) self.assertAlmostEqual( acq.GetPoint(17).GetValues()[16, 2], 564.4166, 3) self.assertAlmostEqual(acq.GetPoint(0).GetResiduals()[0], 1.3333, 3) self.assertAlmostEqual(acq.GetPoint(14).GetResiduals()[20], 1.91667, 3) self.assertAlmostEqual(acq.GetAnalog(0).GetValues()[0], -26.6599, 3) self.assertAlmostEqual(acq.GetAnalog(0).GetValues()[1], -25.8, 3) self.assertEqual(acq.GetEventNumber(), 3) self.assertEqual(acq.GetEvent(0).GetLabel(), 'RIC') self.assertAlmostEqual(acq.GetEvent(0).GetTime(), 2.72, 3) self.assertEqual(acq.GetEvent(1).GetLabel(), 'RHS') self.assertAlmostEqual(acq.GetEvent(1).GetTime(), 5.40, 3) self.assertEqual(acq.GetEvent(2).GetLabel(), 'RTO') self.assertAlmostEqual(acq.GetEvent(2).GetTime(), 7.32, 3)
def open_c3d(f_path=None): if f_path is None: return None reader = btk.btkAcquisitionFileReader() reader.SetFilename(f_path) reader.Update() acq = reader.GetOutput() return acq
def __init__(self, input_data): """Loads a motion capture file (currently a C3D file) to create a new MocapFile object """ import btk #Declare fields self._all_frames = None self._timestamps = None self._read_pointer = 0 #Next element that will be returned by read() #Check whether data is another MocapFile instance if hasattr(input_data, '_all_frames') and hasattr(input_data, '_timestamps'): self._all_frames = input_data._all_frames self._timestamps = input_data._timestamps #If not, treat data as a filepath to a C3D file else: #Initialize the file reader data = btk.btkAcquisitionFileReader() data.SetFilename(input_data) data.Update() data = data.GetOutput() #Get the number of markers tracked in the file num_points = 0 run = True while run: try: data.GetPoint(num_points) num_points = num_points + 1 except(RuntimeError): run = False #Get the length of the file length = data.GetPointFrameNumber() #Load the file data into an array self._all_frames = sp.empty((num_points, 3, length)) for i in range(num_points): self._all_frames[i,:,:] = data.GetPoint(i).GetValues().T #Replace occluded markers (all zeros) with NaNs norms = la.norm(self._all_frames, axis=1) ones = sp.ones(norms.shape) nans = ones * sp.nan occluded_mask = np.where(norms != 0.0, ones, nans) occluded_mask = np.expand_dims(occluded_mask, axis=1) self._all_frames = self._all_frames * occluded_mask #Calculate and save the timestamps frequency = data.GetPointFrequency() period = 1/frequency self._timestamps = sp.array(range(length), dtype='float') * period #Make the arrays read-only self._all_frames.flags.writeable = False self._timestamps.flags.writeable = False
def test_DefaultLabelsAndPrefix(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample04/sub_labels.c3d') reader.Update() skvm = btk.btkSeparateKnownVirtualMarkersFilter() skvm.SetInput(reader.GetOutput().GetPoints()) skvm.SetLabelPrefix('Matt:') skvm.Update() # markers points = skvm.GetOutput(0) self.assertEqual(points.GetItemNumber(), 50) inc = 0 # virtual used for axes points = skvm.GetOutput(1) self.assertEqual(points.GetItemNumber(), 36) inc = 0 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LFEO'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LFEA'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LFEL'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LFEP'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LFOO'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LFOA'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LFOL'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LFOP'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LTIO'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LTIA'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LTIL'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LTIP'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LTOO'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LTOA'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LTOL'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:LTOP'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:PELO'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:PELA'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:PELL'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:PELP'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RFEO'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RFEA'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RFEL'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RFEP'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RFOO'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RFOA'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RFOL'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RFOP'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RTIO'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RTIA'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RTIL'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RTIP'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RTOO'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RTOA'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RTOL'); inc +=1 self.assertEqual(points.GetItem(inc).GetLabel(), 'Matt:RTOP') # other virtual markers points = skvm.GetOutput(2) self.assertEqual(points.GetItemNumber(), 0) # other type of points points = skvm.GetOutput(3) self.assertEqual(points.GetItemNumber(), 28)
def test_PluginC3D_Threshold50(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + "sample09/PlugInC3D.c3d") reader.Update() pfe = btk.btkForcePlatformsExtractor() grwf = btk.btkGroundReactionWrenchFilter() dswc = btk.btkWrenchCollectionDownsampleFilter() dswc.SetUpDownRatio(reader.GetOutput().GetNumberAnalogSamplePerFrame()) pfe.SetInput(reader.GetOutput()) grwf.SetInput(pfe.GetOutput()) dswc.SetInput(grwf.GetOutput()) vgrfged = btk.btkVerticalGroundReactionForceGaitEventDetector() vgrfged.SetInput(dswc.GetOutput()) vgrfged.SetThresholdValue(50) vgrfged.SetForceplateContextMapping(["Right", "Left"]) vgrfged.SetAcquisitionInformation( reader.GetOutput().GetFirstFrame(), reader.GetOutput().GetPointFrequency(), "") output = vgrfged.GetOutput() output.Update() self.assertEqual(output.GetItemNumber(), 4) ev = output.GetItem(0) self.assertEqual(ev.GetLabel(), "Foot Strike") self.assertEqual(ev.GetContext(), "Right") self.assertEqual( ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 1) self.assertEqual(ev.GetFrame(), 67) self.assertEqual(ev.GetTime(), 67.0 / 60.0) ev = output.GetItem(1) self.assertEqual(ev.GetLabel(), "Foot Off") self.assertEqual(ev.GetContext(), "Right") self.assertEqual( ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 2) self.assertEqual(ev.GetFrame(), 114) self.assertEqual(ev.GetTime(), 114.0 / 60.0) ev = output.GetItem(2) self.assertEqual(ev.GetLabel(), "Foot Strike") self.assertEqual(ev.GetContext(), "Left") self.assertEqual( ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 1) self.assertEqual(ev.GetFrame(), 109) self.assertEqual(ev.GetTime(), 109.0 / 60.0) ev = output.GetItem(3) self.assertEqual(ev.GetLabel(), "Foot Off") self.assertEqual(ev.GetContext(), "Left") self.assertEqual( ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 2) self.assertEqual(ev.GetFrame(), 148) self.assertEqual(ev.GetTime(), 148.0 / 60.0)
def extract_gait_cycle_intervals(c3d_file_path): """Extracts gait cycle intervals from .c3d file. Parameters ---------- c3d_file_path: file path Returns ------- tuple: right and left leg intervals """ c3d = btk.btkAcquisitionFileReader() c3d.SetFilename(c3d_file_path) c3d.Update() acq = c3d.GetOutput() fps = acq.GetPointFrequency() first_frame = acq.GetFirstFrame() opensim_sync = first_frame / fps # extract all events from c3d file right_events = {} left_events = {} for i in range(acq.GetEventNumber()): label = acq.GetEvent(i).GetLabel() time = acq.GetEvent(i).GetTime() - opensim_sync context = acq.GetEvent(i).GetContext() if context == 'Right': right_events.update({time: label}) if context == 'Left': left_events.update({time: label}) right_events = dict(sorted(right_events.items())) left_events = dict(sorted(left_events.items())) # print(right_events) # print(left_events) # extract intervals def extract_intervals_from_events(events): intervals = [] start = None for key, val in events.items(): if val == 'Foot Strike': if start is None: start = key else: intervals.append([start, key]) start = key return intervals right_intervals = extract_intervals_from_events(right_events) left_intervals = extract_intervals_from_events(left_events) return right_intervals, left_intervals
def _get_c3dacq(c3dfile): """Cache c3dacq if filename and digest match""" reader = btk.btkAcquisitionFileReader() # Py2: btk interface cannot take unicode, so encode to latin-1 first if sys.version_info.major == 2: c3dfile = c3dfile.encode('latin-1') reader.SetFilename(c3dfile) reader.Update() return reader.GetOutput()
def test_ConversionFromFile(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample09/PlugInC3D.c3d') acq = reader.GetOutput() uc = btk.btkAcquisitionUnitConverter() uc.SetInput(acq) uc.SetUnit(btk.btkAcquisitionUnitConverter.Length, 'm') uc.SetUnit(btk.btkAcquisitionUnitConverter.Angle, 'rad') uc.SetUnit(btk.btkAcquisitionUnitConverter.Moment, 'Nm') uc.Update() acq2 = uc.GetOutput() self.assertEqual(acq2.GetPointUnit(btk.btkPoint.Scalar), 'm') self.assertEqual(acq.GetFirstFrame(), acq2.GetFirstFrame()) self.assertEqual(acq.GetPointFrequency(), acq2.GetPointFrequency()) self.assertEqual(acq.GetPointNumber(), acq2.GetPointNumber()) self.assertEqual(acq.GetPointFrameNumber(), acq2.GetPointFrameNumber()) self.assertEqual(acq.GetAnalogFrequency(), acq2.GetAnalogFrequency()) self.assertEqual(acq.GetAnalogNumber(), acq2.GetAnalogNumber()) for j in range(0, acq.GetPointNumber()): s = 1.0 t = acq.GetPoint(j).GetType() if (t == btk.btkPoint.Marker) or (t == btk.btkPoint.Scalar): s = 0.001 elif (t == btk.btkPoint.Angle): s = 1.745329251994e-02 elif (t == btk.btkPoint.Moment): s = 0.001 for i in range(1, 50): self.assertAlmostEqual( acq.GetPoint(j).GetValues()[i, 0] * s, acq2.GetPoint(j).GetValues()[i, 0], 10) self.assertAlmostEqual( acq.GetPoint(j).GetValues()[i, 1] * s, acq2.GetPoint(j).GetValues()[i, 1], 10) self.assertAlmostEqual( acq.GetPoint(j).GetValues()[i, 2] * s, acq2.GetPoint(j).GetValues()[i, 2], 10) for j in range(0, acq.GetAnalogNumber()): s = 1.0 unit = acq.GetAnalog(j).GetUnit() if (unit == 'Nmm'): s = 0.001 for i in range(1, 50): self.assertAlmostEqual( acq.GetAnalog(j).GetValues()[i] * s, acq2.GetAnalog(j).GetValues()[i], 10) self.assertAlmostEqual( acq.GetMetaData().GetChild('SEG').GetChild( 'MARKER_DIAMETER').GetInfo().ToDouble(0) * 0.001, acq2.GetMetaData().GetChild('SEG').GetChild( 'MARKER_DIAMETER').GetInfo().ToDouble(0), 5)
def test_ParameterOverflow(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'others/parameterOverflow.c3d') reader.Update() acq = reader.GetOutput() itAnalysis = acq.GetMetaData().FindChild('ANALYSIS') self.assertTrue(itAnalysis != acq.GetMetaData().End()) if (itAnalysis != acq.GetMetaData().End()): self.assertTrue(itAnalysis.value().FindChild('VALUES') != itAnalysis.value().End())
def test_Gait_NoMapping(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + "others/Gait.c3d") reader.Update() pfe = btk.btkForcePlatformsExtractor() grwf = btk.btkGroundReactionWrenchFilter() dswc = btk.btkWrenchCollectionDownsampleFilter() dswc.SetUpDownRatio(reader.GetOutput().GetNumberAnalogSamplePerFrame()) pfe.SetInput(reader.GetOutput()) grwf.SetInput(pfe.GetOutput()) dswc.SetInput(grwf.GetOutput()) vgrfged = btk.btkVerticalGroundReactionForceGaitEventDetector() vgrfged.SetInput(dswc.GetOutput()) vgrfged.SetAcquisitionInformation( reader.GetOutput().GetFirstFrame(), reader.GetOutput().GetPointFrequency(), "") output = vgrfged.GetOutput() output.Update() self.assertEqual(output.GetItemNumber(), 4) ev = output.GetItem(0) self.assertEqual(ev.GetLabel(), "Foot Strike") self.assertEqual(ev.GetContext(), "General") self.assertEqual( ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 1) self.assertEqual(ev.GetFrame(), 257) self.assertEqual(ev.GetTime(), 2.57) ev = output.GetItem(1) self.assertEqual(ev.GetLabel(), "Foot Off") self.assertEqual(ev.GetContext(), "General") self.assertEqual( ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 2) self.assertEqual(ev.GetFrame(), 316) self.assertEqual(ev.GetTime(), 3.16) ev = output.GetItem(2) self.assertEqual(ev.GetLabel(), "Foot Strike") self.assertEqual(ev.GetContext(), "General") self.assertEqual( ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 1) self.assertEqual(ev.GetFrame(), 209) self.assertEqual(ev.GetTime(), 2.09) ev = output.GetItem(3) self.assertEqual(ev.GetLabel(), "Foot Off") self.assertEqual(ev.GetContext(), "General") self.assertEqual( ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 2) self.assertEqual(ev.GetFrame(), 267) self.assertEqual(ev.GetTime(), 2.67)
def smartReader(filename): """ Function to read a c3d file with BTK. :param filename: (str) path and filename of the c3d :return: (btkAcquisition) btk Acquisition instance """ reader = btk.btkAcquisitionFileReader() reader.SetFilename(filename) reader.Update() acq = reader.GetOutput() return acq
def test_FileSample10Type4a(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + "sample10/type-4a.c3d") pfe = btk.btkForcePlatformsExtractor() grwf = btk.btkGroundReactionWrenchFilter() pfe.SetInput(reader.GetOutput()) grwf.SetInput(pfe.GetOutput()) grwc = grwf.GetOutput() grwc.Update() self.assertEqual(grwc.GetItemNumber(), 2) grw1 = grwc.GetItem(0) self.assertEqual(grw1.GetPosition().GetFrameNumber(), 5760)
def test_Sample05_vicon512(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample05/vicon512.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetPointFrequency(), 120) self.assertEqual(acq.GetPointNumber(), 45) self.assertEqual(acq.GetPointFrameNumber(), 6492) self.assertEqual(acq.GetAnalogFrequency(), 1080) self.assertEqual(acq.GetAnalogNumber(), 23) self.assertEqual(acq.GetAnalogFrameNumber(), 6492 * 9)
def test_Sample13_Dance(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample13/Dance.c3d') reader.Update() acq = reader.GetOutput() self.assertAlmostEqual(acq.GetPointFrequency(), 65.05, 2) self.assertEqual(acq.GetPointNumber(), 40) self.assertEqual(acq.GetPointFrameNumber(), 499) self.assertAlmostEqual(acq.GetAnalogFrequency(), 65.05, 2) self.assertEqual(acq.GetAnalogNumber(), 8) self.assertEqual(acq.GetAnalogFrameNumber(), 499)
def test_Sample20_phasespace_sample(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample20/phasespace_sample.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetPointFrequency(), 30) self.assertEqual(acq.GetPointNumber(), 40) self.assertEqual(acq.GetPointFrameNumber(), 701) self.assertEqual(acq.GetAnalogFrequency(), 30) self.assertEqual(acq.GetAnalogNumber(), 0) self.assertEqual(acq.GetAnalogFrameNumber(), 701)
def test_Sample13_golfswing(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample13/golfswing.c3d') reader.Update() acq = reader.GetOutput() self.assertAlmostEqual(acq.GetPointFrequency(), 107.53, 2) self.assertEqual(acq.GetPointNumber(), 29) self.assertEqual(acq.GetPointFrameNumber(), 514) self.assertAlmostEqual(acq.GetAnalogFrequency(), 107.53, 2) self.assertEqual(acq.GetAnalogNumber(), 8) self.assertEqual(acq.GetAnalogFrameNumber(), 514)
def test_Sample19_sample19(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample19/sample19.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetPointFrequency(), 60) self.assertEqual(acq.GetPointNumber(), 0) self.assertEqual(acq.GetPointFrameNumber(), 34672) self.assertEqual(acq.GetAnalogFrequency(), 1080) self.assertEqual(acq.GetAnalogNumber(), 2) self.assertEqual(acq.GetAnalogFrameNumber(), 18 * 34672)
def test_Sample22_BKINtechnologies(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample22/BKINtechnologies.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetEventNumber(), 2) self.assertEqual(acq.GetEvent(0).GetLabel(), 'STAY_CENTRE') self.assertAlmostEqual(acq.GetEvent(0).GetTime(), 0.0, 3) self.assertEqual(acq.GetEvent(0).GetDescription(), 'subject must wait at centre starting now') self.assertEqual(acq.GetEvent(1).GetLabel(), 'TARGET_ON') self.assertAlmostEqual(acq.GetEvent(1).GetTime(), 1.6140, 3) self.assertEqual(acq.GetEvent(1).GetDescription(), 'Target light ON, start waiting for subject to leave centre target')
def test_UTF8(self): # The Windows charset seems not compatible with hardcoded UTF-8 strings. The test is discarded under Windows. if (platform.system() != 'Windows'): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'others/Я могу есть стекло/оно мне не вредит.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetPointFrequency(), 250.0) self.assertEqual(acq.GetPointNumber(), 27) self.assertEqual(acq.GetAnalogFrequency(), 1000.0) self.assertEqual(acq.GetAnalogNumber(), 6) self.assertEqual(acq.GetPoint(0).GetLabel(), 'AbcdeFghijk:RASI') self.assertEqual(acq.GetPoint(26).GetLabel(), 'AbcdeFghijk:LFIN')
def test_FileSample01Eb015pi(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + "sample01/Eb015pi.c3d") acq = reader.GetOutput() pfe = btk.btkForcePlatformsExtractor() pfe.SetInput(reader.GetOutput()) pfc = pfe.GetOutput() pfe.Update() self.assertEqual(pfc.GetItemNumber(), 2) pf1 = pfc.GetItem(0) self.assertEqual(pf1.GetType(), 2) self.assertEqual(pf1.GetChannelNumber(), 6) self.assertEqual(pf1.GetChannel(0).GetLabel(), "FX1") self.assertEqual(pf1.GetChannel(1).GetLabel(), "FY1") self.assertEqual(pf1.GetChannel(2).GetLabel(), "FZ1") self.assertEqual(pf1.GetChannel(3).GetLabel(), "MX1") self.assertEqual(pf1.GetChannel(4).GetLabel(), "MY1") self.assertEqual(pf1.GetChannel(5).GetLabel(), "MZ1") o1 = numpy.array([[-4.4], [1.9], [-21.6]]) numpy.testing.assert_array_almost_equal(pf1.GetOrigin(), o1) c11 = numpy.array([[520.0451], [1242.1694], [0.6219]]) c21 = numpy.array([[57.0463], [1243.1996], [0.6211]]) c31 = numpy.array([[58.1765], [1751.1963], [2.0812]]) c41 = numpy.array([[521.1754], [1750.1661], [2.0820]]) numpy.testing.assert_array_almost_equal(pf1.GetCorner(0), c11, 4) numpy.testing.assert_array_almost_equal(pf1.GetCorner(1), c21, 4) numpy.testing.assert_array_almost_equal(pf1.GetCorner(2), c31, 4) numpy.testing.assert_array_almost_equal(pf1.GetCorner(3), c41, 4) cs1 = numpy.concatenate((c11,c21,c31,c41), axis=1) numpy.testing.assert_array_almost_equal(pf1.GetCorners(), cs1, 4) pf2 = pfc.GetItem(1) self.assertEqual(pf2.GetType(), 2) self.assertEqual(pf2.GetChannelNumber(), 6) self.assertEqual(pf2.GetChannel(0).GetLabel(), "FX2") self.assertEqual(pf2.GetChannel(1).GetLabel(), "FY2") self.assertEqual(pf2.GetChannel(2).GetLabel(), "FZ2") self.assertEqual(pf2.GetChannel(3).GetLabel(), "MX2") self.assertEqual(pf2.GetChannel(4).GetLabel(), "MY2") self.assertEqual(pf2.GetChannel(5).GetLabel(), "MZ2") o2 = numpy.array([[-4.06] , [3.81], [-20.06]]) numpy.testing.assert_array_almost_equal(pf2.GetOrigin(), o2) c12 = numpy.array([[53.6554] , [1139.9977], [1.9204]]) c22 = numpy.array([[516.6432] , [1143.3159], [1.2880]]) c32 = numpy.array([[520.2825] , [635.3301], [0.1814]]) c42 = numpy.array([[57.2948] , [632.0118], [0.8138]]) numpy.testing.assert_array_almost_equal(pf2.GetCorner(0), c12, 4) numpy.testing.assert_array_almost_equal(pf2.GetCorner(1), c22, 4) numpy.testing.assert_array_almost_equal(pf2.GetCorner(2), c32, 4) numpy.testing.assert_array_almost_equal(pf2.GetCorner(3), c42, 4) cs2 = numpy.concatenate((c12,c22,c32,c42), axis=1) numpy.testing.assert_array_almost_equal(pf2.GetCorners(), cs2, 4)
def get_data(self, in_file, in_data=None): '''Get the sampling rate, as well as the recorded data, and assign them to the corresponding attributes of "self". Parameters ---------- in_file : string Filename of the data-file in_data : not used here Assigns ------- - rate : rate - acc : acceleration - omega : angular_velocity - mag : mag_field_direction ''' # Read the data # Get the sampling rate try: reader = btk.btkAcquisitionFileReader() reader.SetFilename(in_file) reader.Update() acq = reader.GetOutput() fp = acq.GetPointFrequency() except FileNotFoundError: print('{0} does not exist!'.format(in_file)) return -1 # Extract the columns that you want, and pass them on acc_x_values = acq.GetAnalog("accel.x").GetValues() acc_y_values = acq.GetAnalog("accel.y").GetValues() acc_z_values = acq.GetAnalog("accel.z").GetValues() gyro_x_values = acq.GetAnalog("gyro.x").GetValues() gyro_y_values = acq.GetAnalog("gyro.y").GetValues() gyro_z_values = acq.GetAnalog("gyro.z").GetValues() mag_x_values = acq.GetAnalog("mag.x").GetValues() mag_y_values = acq.GetAnalog("mag.y").GetValues() mag_z_values = acq.GetAnalog("mag.z").GetValues() in_data = { 'rate': fp, 'acc': np.column_stack((acc_x_values, acc_y_values, acc_z_values)), 'omega': np.column_stack( (gyro_x_values, gyro_y_values, gyro_z_values)), 'mag': np.column_stack((mag_x_values, mag_y_values, mag_z_values)) } self._set_data(in_data)
def get_marker_names(_filename): _reader = btk.btkAcquisitionFileReader() # build a btk _reader object _reader.SetFilename(_filename) # set a filename to the _reader _reader.Update() _acq = _reader.GetOutput() _frame_max = _acq.GetPointFrameNumber() #get the number of frames _all_label = [] for _j_index in range(0, _frame_max): _points = {} for _i_index in range(_acq.GetPointNumber()): _point = _acq.GetPoint(_i_index) _label = _point.GetLabel() _all_label.append(_label) return _all_label
def test_Sample09_PlugInC3D(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample09/PlugInC3D.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetPoint(0).GetType(), btk.btkPoint.Marker) self.assertEqual(acq.GetPoint(18).GetType(), btk.btkPoint.Angle) self.assertEqual(acq.GetPoint(64).GetType(), btk.btkPoint.Force) self.assertEqual(acq.GetPoint(72).GetType(), btk.btkPoint.Moment) self.assertEqual(acq.GetPoint(80).GetType(), btk.btkPoint.Power) self.assertEqual(acq.GetAnalog(0).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(1).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(2).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(3).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(4).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(5).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(6).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(7).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(8).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(9).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(10).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(11).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(12).GetGain(), btk.btkAnalog.PlusMinus10) self.assertEqual(acq.GetAnalog(13).GetGain(), btk.btkAnalog.PlusMinus10) self.assertEqual(acq.GetAnalog(14).GetGain(), btk.btkAnalog.PlusMinus10) self.assertEqual(acq.GetAnalog(15).GetGain(), btk.btkAnalog.PlusMinus10) self.assertEqual(acq.GetAnalog(16).GetGain(), btk.btkAnalog.PlusMinus10) self.assertEqual(acq.GetAnalog(17).GetGain(), btk.btkAnalog.PlusMinus10) self.assertEqual(acq.GetAnalog(18).GetGain(), btk.btkAnalog.PlusMinus10) self.assertEqual(acq.GetAnalog(19).GetGain(), btk.btkAnalog.PlusMinus10) self.assertEqual(acq.GetAnalog(20).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(21).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(22).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(23).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(24).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(25).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(26).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(27).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(28).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(29).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(30).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(31).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(32).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(33).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(34).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetAnalog(35).GetGain(), btk.btkAnalog.PlusMinus5) self.assertEqual(acq.GetPointFrameNumber(), acq.GetMetaData().GetChild('POINT').GetChild('FRAMES').GetInfo().ToInt(0))
def loadData(self, path): if not ntpath.isfile(path): print 'Can not open ' + path self.acq = None self.timer.stop() return self.dataPath, self.dataFile = ntpath.split(ntpath.abspath(path)) try: reader = btk.btkAcquisitionFileReader() reader.SetFilename(path) reader.Update() self.acq = reader.GetOutput() except RuntimeError: print 'File format is not valid ' + path self.acq = None self.timer.stop() return if self.acq: print 'C3D file loaded ' + path self.frequency = self.acq.GetPointFrequency() self.totalFrame = self.acq.GetPointFrameNumber() self.totalPoint = self.acq.GetPointNumber() print 'Sample Frequency :', self.acq.GetPointFrequency() print 'Total Frame :', self.acq.GetPointFrameNumber() print 'Marker Number :', self.acq.GetPointNumber() self.maxDataValue = 0 for i in range(self.totalPoint): point = self.acq.GetPoint(i) for j in range(self.totalFrame): pos = point.GetValues()[j,:] if pos[0] > self.maxDataValue: self.maxDataValue = pos[0] if pos[1] > self.maxDataValue: self.maxDataValue = pos[1] if pos[2] > self.maxDataValue: self.maxDataValue = pos[2] self.paused = False self.currentFrame = 0 self.timer.setInterval(int(1000 / self.frequency)) self.timer.start() self.dataLoaded.emit()
def test_UTF8(self): # The Windows charset seems not compatible with hardcoded UTF-8 strings. The test is discarded under Windows. if (platform.system() != 'Windows'): reader = btk.btkAcquisitionFileReader() reader.SetFilename( _TDDConfigure.C3DFilePathIN + 'others/Я могу есть стекло/оно мне не вредит.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetPointFrequency(), 250.0) self.assertEqual(acq.GetPointNumber(), 27) self.assertEqual(acq.GetAnalogFrequency(), 1000.0) self.assertEqual(acq.GetAnalogNumber(), 6) self.assertEqual(acq.GetPoint(0).GetLabel(), 'AbcdeFghijk:RASI') self.assertEqual(acq.GetPoint(26).GetLabel(), 'AbcdeFghijk:LFIN')
def test_PluginC3D_Threshold50(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + "sample09/PlugInC3D.c3d") reader.Update() pfe = btk.btkForcePlatformsExtractor() grwf = btk.btkGroundReactionWrenchFilter() dswc = btk.btkWrenchCollectionDownsampleFilter() dswc.SetUpDownRatio(reader.GetOutput().GetNumberAnalogSamplePerFrame()) pfe.SetInput(reader.GetOutput()) grwf.SetInput(pfe.GetOutput()) dswc.SetInput(grwf.GetOutput()) vgrfged = btk.btkVerticalGroundReactionForceGaitEventDetector() vgrfged.SetInput(dswc.GetOutput()) vgrfged.SetThresholdValue(50) vgrfged.SetForceplateContextMapping(["Right","Left"]) vgrfged.SetAcquisitionInformation(reader.GetOutput().GetFirstFrame(), reader.GetOutput().GetPointFrequency(), "") output = vgrfged.GetOutput() output.Update() self.assertEqual(output.GetItemNumber(), 4) ev = output.GetItem(0) self.assertEqual(ev.GetLabel(), "Foot Strike") self.assertEqual(ev.GetContext(), "Right") self.assertEqual(ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 1) self.assertEqual(ev.GetFrame(), 67) self.assertEqual(ev.GetTime(), 67.0/60.0) ev = output.GetItem(1) self.assertEqual(ev.GetLabel(), "Foot Off") self.assertEqual(ev.GetContext(), "Right") self.assertEqual(ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 2) self.assertEqual(ev.GetFrame(), 114) self.assertEqual(ev.GetTime(), 114.0/60.0) ev = output.GetItem(2) self.assertEqual(ev.GetLabel(), "Foot Strike") self.assertEqual(ev.GetContext(), "Left") self.assertEqual(ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 1) self.assertEqual(ev.GetFrame(), 109) self.assertEqual(ev.GetTime(), 109.0/60.0) ev = output.GetItem(3) self.assertEqual(ev.GetLabel(), "Foot Off") self.assertEqual(ev.GetContext(), "Left") self.assertEqual(ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 2) self.assertEqual(ev.GetFrame(), 148) self.assertEqual(ev.GetTime(), 148.0/60.0)
def extract_metaData_pycgm2(filename): reader = btk.btkAcquisitionFileReader() reader.SetFilename(str(filename)) reader.Update() acq = reader.GetOutput() md = acq.GetMetaData() nameParameters = [ "Bodymass", "Height", "LLegLength", "RLegLength", "LKneeWidth", "RKneeWidth", "LAnkleWidth", "RAnkleWidth", "LSoleDelta", "RSoleDelta", "InterAsisDistance", "LAsisTrocanterDistance", "LTibialTorsion", "LThighRotation", "LShankRotation", "RAsisTrocanterDistance", "RTibialTorsion", "RThighRotation", "RShankRotation" ] extracted_param = {} for nameParameter in nameParameters: extracted_param[nameParameter] = md.FindChild("PROCESSING").\ value().FindChild(nameParameter).\ value().GetInfo().ToDouble()[0] required_mp = { "Bodymass": extracted_param['Bodymass'], "Height": extracted_param['Height'], "LeftLegLength": extracted_param['LLegLength'], "RightLegLength": extracted_param['RLegLength'], "LeftKneeWidth": extracted_param['LKneeWidth'], "RightKneeWidth": extracted_param['RKneeWidth'], "LeftAnkleWidth": extracted_param['LAnkleWidth'], "RightAnkleWidth": extracted_param['RAnkleWidth'], "LeftSoleDelta": extracted_param['LSoleDelta'], "RightSoleDelta": extracted_param['RSoleDelta'] } optional_mp = { "InterAsisDistance": extracted_param['InterAsisDistance'], "LeftAsisTrocanterDistance": extracted_param['LAsisTrocanterDistance'], "LeftTibialTorsion": extracted_param['LTibialTorsion'], "LeftThighRotation": extracted_param['LThighRotation'], "LeftShankRotation": extracted_param['LShankRotation'], "RightAsisTrocanterDistance": extracted_param['RAsisTrocanterDistance'], "RightTibialTorsion": extracted_param['RTibialTorsion'], "RightThighRotation": extracted_param['RThighRotation'], "RightShankRotation": extracted_param['RShankRotation'] } return required_mp, optional_mp
def __init__(self, input_data): """Loads a motion capture file (currently a C3D file) to create a new MocapFile object """ import btk all_frames = None timestamps = None #Initialize the file reader data = btk.btkAcquisitionFileReader() data.SetFilename(input_data) data.Update() data = data.GetOutput() #Get the number of markers tracked in the file num_points = 0 run = True while run: try: data.GetPoint(num_points) num_points = num_points + 1 except (RuntimeError): run = False #Get the length of the file length = data.GetPointFrameNumber() #Load the file data into an array all_frames = sp.empty((num_points, 3, length)) for i in range(num_points): all_frames[i, :, :] = data.GetPoint(i).GetValues().T #Replace occluded markers (all zeros) with NaNs norms = la.norm(all_frames, axis=1) ones = sp.ones(norms.shape) nans = ones * sp.nan occluded_mask = np.where(norms != 0.0, ones, nans) occluded_mask = np.expand_dims(occluded_mask, axis=1) all_frames = all_frames * occluded_mask #Calculate and save the timestamps frequency = data.GetPointFrequency() period = 1 / frequency timestamps = sp.array(range(length), dtype='float') * period # Initialize this OfflineMocapSource with the resulting frames and timestamps arrays super(FileMocapSource, self).__init__(frames, timestamps)
def test_Gait_NoMapping(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + "others/Gait.c3d") reader.Update() pfe = btk.btkForcePlatformsExtractor() grwf = btk.btkGroundReactionWrenchFilter() dswc = btk.btkWrenchCollectionDownsampleFilter() dswc.SetUpDownRatio(reader.GetOutput().GetNumberAnalogSamplePerFrame()) pfe.SetInput(reader.GetOutput()) grwf.SetInput(pfe.GetOutput()) dswc.SetInput(grwf.GetOutput()) vgrfged = btk.btkVerticalGroundReactionForceGaitEventDetector() vgrfged.SetInput(dswc.GetOutput()) vgrfged.SetAcquisitionInformation(reader.GetOutput().GetFirstFrame(), reader.GetOutput().GetPointFrequency(), "") output = vgrfged.GetOutput() output.Update() self.assertEqual(output.GetItemNumber(), 4) ev = output.GetItem(0) self.assertEqual(ev.GetLabel(), "Foot Strike") self.assertEqual(ev.GetContext(), "General") self.assertEqual(ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 1) self.assertEqual(ev.GetFrame(), 257) self.assertEqual(ev.GetTime(), 2.57) ev = output.GetItem(1) self.assertEqual(ev.GetLabel(), "Foot Off") self.assertEqual(ev.GetContext(), "General") self.assertEqual(ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 2) self.assertEqual(ev.GetFrame(), 316) self.assertEqual(ev.GetTime(), 3.16) ev = output.GetItem(2) self.assertEqual(ev.GetLabel(), "Foot Strike") self.assertEqual(ev.GetContext(), "General") self.assertEqual(ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 1) self.assertEqual(ev.GetFrame(), 209) self.assertEqual(ev.GetTime(), 2.09) ev = output.GetItem(3) self.assertEqual(ev.GetLabel(), "Foot Off") self.assertEqual(ev.GetContext(), "General") self.assertEqual(ev.GetDetectionFlags(), btk.btkEvent.Automatic | btk.btkEvent.FromForcePlatform) self.assertEqual(ev.GetId(), 2) self.assertEqual(ev.GetFrame(), 267) self.assertEqual(ev.GetTime(), 2.67)
def test_FileSample19Sample19(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + "sample19/sample19.c3d") pfe = btk.btkForcePlatformsExtractor() pfe.SetInput(reader.GetOutput()) pfc = pfe.GetOutput() pfe.Update() self.assertEqual(pfc.GetItemNumber(), 4) pf1 = pfc.GetItem(0) self.assertEqual(pf1.GetChannelNumber(), 6) self.assertEqual(pf1.GetChannel(0).GetFrameNumber(), 34672 * 18) self.assertEqual(pf1.GetChannel(0).GetLabel(), "FP1C1") self.assertEqual(pf1.GetChannel(1).GetLabel(), "FP1C2") self.assertEqual(pf1.GetChannel(2).GetLabel(), "FP1C3") self.assertEqual(pf1.GetChannel(3).GetLabel(), "FP1C4") self.assertEqual(pf1.GetChannel(4).GetLabel(), "FP1C5") self.assertEqual(pf1.GetChannel(5).GetLabel(), "FP1C6") self.assertAlmostEqual(pf1.GetChannel(3).GetValues()[561], 0.0, 5)
def test_Sample08_TEST(self): reader = btk.btkAcquisitionFileReader() # TESTAPI reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample08/TESTAPI.c3d') reader.Update() TESTAPI = reader.GetOutput() # TESTBPI reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample08/TESTBPI.c3d') reader.Update() TESTBPI = reader.GetOutput() # TESTCPI reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample08/TESTCPI.c3d') reader.Update() TESTCPI = reader.GetOutput() # TESTDPI reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample08/TESTDPI.c3d') reader.Update() TESTDPI = reader.GetOutput()
def test_ConversionFromFile(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample09/PlugInC3D.c3d') acq = reader.GetOutput() uc = btk.btkAcquisitionUnitConverter() uc.SetInput(acq) uc.SetUnit(btk.btkAcquisitionUnitConverter.Length, 'm') uc.SetUnit(btk.btkAcquisitionUnitConverter.Angle, 'rad') uc.SetUnit(btk.btkAcquisitionUnitConverter.Moment, 'Nm') uc.Update() acq2 = uc.GetOutput() self.assertEqual(acq2.GetPointUnit(btk.btkPoint.Scalar), 'm') self.assertEqual(acq.GetFirstFrame(), acq2.GetFirstFrame()) self.assertEqual(acq.GetPointFrequency(), acq2.GetPointFrequency()) self.assertEqual(acq.GetPointNumber(), acq2.GetPointNumber()) self.assertEqual(acq.GetPointFrameNumber(), acq2.GetPointFrameNumber()) self.assertEqual(acq.GetAnalogFrequency(), acq2.GetAnalogFrequency()) self.assertEqual(acq.GetAnalogNumber(), acq2.GetAnalogNumber()) for j in range(0,acq.GetPointNumber()): s = 1.0 t = acq.GetPoint(j).GetType() if (t == btk.btkPoint.Marker) or (t == btk.btkPoint.Scalar): s = 0.001 elif (t == btk.btkPoint.Angle): s = 1.745329251994e-02 elif (t == btk.btkPoint.Moment): s = 0.001 for i in range(1,50): self.assertAlmostEqual(acq.GetPoint(j).GetValues()[i,0] * s, acq2.GetPoint(j).GetValues()[i,0], 10) self.assertAlmostEqual(acq.GetPoint(j).GetValues()[i,1] * s, acq2.GetPoint(j).GetValues()[i,1], 10) self.assertAlmostEqual(acq.GetPoint(j).GetValues()[i,2] * s, acq2.GetPoint(j).GetValues()[i,2], 10) for j in range(0,acq.GetAnalogNumber()): s = 1.0 unit = acq.GetAnalog(j).GetUnit() if (unit == 'Nmm'): s = 0.001 for i in range(1,50): self.assertAlmostEqual(acq.GetAnalog(j).GetValues()[i] * s, acq2.GetAnalog(j).GetValues()[i], 10) self.assertAlmostEqual(acq.GetMetaData().GetChild('SEG').GetChild('MARKER_DIAMETER').GetInfo().ToDouble(0) * 0.001, acq2.GetMetaData().GetChild('SEG').GetChild('MARKER_DIAMETER').GetInfo().ToDouble(0), 5)
def test_Sample22_BKINtechnologies(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample22/BKINtechnologies.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetEventNumber(), 2) self.assertEqual(acq.GetEvent(0).GetLabel(), 'STAY_CENTRE') self.assertAlmostEqual(acq.GetEvent(0).GetTime(), 0.0, 3) self.assertEqual( acq.GetEvent(0).GetDescription(), 'subject must wait at centre starting now') self.assertEqual(acq.GetEvent(1).GetLabel(), 'TARGET_ON') self.assertAlmostEqual(acq.GetEvent(1).GetTime(), 1.6140, 3) self.assertEqual( acq.GetEvent(1).GetDescription(), 'Target light ON, start waiting for subject to leave centre target' )
def array_from_c3d(self, file_c3d): """ Returns the array representation of a C3D file. """ reader = btk.btkAcquisitionFileReader() reader.SetFilename(file_c3d) reader.Update() acq = reader.GetOutput() N = acq.GetPointFrameNumber() nber_points = acq.GetPointNumber() result = [] points_coords = np.array([acq.GetPoint(j).GetValues() for j in range(nber_points)]) for i in range(N): result.append(points_coords[:, i]) return np.array(result)
def test_Sample02_sgi_real(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample02/sgi_real.c3d') reader.Update() acq = reader.GetOutput() self.assertEqual(acq.GetPointFrequency(), 50) self.assertEqual(acq.GetPointNumber(), 36) self.assertEqual(acq.GetPointFrameNumber(), 89) self.assertEqual(acq.GetAnalogFrequency(), 200) self.assertEqual(acq.GetAnalogNumber(), 16) self.assertEqual(acq.GetAnalogFrameNumber(), 89 * 4) self.assertEqual(acq.GetPoint(3).GetLabel(), 'RSK1') self.assertAlmostEqual(acq.GetPoint(3).GetValue(16,0), 384.0944, 3) self.assertAlmostEqual(acq.GetPoint(3).GetValue(16,1), 523.8417, 3) self.assertAlmostEqual(acq.GetPoint(3).GetValue(16,2), 311.2683, 3) self.assertEqual(acq.GetAnalog(2).GetLabel(), 'FZ1') self.assertAlmostEqual(acq.GetAnalog(2).GetValue(15), 8.9280, 3) self.assertAlmostEqual(acq.GetAnalog(2).GetValue(39), 5.952, 3)
def test_Sample21_sample21(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample21/sample21.c3d') reader.Update()
def test_NoFile(self): reader = btk.btkAcquisitionFileReader() self.assertRaises(RuntimeError, reader.Update)
import btk import matplotlib.pyplot as plt # matplotlib inline import numpy as np import pprint as p from mpl_toolkits.mplot3d import Axes3D import matplotlib.animation as animation import sys reader = btk.btkAcquisitionFileReader() # build a btk reader object reader.SetFilename("GaitNormal0003-processed.c3d") # set a filename to the reader acq = reader.GetOutput() # btk aquisition object acq.Update() # Update ProcessObject associated with DataObject clone = acq.Clone() for i in range(0, acq.GetAnalogs().GetItemNumber()): print(acq.GetAnalog(i).GetLabel()) # plots the values for forces on the z axis in the three plates ana = acq.GetAnalog("Fz1") fz1 = ana.GetValues() / ana.GetScale() # modifies the values in the z axis 1st force plate ana = clone.GetAnalog("Fz1") valz1 = ana.GetValues() scalez1 = ana.GetScale() x = 0
def test_Sample28_type1(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample28/type1.C3D') reader.Update()
def test_TwinsFromFile_Concat(self): reader = btk.btkAcquisitionFileReader() reader.SetFilename(_TDDConfigure.C3DFilePathIN + 'sample09/PlugInC3D.c3d') input = reader.GetOutput() merger = btk.btkMergeAcquisitionFilter() merger.SetInput(0, input) merger.SetInput(1, input) merger.Update() output = merger.GetOutput() self.assertEqual(output.GetPointFrequency(), input.GetPointFrequency()) self.assertEqual(output.GetAnalogFrequency(), input.GetAnalogFrequency()) self.assertEqual(output.GetPointNumber(), input.GetPointNumber() * 2) self.assertEqual(output.GetAnalogNumber(), input.GetAnalogNumber() * 2) self.assertEqual(output.GetPointFrameNumber(), input.GetPointFrameNumber()) self.assertEqual(output.GetAnalogFrameNumber(), input.GetAnalogFrameNumber()) self.assertEqual(output.GetEventNumber(), input.GetEventNumber()) for i in range(0,input.GetPointNumber()): self.assertEqual(output.GetPoint(i).GetLabel(), input.GetPoint(i).GetLabel()) self.assertEqual(output.GetPoint(i + input.GetPointNumber()).GetLabel(), input.GetPoint(i).GetLabel() + '_2') for i in range(0,input. GetAnalogNumber()): self.assertEqual(output.GetAnalog(i).GetLabel(), input.GetAnalog(i).GetLabel()) self.assertEqual(output.GetAnalog(i + input.GetAnalogNumber()).GetLabel(), input.GetAnalog(i).GetLabel() + '_2') md = output.GetMetaData() fp = md.GetChild('FORCE_PLATFORM') used = fp.GetChild('USED').GetInfo().ToInt(0) self.assertEqual(used, 4) corners = fp.GetChild('CORNERS').GetInfo() self.assertEqual(corners.GetDimensions()[2], used) self.assertEqual(len(corners.ToDouble()), 48) corners2Val = input.GetMetaData().GetChild('FORCE_PLATFORM').GetChild('CORNERS').GetInfo().ToDouble() for i in range(0,24): self.assertAlmostEqual(corners.ToDouble(i), corners2Val[i], 5) self.assertAlmostEqual(corners.ToDouble(i+24), corners2Val[i], 5) channel = fp.GetChild('CHANNEL').GetInfo() self.assertEqual(channel.GetDimensions()[1], used) self.assertEqual(len(channel.ToInt()), 24) channel2Val = input.GetMetaData().GetChild('FORCE_PLATFORM').GetChild('CHANNEL').GetInfo().ToInt() for i in range(0,12): self.assertEqual(channel.ToInt(i), channel2Val[i]) self.assertEqual(channel.ToInt(i+12), channel2Val[i] + 12) type = fp.GetChild('TYPE').GetInfo() self.assertEqual(type.GetDimensions()[0], used) self.assertEqual(len(type.ToInt()), 4) type2Val = input.GetMetaData().GetChild('FORCE_PLATFORM').GetChild('TYPE').GetInfo().ToInt() for i in range(0,2): self.assertEqual(type.ToInt(i), type2Val[i]) self.assertEqual(type.ToInt(i+2), type2Val[i]) origin = fp.GetChild('ORIGIN').GetInfo() self.assertEqual(origin.GetDimensions()[1], used) self.assertEqual(len(origin.ToDouble()), 12) origin2Val = input.GetMetaData().GetChild('FORCE_PLATFORM').GetChild('ORIGIN').GetInfo().ToDouble() for i in range(0,6): self.assertAlmostEqual(origin.ToDouble(i), origin2Val[i], 5) self.assertAlmostEqual(origin.ToDouble(i+6), origin2Val[i], 5) mdPointIt = md.FindChild('POINT') self.assertTrue(mdPointIt != md.End()) if (mdPointIt != md.End()): self.assertEqual(mdPointIt.value().GetChildNumber(), 2) self.assertTrue(mdPointIt.value().FindChild('X_SCREEN') != mdPointIt.value().End()) self.assertTrue(mdPointIt.value().FindChild('Y_SCREEN') != mdPointIt.value().End()) self.assertTrue(md.FindChild('ANALOG') == md.End()) self.assertTrue(md.FindChild('EVENT') == md.End()) self.assertTrue(md.FindChild('TRIAL') != md.End()) self.assertTrue(md.FindChild('SUBJECTS') != md.End()) self.assertTrue(md.FindChild('SEG') != md.End()) self.assertTrue(md.FindChild('EVENT_CONTEXT') != md.End()) self.assertEqual(md.GetChildNumber(), 6) start = md.GetChild('TRIAL').GetChild('ACTUAL_START_FIELD').GetInfo().ToInt() stop = md.GetChild('TRIAL').GetChild('ACTUAL_END_FIELD').GetInfo().ToInt() self.assertEqual(output.GetFirstFrame(), start[0] + start[1] * 65535) self.assertEqual(output.GetLastFrame(), stop[0] + stop[1] * 65535)