def test_connecting(self):
        # We'll create a model from scratch and set up its joints with
        # the socket interface.
        model = osim.Model()
        b1 = osim.Body("b1", 1, osim.Vec3(1), osim.Inertia(1))
        b2 = osim.Body("b2", 2, osim.Vec3(1), osim.Inertia(1))

        j1 = osim.PinJoint()
        j1.setName("j1")
        j1.updSocket("parent_frame").connect(model.getGround())
        j1.connectSocket_child_frame(b1)

        j2 = osim.PinJoint()
        j2.setName("j2")
        j2.connectSocket_parent_frame(b1)
        j2.updSocket("child_frame").connect(b2)

        model.addBody(b1)
        model.addBody(b2)
        model.addJoint(j1)
        model.addJoint(j2)

        state = model.initSystem()

        # Check that the connectees point to the correct object.
        assert j1.getConnectee("parent_frame").this == model.getGround().this
        assert j1.getConnectee("child_frame").this == b1.this
        assert j2.getConnectee("parent_frame").this == b1.this
        assert j2.getConnectee("child_frame").this == b2.this

        # Make sure we can call methods of the concrete connectee type
        # (that the downcast succeeded).
        assert j1.getConnectee("child_frame").getMass() == 1
        assert j2.getConnectee("child_frame").getMass() == 2
Exemple #2
0
    def test_vec3_typemaps(self):
        npv = np.array([5, 3, 6])
        v1 = osim.Vec3(npv)
        v2 = v1.to_numpy()
        assert (npv == v2).all()

        # Incorrect size.
        with self.assertRaises(RuntimeError):
            osim.Vec3(np.array([]))
        with self.assertRaises(RuntimeError):
            osim.Vec3(np.array([5, 1]))
        with self.assertRaises(RuntimeError):
            osim.Vec3(np.array([5, 1, 6, 3]))

        # createFromMat()
        npv = np.array([1, 6, 8])
        v1 = osim.Vec3.createFromMat(npv)
        v2 = v1.to_numpy()
        assert (npv == v2).all()

        # Incorrect size.
        with self.assertRaises(RuntimeError):
            osim.Vec3.createFromMat(np.array([]))
        with self.assertRaises(RuntimeError):
            osim.Vec3.createFromMat(np.array([5, 1]))
        with self.assertRaises(RuntimeError):
            osim.Vec3.createFromMat(np.array([5, 1, 6, 3]))
 def test_vector_rowvector(self):
     print()
     print('Test transpose RowVector to Vector.')
     row = osim.RowVector([1, 2, 3, 4])
     col = row.transpose()
     assert (col[0] == row[0] and
             col[1] == row[1] and
             col[2] == row[2] and
             col[3] == row[3])
     print('Test transpose Vector to RowVector.')
     row_copy = col.transpose()
     assert (row_copy[0] == row[0] and
             row_copy[1] == row[1] and
             row_copy[2] == row[2] and
             row_copy[3] == row[3])
     print('Test transpose RowVectorOfVec3 to VectorOfVec3.')
     row = osim.RowVectorOfVec3([osim.Vec3(1, 2, 3), 
                                 osim.Vec3(4, 5, 6),
                                 osim.Vec3(7, 8, 9)])
     col = row.transpose()
     assert (str(col[0]) == str(row[0]) and
             str(col[1]) == str(row[1]) and
             str(col[2]) == str(row[2]))
     print('Test transpose VectorOfVec3 to RowVectorOfVec3.')
     row_copy = col.transpose()
     assert (str(row_copy[0]) == str(row[0]) and
             str(row_copy[1]) == str(row[1]) and
             str(row_copy[2]) == str(row[2]))
Exemple #4
0
    def test_vec3_operators(self):
        v1 = osim.Vec3(1, 2, 3)
        # Tests __getitem__().
        assert v1[0] == 1
        assert v1[1] == 2

        # Out of bounds.
        with self.assertRaises(RuntimeError):
            v1[-1]
        with self.assertRaises(RuntimeError):
            v1[3]
        with self.assertRaises(RuntimeError):
            v1[5]

        # Tests __setitem__().
        v1[0] = 5
        assert v1[0] == 5

        # Out of bounds.
        with self.assertRaises(RuntimeError):
            v1[-1] = 5
        with self.assertRaises(RuntimeError):
            v1[3] = 1.3

        # Add. TODO removed for now.
        v2 = osim.Vec3(5, 6, 7)
        #v3 = v1 + v2
        #assert v3[0] == 10
        #assert v3[1] == 8
        #assert v3[2] == 10

        # Length.
        assert len(v2) == 3
Exemple #5
0
    def __init__(self,
                 *args,
                 one_target=False,
                 max_speed=5.,
                 kin_coef=0.,
                 vel_prof_coef=0.,
                 acc_coef=0.,
                 **kwargs):
        super(Arm2DEnv, self).__init__(*args, **kwargs)
        blockos = opensim.Body('target', 0.0001, opensim.Vec3(0),
                               opensim.Inertia(1, 1, .0001, 0, 0, 0))
        self.target_joint = opensim.PlanarJoint(
            'target-joint',
            self.osim_model.model.getGround(),  # PhysicalFrame
            opensim.Vec3(0, 0, 0),
            opensim.Vec3(0, 0, 0),
            blockos,  # PhysicalFrame
            opensim.Vec3(0, 0, -0.25),
            opensim.Vec3(0, 0, 0))

        geometry = opensim.Ellipsoid(0.02, 0.02, 0.02)
        geometry.setColor(opensim.Green)
        blockos.attachGeometry(geometry)
        self.one_target = one_target
        self.target_generated = False
        self.osim_model.model.addJoint(self.target_joint)
        self.osim_model.model.addBody(blockos)
        self.osim_model.model.initSystem()
        self.kin_coef = kin_coef
        self.vel_prof_coef = vel_prof_coef
        self.max_speed = max_speed
Exemple #6
0
def test(model_path, visualize):
    model = opensim.Model(model_path)
    brain = opensim.PrescribedController()
    model.addController(brain)
    state = model.initSystem()

    muscleSet = model.getMuscles()
    for j in range(muscleSet.getSize()):
        brain.addActuator(muscleSet.get(j))
        func = opensim.Constant(1.0)
        brain.prescribeControlForActuator(j, func)

    block = opensim.Body('block', 0.0001, opensim.Vec3(0),
                         opensim.Inertia(1, 1, .0001, 0, 0, 0))
    model.addComponent(block)
    pj = opensim.PlanarJoint(
        'pin',
        model.getGround(),  # PhysicalFrame
        opensim.Vec3(0, 0, 0),
        opensim.Vec3(0, 0, 0),
        block,  # PhysicalFrame
        opensim.Vec3(0, 0, 0),
        opensim.Vec3(0, 0, 0))
    model.addComponent(pj)
    model.initSystem()
    pj.getCoordinate(1)
        def print_model():
            model = osim.Model()
            model.setName('model')

            # Create a body with name 'body', mass of 1 kg, center of mass at
            # the origin of the body, and unit inertia
            # (Ixx = Iyy = Izz = 1 kg-m^2).
            body = osim.Body('body', 1.0, osim.Vec3(0), osim.Inertia(1))

            # Create a free joint (all 6 degrees of freedom) with Ground as
            # the parent body and 'body' as the child body.
            joint = osim.FreeJoint('joint', model.getGround(), body)

            # Add the body and joint to the model.
            model.addComponent(body)
            model.addComponent(joint)

            # Create a TableReporter to save quantities to a file after
            # simulating.
            reporter = osim.TableReporterVec3()
            reporter.setName('reporter')
            reporter.set_report_time_interval(0.1)
            reporter.addToReport(model.getOutput('com_position'))
            reporter.getInput('inputs').setAlias(0, 'com_pos')

            # Display what input-output connections look like in XML
            # (in .osim files).
            print("Reporter input-output connections in XML:\n" + \
                  reporter.dump())

            model.addComponent(reporter)

            model.printToXML(model_filename)
Exemple #8
0
def print_model():
    model = osim.Model()
    model.setName('model')

    # Create a body with name 'body', mass of 1 kg, center of mass at the
    # origin of the body, and unit inertia (Ixx = Iyy = Izz = 1 kg-m^2).
    body = osim.Body('body', 1.0, osim.Vec3(0), osim.Inertia(1))

    # Create a free joint (all 6 degrees of freedom) with Ground as the parent
    # body and 'body' as the child body.
    joint = osim.FreeJoint('joint', model.getGround(), body)

    # Add the body and joint to the model.
    model.addComponent(body)
    model.addComponent(joint)

    # Create a TableReporter to save quantities to a file after simulating.
    reporter = osim.TableReporterVec3()
    reporter.setName('reporter')
    reporter.set_report_time_interval(0.1)
    # Report the position of the origin of the body.
    reporter.addToReport(body.getOutput('position'))
    # For comparison, we will also get the center of mass position from the
    # Model, and we can check that the two outputs are the same for our
    # one-body system. The (optional) second argument is an alias for the name
    # of the output; it is used as the column label in the table.
    reporter.addToReport(model.getOutput('com_position'), 'com_pos')
    # Display what input-output connections look like in XML (in .osim files).
    print("Reporter input-output connections in XML:\n" + reporter.dump())

    model.addComponent(reporter)

    model.printToXML(model_filename)
Exemple #9
0
def slackLenCom(num):
    slackLen = float(num)
    fibLen = lo.get()
    totLen = fibLen + slackLen
    if totLen > 0.45:
        diff = totLen - 0.45
        setter = fibLen - diff
        scaleLo.set(setter)
    elif totLen < 0.15:
        diff = 0.15 - totLen
        setter = diff + fibLen
        scaleLo.set(setter)
    setter = float(lo.get()) + float(ls.get())
    labelTotLen.configure(
        text="distance between origin and attachment: %0.2f" % setter)
    newMuscle.set_tendon_slack_length(float(num))
    blockLoc = newMuscle.getGeometryPath().getPathPointSet().get(
        1).getLocation().get(2)
    # Left muscle
    if blockLoc > 0:
        groundLoc = blockLoc + fibLen + slackLen

# Right muscle
    else:
        groundLoc = blockLoc - fibLen - slackLen
        vector = osim.Vec3(0, 0.5, groundLoc)
        newMuscle.updGeometryPath().getPathPointSet().get(0).setLocation(
            initState, vector)
Exemple #10
0
    def generate_results(self, root_dir, args):
        model = osim.Model()
        body = osim.Body("b", 1, osim.Vec3(0), osim.Inertia(0))
        model.addBody(body)

        joint = osim.SliderJoint("j", model.getGround(), body)
        joint.updCoordinate().setName("coord")
        model.addJoint(joint)

        damper = osim.SpringGeneralizedForce("coord")
        damper.setViscosity(-1.0)
        model.addForce(damper)

        actu = osim.CoordinateActuator("coord")
        model.addForce(actu)
        model.finalizeConnections()

        moco = osim.MocoStudy()
        problem = moco.updProblem()

        problem.setModel(model)
        problem.setTimeBounds(0, 2)
        problem.setStateInfo("/jointset/j/coord/value", [-10, 10], 0, 5)
        problem.setStateInfo("/jointset/j/coord/speed", [-10, 10], 0, 2)
        problem.setControlInfo("/forceset/coordinateactuator", [-50, 50])

        problem.addGoal(osim.MocoControlGoal("effort", 0.5))

        solver = moco.initCasADiSolver()
        solver.set_num_mesh_intervals(50)
        solution = moco.solve()
        solution.write(self.solution_file % root_dir)
Exemple #11
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
Exemple #12
0
    def test_SimTKArray(self):
        # Initally created to test the creation of a separate simbody module.
        ad = osim.SimTKArrayDouble()
        ad.push_back(1)

        av3 = osim.SimTKArrayVec3()
        av3.push_back(osim.Vec3(8))
        assert av3.at(0).get(0) == 8
Exemple #13
0
    def test_SimbodyMatterSubsystem(self):
        model = osim.Model(
            os.path.join(test_dir, "gait10dof18musc_subject01.osim"))
        s = model.initSystem()
        smss = model.getMatterSubsystem()

        assert smss.calcSystemMass(s) == model.getTotalMass(s)
        assert (smss.calcSystemMassCenterLocationInGround(s)[0] ==
                model.calcMassCenterPosition(s)[0])
        assert (smss.calcSystemMassCenterLocationInGround(s)[1] ==
                model.calcMassCenterPosition(s)[1])
        assert (smss.calcSystemMassCenterLocationInGround(s)[2] ==
                model.calcMassCenterPosition(s)[2])

        J = osim.Matrix()
        smss.calcSystemJacobian(s, J)
        # 6 * number of mobilized bodies
        assert J.nrow() == 6 * (model.getBodySet().getSize() + 1)
        assert J.ncol() == model.getCoordinateSet().getSize()

        v = osim.Vec3()
        smss.calcStationJacobian(s, 2, v, J)
        assert J.nrow() == 3
        assert J.ncol() == model.getCoordinateSet().getSize()

        # Inverse dynamics from SimbodyMatterSubsystem.calcResidualForce().
        # For the given inputs, we will actually be computing the first column
        # of the mass matrix. We accomplish this by setting all inputs to 0
        # except for the acceleration of the first coordinate.
        #   f_residual = M udot + f_inertial + f_applied
        #              = M ~[1, 0, ...] + 0 + 0
        model.realizeVelocity(s)
        appliedMobilityForces = osim.Vector()
        appliedBodyForces = osim.VectorOfSpatialVec()
        knownUdot = osim.Vector(s.getNU(), 0.0)
        knownUdot[0] = 1.0
        knownLambda = osim.Vector()
        residualMobilityForces = osim.Vector()
        smss.calcResidualForce(s, appliedMobilityForces, appliedBodyForces,
                               knownUdot, knownLambda, residualMobilityForces)
        assert residualMobilityForces.size() == s.getNU()

        # Explicitly compute the first column of the mass matrix, then copmare.
        massMatrixFirstColumn = osim.Vector()
        smss.multiplyByM(s, knownUdot, massMatrixFirstColumn)
        assert massMatrixFirstColumn.size() == residualMobilityForces.size()
        for i in range(massMatrixFirstColumn.size()):
            self.assertAlmostEqual(massMatrixFirstColumn[i],
                                   residualMobilityForces[i])

        # InverseDynamicsSolver.
        # Using accelerations from forward dynamics should give 0 residual.
        model.realizeAcceleration(s)
        idsolver = osim.InverseDynamicsSolver(model)
        residual = idsolver.solve(s, s.getUDot())
        assert residual.size() == s.getNU()
        for i in range(residual.size()):
            assert abs(residual[i]) < 1e-10
Exemple #14
0
    def _load_from_property_list(self, property_list):

        self.model = property_list["model"]
        self.sensor_to_opensim_rotations = opensim.Vec3(
            property_list["sensor_to_opensim_rotations"])
        self.experimental_orientations = opensim.TimeSeriesTableQuaternion(
            property_list["experimental_orientations"])
        self.time_start = property_list["time_start"]
        self.time_final = property_list["time_final"]
    def test_connecting_and_iterate_inputs(self):
        m = osim.Model()
        b = osim.Body('b1', 2.0, osim.Vec3(1, 0, 0), osim.Inertia(1))
        j = osim.PinJoint('pin', m.getGround(), b)

        # Source.
        source = osim.TableSource()
        source.setName("source")

        table = osim.TimeSeriesTable()
        table.setColumnLabels(('col1', 'col2', 'col3', 'col4'))
        row = osim.RowVector([1, 2, 3, 4])
        table.appendRow(0.0, row)
        row = osim.RowVector([2, 3, 4, 5])
        table.appendRow(1.0, row)
        source.setTable(table)

        # Reporter.
        rep = osim.ConsoleReporter()
        rep.setName("rep")

        m.addBody(b)
        m.addJoint(j)
        m.addComponent(source)
        m.addComponent(rep)

        # Connect.
        # There are multiple ways to perform the connection, especially
        # for reporters.
        coord = j.get_coordinates(0)
        rep.updInput('inputs').connect(coord.getOutput('value'))
        rep.connectInput_inputs(coord.getOutput('speed'), 'spd')
        rep.connectInput_inputs(source.getOutput('column').getChannel('col1'))
        rep.addToReport(
            source.getOutput('column').getChannel('col2'), 'second_col')

        s = m.initSystem()

        # Access and iterate through AbstractInputs, using names.
        expectedLabels = [
            '/model/jointset/pin/pin_coord_0|value', 'spd',
            '/model/source|column:col1', 'second_col'
        ]
        i = 0
        for name in rep.getInputNames():
            # Actually, there is only one input, which we connected to 4
            # channels.
            assert rep.getInput(name).getNumConnectees() == 4
            for j in range(4):
                assert (rep.getInput(name).getLabel(j) == expectedLabels[j])
            i += 1

        # Access concrete Input.
        # Input value is column 2 at time 0.
        assert (osim.InputDouble.safeDownCast(rep.getInput('inputs')).getValue(
            s, 3) == 2.0)
Exemple #16
0
    def __init__(self, *args, **kwargs):
        super(Arm2DEnv, self).__init__(*args, **kwargs)
        blockos = opensim.Body('target', 0.0001 , opensim.Vec3(0), opensim.Inertia(1,1,.0001,0,0,0) );
        self.target_joint = opensim.PlanarJoint('target-joint',
                                  self.osim_model.model.getGround(), # PhysicalFrame
                                  opensim.Vec3(0, 0, 0),
                                  opensim.Vec3(0, 0, 0),
                                  blockos, # PhysicalFrame
                                  opensim.Vec3(0, 0, -0.25),
                                  opensim.Vec3(0, 0, 0))

        geometry = opensim.Ellipsoid(0.02, 0.02, 0.02);
        geometry.setColor(opensim.Green);
        blockos.attachGeometry(geometry)

        self.osim_model.model.addJoint(self.target_joint)
        self.osim_model.model.addBody(blockos)

        self.osim_model.model.initSystem()
Exemple #17
0
def mirror_z(table, label):
    """Mirror the z-component of the vector.

    Parameters
    ----------
    label: string containing the name of the column you want to convert

    """
    c = table.updDependentColumn(label)
    for i in range(c.size()):
        c[i] = opensim.Vec3(c[i][0], c[i][1], -c[i][2])
Exemple #18
0
def mm_to_m(table, label):
    """Scale from units in mm for units in m.

    Parameters
    ----------
    label: string containing the name of the column you want to convert

    """
    c = table.updDependentColumn(label)
    for i in range(c.size()):
        c[i] = opensim.Vec3(c[i][0] * 0.001, c[i][1] * 0.001, c[i][2] * 0.001)
def createPointActuator(body,
                        point,
                        direction,
                        name,
                        optimal_force=10,
                        min_control=-float('inf'),
                        max_control=float('inf'),
                        point_is_global=False,
                        force_is_global=True):
    point_actuator = opensim.PointActuator()
    point_actuator.set_body(body)
    point_actuator.set_point(opensim.Vec3(point[0], point[1], point[2]))
    point_actuator.set_direction(
        opensim.Vec3(direction[0], direction[1], direction[2]))
    point_actuator.setOptimalForce(optimal_force)
    point_actuator.setMinControl(min_control)
    point_actuator.setMaxControl(max_control)
    point_actuator.setName(name)
    point_actuator.set_point_is_global(point_is_global)
    point_actuator.set_force_is_global(force_is_global)
    return (point_actuator)
Exemple #20
0
 def __init__(self, property_list=None):
     # Define properties, set default values.
     self.model = None
     self.sensor_to_opensim_rotations = opensim.Vec3()
     self.static_orientations = opensim.TimeSeriesTableQuaternion()
     self.base_heading_axis = ""
     self.base_imu = ""
     self.output_file_name = ""
     
     # Initialise from OpenSim's IK setup file.
     if property_list:
         self._load_properties(property_list)
Exemple #21
0
    def test_createRep(self):
        model = osim.Model()
        model.setName('sliding_mass')
        model.set_gravity(osim.Vec3(0, 0, 0))
        body = osim.Body('body', 2.0, osim.Vec3(0), osim.Inertia(0))
        model.addComponent(body)

        joint = osim.SliderJoint('slider', model.getGround(), body)
        coord = joint.updCoordinate()
        coord.setName('position')
        model.addComponent(joint)
        model.finalizeConnections()

        study = osim.MocoStudy()
        study.setName('sliding_mass')

        mp = study.updProblem()
        mp.setModel(model)

        pr = mp.createRep()
        assert (len(pr.createStateInfoNames()) == 2)
Exemple #22
0
 def test_TimeSeriesTableVec3(self):
     table = osim.TimeSeriesTableVec3()
     # Set columns labels.
     table.setColumnLabels(['0', '1', '2'])
     assert table.getColumnLabels() == ('0', '1', '2')
     # Append a row to the table.
     row = osim.RowVectorOfVec3(
         [osim.Vec3(1, 2, 3),
          osim.Vec3(4, 5, 6),
          osim.Vec3(7, 8, 9)])
     table.appendRow(0.1, row)
     assert table.getNumRows() == 1
     assert table.getNumColumns() == 3
     row0 = table.getRowAtIndex(0)
     assert (str(row0[0]) == str(row[0]) and str(row0[1]) == str(row[1])
             and str(row0[2]) == str(row[2]))
     # Append another row to the table.
     row = osim.RowVectorOfVec3(
         [osim.Vec3(2, 4, 6),
          osim.Vec3(8, 10, 12),
          osim.Vec3(14, 16, 18)])
     table.appendRow(0.2, row)
     assert table.getNumRows() == 2
     assert table.getNumColumns() == 3
     row1 = table.getRow(0.2)
     assert (str(row1[0]) == str(row[0]) and str(row1[1]) == str(row[1])
             and str(row1[2]) == str(row[2]))
     # Append another row to the table with a timestamp
     # less than the previous one. Exception expected.
     try:
         table.appendRow(0.15, row)
         assert False
     except RuntimeError:
         pass
Exemple #23
0
def createSlidingMassModel():
    model = osim.Model()
    model.setName("sliding_mass")
    model.set_gravity(osim.Vec3(0, 0, 0))
    body = osim.Body("body", 10.0, osim.Vec3(0), osim.Inertia(0))
    model.addComponent(body)

    # Allows translation along x.
    joint = osim.SliderJoint("slider", model.getGround(), body)
    coord = joint.updCoordinate(osim.SliderJoint.Coord_TranslationX)
    coord.setName("position")
    model.addComponent(joint)

    actu = osim.CoordinateActuator()
    actu.setCoordinate(coord)
    actu.setName("actuator")
    actu.setOptimalForce(1)
    actu.setMinControl(-10)
    actu.setMaxControl(10)
    model.addComponent(actu)

    return model
Exemple #24
0
    def _load_from_setup_file(self, file_path):
        # Initialise properties for the IMU IK tool from an OpenSim Inverse Kinematics setup file.

        tool = opensim.IMUInverseKinematicsTool(file_path)
        self.accuracy = tool.get_accuracy()
        self.constraint_weight = tool.get_constraint_weight()
        self.sensor_to_opensim_rotations = opensim.Vec3(
            tool.get_sensor_to_opensim_rotations()
        )  # must be copied into Vec3, or will disappear when passed
        self.model_file = tool.get_model_file()
        self.orientation_file = tool.get_orientations_file()
        self.time_final = tool.getEndTime()
        self.time_start = tool.getStartTime()
Exemple #25
0
 def com_in_pelvis():
     import opensim
     m = opensim.Model(self.output_model_fpath)
     init_state = m.initSystem()
     com_in_ground = m.calcMassCenterPosition(init_state)
     com_in_pelvis = opensim.Vec3()
     simbody_engine = m.getSimbodyEngine()
     simbody_engine.transformPosition(init_state,
             m.getBodySet().get('ground'), com_in_ground,
             m.getBodySet().get('pelvis'), com_in_pelvis)
     com_xmeas = str(com_in_pelvis.get(0))
     com_ymeas = str(com_in_pelvis.get(1))
     com_zmeas = str(com_in_pelvis.get(2))
     return com_xmeas, com_ymeas, com_zmeas
Exemple #26
0
def callBack(): 
    try:
        #makes a copy of the original model
        newModel.printToXML("C:/Users/mhmdk/Desktop/Co-op files/co-op semester 1/Python Code/newVersion.osim")
        newVersionModel = osim.Model("C:/Users/mhmdk/Desktop/Co-op files/co-op semester 1/Python Code/newVersion.osim")
        newVersionBase = newVersionModel.getMuscles().get(0)
        newVersionMuscle = osim.Millard2012EquilibriumMuscle.safeDownCast(newVersionBase)
        
        fibLen = float(lo.get())
        slackLen = float(ls.get())
    
        blockLoc = newVersionMuscle.getGeometryPath().getPathPointSet().get(1).getLocation().get(2)
        # Left muscle
        if blockLoc > 0:
            groundLoc = blockLoc + fibLen + slackLen
        #right muscle
        else:
            groundLoc = blockLoc - fibLen - slackLen
        vector = osim.Vec3(0, 0.05, groundLoc)
        newVersionMuscle.updGeometryPath().getPathPointSet().get(0).setLocation(initState, vector)
        
        newVersionModel.initSystem()
        
        #creates a new states file that corresponds to the sliders
        new_states_file = open("corrected_tug_of_war_states.sto", "w")
    
        new_states_file.write("Tug_of_War_Competition\n")
        new_states_file.write("nRows = 1\n")
        new_states_file.write("nColumns = 7\n")
        new_states_file.write("inDegree = no\n")
        new_states_file.write("endheader\n")
        new_states_file.write("time\tblock_tz\tblock_tz_u\tRightMuscle.activation\tRightMuscle.fiber_length\tLeftMuscle.activation\tLeftMuscle.fiber_length\n")
        new_states_file.write("0\t0\t0\t0.01\t" + str(newVersionMuscle.get_optimal_fiber_length()) +"\t0.01\t0.1")
        
        new_states_file.close()
        
        #creates the forward tool and force reporter
        reporter = osim.ForceReporter(newVersionModel)
        newVersionModel.addAnalysis(reporter)
        fwd_tool = osim.ForwardTool()
        fwd_tool.setControlsFileName("C:\OpenSim 3.3\Models\Tug_of_War\Tug_of_War_Millard_controls_corrected.xml")
        fwd_tool.setStatesFileName("C:\Users\mhmdk\Desktop\Co-op files\co-op semester 1\Python Code\corrected_tug_of_war_states.sto")
        fwd_tool.setModel(newVersionModel)
    
        fwd_tool.run()
        updater()
    except osim.OpenSimException:
        messagebox.showwarning("Warning", "The parameter combination is physiologically impossible")
Exemple #27
0
    def to_trc(self, filename):
        """
        Write a trc file from a Markers3dOsim
        Parameters
        ----------
        filename : string
            path of the file to write
        """
        filename = Path(filename)
        # Make sure the directory exists, otherwise create it
        if not filename.parents[0].is_dir():
            filename.parents[0].mkdir()

        # Make sure the metadata are set
        if not self.get_rate:
            raise ValueError(
                'get_rate is empty. Please fill with `your_variable.get_rate = 100.0` for example'
            )
        if not self.get_unit:
            raise ValueError(
                'get_unit is empty. Please fill with `your_variable.get_unit = "mm"` for example'
            )
        if not self.get_labels:
            raise ValueError(
                'get_labels is empty. Please fill with `your_variable.get_labels = ["M1", "M2"]` for example'
            )

        table = osim.TimeSeriesTableVec3()

        # set metadata
        table.setColumnLabels(self.get_labels)
        table.addTableMetaDataString('DataRate', str(self.get_rate))
        table.addTableMetaDataString('Units', self.get_unit)

        time_vector = np.arange(start=0,
                                stop=1 / self.get_rate * self.shape[2],
                                step=1 / self.get_rate)

        for iframe in range(self.shape[-1]):
            a = np.round(self.get_frame(iframe)[:-1, ...], decimals=4)
            row = osim.RowVectorOfVec3([
                osim.Vec3(a[0, i], a[1, i], a[2, i])
                for i in range(a.shape[-1])
            ])
            table.appendRow(time_vector[iframe], row)

        adapter = osim.TRCFileAdapter()
        adapter.write(table, str(filename))
Exemple #28
0
def rotate_data_table(table, axis, deg):
    """Rotate OpenSim::TimeSeriesTableVec3 entries using an axis and angle.

    Parameters
    ----------
    table: OpenSim.common.TimeSeriesTableVec3

    axis: 3x1 vector

    deg: angle in degrees

    """
    R = opensim.Rotation(np.deg2rad(deg),
                         opensim.Vec3(axis[0], axis[1], axis[2]))
    for i in range(table.getNumRows()):
        vec = table.getRowAtIndex(i)
        vec_rotated = R.multiply(vec)
        table.setRowAtIndex(i, vec_rotated)
Exemple #29
0
    def test_Joint(self):
        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.FreeJoint("joint", a.getGround(), loc_in_parent,
                               orient_in_parent, body, loc_in_body,
                               orient_in_parent)
        del joint
        spatialTransform = osim.SpatialTransform()
        joint = osim.CustomJoint("joint", a.getGround(), loc_in_parent,
                                 orient_in_parent, body, loc_in_body,
                                 orient_in_parent, spatialTransform)
        del joint
        joint = osim.EllipsoidJoint("joint", a.getGround(), loc_in_parent,
                                    orient_in_parent, body, loc_in_body,
                                    orient_in_parent, osim.Vec3(1, 1, 1))
        del joint
        joint = osim.BallJoint("joint", a.getGround(), loc_in_parent,
                               orient_in_parent, body, loc_in_body,
                               orient_in_parent)
        del joint
        joint = osim.PinJoint("joint", a.getGround(), loc_in_parent,
                              orient_in_parent, body, loc_in_body,
                              orient_in_parent)
        del joint
        joint = osim.SliderJoint("joint", a.getGround(), loc_in_parent,
                                 orient_in_parent, body, loc_in_body,
                                 orient_in_parent)
        del joint
        joint = osim.WeldJoint("joint", a.getGround(), loc_in_parent,
                               orient_in_parent, body, loc_in_body,
                               orient_in_parent)
        del joint
        joint = osim.GimbalJoint("joint", a.getGround(), loc_in_parent,
                                 orient_in_parent, body, loc_in_body,
                                 orient_in_parent)
        del joint
        joint = osim.UniversalJoint("joint", a.getGround(), loc_in_parent,
                                    orient_in_parent, body, loc_in_body,
                                    orient_in_parent)
        del joint
        joint = osim.PlanarJoint("joint", a.getGround(), loc_in_parent,
                                 orient_in_parent, body, loc_in_body,
                                 orient_in_parent)
        del joint
def createTorqueActuator(bodyA,
                         bodyB,
                         axis,
                         name,
                         optimal_force=10,
                         torque_global=True,
                         min_control=-float('inf'),
                         max_control=float('inf')):
    torque_actuator = opensim.TorqueActuator()
    torque_actuator.setBodyA(bodyA)
    torque_actuator.setBodyB(bodyB)
    torque_actuator.setAxis(opensim.Vec3(axis[0], axis[1], axis[2]))
    torque_actuator.setOptimalForce(optimal_force)
    torque_actuator.setTorqueIsGlobal(torque_global)
    torque_actuator.setMinControl(min_control)
    torque_actuator.setMaxControl(max_control)
    torque_actuator.setName(name)
    return (torque_actuator)