Пример #1
0
def _load_virtual_markers():
    markers = {}
    marker_coords = {}

    if opensim_version == 4.0:
        _dummy_model = opensim.Model()
        _osim_markerset = opensim.MarkerSet(_dummy_model, MARKERSET_PATH)
    else:
        _osim_markerset = opensim.MarkerSet(MARKERSET_PATH)

    for mi in range(_osim_markerset.getSize()):
        osim_marker = _osim_markerset.get(mi)

        # create a copy because the markerset and its marers only exists
        # in the function
        _v = opensim.Vec3()
        osim_marker.getOffset(_v)
        offset = np.array([_v.get(i) for i in range(3)])
        marker = Marker(
            name=osim_marker.getName(),
            bodyname=osim_marker.getBodyName(),
            offset=offset,
        )
        markers[marker.name] = marker
        marker_coords[marker.name] = marker.offset

    return markers, marker_coords
Пример #2
0
    def check_tasks(self):
        """Lists tasks that are <apply>'d for markers that either
        don't exist in the model or are not in the TRC file.

        Also lists tasks for which there is data, but that are either not in
        the model or do not have an IK task.

        """
        scale = osm.ScaleTool(self.setup_fpath)
        tasks = scale.getMarkerPlacer().getIKTaskSet()
        trc = util.TRCFile(self.marker_trajectories_fpath)
        trc_names = trc.marker_names
        model = osm.Model(self.generic_model_fpath)
        markerset = osm.MarkerSet(self.prescale_markerset_fpath)

        # Markers with IK tasks but without data.
        # ---------------------------------------
        markers_without_data = []
        for i in range(tasks.getSize()):
            task = tasks.get(i)
            name = task.getName()
            applied = task.getApply()

            if applied:
                if (not name in trc_names) or (not markerset.contains(name)):
                    if task.getConcreteClassName() != 'IKCoordinateTask':
                        markers_without_data.append(name)

        if markers_without_data != [] and not self.ignore_nonexistant_data:
            raise Exception('There are IK tasks for the following markers, '
                    'yet data does not exist for them: {}'.format(
                        markers_without_data))
        del name

        # Markers for which there is data but they're not specified elsewhere.
        # --------------------------------------------------------------------
        unused_markers = []
        for name in trc.marker_names:
            if (not markerset.contains(name)) or (not tasks.contains(name)):
                unused_markers.append(name)
        if unused_markers != []:
            raise Exception("You have data for the following markers, but "
                    "you are not using them in Scale's IK: {}".format(
                        unused_markers))

        # No data for these markers in the model or prescale markerset.
        # -------------------------------------------------------------
        excess_model_markers = []
        for im in range(markerset.getSize()):
            name = markerset.get(im).getName()
            if not tasks.contains(name):
                excess_model_markers.append(name)
        if excess_model_markers != []:
            raise Exception("The following model markers do not have tasks or "
                    "experimental data: {}".format(excess_model_markers))
Пример #3
0
def test_markAdoptedSets():

    # Set's.
    fus = osim.FunctionSet()
    fu1 = osim.Constant()
    fus.adoptAndAppend(fu1)
    del fus
    del fu1

    gs = osim.GeometrySet()
    dg = osim.DisplayGeometry()
    gs.adoptAndAppend(dg)
    del gs
    del dg

    s = osim.ScaleSet()
    o = osim.Scale()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.ForceSet()
    o = osim.BushingForce()
    s.adoptAndAppend(o)
    del s
    del o

    cs = osim.ControllerSet()
    csc = osim.PrescribedController()
    cs.adoptAndAppend(csc)
    del cs
    del csc

    s = osim.ContactGeometrySet()
    o = osim.ContactHalfSpace()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.AnalysisSet()
    o = osim.MuscleAnalysis()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.ControlSet()
    o = osim.ControlLinear()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.MarkerSet()
    o = osim.Marker()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.BodySet()
    o = osim.Body()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.BodyScaleSet()
    o = osim.BodyScale()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.CoordinateSet()
    o = osim.Coordinate()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.JointSet()
    o = osim.BallJoint()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.PathPointSet()
    o = osim.PathPoint()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.IKTaskSet()
    o = osim.IKMarkerTask()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.MarkerPairSet()
    o = osim.MarkerPair()
    s.adoptAndAppend(o)
    del s
    del o

    s = osim.MeasurementSet()
    o = osim.Measurement()
    s.adoptAndAppend(o)
    del s
    del o

    # TODO
    # s = osim.ProbeSet()
    # o = osim.Umberger2010MuscleMetabolicsProbe()
    # s.adoptAndAppend(o)
    # del s
    # del o

    s = osim.ConstraintSet()
    a = osim.Model()
    body = osim.Body('body', 1.0, osim.Vec3(0, 0, 0), osim.Inertia(0, 0, 0))

    loc_in_parent = osim.Vec3(0, -0, 0)
    orient_in_parent = osim.Vec3(0, 0, 0)
    loc_in_body = osim.Vec3(0, 0, 0)
    orient_in_body = osim.Vec3(0, 0, 0)
    joint = osim.WeldJoint("weld_joint", a.getGroundBody(), loc_in_parent,
                           orient_in_parent, body, loc_in_body,
                           orient_in_parent)
    a.addBody(body)

    constr = osim.ConstantDistanceConstraint()
    constr.setBody1ByName("ground")
    constr.setBody1PointLocation(osim.Vec3(0, 0, 0))
    constr.setBody2ByName("body")
    constr.setBody2PointLocation(osim.Vec3(1, 0, 0))
    constr.setConstantDistance(1)

    s.adoptAndAppend(constr)
def scale():
    import os
    import opensim as osim
    import shutil
    import directories

    # Global Directories
    allDir = list(directories.main(directories))
    parentDir = allDir[0]
    paramsDir = allDir[1]
    genericDir = allDir[2]
    subID = allDir[4]
    subResultsDir = allDir[5]

    # Get generic Model
    genericModel = "gait2354_LockedJoints.osim"
    genericModelFile = genericDir + "/" + genericModel

    if not os.path.exists(subResultsDir):
        os.mkdir(subResultsDir)

    # generic input XML files
    scaleSetupFull = paramsDir + "/setupScale.xml"
    markerSetFull = paramsDir + "/markerSet.xml"
    # Make scale directory if non-existent
    scaleResultsDir = subResultsDir + "/scale"
    if os.path.exists(scaleResultsDir):
        shutil.rmtree(scaleResultsDir, ignore_errors=True)
    if not os.path.exists(scaleResultsDir):
        os.mkdir(scaleResultsDir)
    # Output XML Files
    outputScaleFile = subID + "_scaleFactors.xml"
    adjustedMarkerSet = subID + "_movedMarkers.xml"
    # Output Model Files
    outputModelFile = subID + ".osim"
    # Input Data Files
    dataFiles = parentDir + "/data/osDemo"
    staticMarkerFile = "subject01_static.trc"
    staticMarkerFull = dataFiles + "/" + staticMarkerFile
    shutil.copy(staticMarkerFull, scaleResultsDir + "/" + staticMarkerFile)

    # Output Data Files
    staticCoordinates = subID + "_staticCoordinates.mot"
    # Subject Measurements
    subjectMass = 72.60000000

    # Load Model
    aModel = osim.Model(genericModelFile)

    aModel.setName(subID)
    # Initialize System
    aModel.initSystem()
    aState = aModel.initSystem()

    # Add Marker Set
    newMarkers = osim.MarkerSet(markerSetFull)
    aModel.replaceMarkerSet(aState, newMarkers)
    # Re-initialize State
    aState = aModel.initSystem()
    # Get Time Array for .trc file
    markerData = osim.MarkerData(staticMarkerFull)
    # Get Initial and Final Time
    initial_time = markerData.getStartFrameTime()
    final_time = markerData.getLastFrameTime()
    # Create an array double and apply the time range
    TimeArray = osim.ArrayDouble()
    TimeArray.set(0, initial_time)
    TimeArray.set(1, final_time)
    # Scale Tool
    scaleTool = osim.ScaleTool(scaleSetupFull)
    scaleTool.setSubjectMass(subjectMass)

    # GenericModelMaker-
    # Tell scale tool to use the loaded model
    scaleTool.getGenericModelMaker().setModelFileName(genericDir + "/" +
                                                      genericModel)
    # # Set the Marker Set file (incase a markerset isnt attached to the model)
    scaleTool.getGenericModelMaker().setMarkerSetFileName(markerSetFull)

    # ModelScaler-
    # Whether or not to use the model scaler during scale
    scaleTool.getModelScaler().setApply(1)
    # Set the marker file (.trc) to be used for scaling
    scaleTool.getModelScaler().setMarkerFileName("/" + staticMarkerFile)
    # set a time range
    scaleTool.getModelScaler().setTimeRange(TimeArray)
    # Indicating whether or not to preserve relative mass between segments
    scaleTool.getModelScaler().setPreserveMassDist(1)
    # Name of OpenSim model file (.osim) to write when done scaling.
    scaleTool.getModelScaler().setOutputModelFileName("")
    # Filename to write scale factors that were applied to the unscaled model (optional)
    scaleTool.getModelScaler().setOutputScaleFileName(outputScaleFile)

    # Run model scaler Tool
    scaleTool.getModelScaler().processModel(aState, aModel, scaleResultsDir,
                                            subjectMass)

    # initialize
    aState = aModel.initSystem()

    # # Marker Placer
    # # Whether or not to use the model scaler during scale
    scaleTool.getMarkerPlacer().setApply(1)
    # # Set the marker placer time range
    scaleTool.getMarkerPlacer().setTimeRange(TimeArray)
    # # Set the marker file (.trc) to be used for scaling
    scaleTool.getMarkerPlacer().setStaticPoseFileName("/" + staticMarkerFile)
    # # Return name to a variable for future use in functions
    scaledAdjustedModel = scaleTool.getMarkerPlacer().setOutputModelFileName(
        "/" + outputModelFile)
    # # Set the output motion filename
    scaleTool.getMarkerPlacer().setOutputMotionFileName("/" +
                                                        staticCoordinates)
    # # Set the output xml of the marker adjustments
    scaleTool.getMarkerPlacer().setOutputMarkerFileName("/" +
                                                        adjustedMarkerSet)
    # # Maximum amount of movement allowed in marker data when averaging
    scaleTool.getMarkerPlacer().setMaxMarkerMovement(-1)
    # # Run Marker Placer
    scaleTool.getMarkerPlacer().processModel(aState, aModel, scaleResultsDir)
    scaleTool.printToXML(scaleResultsDir + "/" + subID + "_setupScale.xml")
    # Clear Terminal
    os.system('cls' if os.name == 'nt' else 'clear')

    shutil.copy(scaleResultsDir + "/" + outputModelFile, subResultsDir)
    return ()
Пример #5
0
             ['femur_l'], ['tibia_l'],
             ['patella_l'], ['talus_l'], ['calcn_l'], ['toes_l'],
             ['torso'], ['torso'],
             ['humerus_r'], ['ulna_r'], ['radius_r'], ['hand_r'],
             ['humerus_l'], ['ulna_l'], ['radius_l'], ['hand_l']])

nBody = bodyNames.shape[0]

# The first step is to create an XML file with all the information used to scale the model

# Load the generic musculoskeletal model
osimModel = osim.Model(generic_MM_Path)
state = osimModel.initSystem()

# Add a marker set to the model
markerSet = osim.MarkerSet(XML_markers_path)
osimModel.replaceMarkerSet(state, markerSet)
state = osimModel.initSystem()

# Get the marker data from a .trc file
markerData = osim.MarkerData(TRC_file)
initial_time = markerData.getStartFrameTime()
final_time = markerData.getLastFrameTime()
TimeArray = osim.ArrayDouble()                                                 # Time range
TimeArray.set(0,initial_time)
TimeArray.set(1,final_time) 

# Scale Tool
scaleTool = osim.ScaleTool(XML_generic_ST_path)
scaleTool.setName('Subject')                                                   # Name of the subject
scaleTool.setSubjectMass(70)                                                   # Mass of the subject