def main(): plt.close("all") parser = argparse.ArgumentParser( description='CGM plot Temporal Kinematics') parser.add_argument('-ps', '--pointSuffix', type=str, help='suffix of model outputs') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if NEXUS_PYTHON_CONNECTED: pointSuffix = args.pointSuffix # --------------------------INPUTS ------------------------------------ DATA_PATH, modelledFilenameNoExt = NEXUS.GetTrialName() modelledFilename = modelledFilenameNoExt + ".c3d" LOGGER.logger.info("data Path: " + DATA_PATH) LOGGER.logger.info("file: " + modelledFilename) # ----- Subject ----- # need subject to find input files subjects = NEXUS.GetSubjectNames() subject = nexusTools.getActiveSubject(NEXUS) LOGGER.logger.info("Subject name : " + subject) # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, modelledFilenameNoExt, subject) acq = nacf.build() # --------------------pyCGM2 MODEL ------------------------------ plot.plotTemporalKinematic(DATA_PATH, modelledFilename, "LowerLimb", pointLabelSuffix=pointSuffix, exportPdf=True, btkAcq=acq) plot.plotTemporalKinematic(DATA_PATH, modelledFilename, "Trunk", pointLabelSuffix=pointSuffix, exportPdf=True, btkAcq=acq) plot.plotTemporalKinematic(DATA_PATH, modelledFilename, "UpperLimb", pointLabelSuffix=pointSuffix, exportPdf=True, btkAcq=acq) else: raise Exception("NO Nexus connection. Turn on Nexus")
def test_interactiveCropping_fromCropped(self): NEXUS = ViconNexus.ViconNexus() DATA_PATH = pyCGM2.TEST_DATA_PATH + "NexusAPI\\BtkAcquisitionCreator\\sample_withx2d\\" filenameNoExt = "gait_cropped" NEXUS.OpenTrial(str(DATA_PATH + filenameNoExt), 30) NEXUS.SetTrialRegionOfInterest(300, 400) subject = nexusTools.getActiveSubject(NEXUS) # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, filenameNoExt, subject) acq = nacf.build() acq0 = btkTools.smartReader( str(DATA_PATH + "forCheckingInteractiveCropped\\gait_cropped - 300-400.c3d")) np.testing.assert_array_almost_equal(acq.GetPoint("LTHI").GetValues(), acq0.GetPoint("LTHI").GetValues(), decimal=2) np.testing.assert_array_almost_equal( acq.GetAnalog("Force.Fz1").GetValues(), acq0.GetAnalog("Force.Fz1").GetValues(), decimal=2) np.testing.assert_array_almost_equal( acq.GetAnalog("Force.Fz2").GetValues(), acq0.GetAnalog("Force.Fz2").GetValues(), decimal=2) np.testing.assert_array_almost_equal( acq.GetAnalog("Force.Fz3").GetValues(), acq0.GetAnalog("Force.Fz3").GetValues(), decimal=2)
def main(): NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if NEXUS_PYTHON_CONNECTED: # run Operation DATA_PATH, filenameLabelledNoExt = NEXUS.GetTrialName() LOGGER.logger.info("data Path: " + DATA_PATH) LOGGER.logger.info("file: " + filenameLabelledNoExt) subject = nexusTools.getActiveSubject( NEXUS) #checkActivatedSubject(NEXUS,subjects) LOGGER.logger.info("Gap filling for subject %s" % (subject)) # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, filenameLabelledNoExt, subject) acq = nacf.build() #acq = btkTools.smartReader(str(DATA_PATH+filenameLabelledNoExt+".c3d")) gfp = gapFilling.LowDimensionalKalmanFilterProcedure() gff = gapFilling.GapFillingFilter(gfp, acq) gff.fill() filledAcq = gff.getFilledAcq() filledMarkers = gff.getFilledMarkers() for marker in filledMarkers: nexusTools.setTrajectoryFromAcq(NEXUS, subject, marker, filledAcq) else: raise Exception("NO Nexus connection. Turn on Nexus")
def test_Kistler4_Noraxon1_Xsens1(self): NEXUS = ViconNexus.ViconNexus() DATA_PATH = pyCGM2.TEST_DATA_PATH + "NexusAPI\\BtkAcquisitionCreator\\sample0\\" filenameNoExt = "gait_cropped" NEXUS.OpenTrial(str(DATA_PATH + filenameNoExt), 30) subject = nexusTools.getActiveSubject(NEXUS) # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, filenameNoExt, subject) acq = nacf.build() acq0 = btkTools.smartReader(str(DATA_PATH + filenameNoExt + ".c3d")) np.testing.assert_array_almost_equal(acq.GetPoint("LTHI").GetValues(), acq0.GetPoint("LTHI").GetValues(), decimal=2) np.testing.assert_array_almost_equal( acq.GetAnalog("Force.Fx1").GetValues(), acq0.GetAnalog("Force.Fx1").GetValues(), decimal=2) np.testing.assert_equal(acq.GetPointFrequency(), acq0.GetPointFrequency()) np.testing.assert_equal(acq.GetNumberAnalogSamplePerFrame(), acq0.GetNumberAnalogSamplePerFrame()) np.testing.assert_equal(acq.GetAnalogFrequency(), acq0.GetAnalogFrequency()) np.testing.assert_equal( btkTools.smartGetMetadata(acq, "FORCE_PLATFORM", "USED"), btkTools.smartGetMetadata(acq0, "FORCE_PLATFORM", "USED")) np.testing.assert_array_almost_equal([ float(x) for x in np.asarray( btkTools.smartGetMetadata(acq, "FORCE_PLATFORM", "CORNERS")) ], [ float(x) for x in np.asarray( btkTools.smartGetMetadata(acq0, "FORCE_PLATFORM", "CORNERS")) ], decimal=2) np.testing.assert_array_almost_equal([ float(x) for x in np.asarray( btkTools.smartGetMetadata(acq, "FORCE_PLATFORM", "ORIGIN")) ], [ float(x) for x in np.asarray( btkTools.smartGetMetadata(acq0, "FORCE_PLATFORM", "ORIGIN")) ], decimal=2) np.testing.assert_array_almost_equal([ float(x) for x in np.asarray( btkTools.smartGetMetadata(acq, "FORCE_PLATFORM", "CHANNEL")) ], [ float(x) for x in np.asarray( btkTools.smartGetMetadata(acq0, "FORCE_PLATFORM", "CHANNEL")) ], decimal=2)
def main(): parser = argparse.ArgumentParser(description='ZeniDetector') parser.add_argument('-fso', '--footStrikeOffset', type=int, help='systenatic foot strike offset on both side') parser.add_argument('-foo', '--footOffOffset', type=int, help='systenatic foot off offset on both side') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if NEXUS_PYTHON_CONNECTED: # run Operation # ----------------------INPUTS------------------------------------------- # --- acquisition file and path---- DATA_PATH, reconstructFilenameLabelledNoExt = NEXUS.GetTrialName() reconstructFilenameLabelled = reconstructFilenameLabelledNoExt + ".c3d" LOGGER.logger.info("data Path: " + DATA_PATH) LOGGER.logger.info("calibration file: " + reconstructFilenameLabelled) #acqGait = btkTools.smartReader(str(DATA_PATH + reconstructFilenameLabelled)) # --------------------------SUBJECT ----------------------------------- # Notice : Work with ONE subject by session subject = nexusTools.getActiveSubject(NEXUS) LOGGER.logger.info("Subject name : " + subject) # --- btk acquisition ---- nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, reconstructFilenameLabelledNoExt, subject) acqGait = nacf.build() # ----------------------EVENT DETECTOR------------------------------- footStrikeOffset = 0 footOffOffset = 0 if args.footStrikeOffset is not None: footStrikeOffset = args.footStrikeOffset if args.footOffOffset is not None: footOffOffset = args.footOffOffset eventDetector.zeni(acqGait, footStrikeOffset=footStrikeOffset, footOffOffset=footOffOffset) # ----------------------DISPLAY ON VICON------------------------------- nexusTools.createEvents(NEXUS, subject, acqGait, ["Foot Strike", "Foot Off"]) # ========END of the nexus OPERATION if run from Nexus ========= else: raise Exception("NO Nexus connection. Turn on Nexus")
def main(): parser = argparse.ArgumentParser(description='') parser.add_argument('--markers', nargs='+') parser.add_argument('--noCorrection', action='store_true', help='disable correction') 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(" Path: " + DATA_PATH) 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 markers = args.markers # markers = cgm.CGM1.LOWERLIMB_TRACKING_MARKERS madp = AnomalyDetectionProcedure.MarkerAnomalyDetectionRollingProcedure( markers, plot=False, window=5, threshold=3) adf = AnomalyFilter.AnomalyDetectionFilter(acq, filename, madp) anomaly = adf.run() if not args.noCorrection: macp = AnomalyCorrectionProcedure.MarkerAnomalyCorrectionProcedure( markers, anomaly["Output"], plot=False, distance_threshold=20) acf = AnomalyFilter.AnomalyCorrectionFilter(acq, filename, macp) acqo = acf.run() # --------------------------PUSH ------------------------------------ for marker in markers: nexusTools.setTrajectoryFromAcq(NEXUS, subject, marker, acqo)
def test_analogDeviceTest(self): NEXUS = ViconNexus.ViconNexus() DATA_PATH = pyCGM2.TEST_DATA_PATH + "NexusAPI\\c3d_x2d\\" filenameNoExt = "gait_GAP" NEXUS.OpenTrial(str(DATA_PATH + filenameNoExt), 30) framerate = NEXUS.GetFrameRate() frames = NEXUS.GetFrameCount() analogFrameRate = NEXUS.GetDeviceDetails(1)[2] device = Devices.AnalogDevice(6) output = device.getChannels()
def test_Kistler4_Noraxon1_Xsens1_wrenchOuputs(self): NEXUS = ViconNexus.ViconNexus() DATA_PATH = pyCGM2.TEST_DATA_PATH + "NexusAPI\\BtkAcquisitionCreator\\sample0\\" filenameNoExt = "gait_cropped" NEXUS.OpenTrial(str(DATA_PATH + filenameNoExt), 30) subject = nexusTools.getActiveSubject(NEXUS) # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, filenameNoExt, subject) acq = nacf.build() #btkTools.smartWriter(acq,"NEWC3D.c3d") # --- ground reaction force wrench --- pfe = btk.btkForcePlatformsExtractor() pfe.SetInput(acq) pfc = pfe.GetOutput() grwf = btk.btkGroundReactionWrenchFilter() grwf.SetInput(pfc) grwc = grwf.GetOutput() grwc.Update() # --- reference values --- acq0 = btkTools.smartReader(DATA_PATH + filenameNoExt + ".c3d") pfe0 = btk.btkForcePlatformsExtractor() pfe0.SetInput(acq0) pfc0 = pfe0.GetOutput() grwf0 = btk.btkGroundReactionWrenchFilter() grwf0.SetInput(pfc0) grwc0 = grwf0.GetOutput() grwc0.Update() np.testing.assert_array_almost_equal( grwc.GetItem(0).GetForce().GetValues(), grwc0.GetItem(0).GetForce().GetValues(), decimal=1) np.testing.assert_array_almost_equal( grwc.GetItem(0).GetMoment().GetValues(), grwc0.GetItem(0).GetMoment().GetValues(), decimal=1) np.testing.assert_array_almost_equal( grwc.GetItem(0).GetPosition().GetValues(), grwc0.GetItem(0).GetPosition().GetValues(), decimal=1)
def test_0(self): NEXUS = ViconNexus.ViconNexus() DATA_PATH = pyCGM2.TEST_DATA_PATH + "NexusAPI\\forcePlatesDetection\\" filename = "gait4FP" NEXUS.OpenTrial(str(DATA_PATH + filename), 30) mfpa = nexusTools.getForcePlateAssignment(NEXUS) acqGait = btkTools.smartReader(str(DATA_PATH + filename + ".c3d")) mappedForcePlate = forceplates.matchingFootSideOnForceplate(acqGait) mappedForcePlate1 = forceplates.matchingFootSideOnForceplate(acqGait, mfpa=mfpa)
def viconnexus(): """Return a ViconNexus() (SDK control object) instance. Raises an exception if Nexus is not running. Returns ------- ViconNexus The instance. """ # by default, just use the global instance global vicon_ # however, if SDK connection has not been established yet or server info # looks invalid, we reestablish the connection; the latter condition occurs # e.g. when Nexus has been restarted (SDK object becomes stale) if vicon_ is None or vicon_.GetServerInfo()[0] != 'Nexus': _check_nexus() vicon_ = ViconNexus.ViconNexus() return vicon_
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 test_forcePlateTest(self): NEXUS = ViconNexus.ViconNexus() DATA_PATH = pyCGM2.TEST_DATA_PATH + "NexusAPI\\c3d_x2d\\" filenameNoExt = "gait_GAP" NEXUS.OpenTrial(str(DATA_PATH + filenameNoExt), 30) #----Btk---- acq0 = btkTools.smartReader(str(DATA_PATH + filenameNoExt + ".c3d")) analogFx = acq0.GetAnalog("Force.Fx1").GetValues() analogFy = acq0.GetAnalog("Force.Fy1").GetValues() analogFz = acq0.GetAnalog("Force.Fz1").GetValues() analogMx = acq0.GetAnalog("Moment.Mx1").GetValues() analogMy = acq0.GetAnalog("Moment.My1").GetValues() analogMz = acq0.GetAnalog("Moment.Mz1").GetValues() pfe = btk.btkForcePlatformsExtractor() pfe.SetInput(acq0) pfc = pfe.GetOutput() pfc.Update() btkfp0 = pfc.GetItem(0) ch0_Fx = btkfp0.GetChannel(0).GetValues() ch1_Fy = btkfp0.GetChannel(1).GetValues() ch2_Fz = btkfp0.GetChannel(2).GetValues() ch3_Mx = btkfp0.GetChannel(3).GetValues() ch4_My = btkfp0.GetChannel(4).GetValues() ch5_Mz = btkfp0.GetChannel(5).GetValues() # --- ground reaction force wrench --- grwf = btk.btkGroundReactionWrenchFilter() grwf.SetInput(pfc) grwc = grwf.GetOutput() grwc.Update() grw0_force = grwc.GetItem(0).GetForce().GetValues() #----Nexus---- nexusForcePlate = Devices.ForcePlate(1) forceLocal = nexusForcePlate.getLocalReactionForce() momentLocal = nexusForcePlate.getLocalReactionMoment()
def test_modelOutputs(self): NEXUS = ViconNexus.ViconNexus() DATA_PATH = pyCGM2.TEST_DATA_PATH + "NexusAPI\\BtkAcquisitionCreator\\sample0\\" filenameNoExt = "gait_cropped_ModelOutputDynamic" NEXUS.OpenTrial(str(DATA_PATH + filenameNoExt), 30) subject = nexusTools.getActiveSubject(NEXUS) # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, filenameNoExt, subject) acq = nacf.build() acq0 = btkTools.smartReader(str(DATA_PATH + filenameNoExt + ".c3d")) np.testing.assert_array_almost_equal( acq.GetPoint("LAnkleAngles").GetValues(), acq0.GetPoint("LAnkleAngles").GetValues(), decimal=2)
def main(): parser = argparse.ArgumentParser(description='EMG-plot_temporalEMG') parser.add_argument('-bpf', '--BandpassFrequencies', nargs='+', help='bandpass filter') parser.add_argument('-elf', '--EnvelopLowpassFrequency', type=int, help='cutoff frequency for emg envelops') parser.add_argument('-c', '--consistency', action='store_true', help='consistency plots') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() ECLIPSE_MODE = False if not NEXUS_PYTHON_CONNECTED: raise Exception("Vicon Nexus is not running") #--------------------------Data Location and subject------------------------------------- if eclipse.getCurrentMarkedNodes() is None: raise Exception("No nodes marked") else: LOGGER.logger.info( "[pyCGM2] - Script worked with marked node of Vicon Eclipse") # --- acquisition file and path---- DATA_PATH, inputFiles = eclipse.getCurrentMarkedNodes() ECLIPSE_MODE = True if len(inputFiles) == 1: raise Exception("Only one node marked") #--------------------------settings------------------------------------- if os.path.isfile(DATA_PATH + "emg.settings"): emgSettings = files.openFile(DATA_PATH, "emg.settings") LOGGER.logger.warning( "[pyCGM2]: emg.settings detected in the data folder") else: emgSettings = None manager = EmgManager.EmgConfigManager(None, localInternalSettings=emgSettings) manager.contruct() # ----------------------INPUTS------------------------------------------- bandPassFilterFrequencies = manager.BandpassFrequencies #emgSettings["Processing"]["BandpassFrequencies"] if args.BandpassFrequencies is not None: if len(args.BandpassFrequencies) != 2: raise Exception( "[pyCGM2] - bad configuration of the bandpass frequencies ... set 2 frequencies only" ) else: bandPassFilterFrequencies = [ float(args.BandpassFrequencies[0]), float(args.BandpassFrequencies[1]) ] LOGGER.logger.info( "Band pass frequency set to %i - %i instead of 20-200Hz", bandPassFilterFrequencies[0], bandPassFilterFrequencies[1]) envelopCutOffFrequency = manager.EnvelopLowpassFrequency #emgSettings["Processing"]["EnvelopLowpassFrequency"] if args.EnvelopLowpassFrequency is not None: envelopCutOffFrequency = args.EnvelopLowpassFrequency LOGGER.logger.info("Cut-off frequency set to %i instead of 6Hz ", envelopCutOffFrequency) consistencyFlag = True if args.consistency else False plotType = "Consistency" if consistencyFlag else "Descriptive" # --------------emg Processing-------------- EMG_LABELS, EMG_MUSCLES, EMG_CONTEXT, NORMAL_ACTIVITIES = manager.getEmgConfiguration( ) if ECLIPSE_MODE: emg.processEMG(DATA_PATH, inputFiles, EMG_LABELS, highPassFrequencies=bandPassFilterFrequencies, envelopFrequency=envelopCutOffFrequency) if len(inputFiles) == 2: analysisInstance1 = analysis.makeAnalysis( DATA_PATH, [inputFiles[0]], type="Gait", kinematicLabelsDict=None, kineticLabelsDict=None, emgChannels=EMG_LABELS, pointLabelSuffix=None, subjectInfo=None, experimentalInfo=None, modelInfo=None, ) emg.normalizedEMG(analysisInstance1, EMG_LABELS, EMG_CONTEXT, method="MeanMax", fromOtherAnalysis=None) analysisInstance2 = analysis.makeAnalysis( DATA_PATH, [inputFiles[1]], type="Gait", kinematicLabelsDict=None, kineticLabelsDict=None, emgChannels=EMG_LABELS, pointLabelSuffix=None, subjectInfo=None, experimentalInfo=None, modelInfo=None, ) emg.normalizedEMG(analysisInstance2, EMG_LABELS, EMG_CONTEXT, method="MeanMax", fromOtherAnalysis=analysisInstance1) # outputName = "Eclipse - CompareNormalizedKinematics" # analysesToCompare = [analysisInstance1, analysisInstance2] comparisonDetails = inputFiles[0] + " Vs " + inputFiles[1] legends = [inputFiles[0], inputFiles[1]] plot.compareEmgEnvelops(DATA_PATH, analysesToCompare, legends, EMG_LABELS, EMG_MUSCLES, EMG_CONTEXT, NORMAL_ACTIVITIES, normalized=True, plotType=plotType, show=True, outputName=comparisonDetails, exportPng=False)
def main(): parser = argparse.ArgumentParser(description='EMG-plot_temporalEMG') parser.add_argument('-bpf', '--BandpassFrequencies', nargs='+',help='bandpass filter') parser.add_argument('-elf','--EnvelopLowpassFrequency', type=int, help='cutoff frequency for emg envelops') parser.add_argument('-c','--consistency', action='store_true', help='consistency plots') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() ECLIPSE_MODE = False if not NEXUS_PYTHON_CONNECTED: raise Exception("Vicon Nexus is not running") #--------------------------Data Location------------------------------------- if eclipse.getCurrentMarkedNodes() is not None: LOGGER.logger.info("[pyCGM2] - Script worked with marked node of Vicon Eclipse") # --- acquisition file and path---- DATA_PATH, inputFiles =eclipse.getCurrentMarkedNodes() ECLIPSE_MODE = True if not ECLIPSE_MODE: LOGGER.logger.info("[pyCGM2] - Script works with the loaded c3d in vicon Nexus") # --- acquisition file and path---- DATA_PATH, inputFileNoExt = NEXUS.GetTrialName() inputFile = inputFileNoExt+".c3d" LOGGER.set_file_handler(DATA_PATH+"pyCGM2.log") #--------------------------settings------------------------------------- if os.path.isfile(DATA_PATH + "emg.settings"): emgSettings = files.openFile(DATA_PATH,"emg.settings") LOGGER.logger.warning("[pyCGM2]: emg.settings detected in the data folder") else: emgSettings = None manager = EmgManager.EmgConfigManager(None,localInternalSettings=emgSettings) manager.contruct() # ----------------------INPUTS------------------------------------------- bandPassFilterFrequencies = manager.BandpassFrequencies#emgSettings["Processing"]["BandpassFrequencies"] if args.BandpassFrequencies is not None: if len(args.BandpassFrequencies) != 2: raise Exception("[pyCGM2] - bad configuration of the bandpass frequencies ... set 2 frequencies only") else: bandPassFilterFrequencies = [float(args.BandpassFrequencies[0]),float(args.BandpassFrequencies[1])] LOGGER.logger.info("Band pass frequency set to %i - %i instead of 20-200Hz",bandPassFilterFrequencies[0],bandPassFilterFrequencies[1]) envelopCutOffFrequency = manager.EnvelopLowpassFrequency#emgSettings["Processing"]["EnvelopLowpassFrequency"] if args.EnvelopLowpassFrequency is not None: envelopCutOffFrequency = args.EnvelopLowpassFrequency LOGGER.logger.info("Cut-off frequency set to %i instead of 6Hz ",envelopCutOffFrequency) consistencyFlag = True if args.consistency else False # --------------emg Processing-------------- EMG_LABELS,EMG_MUSCLES,EMG_CONTEXT,NORMAL_ACTIVITIES = manager.getEmgConfiguration() if not ECLIPSE_MODE: # --------------------------SUBJECT ------------------------------------ subject = nexusTools.getActiveSubject(NEXUS) # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter(DATA_PATH,inputFileNoExt,subject) acq = nacf.build() emg.processEMG_fromBtkAcq(acq, EMG_LABELS, highPassFrequencies=bandPassFilterFrequencies, envelopFrequency=envelopCutOffFrequency) # high pass then low pass for all c3ds # emgAnalysis = analysis.makeEmgAnalysis(DATA_PATH, [inputFile], EMG_LABELS,btkAcqs = [acq]) emgAnalysis = analysis.makeAnalysis(DATA_PATH, [inputFile], type="Gait", kinematicLabelsDict=None, kineticLabelsDict=None, emgChannels = EMG_LABELS, pointLabelSuffix=None, btkAcqs=[acq], subjectInfo=None, experimentalInfo=None,modelInfo=None, ) outputName = inputFile else: emg.processEMG(DATA_PATH, inputFiles, EMG_LABELS, highPassFrequencies=bandPassFilterFrequencies, envelopFrequency=envelopCutOffFrequency) emgAnalysis = analysis.makeAnalysis(DATA_PATH, [inputFile], type="Gait", kinematicLabelsDict=None, kineticLabelsDict=None, emgChannels = EMG_LABELS, pointLabelSuffix=None, subjectInfo=None, experimentalInfo=None,modelInfo=None, ) outputName = "Eclipse - NormalizedEMG" if not consistencyFlag: plot.plotDescriptiveEnvelopEMGpanel(DATA_PATH,emgAnalysis, EMG_LABELS,EMG_MUSCLES,EMG_CONTEXT, NORMAL_ACTIVITIES, normalized=False,exportPdf=True,outputName=outputName) else: plot.plotConsistencyEnvelopEMGpanel(DATA_PATH,emgAnalysis, EMG_LABELS,EMG_MUSCLES,EMG_CONTEXT, NORMAL_ACTIVITIES, normalized=False,exportPdf=True,outputName=outputName)
except: LOGGER.logger.info("[pyCGM2] pyCGM2-embedded btk not imported") import btk from pyCGM2.Tools import btkTools # vicon nexus try: import ViconNexus except: from viconnexusapi import ViconNexus from pyCGM2.Nexus import nexusTools, Devices from pyCGM2.Utils import utils NEXUS = ViconNexus.ViconNexus() class NexusModelFilter(object): def __init__(self, NEXUS, iModel, iAcq, vskName, pointSuffix, staticProcessing=False): """ Constructor :Parameters: - `NEXUS` () - Nexus environment
def main(): plt.close("all") parser = argparse.ArgumentParser(description='CGM plot stp') parser.add_argument('-ps', '--pointSuffix', type=str, help='suffix added to pyCGM2 outputs') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() ECLIPSE_MODE = False if not NEXUS_PYTHON_CONNECTED: raise Exception("Vicon Nexus is not running") pointSuffix = args.pointSuffix #--------------------------Data Location and subject------------------------------------- if eclipse.getCurrentMarkedNodes() is not None: LOGGER.logger.info( "[pyCGM2] - Script worked with marked node of Vicon Eclipse") # --- acquisition file and path---- DATA_PATH, modelledFilenames = eclipse.getCurrentMarkedNodes() ECLIPSE_MODE = True if not ECLIPSE_MODE: LOGGER.logger.info( "[pyCGM2] - Script works with the loaded c3d in vicon Nexus") # --------------------------INPUTS ------------------------------------ DATA_PATH, modelledFilenameNoExt = NEXUS.GetTrialName() modelledFilename = modelledFilenameNoExt + ".c3d" LOGGER.logger.info("data Path: " + DATA_PATH) LOGGER.logger.info("file: " + modelledFilename) # ----- Subject ----- # need subject to find input files # subjects = NEXUS.GetSubjectNames() subject = nexusTools.getActiveSubject(NEXUS) LOGGER.logger.info("Subject name : " + subject) if not ECLIPSE_MODE: # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, modelledFilenameNoExt, subject) acq = nacf.build() # --------------------------PROCESSING -------------------------------- analysisInstance = analysis.makeAnalysis(DATA_PATH, [modelledFilename], type="Gait", kineticLabelsDict=None, emgChannels=None, pointLabelSuffix=pointSuffix, btkAcqs=[acq], subjectInfo=None, experimentalInfo=None, modelInfo=None) outputName = modelledFilename else: # --------------------------PROCESSING -------------------------------- analysisInstance = analysis.makeAnalysis(DATA_PATH, modelledFilenames, type="Gait", kineticLabelsDict=None, emgChannels=None, pointLabelSuffix=pointSuffix, subjectInfo=None, experimentalInfo=None, modelInfo=None) outputName = "Eclipse - SpatioTemporal parameters" plot.plot_spatioTemporal(DATA_PATH, analysisInstance, exportPdf=True, outputName=outputName)
def main(): plt.close("all") parser = argparse.ArgumentParser(description='CGM plot Normalized Kinematics') parser.add_argument('-nd','--normativeData', type=str, help='normative Data set (Schwartz2008 or Pinzone2014)', default="Schwartz2008") parser.add_argument('-ndm','--normativeDataModality', type=str, help="if Schwartz2008 [VerySlow,SlowFree,Fast,VeryFast] - if Pinzone2014 [CentreOne,CentreTwo]", default="Free") parser.add_argument('-ps','--pointSuffix', type=str, help='suffix of model outputs') parser.add_argument('-c','--consistency', action='store_true', help='consistency plots') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() ECLIPSE_MODE = False if not NEXUS_PYTHON_CONNECTED: raise Exception("Vicon Nexus is not running") #--------------------------Data Location and subject------------------------------------- if eclipse.getCurrentMarkedNodes() is None: raise Exception("No nodes marked") else: LOGGER.logger.info("[pyCGM2] - Script worked with marked node of Vicon Eclipse") # --- acquisition file and path---- DATA_PATH, modelledFilenames =eclipse.getCurrentMarkedNodes() ECLIPSE_MODE = True if len(modelledFilenames)== 1: raise Exception("Only one node marked") subject = nexusTools.getActiveSubject(NEXUS) LOGGER.logger.info( "Subject name : " + subject ) #-----------------------SETTINGS--------------------------------------- normativeData = {"Author" : args.normativeData, "Modality" : args.normativeDataModality} if normativeData["Author"] == "Schwartz2008": chosenModality = normativeData["Modality"] elif normativeData["Author"] == "Pinzone2014": chosenModality = normativeData["Modality"] nds = normativeDatasets.NormativeData(normativeData["Author"],chosenModality) consistencyFlag = True if args.consistency else False plotType = "Consistency" if consistencyFlag else "Descriptive" pointSuffix = args.pointSuffix if ECLIPSE_MODE: if len(modelledFilenames) == 2: analysisInstance1 = analysis.makeAnalysis(DATA_PATH, [modelledFilenames[0]], type="Gait", kinematicLabelsDict=None, emgChannels = None, pointLabelSuffix=pointSuffix, subjectInfo=None, experimentalInfo=None,modelInfo=None, ) analysisInstance2 = analysisInstance1 = analysis.makeAnalysis(DATA_PATH, [modelledFilenames[1]], type="Gait", kinematicLabelsDict=None, emgChannels = None, pointLabelSuffix=pointSuffix, subjectInfo=None, experimentalInfo=None,modelInfo=None, ) # outputName = "Eclipse - CompareNormalizedKinematics" # analysesToCompare = [analysisInstance1, analysisInstance2] comparisonDetails = modelledFilenames[0] + " Vs " + modelledFilenames[1] legends =[modelledFilenames[0],modelledFilenames[1]] plot.compareKinetic(DATA_PATH,analysesToCompare,legends,"Left","LowerLimb",nds,plotType=plotType,type="Gait",pointSuffixes=None, show=False, outputName=comparisonDetails,exportPdf=True) plot.compareKinetic(DATA_PATH,analysesToCompare,legends,"Right","LowerLimb",nds,plotType=plotType,type="Gait",pointSuffixes=None, show=False, outputName=comparisonDetails,exportPdf=True) plt.show()
#!/usr/bin/python # -*- coding: iso-8859-15 -*- from __future__ import print_function import os, sys from viconnexusapi import ViconNexus from plotly import tools import plotly.offline as offline import plotly.graph_objects as go from plotly.subplots import make_subplots print ('Generating IMU device graphs...') vicon = ViconNexus.ViconNexus() SessionLoc = vicon.GetTrialName()[0] SubjectName = vicon.GetSubjectNames() devicenames = vicon.GetDeviceNames() imudevicename = {} color_accel = '#065374' color_gyro = '#b61641' color_mag = '#20ac9e' color_global = '#73072f' color_highG = '#051876' for imudevicename in devicenames: if imudevicename in devicenames: imuid = vicon.GetDeviceIDFromName(imudevicename) dname, dtype, drate, outputids, _, _ = vicon.GetDeviceDetails(imuid)
def main(): parser = argparse.ArgumentParser(description='2Dof Knee Calibration') parser.add_argument('-s','--side', type=str, help="Side : Left or Right") parser.add_argument('-b','--beginFrame', type=int, help="begin frame") parser.add_argument('-e','--endFrame', type=int, help="end frame") args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if NEXUS_PYTHON_CONNECTED: # run Operation DATA_PATH, reconstructedFilenameLabelledNoExt = NEXUS.GetTrialName() reconstructFilenameLabelled = reconstructedFilenameLabelledNoExt+".c3d" LOGGER.logger.info( "data Path: "+ DATA_PATH ) LOGGER.logger.info( "reconstructed file: "+ reconstructFilenameLabelled) # --------------------------SUBJECT ----------------------------------- # Notice : Work with ONE subject by session subjects = NEXUS.GetSubjectNames() subject = nexusTools.getActiveSubject(NEXUS) LOGGER.logger.info( "Subject name : " + subject ) # --------------------pyCGM2 MODEL - INIT ------------------------------ model = files.loadModel(DATA_PATH,subject) LOGGER.logger.info("loaded model : %s" %(model.version )) if model.version == "CGM1.0": if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM1-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,"CGM1-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,"CGM1-pyCGM2.settings") elif model.version == "CGM1.1": if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM1_1-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,"CGM1_1-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,"CGM1_1-pyCGM2.settings") elif model.version == "CGM2.1": if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_1-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,"CGM2_1-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,"CGM2_1-pyCGM2.settings") elif model.version == "CGM2.2": if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_2-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,"CGM2_2-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,"CGM2_2-pyCGM2.settings") 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 ["CGM1.0"]: translators = files.getTranslators(DATA_PATH,"CGM1.translators") elif model.version in ["CGM1.1"]: translators = files.getTranslators(DATA_PATH,"CGM1_1.translators") elif model.version in ["CGM2.1"]: translators = files.getTranslators(DATA_PATH,"CGM2_1.translators") elif model.version in ["CGM2.2"]: translators = files.getTranslators(DATA_PATH,"CGM2_2.translators") elif 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.calibration2Dof(model, DATA_PATH,reconstructFilenameLabelled,translators, args.side,args.beginFrame,args.endFrame,None,forceBtkAcq=acq) # ----------------------SAVE------------------------------------------- files.saveModel(model,DATA_PATH,subject) LOGGER.logger.warning("model updated with a %s knee calibrated with 2Dof method" %(side)) # save mp files.saveMp(mpInfo,model,DATA_PATH,mpFilename) # ----------------------VICON INTERFACE------------------------------------------- #--- update mp nexusUtils.updateNexusSubjectMp(NEXUS,model,subject) 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() ) # --------------------------NEW MOTION FILTER - DISPLAY BONES--------- scp=modelFilters.StaticCalibrationProcedure(model) if model.version in ["CGM1.0","CGM1.1","CGM2.1","CGM2.2"]: modMotion=modelFilters.ModelMotionFilter(scp,acqFunc,model,enums.motionMethod.Determinist) modMotion.compute() elif model.version in ["CGM2.3","CGM2.4"]: proximalSegmentLabel=str(side+" Thigh") distalSegmentLabel=str(side+" Shank") # Motion modMotion=modelFilters.ModelMotionFilter(scp,acqFunc,model,enums.motionMethod.Sodervisk) modMotion.segmentalCompute([proximalSegmentLabel,distalSegmentLabel]) # -- add nexus Bones if side == "Left": nexusTools.appendBones(NEXUS,subject,acqFunc,"LFE1", model.getSegment("Left Thigh"),OriginValues = acqFunc.GetPoint("LKJC").GetValues() ) LOGGER.logger.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() ) LOGGER.logger.warning("offset %s" %(str(model.mp_computed["RightKneeFuncCalibrationOffset"] ))) else: raise Exception("NO Nexus connection. Turn on Nexus")
def main(): parser = argparse.ArgumentParser( description='SARA Functional Knee Calibration') parser.add_argument('-s', '--side', type=str, help="Side : Left or Right") parser.add_argument('-b', '--beginFrame', type=int, help="begin frame") parser.add_argument('-e', '--endFrame', type=int, help="end frame") args = parser.parse_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" LOGGER.logger.info("data Path: " + DATA_PATH) LOGGER.logger.info("reconstructed file: " + reconstructFilenameLabelled) # --------------------------SUBJECT ----------------------------------- # Notice : Work with ONE subject by session subjects = NEXUS.GetSubjectNames() subject = nexusTools.getActiveSubject(NEXUS) LOGGER.logger.info("Subject name : " + subject) # --------------------pyCGM2 MODEL ------------------------------ model = files.loadModel(DATA_PATH, subject) LOGGER.logger.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) LOGGER.logger.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()) LOGGER.logger.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()) LOGGER.logger.warning( "offset %s" % (str(model.mp_computed["RightKneeFuncCalibrationOffset"]))) else: raise Exception("NO Nexus connection. Turn on Nexus")
def main(): parser = argparse.ArgumentParser(description='CGM2.4 Calibration') parser.add_argument('-l','--leftFlatFoot', type=int, help='left flat foot option') parser.add_argument('-r','--rightFlatFoot',type=int, help='right flat foot option') parser.add_argument('-hf','--headFlat',type=int, help='head flat option') parser.add_argument('-md','--markerDiameter', type=float, help='marker diameter') parser.add_argument('-ps','--pointSuffix', type=str, help='suffix of model outputs') parser.add_argument('--check', action='store_true', help='force model output suffix') parser.add_argument('--noIk', action='store_true', help='cancel inverse kinematic') parser.add_argument('--resetMP', action='store_true', help='reset optional mass parameters') parser.add_argument('--forceLHJC', nargs='+') parser.add_argument('--forceRHJC', nargs='+') parser.add_argument('-ae','--anomalyException', action='store_true', help='stop if anomaly detected ') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if NEXUS_PYTHON_CONNECTED: # run Operation # --------------------GLOBAL SETTINGS ------------------------------ # ( in user/AppData) if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_4-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH,"CGM2_4-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER,"CGM2_4-pyCGM2.settings") argsManager = CgmArgsManager.argsManager_cgm(settings,args) leftFlatFoot = argsManager.getLeftFlatFoot() rightFlatFoot = argsManager.getRightFlatFoot() headFlat = argsManager.getHeadFlat() markerDiameter = argsManager.getMarkerDiameter() pointSuffix = argsManager.getPointSuffix("cgm2.4") ik_flag = argsManager.enableIKflag() hjcMethod = settings["Calibration"]["HJC"] lhjc = argsManager.forceHjc("left") rhjc = argsManager.forceHjc("right") if lhjc is not None: hjcMethod["Left"] = lhjc if rhjc is not None: hjcMethod["Right"] = rhjc # --------------------------LOADING------------------------------ DATA_PATH, calibrateFilenameLabelledNoExt = NEXUS.GetTrialName() calibrateFilenameLabelled = calibrateFilenameLabelledNoExt+".c3d" LOGGER.logger.info( "data Path: "+ DATA_PATH ) LOGGER.set_file_handler(DATA_PATH+"pyCGM2-Calibration.log") LOGGER.logger.info( "calibration file: "+ calibrateFilenameLabelled) # --------------------------SUBJECT ----------------------------------- # Notice : Work with ONE subject by session subjects = NEXUS.GetSubjectNames() subject = nexusTools.getActiveSubject(NEXUS) Parameters = NEXUS.GetSubjectParamNames(subject) required_mp,optional_mp = nexusUtils.getNexusSubjectMp(NEXUS,subject,resetFlag=args.resetMP) # --------------------------SESSION INFOS ----------------------------- # --------------------------SESSIONS INFOS ----------------------------------- mpInfo,mpFilename = files.getMpFileContent(DATA_PATH,"mp.pyCGM2",subject) # translators management translators = files.getTranslators(DATA_PATH,"CGM2_4.translators") if not translators: translators = settings["Translators"] # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter(DATA_PATH,calibrateFilenameLabelledNoExt,subject) acq = nacf.build() # --------------------------CONFIG ------------------------------------ model,finalAcqStatic,detectAnomaly = cgm2_4.calibrate(DATA_PATH,calibrateFilenameLabelled,translators,settings, required_mp,optional_mp, ik_flag,leftFlatFoot,rightFlatFoot,headFlat, markerDiameter, hjcMethod, pointSuffix,forceBtkAcq=acq, anomalyException=args.anomalyException) # ----------------------SAVE------------------------------------------- files.saveModel(model,DATA_PATH,subject) # save mp files.saveMp(mpInfo,model,DATA_PATH,mpFilename) # ----------------------DISPLAY ON VICON------------------------------- nexusUtils.updateNexusSubjectMp(NEXUS,model,subject) nexusFilters.NexusModelFilter(NEXUS, model,finalAcqStatic,subject, pointSuffix, staticProcessing=True).run() # ========END of the nexus OPERATION if run from Nexus ========= else: raise Exception("NO Nexus connection. Turn on Nexus")
def main(): plt.close("all") parser = argparse.ArgumentParser(description='CGM plotMAP') parser.add_argument( '-nd', '--normativeData', type=str, help='normative Data set (Schwartz2008 or Pinzone2014)', default="Schwartz2008") parser.add_argument( '-ndm', '--normativeDataModality', type=str, help= "if Schwartz2008 [VerySlow,SlowFree,Fast,VeryFast] - if Pinzone2014 [CentreOne,CentreTwo]", default="Free") parser.add_argument('-ps', '--pointSuffix', type=str, help='suffix of model outputs') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if not NEXUS_PYTHON_CONNECTED: raise Exception("Vicon Nexus is not running") #-----------------------SETTINGS--------------------------------------- pointSuffix = args.pointSuffix #-----------------------SETTINGS--------------------------------------- normativeData = { "Author": args.normativeData, "Modality": args.normativeDataModality } if normativeData["Author"] == "Schwartz2008": chosenModality = normativeData["Modality"] elif normativeData["Author"] == "Pinzone2014": chosenModality = normativeData["Modality"] nds = normativeDatasets.NormativeData(normativeData["Author"], chosenModality) #--------------------------Data Location and subject------------------------------------- if eclipse.getCurrentMarkedNodes() is not None: LOGGER.logger.info( "[pyCGM2] - Script worked with marked node of Vicon Eclipse") # --- acquisition file and path---- DATA_PATH, modelledFilenames = eclipse.getCurrentMarkedNodes() ECLIPSE_MODE = True if not ECLIPSE_MODE: LOGGER.logger.info( "[pyCGM2] - Script works with the loaded c3d in vicon Nexus") # --- acquisition file and path---- DATA_PATH, modelledFilenameNoExt = NEXUS.GetTrialName() modelledFilename = modelledFilenameNoExt + ".c3d" LOGGER.logger.info("data Path: " + DATA_PATH) LOGGER.logger.info("file: " + modelledFilename) # ----- Subject ----- # need subject to find input files subject = nexusTools.getActiveSubject(NEXUS) LOGGER.logger.info("Subject name : " + subject) if not ECLIPSE_MODE: # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, modelledFilenameNoExt, subject) acq = nacf.build() # --------------------------PROCESSING -------------------------------- analysisInstance = analysis.makeAnalysis(DATA_PATH, [modelledFilename], type="Gait", kineticLabelsDict=None, emgChannels=None, pointLabelSuffix=pointSuffix, btkAcqs=[acq], subjectInfo=None, experimentalInfo=None, modelInfo=None) outputName = modelledFilename else: analysisInstance = analysis.makeAnalysis(DATA_PATH, type="Gait", kineticLabelsDict=None, emgChannels=None, pointLabelSuffix=pointSuffix, subjectInfo=None, experimentalInfo=None, modelInfo=None) outputName = "Eclipse-MAP" plot.plot_MAP(DATA_PATH, analysisInstance, nds, exportPdf=True, outputName=outputName, pointLabelSuffix=pointSuffix)
def main(): parser = argparse.ArgumentParser(description='CGM1 Calibration') parser.add_argument('-l', '--leftFlatFoot', type=int, help='left flat foot option') parser.add_argument('-r', '--rightFlatFoot', type=int, help='right flat foot option') parser.add_argument('-hf', '--headFlat', type=int, help='head flat option') parser.add_argument('-md', '--markerDiameter', type=float, help='marker diameter') parser.add_argument('-ps', '--pointSuffix', type=str, help='suffix of model outputs') parser.add_argument('--check', action='store_true', help='force model output suffix') parser.add_argument('--resetMP', action='store_true', help='reset optional mass parameters') parser.add_argument('-ae', '--anomalyException', action='store_true', help='stop if anomaly detected ') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if NEXUS_PYTHON_CONNECTED: # run Operation # --------------------------GLOBAL SETTINGS ------------------------------------ # global setting ( in user/AppData) if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM1-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH, "CGM1-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER, "CGM1-pyCGM2.settings") # --------------------------CONFIG ------------------------------------ argsManager = CgmArgsManager.argsManager_cgm1(settings, args) leftFlatFoot = argsManager.getLeftFlatFoot() rightFlatFoot = argsManager.getRightFlatFoot() headFlat = argsManager.getHeadFlat() markerDiameter = argsManager.getMarkerDiameter() pointSuffix = argsManager.getPointSuffix("cgm1") DATA_PATH, calibrateFilenameLabelledNoExt = NEXUS.GetTrialName() calibrateFilenameLabelled = calibrateFilenameLabelledNoExt + ".c3d" LOGGER.logger.info("data Path: " + DATA_PATH) LOGGER.set_file_handler(DATA_PATH + "pyCGM2-Calibration.log") LOGGER.logger.info("calibration file: " + calibrateFilenameLabelled) # --------------------------SUBJECT ------------------------------------ subjects = NEXUS.GetSubjectNames() subject = nexusTools.getActiveSubject( NEXUS) #checkActivatedSubject(NEXUS,subjects) Parameters = NEXUS.GetSubjectParamNames(subject) required_mp, optional_mp = nexusUtils.getNexusSubjectMp( NEXUS, subject, resetFlag=args.resetMP) # -------------------------- INFOS ------------------------------------ mpInfo, mpFilename = files.getMpFileContent(DATA_PATH, "mp.pyCGM2", subject) # translators management translators = files.getTranslators(DATA_PATH, "CGM1.translators") if not translators: translators = settings["Translators"] # btkAcq builder nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, calibrateFilenameLabelledNoExt, subject) acq = nacf.build() # --------------------------MODELLING PROCESSING ----------------------- model, acqStatic, detectAnomaly = cgm1.calibrate( DATA_PATH, calibrateFilenameLabelled, translators, required_mp, optional_mp, leftFlatFoot, rightFlatFoot, headFlat, markerDiameter, pointSuffix, forceBtkAcq=acq, anomalyException=args.anomalyException) # ----------------------SAVE------------------------------------------- #pyCGM2.model files.saveModel(model, DATA_PATH, subject) # save mp files.saveMp(mpInfo, model, DATA_PATH, mpFilename) # ----------------------DISPLAY ON VICON------------------------------- nexusUtils.updateNexusSubjectMp(NEXUS, model, subject) nexusFilters.NexusModelFilter(NEXUS, model, acqStatic, subject, pointSuffix, staticProcessing=True).run()
def main(): parser = argparse.ArgumentParser(description='CGM2-3 Fitting') parser.add_argument( '--proj', type=str, help='Moment Projection. Choice : Distal, Proximal, Global') parser.add_argument('-md', '--markerDiameter', type=float, help='marker diameter') parser.add_argument('--noIk', action='store_true', help='cancel inverse kinematic') parser.add_argument('-ps', '--pointSuffix', type=str, help='suffix of model outputs') parser.add_argument('--check', action='store_true', help='force model output suffix') parser.add_argument('-a', '--accuracy', type=float, help='Inverse Kinematics accuracy') parser.add_argument('-ae', '--anomalyException', action='store_true', help='stop if anomaly detected ') parser.add_argument('-fi', '--frameInit', type=int, help='first frame to process') parser.add_argument('-fe', '--frameEnd', type=int, help='last frame to process') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if NEXUS_PYTHON_CONNECTED: # run Operation # --------------------GLOBAL SETTINGS ------------------------------ # global setting ( in user/AppData) if os.path.isfile(pyCGM2.PYCGM2_APPDATA_PATH + "CGM2_3-pyCGM2.settings"): settings = files.openFile(pyCGM2.PYCGM2_APPDATA_PATH, "CGM2_3-pyCGM2.settings") else: settings = files.openFile(pyCGM2.PYCGM2_SETTINGS_FOLDER, "CGM2_3-pyCGM2.settings") # --------------------------CONFIG ------------------------------------ argsManager = CgmArgsManager.argsManager_cgm(settings, args) markerDiameter = argsManager.getMarkerDiameter() pointSuffix = argsManager.getPointSuffix("cgm2.3") momentProjection = argsManager.getMomentProjection() ik_flag = argsManager.enableIKflag ikAccuracy = argsManager.getIkAccuracy() # ----------------------LOADING------------------------------------------- DATA_PATH, reconstructFilenameLabelledNoExt = NEXUS.GetTrialName() reconstructFilenameLabelled = reconstructFilenameLabelledNoExt + ".c3d" LOGGER.logger.info("data Path: " + DATA_PATH) LOGGER.set_file_handler(DATA_PATH + "pyCGM2-Fitting.log") LOGGER.logger.info("calibration file: " + reconstructFilenameLabelled) # --------------------------SUBJECT ----------------------------------- # Notice : Work with ONE subject by session subjects = NEXUS.GetSubjectNames() subject = nexusTools.getActiveSubject(NEXUS) LOGGER.logger.info("Subject name : " + subject) # --------------------pyCGM2 MODEL ------------------------------ model = files.loadModel(DATA_PATH, subject) # -------------------------- MP ------------------------------------ # allow alteration of thigh offset model.mp_computed[ "LeftThighRotationOffset"] = NEXUS.GetSubjectParamDetails( subject, "LeftThighRotation")[0] model.mp_computed[ "RightThighRotationOffset"] = NEXUS.GetSubjectParamDetails( subject, "RightThighRotation")[0] # --------------------------CHECKING ----------------------------------- # check model LOGGER.logger.info("loaded model : %s" % (model.version)) if model.version != "CGM2.3": raise Exception( "%s-pyCGM2.model file was not calibrated from the CGM2.3 calibration pipeline" % subject) # --------------------------SESSION INFOS ------------------------------------ # translators management translators = files.getTranslators(DATA_PATH, "CGM2_3.translators") if not translators: translators = settings["Translators"] # ikweight ikWeight = files.getIKweightSet(DATA_PATH, "CGM2_3.ikw") if not ikWeight: ikWeight = settings["Fitting"]["Weight"] #force plate assignement from Nexus mfpa = nexusTools.getForcePlateAssignment(NEXUS) # btkAcquisition nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, reconstructFilenameLabelledNoExt, subject) acq = nacf.build() # --------------------------MODELLING PROCESSING ----------------------- finalAcqGait, detectAnomaly = cgm2_3.fitting( model, DATA_PATH, reconstructFilenameLabelled, translators, settings, ik_flag, markerDiameter, pointSuffix, mfpa, momentProjection, forceBtkAcq=acq, ikAccuracy=ikAccuracy, anomalyException=args.anomalyException, frameInit=args.frameInit, frameEnd=args.frameEnd) # ----------------------DISPLAY ON VICON------------------------------- nexusFilters.NexusModelFilter(NEXUS, model, finalAcqGait, subject, pointSuffix).run() nexusTools.createGeneralEvents(NEXUS, subject, finalAcqGait, ["Left-FP", "Right-FP"]) # ========END of the nexus OPERATION if run from Nexus ========= else: raise Exception("NO Nexus connection. Turn on Nexus")
def main(): parser = argparse.ArgumentParser(description='EMG-plot_temporalEMG') parser.add_argument('-bpf', '--BandpassFrequencies', nargs='+', help='bandpass filter') parser.add_argument('-ecf', '--EnvelopLowpassFrequency', type=int, help='cutoff frequency for emg envelops') parser.add_argument('-r', '--raw', action='store_true', help='rectified data') parser.add_argument('-ina', '--ignoreNormalActivity', action='store_true', help='do not display normal activity') args = parser.parse_args() NEXUS = ViconNexus.ViconNexus() NEXUS_PYTHON_CONNECTED = NEXUS.Client.IsConnected() if NEXUS_PYTHON_CONNECTED: # run Operation # --- acquisition file and path---- DATA_PATH, inputFileNoExt = NEXUS.GetTrialName() inputFile = inputFileNoExt + ".c3d" #--------------------------settings------------------------------------- if os.path.isfile(DATA_PATH + "emg.settings"): emgSettings = files.openFile(DATA_PATH, "emg.settings") LOGGER.logger.warning( "[pyCGM2]: emg.settings detected in the data folder") else: emgSettings = None manager = EmgManager.EmgConfigManager( None, localInternalSettings=emgSettings) manager.contruct() # ----------------------INPUTS------------------------------------------- bandPassFilterFrequencies = manager.BandpassFrequencies #emgSettings["Processing"]["BandpassFrequencies"] if args.BandpassFrequencies is not None: if len(args.BandpassFrequencies) != 2: raise Exception( "[pyCGM2] - bad configuration of the bandpass frequencies ... set 2 frequencies only" ) else: bandPassFilterFrequencies = [ float(args.BandpassFrequencies[0]), float(args.BandpassFrequencies[1]) ] LOGGER.logger.info( "Band pass frequency set to %i - %i instead of 20-200Hz", bandPassFilterFrequencies[0], bandPassFilterFrequencies[1]) envelopCutOffFrequency = manager.EnvelopLowpassFrequency #emgSettings["Processing"]["EnvelopLowpassFrequency"] if args.EnvelopLowpassFrequency is not None: envelopCutOffFrequency = args.EnvelopLowpassFrequency LOGGER.logger.info("Cut-off frequency set to %i instead of 6Hz ", envelopCutOffFrequency) rectifyBool = False if args.raw else True # --------------------------SUBJECT ------------------------------------ subjects = NEXUS.GetSubjectNames() subject = nexusTools.getActiveSubject(NEXUS) # btk Acquisition nacf = nexusFilters.NexusConstructAcquisitionFilter( DATA_PATH, inputFileNoExt, subject) acq = nacf.build() # --------------emg Processing-------------- EMG_LABELS, EMG_MUSCLES, EMG_CONTEXT, NORMAL_ACTIVITIES = manager.getEmgConfiguration( ) emg.processEMG_fromBtkAcq( acq, EMG_LABELS, highPassFrequencies=bandPassFilterFrequencies, envelopFrequency=envelopCutOffFrequency ) # high pass then low pass for all c3ds plot.plotTemporalEMG(DATA_PATH, inputFile, EMG_LABELS, EMG_MUSCLES, EMG_CONTEXT, NORMAL_ACTIVITIES, exportPdf=True, rectify=rectifyBool, btkAcq=acq, ignoreNormalActivity=args.ignoreNormalActivity) else: raise Exception("NO Nexus connection. Turn on Nexus")