def appendMarkers(self): markersLoaded = NEXUS.GetMarkerNames(self.m_subject) markers = [] for i in range(0, len(markersLoaded)): data = NEXUS.GetTrajectory(self.m_subject, markersLoaded[i]) if data != ([], [], [], []): markers.append(markersLoaded[i]) for marker in markers: rawDataX, rawDataY, rawDataZ, E = NEXUS.GetTrajectory( self.m_subject, marker) E = np.asarray(E).astype("float") - 1 values = np.array([ np.asarray(rawDataX), np.asarray(rawDataY), np.asarray(rawDataZ) ]).T start = self.m_firstFrame - self.m_trialFirstFrame end = self.m_lastFrame - self.m_trialFirstFrame values_cut = values[start:end + 1, :] E_cut = E[start:end + 1] btkTools.smartAppendPoint(self.m_acq, marker, values_cut, PointType=btk.btkPoint.Marker, desc="", residuals=E_cut)
def compute(self): for nodeLabel in self.scoreProcedure.m_scoreDefinition.keys(): proxLabel = self.scoreProcedure.m_scoreDefinition[nodeLabel][ "proximal"] distLabel = self.scoreProcedure.m_scoreDefinition[nodeLabel][ "distal"] proxNode = self.m_model.getSegment( proxLabel).anatomicalFrame.getNodeTrajectory(nodeLabel) distNode = self.m_model.getSegment( distLabel).anatomicalFrame.getNodeTrajectory(nodeLabel) score = numeric.rms((proxNode - distNode), axis=1) scoreValues = np.array([ score, np.zeros(self.acq.GetPointFrameNumber()), np.zeros(self.acq.GetPointFrameNumber()) ]).T btkTools.smartAppendPoint(self.acq, str(nodeLabel + "_Score"), scoreValues, PointType=btk.btkPoint.Scalar, desc="Score")
def gaitTrialProgressionY_backward_lateralX_static(cls): """ """ MAIN_PATH = pyCGM2.TEST_DATA_PATH + "operations\\progression\\" gaitFilename="static_Y_backward.c3d" acq = btkTools.smartReader(str(MAIN_PATH + gaitFilename)) valSACR=(acq.GetPoint("LPSI").GetValues() + acq.GetPoint("RPSI").GetValues()) / 2.0 btkTools.smartAppendPoint(acq,"SACR",valSACR,desc="") valMidAsis=(acq.GetPoint("LASI").GetValues() + acq.GetPoint("RASI").GetValues()) / 2.0 btkTools.smartAppendPoint(acq,"midASIS",valMidAsis,desc="") longitudinalAxis,forwardProgression,globalFrame = btkTools.findProgressionAxisFromPelvicMarkers(acq,["LASI","LPSI","RASI","RPSI"]) np.testing.assert_equal( longitudinalAxis,"Y") np.testing.assert_equal( forwardProgression,False) np.testing.assert_equal( globalFrame,"YXZ") longitudinalAxis2,forwardProgression2,globalFrame2 = btkTools.findProgressionAxisFromLongAxis(acq,"LPSI","LASI") np.testing.assert_equal( longitudinalAxis2,"Y") np.testing.assert_equal( forwardProgression2,False) np.testing.assert_equal( globalFrame2,"YXZ")
def gaitTrialProgressionY_forward_lateralX(cls): """ """ MAIN_PATH = pyCGM2.TEST_DATA_PATH + "operations\\progression\\" gaitFilename = "gait_Y_forward.c3d" acq = btkTools.smartReader(str(MAIN_PATH + gaitFilename)) valSACR = (acq.GetPoint("LPSI").GetValues() + acq.GetPoint("RPSI").GetValues()) / 2.0 btkTools.smartAppendPoint(acq, "SACR", valSACR, desc="") valMidAsis = (acq.GetPoint("LASI").GetValues() + acq.GetPoint("RASI").GetValues()) / 2.0 btkTools.smartAppendPoint(acq, "midASIS", valMidAsis, desc="") validFrames, vff, vlf = btkTools.findValidFrames( acq, ["LPSI", "LASI", "RPSI"]) longitudinalAxis, forwardProgression, globalFrame = btkTools.findProgression( acq, "LASI") np.testing.assert_equal(longitudinalAxis, "Y") np.testing.assert_equal(forwardProgression, True) np.testing.assert_equal(globalFrame, "YXZ")
def test_gaitTrialProgressionY_forward_lateralX(self): """ """ MAIN_PATH = pyCGM2.TEST_DATA_PATH + "LowLevel\\ProgressionFrame\\sample 1\\" gaitFilename = "gait_Y_forward.c3d" acq = btkTools.smartReader(MAIN_PATH + gaitFilename) pfp = progressionFrame.PelvisProgressionFrameProcedure() pff = progressionFrame.ProgressionFrameFilter(acq, pfp) pff.compute() np.testing.assert_equal(pff.outputs["progressionAxis"], "Y") np.testing.assert_equal(pff.outputs["forwardProgression"], True) np.testing.assert_equal(pff.outputs["globalFrame"], "YXZ") valSACR = (acq.GetPoint(utils.str("LPSI")).GetValues() + acq.GetPoint(utils.str("RPSI")).GetValues()) / 2.0 btkTools.smartAppendPoint(acq, "SACR", valSACR, desc="") pfp = progressionFrame.PelvisProgressionFrameProcedure( backMarkers=["SACR"]) pff = progressionFrame.ProgressionFrameFilter(acq, pfp) pff.compute() np.testing.assert_equal(pff.outputs["progressionAxis"], "Y") np.testing.assert_equal(pff.outputs["forwardProgression"], True) np.testing.assert_equal(pff.outputs["globalFrame"], "YXZ")
def compute(self): for nodeLabel in self.scoreProcedure.m_scoreDefinition.keys(): try: proxLabel = self.scoreProcedure.m_scoreDefinition[nodeLabel][ "proximal"] distLabel = self.scoreProcedure.m_scoreDefinition[nodeLabel][ "distal"] proxNode = self.m_model.getSegment(proxLabel).getReferential( 'TF').getNodeTrajectory(nodeLabel) distNode = self.m_model.getSegment(distLabel).getReferential( 'TF').getNodeTrajectory(nodeLabel) score = numeric.rms((proxNode - distNode), axis=1) scoreValues = np.array([ score, np.zeros(self.acq.GetPointFrameNumber()), np.zeros(self.acq.GetPointFrameNumber()) ]).T btkTools.smartAppendPoint(self.acq, str(nodeLabel + "_Score"), scoreValues, PointType=btk.btkPoint.Scalar, desc="Score") except: LOGGER.logger.error( "[pyCGM2] Score residual for node (%s) not computed" % (nodeLabel))
def getComTrajectory(self, exportBtkPoint=False, btkAcq=None): """ Get global trajectory of the centre of mass :Parameters: - `exportBtkPoint` (bool) - enable export as btk point - `btkAcq` (btk acquisition) - a btk acquisition instance :Return: - `values` (numpy.array(n,3)) - values of the com trajectory """ frameNumber = len(self.anatomicalFrame.motion) values = np.zeros((frameNumber, 3)) for i in range(0, frameNumber): values[i, :] = np.dot( self.anatomicalFrame.motion[i].getRotation(), self.m_bsp["com"] ) + self.anatomicalFrame.motion[i].getTranslation() if exportBtkPoint: if btkAcq != None: btkTools.smartAppendPoint(btkAcq, self.name + "_com", values, desc="com") return values
def gaitTrialGarches(cls): """ """ MAIN_PATH = pyCGM2.TEST_DATA_PATH + "operations\\progression\\" translators = { "LASI":"L.ASIS", "RASI":"R.ASIS", "LPSI":"L.PSIS", "RPSI":"R.PSIS", "RTHI":"R.Thigh", "RKNE":"R.Knee", "RTHAP":"R.THAP", "RTHAD":"R.THAD", "RTIB":"R.Shank", "RANK":"R.Ankle", "RTIAP":"R.TIAP", "RTIAD":"R.TIAD", "RHEE":"R.Heel", "RSMH":"R.SMH", "RTOE":"R.Toe", "RFMH":"R.FMH", "RVMH":"R.VMH", "LTHI":"L.Thigh", "LKNE":"L.Knee", "LTHAP":"L.THAP", "LTHAD":"L.THAD", "LTIB":"L.Shank", "LANK":"L.Ankle", "LTIAP":"L.TIAP", "LTIAD":"L.TIAD", "LHEE":"L.Heel", "LSMH":"L.SMH", "LTOE":"L.Toe", "LFMH":"L.FMH", "LVMH":"L.VMH", "RKNM":"R.Knee.Medial", "LKNM":"L.Knee.Medial", "RMED":"R.Ankle.Medial", "LMED":"L.Ankle.Medial" } gaitFilename="gait_garches_issue.c3d" acq = btkTools.smartReader(str(MAIN_PATH + gaitFilename),translators =translators ) valSACR=(acq.GetPoint("RPSI").GetValues() + acq.GetPoint("LPSI").GetValues()) / 2.0 btkTools.smartAppendPoint(acq,"SACR",valSACR,desc="") valMidAsis=(acq.GetPoint("RASI").GetValues() + acq.GetPoint("LASI").GetValues()) / 2.0 btkTools.smartAppendPoint(acq,"midASIS",valMidAsis,desc="") longitudinalAxis,forwardProgression,globalFrame = btkTools.findProgression(acq,"LASI") longitudinalAxis2,forwardProgression2,globalFrame2 = btkTools.findProgressionAxisFromPelvicMarkers(acq,["LASI","LPSI","RASI","RPSI"]) np.testing.assert_equal( longitudinalAxis,"Y") np.testing.assert_equal( longitudinalAxis2,"Y")
def test_appendPoint(self): filename = pyCGM2.TEST_DATA_PATH + "LowLevel\\IO\\Hånnibøl_c3d\\static.c3d" acq = btkTools.smartReader(filename, translators=None) values = acq.GetPoint(utils.str("LASI")).GetValues() btkTools.smartAppendPoint(acq, "LASI2", values, PointType=btk.btkPoint.Marker, desc="toto", residuals=None)
def appendForcePlateCornerAsMarker(btkAcq): """ Add a marker at each force plate corners :Parameters: - `btkAcq` (btkAcquisition) : Btk acquisition instance from a c3d """ # --- ground reaction force wrench --- pfe = btk.btkForcePlatformsExtractor() pfe.SetInput(btkAcq) pfc = pfe.GetOutput() pfc.Update() for i in range(0, pfc.GetItemNumber()): val_corner0 = pfc.GetItem(i).GetCorner(0).T * np.ones( (btkAcq.GetPointFrameNumber(), 3)) btkTools.smartAppendPoint(btkAcq, "fp" + str(i) + "corner0", val_corner0, desc="forcePlate") val_corner1 = pfc.GetItem(i).GetCorner(1).T * np.ones( (btkAcq.GetPointFrameNumber(), 3)) btkTools.smartAppendPoint(btkAcq, "fp" + str(i) + "corner1", val_corner1, desc="forcePlate") val_corner2 = pfc.GetItem(i).GetCorner(2).T * np.ones( (btkAcq.GetPointFrameNumber(), 3)) btkTools.smartAppendPoint(btkAcq, "fp" + str(i) + "corner2", val_corner2, desc="forcePlate") val_corner3 = pfc.GetItem(i).GetCorner(3).T * np.ones( (btkAcq.GetPointFrameNumber(), 3)) btkTools.smartAppendPoint(btkAcq, "fp" + str(i) + "corner3", val_corner3, desc="forcePlate") val_origin = ( pfc.GetItem(i).GetCorner(0) + pfc.GetItem(i).GetCorner(1) + pfc.GetItem(i).GetCorner(2) + pfc.GetItem(i).GetCorner(3)) / 4.0 val_origin2 = val_origin.T * np.ones((btkAcq.GetPointFrameNumber(), 3)) btkTools.smartAppendPoint(btkAcq, "fp" + str(i) + "origin", val_origin2, desc="forcePlate")
def test_progressionFrameIssue(self): """ """ MAIN_PATH = pyCGM2.TEST_DATA_PATH + "\\Issues\\BrianH\\progressionFrame Issue\\" gaitFilename = "walk09.c3d" acq = btkTools.smartReader(MAIN_PATH + gaitFilename) valSACR = acq.GetPoint(utils.str("SACR")).GetValues() btkTools.smartAppendPoint(acq, "RPSI", valSACR, desc="") btkTools.smartAppendPoint(acq, "LPSI", valSACR, desc="") pfp = progressionFrame.PelvisProgressionFrameProcedure() pff = progressionFrame.ProgressionFrameFilter(acq, pfp) pff.compute() np.testing.assert_equal(pff.outputs["progressionAxis"], "X") np.testing.assert_equal(pff.outputs["forwardProgression"], True) gaitFilename = "walk11.c3d" acq = btkTools.smartReader(str(MAIN_PATH + gaitFilename)) valSACR = acq.GetPoint(utils.str("SACR")).GetValues() btkTools.smartAppendPoint(acq, "RPSI", valSACR, desc="") btkTools.smartAppendPoint(acq, "LPSI", valSACR, desc="") pfp = progressionFrame.PelvisProgressionFrameProcedure() pff = progressionFrame.ProgressionFrameFilter(acq, pfp) pff.compute() np.testing.assert_equal(pff.outputs["progressionAxis"], "X") np.testing.assert_equal(pff.outputs["forwardProgression"], True)
def fill(self, acq): logging.info("----LowDimensionalKalmanFilter gap filling----") btkmarkersLoaded = btkTools.GetMarkerNames(acq) ff = acq.GetFirstFrame() lf = acq.GetLastFrame() pfn = acq.GetPointFrameNumber() btkmarkers = [] for ml in btkmarkersLoaded: if btkTools.isPointExist(acq, ml): btkmarkers.append(ml) # -------- logging.debug("Populating data matrix") rawDatabtk = np.zeros((pfn, len(btkmarkers) * 3)) for i in range(0, len(btkmarkers)): values = acq.GetPoint(btkmarkers[i]).GetValues() residualValues = acq.GetPoint(btkmarkers[i]).GetResiduals() rawDatabtk[:, 3 * i - 3] = values[:, 0] rawDatabtk[:, 3 * i - 2] = values[:, 1] rawDatabtk[:, 3 * i - 1] = values[:, 2] E = residualValues[:, 0] rawDatabtk[np.asarray(E) == -1, 3 * i - 3] = np.nan rawDatabtk[np.asarray(E) == -1, 3 * i - 2] = np.nan rawDatabtk[np.asarray(E) == -1, 3 * i - 1] = np.nan Y2 = self._smooth(rawDatabtk, tol=1e-2, sigR=1e-3, keepOriginal=True) logging.debug("writing trajectories") # Create new smoothed trjectories filledMarkers = list() for i in range(0, len(btkmarkers)): targetMarker = btkmarkers[i] if btkTools.isGap(acq, targetMarker): logging.info("marker (%s) --> filled" % (targetMarker)) filledMarkers.append(targetMarker) val_final = np.zeros((pfn, 3)) val_final[:, 0] = Y2[:, 3 * i - 3] val_final[:, 1] = Y2[:, 3 * i - 2] val_final[:, 2] = Y2[:, 3 * i - 1] btkTools.smartAppendPoint(acq, targetMarker, val_final) logging.info( "----LowDimensionalKalmanFilter gap filling [complete]----") return acq, filledMarkers
def main(): # parser = argparse.ArgumentParser(description='') # parser.add_argument('-l','--leftFlatFoot', type=int, help='left flat foot option') # parser.add_argument('-md','--markerDiameter', type=float, help='marker diameter') # parser.add_argument('-ps','--pointSuffix', type=str, help='suffix of model outputs') # parser.add_argument('--check', action='store_true', help='force model output suffix') # parser.add_argument('--forceLHJC', nargs='+') # args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if NEXUS_PYTHON_CONNECTED: # run Operation DATA_PATH, filename = NEXUS.GetTrialName() LOGGER.logger.info("data Path: " + DATA_PATH) LOGGER.set_file_handler(DATA_PATH + "pyCGM2.log") LOGGER.logger.info(" file: " + filename) # --------------------------SUBJECT ------------------------------------ subjects = NEXUS.GetSubjectNames() subject = nexusTools.getActiveSubject( NEXUS) #checkActivatedSubject(NEXUS,subjects) Parameters = NEXUS.GetSubjectParamNames(subject) # --------------------------PULL ------------------------------------ nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, filename, subject) acq = nacf.build() # --------------------------process ------------------------------------ # Work with BTK Here values = (acq.GetPoint("LTIAP").GetValues() + acq.GetPoint("LTIB").GetValues()) / 2.0 btkTools.smartAppendPoint(acq, "LTIAD", values, PointType=btk.btkPoint.Marker, desc="", residuals=None)
def decomposeTrackingMarkers(self,acq,TechnicalFrameLabel): # decompose marker and keep a noisy signal along one axis only. # # :Parameters: # - `acq` (btk-acq) - # - `TechnicalFrameLabel` (str) - label of the technical Frame # # .. todo:: # # - comment travailler avec des referentiels techniques differents par segment # - rajouter des exceptions for seg in self.m_segmentCollection: for marker in seg.m_tracking_markers: nodeTraj= seg.getReferential(TechnicalFrameLabel).getNodeTrajectory(marker) markersTraj =acq.GetPoint(marker).GetValues() markerTrajectoryX=np.array( [ markersTraj[:,0], nodeTraj[:,1], nodeTraj[:,2]]).T markerTrajectoryY=np.array( [ nodeTraj[:,0], markersTraj[:,1], nodeTraj[:,2]]).T markerTrajectoryZ=np.array( [ nodeTraj[:,0], nodeTraj[:,1], markersTraj[:,2]]).T btkTools.smartAppendPoint(acq,marker+"-X",markerTrajectoryX,PointType=btk.btkPoint.Marker, desc="") btkTools.smartAppendPoint(acq,marker+"-Y",markerTrajectoryY,PointType=btk.btkPoint.Marker, desc="") btkTools.smartAppendPoint(acq,marker+"-Z",markerTrajectoryZ,PointType=btk.btkPoint.Marker, desc="")
def displayMotionViconCoordinateSystem(self, acqui, segmentLabel, targetPointLabelO, targetPointLabelX, targetPointLabelY, targetPointLabelZ, referential="Anatomic"): seg = self.getSegment(segmentLabel) origin = np.zeros((acqui.GetPointFrameNumber(), 3)) valX = np.zeros((acqui.GetPointFrameNumber(), 3)) valY = np.zeros((acqui.GetPointFrameNumber(), 3)) valZ = np.zeros((acqui.GetPointFrameNumber(), 3)) if referential == "Anatomic": ref = seg.anatomicalFrame else: ref = seg.getReferential("TF") for i in range(0, acqui.GetPointFrameNumber()): origin[i, :] = ref.motion[i].getTranslation() valX[i, :] = np.dot(ref.motion[i].getRotation(), np.array([100.0, 0.0, 0.0 ])) + ref.motion[i].getTranslation() valY[i, :] = np.dot(ref.motion[i].getRotation(), np.array([0.0, 100.0, 0.0 ])) + ref.motion[i].getTranslation() valZ[i, :] = np.dot(ref.motion[i].getRotation(), np.array([0.0, 0.0, 100.0 ])) + ref.motion[i].getTranslation() btkTools.smartAppendPoint(acqui, targetPointLabelO, origin, desc="") btkTools.smartAppendPoint(acqui, targetPointLabelX, valX, desc="") btkTools.smartAppendPoint(acqui, targetPointLabelY, valY, desc="") btkTools.smartAppendPoint(acqui, targetPointLabelZ, valZ, desc="")
def displayStaticCoordinateSystem(self, aquiStatic, segmentLabel, targetPointLabel, referential="Anatomic"): """ Display a coordinate system. Its Axis are represented by 3 virtual markers suffixed by (_X,_Y,_Z) :Parameters: - `aquiStatic` (btkAcquisition) - btkAcquisition instance from a static c3d - `segmentLabel` (str) - segment label - `targetPointLabel` (str) - label of the point defining axis limits - `referential` (str) - type of segment coordinate system you want dislay ( if other than *Anatomic*, Technical Coordinate system will be displayed ) """ seg = self.getSegment(segmentLabel) if referential == "Anatomic": ref = seg.anatomicalFrame else: ref = seg.getReferential("TF") val = np.dot(ref.static.getRotation(), np.array( [100.0, 0.0, 0.0])) + ref.static.getTranslation() btkTools.smartAppendPoint(aquiStatic, targetPointLabel + "_X", val * np.ones( (aquiStatic.GetPointFrameNumber(), 3)), desc="") val = np.dot(ref.static.getRotation(), np.array( [0.0, 100.0, 0.0])) + ref.static.getTranslation() btkTools.smartAppendPoint(aquiStatic, targetPointLabel + "_Y", val * np.ones( (aquiStatic.GetPointFrameNumber(), 3)), desc="") val = np.dot(ref.static.getRotation(), np.array( [0.0, 0, 100.0])) + ref.static.getTranslation() btkTools.smartAppendPoint(aquiStatic, targetPointLabel + "_Z", val * np.ones( (aquiStatic.GetPointFrameNumber(), 3)), desc="")
def nexus_x2d(cls): NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() DATA_PATH = "C:\\Users\\HLS501\\Documents\\VICON DATA\\pyCGM2-Data\\operations\\gapFilling\\gaitWithGaps_withX2d\\" filenameNoExt = "gait_GAP" NEXUS.OpenTrial(str(DATA_PATH + filenameNoExt), 30) acq_filled = btkTools.smartReader( str(DATA_PATH + "gait_GAP.-moGap.c3d")) subject = NEXUS.GetSubjectNames()[0] print "Gap filling for subject ", subject markersLoaded = NEXUS.GetMarkerNames( subject) # nexus2.7 return all makers, even calibration only frames = NEXUS.GetFrameCount() markers = [] for i in range(0, len(markersLoaded)): data = NEXUS.GetTrajectory(subject, markersLoaded[i]) if data != ([], [], [], []): markers.append(markersLoaded[i]) #--------- acq = btkTools.smartReader(str(DATA_PATH + filenameNoExt + ".c3d")) btkmarkersLoaded = btkTools.GetMarkerNames(acq) ff = acq.GetFirstFrame() lf = acq.GetLastFrame() pfn = acq.GetPointFrameNumber() btkmarkers = [] for ml in btkmarkersLoaded: if btkTools.isPointExist(acq, ml): btkmarkers.append(ml) #--------- print "Populating data matrix" rawData = np.zeros((frames, len(markers) * 3)) for i in range(0, len(markers)): print i rawData[:, 3 * i - 3], rawData[:, 3 * i - 2], rawData[:, 3 * i - 1], E = NEXUS.GetTrajectory( subject, markers[i]) rawData[np.asarray(E) == 0, 3 * i - 3] = np.nan rawData[np.asarray(E) == 0, 3 * i - 2] = np.nan rawData[np.asarray(E) == 0, 3 * i - 1] = np.nan Y = smooth(rawData, tol=1e-2, sigR=1e-3, keepOriginal=True) print "Writing new trajectories" # Create new smoothed trjectories for i in range(0, len(markers)): if markers[i] == "LTHAD": E = np.ones((len(E), 1)).tolist() val0 = Y[:, 3 * i - 3].tolist() val1 = Y[:, 3 * i - 2].tolist() val2 = Y[:, 3 * i - 1].tolist() #NEXUS.SetTrajectory(subject,markers[i],Y[:,3*i-3].tolist(),Y[:,3*i-2].tolist(),Y[:,3*i-1].tolist(),E) print "Done" # -------- print "Populating data matrix" rawDatabtk = np.zeros((pfn, len(btkmarkers) * 3)) for i in range(0, len(btkmarkers)): values = acq.GetPoint(btkmarkers[i]).GetValues() residualValues = acq.GetPoint(btkmarkers[i]).GetResiduals() rawDatabtk[:, 3 * i - 3] = values[:, 0] rawDatabtk[:, 3 * i - 2] = values[:, 1] rawDatabtk[:, 3 * i - 1] = values[:, 2] E = residualValues[:, 0] rawDatabtk[np.asarray(E) == -1, 3 * i - 3] = np.nan rawDatabtk[np.asarray(E) == -1, 3 * i - 2] = np.nan rawDatabtk[np.asarray(E) == -1, 3 * i - 1] = np.nan Y2 = smooth(rawDatabtk, tol=1e-2, sigR=1e-3, keepOriginal=True) print "Writing new trajectories" # Create new smoothed trjectories for i in range(0, len(btkmarkers)): targetMarker = btkmarkers[i] if btkTools.isGap(acq, targetMarker): val_final = np.zeros((pfn, 3)) val_final[:, 0] = Y2[:, 3 * i - 3] val_final[:, 1] = Y2[:, 3 * i - 2] val_final[:, 2] = Y2[:, 3 * i - 1] btkTools.smartAppendPoint(acq, targetMarker, val_final) nexusTools.setTrajectoryFromAcq(NEXUS, subject, targetMarker, acq) print "Done"
subject, acqFunc, "RFE0", model.getSegment("Right Thigh"), OriginValues=acqFunc.GetPoint("RKJC").GetValues()) proximalSegmentLabel = str(side + " Thigh") distalSegmentLabel = str(side + " Shank") # add modelled markers meanOr_inThigh = model.getSegment(proximalSegmentLabel).getReferential( "TF").getNodeTrajectory("KJC_Sara") meanAxis_inThigh = model.getSegment( proximalSegmentLabel).getReferential("TF").getNodeTrajectory( "KJC_SaraAxis") btkTools.smartAppendPoint(acqFunc, side + "_KJC_Sara", meanOr_inThigh) btkTools.smartAppendPoint(acqFunc, side + "_KJC_SaraAxis", meanAxis_inThigh) nexusTools.appendModelledMarkerFromAcq(NEXUS, subject, side + "_KJC_Sara", acqFunc) nexusTools.appendModelledMarkerFromAcq(NEXUS, subject, side + "_KJC_SaraAxis", acqFunc) #---Second model motion filter # consider new anatomical frame scp = modelFilters.StaticCalibrationProcedure(model) modMotion = modelFilters.ModelMotionFilter( scp, acqFunc, model, enums.motionMethod.Sodervisk) modMotion.segmentalCompute([proximalSegmentLabel, distalSegmentLabel])
def run(self, acqMotion, acqMotionFilename, exportSetUp=True): """ Run kinematic fitting :Parameters: - `acqMotion` (btk.Acquisition) - acquisition of a motion trial - `acqMotionFilename` (filename) - filename of the motion trial """ acqMotion_forIK = btk.btkAcquisition.Clone(acqMotion) progressionAxis, forwardProgression, globalFrame = btkTools.findProgressionAxisFromPelvicMarkers( acqMotion, ["LASI", "RASI", "RPSI", "LPSI"]) # --- ikTasks # UPDATE method - ik tags ( need task in the initial iktools) for markerIt in self.m_procedure.ikTags.keys(): self._osimIK.updateIKTask(markerIt, self.m_procedure.ikTags[markerIt]) # --- configuration and run IK if os.path.isfile(self.opensimOutputDir + "ik_model_marker_locations.sto"): os.remove(self.opensimOutputDir + "ik_model_marker_locations.sto") R_LAB_OSIM = osimProcessing.setGlobalTransormation_lab_osim( progressionAxis, forwardProgression) self._osimIK.config(R_LAB_OSIM, acqMotion_forIK, acqMotionFilename) if exportSetUp: if os.path.isfile(self.opensimOutputDir + "scaledModel-ikSetUp.xml"): os.remove(self.opensimOutputDir + "scaledModel-ikSetUp.xml") self.exportXml("scaledModel-ikSetUp.xml", path=self.opensimOutputDir) self._osimIK.run() # --- gernerate acq with rigid markers acqMotionFinal = btk.btkAcquisition.Clone(acqMotion) for marker in self.m_procedure.ikTags.keys(): if self.m_procedure.ikTags[marker] != 0: values = osimProcessing.sto2pointValues( self.opensimOutputDir + "ik_model_marker_locations.sto", marker, R_LAB_OSIM) lenOsim = len(values) lenc3d = acqMotion.GetPoint(marker).GetFrameNumber() if lenOsim < lenc3d: logging.warning(" size osim (%i) inferior to c3d (%i)" % (lenOsim, lenc3d)) values2 = np.zeros((lenc3d, 3)) values2[0:lenOsim, :] = values values2[lenOsim:lenc3d, :] = acqMotion.GetPoint( marker).GetValues()[lenOsim:lenc3d, :] btkTools.smartAppendPoint( acqMotionFinal, marker + "_m", acqMotionFinal.GetPoint(marker).GetValues(), desc="measured") # new acq with marker overwrited btkTools.smartAppendPoint( acqMotionFinal, marker, values2, desc="kinematic fitting" ) # new acq with marker overwrited else: btkTools.smartAppendPoint( acqMotionFinal, marker + "_m", acqMotionFinal.GetPoint(marker).GetValues(), desc="measured") # measured marker suffix with _m btkTools.smartAppendPoint( acqMotionFinal, marker, values, desc="kinematic fitting" ) # new acq with marker overwrited return acqMotionFinal
from pyCGM2.Tools import btkTools from pyCGM2.Utils import files if __name__ == "__main__": DATA_PATH = pyCGM2.TEST_DATA_PATH + "MODEL\\Custom\\sample0\\" staticFilename = "static.c3d" dynamicFilename = "dynamic.c3d" acqStatic = btkTools.smartReader(str(DATA_PATH + staticFilename)) acqDynamic = btkTools.smartReader(str(DATA_PATH + dynamicFilename)) # new markers valSACR = (acqStatic.GetPoint("LPSI").GetValues() + acqStatic.GetPoint("RPSI").GetValues()) / 2.0 btkTools.smartAppendPoint(acqStatic, "SACR", valSACR, desc="") valMidAsis = (acqStatic.GetPoint("LASI").GetValues() + acqStatic.GetPoint("RASI").GetValues()) / 2.0 btkTools.smartAppendPoint(acqStatic, "midASIS", valMidAsis, desc="") valLMET = (acqStatic.GetPoint("LFMH").GetValues() + acqStatic.GetPoint("LVMH").GetValues()) / 2.0 btkTools.smartAppendPoint(acqStatic, "LMET", valLMET, desc="") valRMET = (acqStatic.GetPoint("RFMH").GetValues() + acqStatic.GetPoint("RVMH").GetValues()) / 2.0 btkTools.smartAppendPoint(acqStatic, "RMET", valRMET, desc="") # anthropometric Me # ---- Model configuration ---- bioMechModel = model.Model() mp = {
def _rightHindFoot_motion_optimize(self, aqui, dictRef, dictAnat, motionMethod): seg = self.getSegment("Right Hindfoot") # --- add RAJC if marker list < 2 - check presence of tracking markers in the acquisition if seg.m_tracking_markers != []: if len(seg.m_tracking_markers) == 2: if "RAJC" not in seg.m_tracking_markers: seg.m_tracking_markers.append("RAJC") logging.debug("RAJC added to tracking marker list") # --- Motion of the Technical frame seg.getReferential("TF").motion = [] # part 1: get global location in Static if seg.m_tracking_markers != []: # work with tracking markers staticPos = np.zeros((len(seg.m_tracking_markers), 3)) i = 0 for label in seg.m_tracking_markers: staticPos[i, :] = seg.getReferential( "TF").static.getNode_byLabel(label).m_global i += 1 # part 2 : get dynamic position ( look out i pick up value in the btkAcquisition) for i in range(0, aqui.GetPointFrameNumber()): if seg.m_tracking_markers != []: # work with traking markers dynPos = np.zeros((len(seg.m_tracking_markers), 3)) # use k = 0 for label in seg.m_tracking_markers: dynPos[k, :] = aqui.GetPoint(label).GetValues()[i, :] k += 1 if motionMethod == pyCGM2Enums.motionMethod.Sodervisk: Ropt, Lopt, RMSE, Am, Bm = cmot.segmentalLeastSquare( staticPos, dynPos) R = np.dot(Ropt, seg.getReferential("TF").static.getRotation()) tOri = np.dot( Ropt, seg.getReferential("TF").static.getTranslation()) + Lopt frame = cfr.Frame() frame.setRotation(R) frame.setTranslation(tOri) frame.m_axisX = R[:, 0] frame.m_axisY = R[:, 1] frame.m_axisZ = R[:, 2] seg.getReferential("TF").addMotionFrame(frame) # --- RvCUN btkTools.smartAppendPoint( aqui, "RvCUN", seg.getReferential("TF").getNodeTrajectory("RvCUN"), desc="opt") # --- Motion of the Anatomical frame seg.anatomicalFrame.motion = [] for i in range(0, aqui.GetPointFrameNumber()): ptOrigin = aqui.GetPoint( str(dictAnat["Right Hindfoot"]['labels'][3])).GetValues()[i, :] #R = np.dot(seg.getReferential("TF").motion[i].getRotation(),relativeSegTech ) R = np.dot( seg.getReferential("TF").motion[i].getRotation(), seg.getReferential("TF").relativeMatrixAnatomic) frame = cfr.Frame() frame.update(R, ptOrigin) seg.anatomicalFrame.addMotionFrame(frame)
def _right_foreFoot_motion(self, aqui, dictRef, dictAnat, options=None): """ :Parameters: - `aqui` (btkAcquisition) - acquisition - `dictRef` (dict) - instance of Model - `frameInit` (int) - starting frame """ seg = self.getSegment("Right Forefoot") # --- motion of the technical referential seg.getReferential("TF").motion = [] # additional markers # NA #computation for i in range(0, aqui.GetPointFrameNumber()): pt1 = aqui.GetPoint( str(dictRef["Right Forefoot"]["TF"]['labels'][0])).GetValues()[ i, :] pt2 = aqui.GetPoint( str(dictRef["Right Forefoot"]["TF"]['labels'][1])).GetValues()[ i, :] pt3 = aqui.GetPoint( str(dictRef["Right Forefoot"]["TF"]['labels'][2])).GetValues()[ i, :] if dictRef["Right Forefoot"]["TF"]['labels'][2] is not None: pt3 = aqui.GetPoint( str(dictRef["Right Forefoot"]["TF"]['labels'] [2])).GetValues()[i, :] # not used v = (pt3 - pt1) else: v = self.getSegment( "Right Shank").anatomicalFrame.motion[i].m_axisY ptOrigin = aqui.GetPoint( str(dictRef["Right Forefoot"]["TF"]['labels'][3])).GetValues()[ i, :] a1 = (pt2 - pt1) a1 = a1 / np.linalg.norm(a1) v = (pt3 - pt1) v = v / np.linalg.norm(v) a2 = np.cross(a1, v) a2 = a2 / np.linalg.norm(a2) x, y, z, R = cfr.setFrameData( a1, a2, dictRef["Right Forefoot"]["TF"]['sequence']) frame = cfr.Frame() frame.m_axisX = x frame.m_axisY = y frame.m_axisZ = z frame.setRotation(R) frame.setTranslation(ptOrigin) seg.getReferential("TF").addMotionFrame(frame) # --- motion of new markers btkTools.smartAppendPoint( aqui, "RvTOE", seg.getReferential("TF").getNodeTrajectory("RvTOE")) btkTools.smartAppendPoint( aqui, "RvD5M", seg.getReferential("TF").getNodeTrajectory("RvD5M")) # --- motion of the anatomical referential seg.anatomicalFrame.motion = [] for i in range(0, aqui.GetPointFrameNumber()): ptOrigin = aqui.GetPoint( str(dictAnat["Right Forefoot"]['labels'][3])).GetValues()[i, :] #R = np.dot(seg.getReferential("TF").motion[i].getRotation(),relativeSegTech ) R = np.dot( seg.getReferential("TF").motion[i].getRotation(), seg.getReferential("TF").relativeMatrixAnatomic) frame = cfr.Frame() frame.update(R, ptOrigin) seg.anatomicalFrame.addMotionFrame(frame)
def _rightForeFoot_calibrate(self, aquiStatic, dictRef, frameInit, frameEnd, options=None): nFrames = aquiStatic.GetPointFrameNumber() seg = self.getSegment("Right Forefoot") # --- additional markers and Update of the marker segment list # new markers ( RvTOE - RvD5M) toe = aquiStatic.GetPoint("RTOE").GetValues() d5 = aquiStatic.GetPoint("RD5M").GetValues() valuesVirtualToe = np.zeros((nFrames, 3)) valuesVirtualD5 = np.zeros((nFrames, 3)) for i in range(0, nFrames): valuesVirtualToe[i, :] = np.array([ toe[i, 0], toe[i, 1], toe[i, 2] - self.mp["rightToeOffset"] ]) #valuesVirtualCun[i,2]])# valuesVirtualD5[i, :] = np.array( [d5[i, 0], d5[i, 1], valuesVirtualToe[i, 2]]) btkTools.smartAppendPoint(aquiStatic, "RvTOE", valuesVirtualToe, desc="virtual") btkTools.smartAppendPoint(aquiStatic, "RvD5M", valuesVirtualD5, desc="virtual-flat ") # update marker list seg.addMarkerLabel("RMidFoot") seg.addMarkerLabel("RvCUN") seg.addMarkerLabel("RvTOE") seg.addMarkerLabel("RvD5M") # --- technical frame selection and construction tf = seg.getReferential("TF") pt1 = aquiStatic.GetPoint( str(dictRef["Right Forefoot"]["TF"]['labels'][0])).GetValues()[ frameInit:frameEnd, :].mean(axis=0) # D5 pt2 = aquiStatic.GetPoint( str(dictRef["Right Forefoot"]["TF"]['labels'][1])).GetValues()[ frameInit:frameEnd, :].mean(axis=0) # Toe if dictRef["Right Forefoot"]["TF"]['labels'][2] is not None: pt3 = aquiStatic.GetPoint( str(dictRef["Right Forefoot"]["TF"]['labels'][2])).GetValues()[ frameInit:frameEnd, :].mean(axis=0) v = (pt3 - pt1) else: v = 100 * np.array([0.0, 0.0, 1.0]) ptOrigin = aquiStatic.GetPoint( str(dictRef["Right Forefoot"]["TF"]['labels'][3])).GetValues()[ frameInit:frameEnd, :].mean(axis=0) a1 = (pt2 - pt1) a1 = a1 / np.linalg.norm(a1) v = v / np.linalg.norm(v) a2 = np.cross(a1, v) a2 = a2 / np.linalg.norm(a2) x, y, z, R = cfr.setFrameData( a1, a2, dictRef["Right Forefoot"]["TF"]['sequence']) tf.static.m_axisX = x tf.static.m_axisY = y tf.static.m_axisZ = z tf.static.setRotation(R) tf.static.setTranslation(ptOrigin) # --- node manager for label in seg.m_markerLabels: globalPosition = aquiStatic.GetPoint( str(label)).GetValues()[frameInit:frameEnd, :].mean(axis=0) tf.static.addNode(label, globalPosition, positionType="Global")
def _rightHindFoot_calibrate(self, aquiStatic, dictRef, frameInit, frameEnd, options=None): nFrames = aquiStatic.GetPointFrameNumber() seg = self.getSegment("Right Hindfoot") # --- additional markers and Update of the marker segment list # new markers # mid point NAV and RP5M valMidFoot = (aquiStatic.GetPoint("RNAV").GetValues() + aquiStatic.GetPoint("RP5M").GetValues()) / 2.0 btkTools.smartAppendPoint(aquiStatic, "RMidFoot", valMidFoot, desc="") # virtual CUN cun = aquiStatic.GetPoint("RCUN").GetValues() valuesVirtualCun = np.zeros((nFrames, 3)) for i in range(0, nFrames): valuesVirtualCun[i, :] = np.array( [cun[i, 0], cun[i, 1], cun[i, 2] - self.mp["rightToeOffset"]]) btkTools.smartAppendPoint(aquiStatic, "RvCUN", valuesVirtualCun, desc="cun Registrate") # update marker list seg.addMarkerLabel("RAJC") # required markers seg.addMarkerLabel("RMidFoot") seg.addMarkerLabel("RvCUN") # --- technical frame selection and construction tf = seg.getReferential("TF") pt1 = aquiStatic.GetPoint( str(dictRef["Right Hindfoot"]["TF"]['labels'][0])).GetValues()[ frameInit:frameEnd, :].mean(axis=0) pt2 = aquiStatic.GetPoint( str(dictRef["Right Hindfoot"]["TF"]['labels'][1])).GetValues()[ frameInit:frameEnd, :].mean(axis=0) if dictRef["Right Hindfoot"]["TF"]['labels'][2] is not None: pt3 = aquiStatic.GetPoint( str(dictRef["Right Hindfoot"]["TF"]['labels'][2])).GetValues()[ frameInit:frameEnd, :].mean(axis=0) # not used v = (pt3 - pt1) else: v = self.getSegment( "Right Shank").anatomicalFrame.static.m_axisY #(pt3-pt1) ptOrigin = aquiStatic.GetPoint( str(dictRef["Right Hindfoot"]["TF"]['labels'][3])).GetValues()[ frameInit:frameEnd, :].mean(axis=0) a1 = (pt2 - pt1) a1 = a1 / np.linalg.norm(a1) v = v / np.linalg.norm(v) a2 = np.cross(a1, v) a2 = a2 / np.linalg.norm(a2) x, y, z, R = cfr.setFrameData( a1, a2, dictRef["Right Hindfoot"]["TF"]['sequence']) tf.static.m_axisX = x tf.static.m_axisY = y tf.static.m_axisZ = z tf.static.setRotation(R) tf.static.setTranslation(ptOrigin) # --- node manager for label in seg.m_markerLabels: globalPosition = aquiStatic.GetPoint( str(label)).GetValues()[frameInit:frameEnd, :].mean(axis=0) tf.static.addNode(label, globalPosition, positionType="Global")
def calibrate(self, aquiStatic, dictRef, dictAnatomic, options=None): """ static calibration :Parameters: - `aquiStatic` (btkAcquisition) - acquisition - `dictRef` (dict) - instance of Model - `options` (kwargs) - use to pass option altering the standard construction .. todo:: shrink and clone the aquisition to seleted frames """ logging.info("=====================================================") logging.info("===================CGM CALIBRATION===================") logging.info("=====================================================") ff = aquiStatic.GetFirstFrame() lf = aquiStatic.GetLastFrame() frameInit = ff - ff frameEnd = lf - ff + 1 if not self.decoratedModel: logging.warning(" Native CGM") if not btkTools.isPointExist(aquiStatic, "LKNE"): btkTools.smartAppendPoint( aquiStatic, "LKNE", np.zeros((aquiStatic.GetPointFrameNumber(), 3))) if not btkTools.isPointExist(aquiStatic, "RKNE"): btkTools.smartAppendPoint( aquiStatic, "RKNE", np.zeros((aquiStatic.GetPointFrameNumber(), 3))) else: logging.warning(" Decorated CGM") # --- PELVIS - THIGH - SHANK #------------------------------------- # calibration of technical Referentials logging.info(" --- Pelvis - TF calibration ---") logging.info(" -------------------------------") self._pelvis_calibrate(aquiStatic, dictRef, frameInit, frameEnd, options=options) # from CGM1 logging.info(" --- Left Thigh - TF calibration ---") logging.info(" -----------------------------------") self._left_thigh_calibrate(aquiStatic, dictRef, frameInit, frameEnd, options=options) # from CGM1 logging.info(" --- Right Thigh - TF calibration ---") logging.info(" ------------------------------------") self._right_thigh_calibrate(aquiStatic, dictRef, frameInit, frameEnd, options=options) # from CGM1 logging.info(" --- Left Shank - TF calibration ---") logging.info(" -----------------------------------") self._left_shank_calibrate(aquiStatic, dictRef, frameInit, frameEnd, options=options) # from CGM1 logging.info(" --- Right Shank - TF calibration ---") logging.info(" ------------------------------------") self._right_shank_calibrate(aquiStatic, dictRef, frameInit, frameEnd, options=options) # from CGM1 # calibration of anatomical Referentials logging.info(" --- Pelvis - AF calibration ---") logging.info(" -------------------------------") self._pelvis_Anatomicalcalibrate(aquiStatic, dictAnatomic, frameInit, frameEnd) self.displayStaticCoordinateSystem( aquiStatic, "Pelvis", "Pelvis", referential="Anatomical") # from CGM1 logging.info(" --- Left Thigh - AF calibration ---") logging.info(" -----------------------------------") self._left_thigh_Anatomicalcalibrate(aquiStatic, dictAnatomic, frameInit, frameEnd) self.displayStaticCoordinateSystem( aquiStatic, "Left Thigh", "LThigh", referential="Anatomical") # from CGM1 logging.info(" --- Right Thigh - AF calibration ---") logging.info(" ------------------------------------") self._right_thigh_Anatomicalcalibrate(aquiStatic, dictAnatomic, frameInit, frameEnd) self.displayStaticCoordinateSystem( aquiStatic, "Right Thigh", "RThigh", referential="Anatomical") # from CGM1 logging.info(" --- Left Shank - AF calibration ---") logging.info(" -----------------------------------") self._left_shank_Anatomicalcalibrate(aquiStatic, dictAnatomic, frameInit, frameEnd) self.displayStaticCoordinateSystem( aquiStatic, "Left Shank", "LShank", referential="Anatomical") # from CGM1 logging.info(" --- Right Shank - AF calibration ---") logging.info(" ------------------------------------") self._right_shank_Anatomicalcalibrate(aquiStatic, dictAnatomic, frameInit, frameEnd) self.displayStaticCoordinateSystem( aquiStatic, "Right Shank", "RShank", referential="Anatomical") # from CGM1 #offsets logging.info(" --- Compute Offsets ---") logging.info(" -----------------------") self.getThighOffset(side="left") self.getThighOffset(side="right") self.getShankOffsets( side="both") # compute TibialRotation and Shank offset self.getAbdAddAnkleJointOffset(side="both") # --- FOOT segment # --------------- # need anatomical flexion axis of the shank. # --- hind foot # -------------- logging.info(" --- Right Hind Foot - TF calibration ---") logging.info(" -----------------------------------------") self._rightHindFoot_calibrate(aquiStatic, dictRef, frameInit, frameEnd, options=options) #self.displayStaticCoordinateSystem( aquiStatic, "Right Hindfoot","RHindFootUncorrected",referential = "technic" ) logging.info(" --- Right Hind Foot - AF calibration ---") logging.info(" -----------------------------------------") self._rightHindFoot_anatomicalCalibrate(aquiStatic, dictAnatomic, frameInit, frameEnd, options=options) self.displayStaticCoordinateSystem(aquiStatic, "Right Hindfoot", "RHindFoot", referential="Anatomical") logging.info(" --- Hind foot Offset---") logging.info(" -----------------------") self.getHindFootOffset(side="both") # --- fore foot # ---------------- logging.info(" --- Right Fore Foot - TF calibration ---") logging.info(" -----------------------------------------") self._rightForeFoot_calibrate(aquiStatic, dictRef, frameInit, frameEnd, options=options) self.displayStaticCoordinateSystem(aquiStatic, "Right Forefoot", "RTechnicForeFoot", referential="Technical") logging.info(" --- Right Fore Foot - AF calibration ---") logging.info(" -----------------------------------------") self._rightForeFoot_anatomicalCalibrate(aquiStatic, dictAnatomic, frameInit, frameEnd) self.displayStaticCoordinateSystem(aquiStatic, "Right Forefoot", "RForeFoot", referential="Anatomical") btkTools.smartWriter(aquiStatic, "tmp-static.c3d")
def CGM2_4_SARA_test(cls): MAIN_PATH = pyCGM2.TEST_DATA_PATH + "CGM2\\cgm2.4\\Knee Calibration\\" staticFilename = "static.c3d" funcFilename = "functional.c3d" gaitFilename = "gait trial 01.c3d" markerDiameter = 14 mp = { 'Bodymass': 69.0, 'LeftLegLength': 930.0, 'RightLegLength': 930.0, 'LeftKneeWidth': 94.0, 'RightKneeWidth': 64.0, 'LeftAnkleWidth': 67.0, 'RightAnkleWidth': 62.0, 'LeftSoleDelta': 0, 'RightSoleDelta': 0, "LeftToeOffset": 0, "RightToeOffset": 0, } acqStatic = btkTools.smartReader(str(MAIN_PATH + staticFilename)) model = cgm2.CGM2_4LowerLimbs() model.configure() model.addAnthropoInputParameters(mp) # --- INITIAL CALIBRATION --- scp = modelFilters.StaticCalibrationProcedure(model) modelFilters.ModelCalibrationFilter(scp, acqStatic, model).compute() # cgm decorator modelDecorator.HipJointCenterDecorator(model).hara() modelDecorator.KneeCalibrationDecorator(model).midCondyles( acqStatic, markerDiameter=markerDiameter, side="both", cgm1Behaviour=True) modelDecorator.AnkleCalibrationDecorator(model).midMaleolus( acqStatic, markerDiameter=markerDiameter, side="both") # final modelFilters.ModelCalibrationFilter( scp, acqStatic, model, seLeftHJCnode="LHJC_Hara", useRightHJCnode="RHJC_Hara", useLeftKJCnode="LKJC_mid", useLeftAJCnode="LAJC_mid", useRightKJCnode="RKJC_mid", useRightAJCnode="RAJC_mid", markerDiameter=markerDiameter).compute() # ------ LEFT KNEE CALIBRATION ------- acqFunc = btkTools.smartReader(str(MAIN_PATH + funcFilename)) # Motion of only left modMotionLeftKnee = modelFilters.ModelMotionFilter( scp, acqFunc, model, pyCGM2Enums.motionMethod.Sodervisk) modMotionLeftKnee.segmentalCompute(["Left Thigh", "Left Shank"]) # decorator modelDecorator.KneeCalibrationDecorator(model).sara( "Left", indexFirstFrame=831, indexLastFrame=1280) # ----add Point into the c3d---- Or_inThigh = model.getSegment("Left Thigh").getReferential( "TF").getNodeTrajectory("KneeFlexionOri") axis_inThigh = model.getSegment("Left Thigh").getReferential( "TF").getNodeTrajectory("KneeFlexionAxis") btkTools.smartAppendPoint(acqFunc, "Left" + "_KneeFlexionOri", Or_inThigh) btkTools.smartAppendPoint(acqFunc, "Left" + "_KneeFlexionAxis", axis_inThigh) # ------ RIGHT KNEE CALIBRATION ------- # Motion of only left modMotionRightKnee = modelFilters.ModelMotionFilter( scp, acqFunc, model, pyCGM2Enums.motionMethod.Sodervisk) modMotionRightKnee.segmentalCompute(["Right Thigh", "Right Shank"]) # decorator modelDecorator.KneeCalibrationDecorator(model).sara("Right", indexFirstFrame=61, indexLastFrame=551) # ----add Point into the c3d---- Or_inThigh = model.getSegment("Right Thigh").getReferential( "TF").getNodeTrajectory("KneeFlexionOri") axis_inThigh = model.getSegment("Right Thigh").getReferential( "TF").getNodeTrajectory("KneeFlexionAxis") btkTools.smartAppendPoint(acqFunc, "Right" + "_KneeFlexionOri", Or_inThigh) btkTools.smartAppendPoint(acqFunc, "Right" + "_KneeFlexionAxis", axis_inThigh) btkTools.smartWriter(acqFunc, "acqFunc-Sara.c3d") #--- FINAL CALIBRATION --- modelFilters.ModelCalibrationFilter( scp, acqStatic, model, useLeftHJCnode="LHJC_Hara", useRightHJCnode="RHJC_Hara", useLeftKJCnode="KJC_Sara", useLeftAJCnode="LAJC_mid", useRightKJCnode="KJC_Sara", useRightAJCnode="RAJC_mid", markerDiameter=markerDiameter, RotateLeftThighFlag=True, RotateRightThighFlag=True).compute() # save static c3d with update KJC btkTools.smartWriter(acqStatic, "Static-SARA.c3d") # ------ Fitting ------- acqGait = btkTools.smartReader(str(MAIN_PATH + gaitFilename)) # Motion FILTER modMotion = modelFilters.ModelMotionFilter( scp, acqGait, model, pyCGM2Enums.motionMethod.Determinist) modMotion.compute() # relative angles modelFilters.ModelJCSFilter(model, acqGait).compute( description="vectoriel", pointLabelSuffix="cgm1_6dof") # absolute angles longitudinalAxis, forwardProgression, globalFrame = btkTools.findProgressionAxisFromPelvicMarkers( acqGait, ["LASI", "RASI", "RPSI", "LPSI"]) modelFilters.ModelAbsoluteAnglesFilter( model, acqGait, segmentLabels=["Left HindFoot", "Right HindFoot", "Pelvis"], angleLabels=["LFootProgress", "RFootProgress", "Pelvis"], eulerSequences=["TOR", "TOR", "ROT"], globalFrameOrientation=globalFrame, forwardProgression=forwardProgression).compute( pointLabelSuffix="cgm1_6dof") # ------- OPENSIM IK -------------------------------------- # --- osim builder --- cgmCalibrationprocedure = opensimFilters.CgmOpensimCalibrationProcedures( model) markersetFile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + "models\\settings\\cgm2_4\\cgm2_4-markerset.xml" osimfile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + "models\\osim\\lowerLimb_ballsJoints.osim" oscf = opensimFilters.opensimCalibrationFilter( osimfile, model, cgmCalibrationprocedure) oscf.addMarkerSet(markersetFile) scalingOsim = oscf.build(exportOsim=False) # --- fitting --- #procedure cgmFittingProcedure = opensimFilters.CgmOpensimFittingProcedure(model) iksetupFile = pyCGM2.OPENSIM_PREBUILD_MODEL_PATH + "models\\settings\\cgm2_4\\cgm2_4-ikSetUp_template.xml" osrf = opensimFilters.opensimFittingFilter(iksetupFile, scalingOsim, cgmFittingProcedure, MAIN_PATH) acqIK = osrf.run(acqGait, str(MAIN_PATH + gaitFilename), exportSetUp=False) # -------- NEW MOTION FILTER ON IK MARKERS ------------------ modMotion_ik = modelFilters.ModelMotionFilter( scp, acqIK, model, pyCGM2Enums.motionMethod.Sodervisk, useForMotionTest=True) modMotion_ik.compute() finalJcs = modelFilters.ModelJCSFilter(model, acqIK) finalJcs.setFilterBool(False) finalJcs.compute(description="ik", pointLabelSuffix="2_ik") # btkTools.smartWriter(acqIK, "gait trial 01 - Fitting.c3d")
def test_FullBody_noOptions(self): DATA_PATH = pyCGM2.TEST_DATA_PATH + "GaitModels\CGM1\\fullBody-native-Options\\" staticFilename = "static.c3d" acqStatic = btkTools.smartReader(DATA_PATH + staticFilename) markerDiameter=14 leftFlatFoot = True rightFlatFoot = True headStraight = True pointSuffix = "test" vskFile = vskTools.getVskFiles(DATA_PATH) vsk = vskTools.Vsk(DATA_PATH + "New Subject.vsk") required_mp,optional_mp = vskTools.getFromVskSubjectMp(vsk, resetFlag=True) model,finalAcqStatic,error = cgm1.calibrate(DATA_PATH, staticFilename, None, required_mp, optional_mp, leftFlatFoot, rightFlatFoot, headStraight, markerDiameter, pointSuffix, displayCoordinateSystem=True) testingUtils.test_offset(model.mp_computed["LeftThighRotationOffset"],acqStatic,"LThighRotation", decimal=3) testingUtils.test_offset(model.mp_computed["RightThighRotationOffset"],acqStatic,"RThighRotation", decimal=3) testingUtils.test_offset(model.mp_computed["LeftShankRotationOffset"],acqStatic,"LShankRotation", decimal=3) testingUtils.test_offset(model.mp_computed["RightShankRotationOffset"],acqStatic,"RShankRotation", decimal=3) testingUtils.test_offset(model.mp_computed["LeftTibialTorsionOffset"],acqStatic,"LTibialTorsion", decimal=3) testingUtils.test_offset(model.mp_computed["RightTibialTorsionOffset"],acqStatic,"RTibialTorsion", decimal=3) testingUtils.test_offset(model.mp_computed["LeftAnkleAbAddOffset"],acqStatic,"LAnkleAbAdd", decimal=3) testingUtils.test_offset(model.mp_computed["RightAnkleAbAddOffset"],acqStatic,"RAnkleAbAdd", decimal=3) testingUtils.test_offset(model.mp_computed["LeftStaticPlantFlexOffset"],acqStatic,"LStaticPlantFlex", decimal=3) testingUtils.test_offset(model.mp_computed["RightStaticPlantFlexOffset"],acqStatic,"RStaticPlantFlex", decimal=3) testingUtils.test_offset(model.mp_computed["LeftStaticRotOffset"],acqStatic,"LStaticRotOff", decimal=3) testingUtils.test_offset(model.mp_computed["RightStaticRotOffset"],acqStatic,"RStaticRotOff", decimal=3) np.testing.assert_equal(model.getSegment("Left Thigh").getReferential("TF").static.getNode_byLabel("LHJC").m_desc ,"Davis") np.testing.assert_equal(model.getSegment("Right Thigh").getReferential("TF").static.getNode_byLabel("RHJC").m_desc ,"Davis") np.testing.assert_equal(model.getSegment("Left Thigh").getReferential("TF").static.getNode_byLabel("LKJC").m_desc ,"Chord") np.testing.assert_equal(model.getSegment("Right Thigh").getReferential("TF").static.getNode_byLabel("RKJC").m_desc ,"Chord") np.testing.assert_equal(model.getSegment("Left Shank").getReferential("TF").static.getNode_byLabel("LKJC").m_desc ,"Chord") np.testing.assert_equal(model.getSegment("Right Shank").getReferential("TF").static.getNode_byLabel("RKJC").m_desc ,"Chord") np.testing.assert_equal(model.getSegment("Left Shank").getReferential("TF").static.getNode_byLabel("LAJC").m_desc ,"Chord") np.testing.assert_equal(model.getSegment("Right Shank").getReferential("TF").static.getNode_byLabel("RAJC").m_desc ,"Chord") np.testing.assert_equal(model.getSegment("Left Foot").getReferential("TF").static.getNode_byLabel("LAJC").m_desc ,"Chord") np.testing.assert_equal(model.getSegment("Right Foot").getReferential("TF").static.getNode_byLabel("RAJC").m_desc ,"Chord") testingUtils.test_point(finalAcqStatic,"LPelvisAngles","LPelvisAngles_test",decimal = 3) testingUtils.test_point(finalAcqStatic,"RPelvisAngles","RPelvisAngles_test",decimal = 3) testingUtils.test_point(finalAcqStatic,"LHipAngles","LHipAngles_test",decimal = 3) testingUtils.test_point(finalAcqStatic,"LKneeAngles","LKneeAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"LAnkleAngles","LAnkleAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"RHipAngles","RHipAngles_test",decimal = 3) testingUtils.test_point(finalAcqStatic,"RKneeAngles","RKneeAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"RAnkleAngles","RAnkleAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"LFootProgressAngles","LFootProgressAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"RFootProgressAngles","RFootProgressAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"LThoraxAngles","LThoraxAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"RThoraxAngles","RThoraxAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"LSpineAngles","LSpineAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"RSpineAngles","RSpineAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"LShoulderAngles","LShoulderAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"RShoulderAngles","RShoulderAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"LElbowAngles","LElbowAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"RElbowAngles","RElbowAngles_test",decimal = 2) testingUtils.test_point(finalAcqStatic,"LHeadAngles","LHeadAngles_test",decimal = 3) testingUtils.test_point(finalAcqStatic,"RHeadAngles","RHeadAngles_test",decimal = 3) # btkTools.smartWriter(finalAcqStatic, str( staticFilename[:-4]+"-pyCGM2modelled.c3d")) # LOGGER.logger.info("Static Calibration -----> Done") gaitFilename="gait1.c3d" mfpa = None reconstructFilenameLabelled = gaitFilename acqGait,error = cgm1.fitting(model,DATA_PATH, reconstructFilenameLabelled, None, markerDiameter, pointSuffix, mfpa, enums.MomentProjection.Proximal, displayCoordinateSystem=True) testingUtils.test_point(acqGait,"LPelvisAngles","LPelvisAngles_test",decimal = 3) testingUtils.test_point(acqGait,"RPelvisAngles","RPelvisAngles_test",decimal = 3) testingUtils.test_point(acqGait,"LHipAngles","LHipAngles_test",decimal = 3) testingUtils.test_point(acqGait,"LKneeAngles","LKneeAngles_test",decimal = 2) testingUtils.test_point(acqGait,"LAnkleAngles","LAnkleAngles_test",decimal = 2) testingUtils.test_point(acqGait,"RHipAngles","RHipAngles_test",decimal = 3) testingUtils.test_point(acqGait,"RKneeAngles","RKneeAngles_test",decimal = 2) testingUtils.test_point(acqGait,"RAnkleAngles","RAnkleAngles_test",decimal = 2) testingUtils.test_point(acqGait,"LFootProgressAngles","LFootProgressAngles_test",decimal = 2) testingUtils.test_point(acqGait,"RFootProgressAngles","RFootProgressAngles_test",decimal = 2) testingUtils.test_point(acqGait,"LThoraxAngles","LThoraxAngles_test",decimal = 2) testingUtils.test_point(acqGait,"RThoraxAngles","RThoraxAngles_test",decimal = 2) testingUtils.test_point(acqGait,"LSpineAngles","LSpineAngles_test",decimal = 2) testingUtils.test_point(acqGait,"RSpineAngles","RSpineAngles_test",decimal = 2) testingUtils.test_point(acqGait,"LShoulderAngles","LShoulderAngles_test",decimal = 2) testingUtils.test_point(acqGait,"RShoulderAngles","RShoulderAngles_test",decimal = 2) testingUtils.test_point(acqGait,"LElbowAngles","LElbowAngles_test",decimal = 2) testingUtils.test_point(acqGait,"RElbowAngles","RElbowAngles_test",decimal = 2) testingUtils.test_point(acqGait,"LHeadAngles","LHeadAngles_test",decimal = 3) testingUtils.test_point(acqGait,"RHeadAngles","RHeadAngles_test",decimal = 3) # testingUtils.test_point(acqGait,"LWristAngles","LWristAngles_test",decimal = 3) fail on z! # testingUtils.test_point(acqGait,"RWristAngles","RWristAngles_test",decimal = 3) fail on Z! # testingUtils.test_point(acqGait,"CentreOfMass","CentreOfMass_test",decimal = 3) btkTools.smartAppendPoint(acqGait,"headCOM_py",model.getSegment("Head").getComTrajectory()) btkTools.smartAppendPoint(acqGait,"ThoraxCOM_py",model.getSegment("Thorax").getComTrajectory()) btkTools.smartAppendPoint(acqGait,"LhumCOM_py",model.getSegment("Left UpperArm").getComTrajectory()) btkTools.smartAppendPoint(acqGait,"LforeCom_py",model.getSegment("Left ForeArm").getComTrajectory()) btkTools.smartAppendPoint(acqGait,"LhandCom_py",model.getSegment("Left Hand").getComTrajectory()) btkTools.smartAppendPoint(acqGait,"RhumCOM_py",model.getSegment("Right UpperArm").getComTrajectory()) btkTools.smartAppendPoint(acqGait,"RforeCom_py",model.getSegment("Right ForeArm").getComTrajectory()) btkTools.smartAppendPoint(acqGait,"RhandCom_py",model.getSegment("Right Hand").getComTrajectory())
def CGM2_4_SARA_test(cls): MAIN_PATH = pyCGM2.TEST_DATA_PATH + "CGM2\\cgm2.4\\Knee Calibration\\" staticFilename = "static.c3d" funcFilename = "functional.c3d" gaitFilename = "gait trial 01.c3d" markerDiameter = 14 mp = { 'Bodymass': 69.0, 'LeftLegLength': 930.0, 'RightLegLength': 930.0, 'LeftKneeWidth': 94.0, 'RightKneeWidth': 64.0, 'LeftAnkleWidth': 67.0, 'RightAnkleWidth': 62.0, 'LeftSoleDelta': 0, 'RightSoleDelta': 0, "LeftToeOffset": 0, "RightToeOffset": 0, } acqStatic = btkTools.smartReader(str(MAIN_PATH + staticFilename)) model = cgm2.CGM2_4() model.configure() model.addAnthropoInputParameters(mp) # --- INITIAL CALIBRATION --- scp = modelFilters.StaticCalibrationProcedure(model) modelFilters.ModelCalibrationFilter(scp, acqStatic, model).compute() # cgm decorator modelDecorator.HipJointCenterDecorator(model).hara() modelDecorator.KneeCalibrationDecorator(model).midCondyles( acqStatic, markerDiameter=markerDiameter, side="both") modelDecorator.AnkleCalibrationDecorator(model).midMaleolus( acqStatic, markerDiameter=markerDiameter, side="both") # final modelFilters.ModelCalibrationFilter( scp, acqStatic, model, seLeftHJCnode="LHJC_Hara", useRightHJCnode="RHJC_Hara", useLeftKJCnode="LKJC_mid", useLeftAJCnode="LAJC_mid", useRightKJCnode="RKJC_mid", useRightAJCnode="RAJC_mid", markerDiameter=markerDiameter).compute() # ------ LEFT KNEE CALIBRATION ------- acqFunc = btkTools.smartReader(str(MAIN_PATH + funcFilename)) # Motion of only left modMotionLeftKnee = modelFilters.ModelMotionFilter( scp, acqFunc, model, enums.motionMethod.Sodervisk) modMotionLeftKnee.segmentalCompute(["Left Thigh", "Left Shank"]) # decorator modelDecorator.KneeCalibrationDecorator(model).sara( "Left", indexFirstFrame=831, indexLastFrame=1280) # ----add Point into the c3d---- Or_inThigh = model.getSegment("Left Thigh").getReferential( "TF").getNodeTrajectory("KneeFlexionOri") axis_inThigh = model.getSegment("Left Thigh").getReferential( "TF").getNodeTrajectory("KneeFlexionAxis") btkTools.smartAppendPoint(acqFunc, "Left" + "_KneeFlexionOri", Or_inThigh) btkTools.smartAppendPoint(acqFunc, "Left" + "_KneeFlexionAxis", axis_inThigh) # ------ RIGHT KNEE CALIBRATION ------- # Motion of only left modMotionRightKnee = modelFilters.ModelMotionFilter( scp, acqFunc, model, enums.motionMethod.Sodervisk) modMotionRightKnee.segmentalCompute(["Right Thigh", "Right Shank"]) # decorator modelDecorator.KneeCalibrationDecorator(model).sara("Right", indexFirstFrame=61, indexLastFrame=551) # ----add Point into the c3d---- Or_inThigh = model.getSegment("Right Thigh").getReferential( "TF").getNodeTrajectory("KneeFlexionOri") axis_inThigh = model.getSegment("Right Thigh").getReferential( "TF").getNodeTrajectory("KneeFlexionAxis") btkTools.smartAppendPoint(acqFunc, "Right" + "_KneeFlexionOri", Or_inThigh) btkTools.smartAppendPoint(acqFunc, "Right" + "_KneeFlexionAxis", axis_inThigh) btkTools.smartWriter(acqFunc, "acqFunc-Sara.c3d") #--- FINAL CALIBRATION --- modelFilters.ModelCalibrationFilter( scp, acqStatic, model, useLeftHJCnode="LHJC_Hara", useRightHJCnode="RHJC_Hara", useLeftKJCnode="KJC_Sara", useLeftAJCnode="LAJC_mid", useRightKJCnode="KJC_Sara", useRightAJCnode="RAJC_mid", markerDiameter=markerDiameter).compute() # save static c3d with update KJC btkTools.smartWriter(acqStatic, "Static-SARA.c3d") # print functional Offsets print model.mp_computed["LeftKneeFuncCalibrationOffset"] print model.mp_computed["RightKneeFuncCalibrationOffset"]
def main(args): NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if NEXUS_PYTHON_CONNECTED: # run Operation # --------------------------PATH + FILE ------------------------------------ DATA_PATH, reconstructedFilenameLabelledNoExt = NEXUS.GetTrialName() reconstructFilenameLabelled = reconstructedFilenameLabelledNoExt + ".c3d" logging.info("data Path: " + DATA_PATH) logging.info("reconstructed file: " + reconstructFilenameLabelled) # --------------------------SUBJECT ----------------------------------- # Notice : Work with ONE subject by session subjects = NEXUS.GetSubjectNames() subject = nexusTools.checkActivatedSubject(NEXUS, subjects) logging.info("Subject name : " + subject) # --------------------pyCGM2 MODEL ------------------------------ model = files.loadModel(DATA_PATH, subject) logging.info("loaded model : %s" % (model.version)) # --------------------------CONFIG ------------------------------------ # --------------------CHECKING ------------------------------ if model.version in ["CGM1.0", "CGM1.1", "CGM2.1", "CGM2.2"]: raise Exception( "Can t use SARA method with your model %s [minimal version : CGM2.3]" % (model.version)) elif model.version == "CGM2.3": if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_3-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH, "CGM2_3-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER, "CGM2_3-pyCGM2.settings") elif model.version in ["CGM2.4"]: if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_4-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH, "CGM2_4-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER, "CGM2_4-pyCGM2.settings") elif model.version in ["CGM2.5"]: if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_5-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH, "CGM2_5-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER, "CGM2_5-pyCGM2.settings") else: raise Exception("model version not found [contact admin]") # --------------------------SESSION INFOS ------------------------------------ mpInfo, mpFilename = files.getMpFileContent(DATA_PATH, "mp.pyCGM2", subject) # translators management if model.version in ["CGM2.3"]: translators = files.getTranslators(DATA_PATH, "CGM2-3.translators") elif model.version in ["CGM2.4"]: translators = files.getTranslators(DATA_PATH, "CGM2-4.translators") elif model.version in ["CGM2.5"]: translators = files.getTranslators(DATA_PATH, "CGM2-5.translators") if not translators: translators = settings["Translators"] # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, reconstructedFilenameLabelledNoExt, subject) acq = nacf.build() # --------------------------MODEL PROCESSING---------------------------- model, acqFunc, side = kneeCalibration.sara( model, DATA_PATH, reconstructFilenameLabelled, translators, args.side, args.beginFrame, args.endFrame, forceBtkAcq=acq) # ----------------------SAVE------------------------------------------- files.saveModel(model, DATA_PATH, subject) logging.warning( "model updated with a %s knee calibrated with SARA method" % (side)) # save mp files.saveMp(mpInfo, model, DATA_PATH, mpFilename) # ----------------------VICON INTERFACE------------------------------------------- #--- update mp nexusUtils.updateNexusSubjectMp(NEXUS, model, subject) # -- add nexus Bones if side == "Left": nexusTools.appendBones( NEXUS, subject, acqFunc, "LFE0", model.getSegment("Left Thigh"), OriginValues=acqFunc.GetPoint("LKJC").GetValues()) elif side == "Right": nexusTools.appendBones( NEXUS, subject, acqFunc, "RFE0", model.getSegment("Right Thigh"), OriginValues=acqFunc.GetPoint("RKJC").GetValues()) proximalSegmentLabel = str(side + " Thigh") distalSegmentLabel = str(side + " Shank") # add modelled markers meanOr_inThigh = model.getSegment(proximalSegmentLabel).getReferential( "TF").getNodeTrajectory("KJC_Sara") meanAxis_inThigh = model.getSegment( proximalSegmentLabel).getReferential("TF").getNodeTrajectory( "KJC_SaraAxis") btkTools.smartAppendPoint(acqFunc, side + "_KJC_Sara", meanOr_inThigh) btkTools.smartAppendPoint(acqFunc, side + "_KJC_SaraAxis", meanAxis_inThigh) nexusTools.appendModelledMarkerFromAcq(NEXUS, subject, side + "_KJC_Sara", acqFunc) nexusTools.appendModelledMarkerFromAcq(NEXUS, subject, side + "_KJC_SaraAxis", acqFunc) #---Second model motion filter # consider new anatomical frame scp = modelFilters.StaticCalibrationProcedure(model) modMotion = modelFilters.ModelMotionFilter( scp, acqFunc, model, enums.motionMethod.Sodervisk) modMotion.segmentalCompute([proximalSegmentLabel, distalSegmentLabel]) # projection of the Sara axis in the transversale plane # -- add nexus Bones if side == "Left": nexusTools.appendBones( NEXUS, subject, acqFunc, "LFE1", model.getSegment("Left Thigh"), OriginValues=acqFunc.GetPoint("LKJC").GetValues()) print model.mp_computed["LeftKneeFuncCalibrationOffset"] logging.warning( "offset %s" % (str(model.mp_computed["LeftKneeFuncCalibrationOffset"]))) elif side == "Right": nexusTools.appendBones( NEXUS, subject, acqFunc, "RFE1", model.getSegment("Right Thigh"), OriginValues=acqFunc.GetPoint("RKJC").GetValues()) logging.warning( "offset %s" % (str(model.mp_computed["RightKneeFuncCalibrationOffset"]))) print model.mp_computed["RightKneeFuncCalibrationOffset"] else: raise Exception("NO Nexus connection. Turn on Nexus")
def appendModelOutputs(self): modelOutputNames = NEXUS.GetModelOutputNames(self.m_subject) if modelOutputNames != []: for modelOutputName in modelOutputNames: data, E = NEXUS.GetModelOutput(self.m_subject, modelOutputName) type = NEXUS.GetModelOutputDetails(self.m_subject, modelOutputName)[0] E = np.asarray(E).astype("float") - 1 values = np.array([ np.asarray(data[0]), np.asarray(data[1]), np.asarray(data[2]) ]).T start = self.m_firstFrame - self.m_trialFirstFrame end = self.m_lastFrame - self.m_trialFirstFrame values_cut = values[start:end + 1, :] E_cut = E[start:end + 1] if type == "Angles": btkTools.smartAppendPoint(self.m_acq, modelOutputName, values_cut, PointType=btk.btkPoint.Angle, desc="", residuals=E_cut) elif type == "Forces": btkTools.smartAppendPoint(self.m_acq, modelOutputName, values_cut, PointType=btk.btkPoint.Force, desc="", residuals=E_cut) elif type == "Moments": btkTools.smartAppendPoint(self.m_acq, modelOutputName, values_cut, PointType=btk.btkPoint.Moment, desc="", residuals=E_cut) elif type == "Powers": btkTools.smartAppendPoint(self.m_acq, modelOutputName, values_cut, PointType=btk.btkPoint.Power, desc="", residuals=E_cut) elif type == "Modeled Markers": btkTools.smartAppendPoint(self.m_acq, modelOutputName, values_cut, PointType=btk.btkPoint.Marker, desc="", residuals=E_cut) else: logging.warning( "[pyCGM2] : Model Output (%s) from Nexus not added to the btk acquisition" % (modelOutputName))