licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
3465
using Documenter using Literate using RigidBodyDynamics, RigidBodyDynamics.OdeIntegrators gendir = joinpath(@__DIR__, "src", "generated") tutorialpages = String[] let rm(gendir, recursive=true, force=true) mkdir(gendir) exampledir = joinpath(@__DIR__, "..", "examples") excludedirs = String[] excludefiles = String[] if VERSION < v"1.1.0" push!(excludefiles, "Symbolic double pendulum.jl") end for subdir in readdir(exampledir) subdir in excludedirs && continue root = joinpath(exampledir, subdir) isdir(root) || continue for file in readdir(root) file in excludefiles && continue name, ext = splitext(file) lowercase(ext) == ".jl" || continue outputdir = joinpath(gendir, subdir) cp(root, outputdir) preprocess = function (str) str = replace(str, "@__DIR__" => "\"$(relpath(root, outputdir))\"") str = replace(str, "# PREAMBLE" => """ # This example is also available as a Jupyter notebook that can be run locally # The notebook can be found in the `examples` directory of the package. # If the notebooks are missing, you may need to run `using Pkg; Pkg.build()`. """) return str end stripped_name = replace(name, r"[\s;]" => "") postprocess = function(str) str = replace(str, "PKG_SETUP" => """ ```@setup $stripped_name import Pkg let original_stdout = stdout out_rd, out_wr = redirect_stdout() @async read(out_rd, String) try Pkg.activate("$(relpath(root, outputdir))") Pkg.instantiate() finally redirect_stdout(original_stdout) close(out_wr) end end ``` """) return str end absfile = joinpath(root, file) tutorialpage = Literate.markdown(absfile, outputdir; preprocess=preprocess, postprocess=postprocess) push!(tutorialpages, relpath(tutorialpage, joinpath(@__DIR__, "src"))) end end end makedocs( modules = [RigidBodyDynamics, RigidBodyDynamics.OdeIntegrators], root = @__DIR__, checkdocs = :exports, sitename ="RigidBodyDynamics.jl", authors = "Twan Koolen and contributors.", pages = [ "Home" => "index.md", "Tutorials" => tutorialpages, "Library" => [ "Spatial vector algebra" => "spatial.md", "Joints" => "joints.md", "Rigid bodies" => "rigidbody.md", "Mechanism" => "mechanism.md", "MechanismState" => "mechanismstate.md", "Kinematics/dynamics algorithms" => "algorithms.md", "Custom collection types" => "customcollections.md", "Cache types" => "caches.md", "Simulation" => "simulation.md", "URDF parsing and writing" => "urdf.md", ], "Benchmarks" => "benchmarks.md", ], format = Documenter.HTML(prettyurls = parse(Bool, get(ENV, "CI", "false"))) ) deploydocs( repo = "github.com/JuliaRobotics/RigidBodyDynamics.jl.git" )
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
626
using Literate function preprocess(str) str = replace(str, "# PREAMBLE" => "") str = replace(str, "# PKG_SETUP" => """ using Pkg Pkg.activate(@__DIR__) Pkg.instantiate() """) return str end exampledir = @__DIR__ for subdir in readdir(exampledir) root = joinpath(exampledir, subdir) isdir(root) || continue @show subdir for file in readdir(root) name, ext = splitext(file) lowercase(ext) == ".jl" || continue absfile = joinpath(root, file) @show absfile Literate.notebook(absfile, root, execute=false, preprocess=preprocess) end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
142
using Pkg for x in readdir() if isdir(x) && isfile(joinpath(x, "Project.toml")) Pkg.activate(x) Pkg.update() end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
6859
# # @__NAME__ # PREAMBLE # PKG_SETUP # ## Setup # In addition to `RigidBodyDynamics`, we'll be using the `StaticArrays` package, used throughout `RigidBodyDynamics`, which provides stack-allocated, fixed-size arrays: using RigidBodyDynamics using LinearAlgebra using StaticArrays # ## Creating a double pendulum `Mechanism` # We're going to create a simple `Mechanism` that represents a [double pendulum](https://en.wikipedia.org/wiki/Double_pendulum). The `Mechanism` type can be thought of as an interconnection of rigid bodies and joints. # # We'll start by creating a 'root' rigid body, representing the fixed world, and using it to create a new `Mechanism`: g = -9.81 # gravitational acceleration in z-direction world = RigidBody{Float64}("world") doublependulum = Mechanism(world; gravity = SVector(0, 0, g)) # Note that the `RigidBody` type is parameterized on the 'scalar type', here `Float64`. # # We'll now add a second body, called 'upper link', to the `Mechanism`. We'll attach it to the world with a revolute joint, with the $y$-axis as the axis of rotation. We'll start by creating a `SpatialInertia`, which stores the inertial properties of the new body: axis = SVector(0., 1., 0.) # joint axis I_1 = 0.333 # moment of inertia about joint axis c_1 = -0.5 # center of mass location with respect to joint axis m_1 = 1. # mass frame1 = CartesianFrame3D("upper_link") # the reference frame in which the spatial inertia will be expressed inertia1 = SpatialInertia(frame1, moment=I_1 * axis * axis', com=SVector(0, 0, c_1), mass=m_1) # Note that the created `SpatialInertia` is annotated with the frame in which it is expressed (in the form of a `CartesianFrame3D`). This is a common theme among `RigidBodyDynamics` objects. Storing frame information with the data obviates the need for the complicated variable naming conventions that are used in some other libraries to disambiguate the frame in which quantities are expressed. It also enables automated reference frame checks. # We'll now create the second body: upperlink = RigidBody(inertia1) # and a new revolute joint called 'shoulder': shoulder = Joint("shoulder", Revolute(axis)) # Creating a `Joint` automatically constructs two new `CartesianFrame3D` objects: a frame directly before the joint, and one directly after. To attach the new body to the world by this joint, we'll have to specify where the frame before the joint is located on the parent body (here, the world): before_shoulder_to_world = one(Transform3D, frame_before(shoulder), default_frame(world)) # Now we can attach the upper link to the world: attach!(doublependulum, world, upperlink, shoulder, joint_pose = before_shoulder_to_world) # which changes the tree representation of the `Mechanism`. # We can attach the lower link in similar fashion: l_1 = -1. # length of the upper link I_2 = 0.333 # moment of inertia about joint axis c_2 = -0.5 # center of mass location with respect to joint axis m_2 = 1. # mass inertia2 = SpatialInertia(CartesianFrame3D("lower_link"), moment=I_2 * axis * axis', com=SVector(0, 0, c_2), mass=m_2) lowerlink = RigidBody(inertia2) elbow = Joint("elbow", Revolute(axis)) before_elbow_to_after_shoulder = Transform3D( frame_before(elbow), frame_after(shoulder), SVector(0, 0, l_1)) attach!(doublependulum, upperlink, lowerlink, elbow, joint_pose = before_elbow_to_after_shoulder) # Now our double pendulum `Mechanism` is complete. # **Note**: instead of defining the `Mechanism` in this way, it is also possible to load in a [URDF](http://wiki.ros.org/urdf) file (an XML file format used in ROS), using the `parse_urdf` function, e.g.: srcdir = dirname(pathof(RigidBodyDynamics)) urdf = joinpath(srcdir, "..", "test", "urdf", "Acrobot.urdf") parse_urdf(urdf) # ## The state of a `Mechanism` # A `Mechanism` stores the joint/rigid body layout, but no state information. State information is separated out into a `MechanismState` object: state = MechanismState(doublependulum) # Let's first set the configurations and velocities of the joints: set_configuration!(state, shoulder, 0.3) set_configuration!(state, elbow, 0.4) set_velocity!(state, shoulder, 1.) set_velocity!(state, elbow, 2.); # The joint configurations and velocities are stored as `Vector`s (denoted $q$ and $v$ respectively in this package) inside the `MechanismState` object: q = configuration(state) v = velocity(state) # ## Kinematics # We are now ready to do kinematics. Here's how you transform a point at the origin of the frame after the elbow joint to world frame: transform(state, Point3D(frame_after(elbow), zero(SVector{3})), default_frame(world)) # Other objects like `Wrench`es, `Twist`s, and `SpatialInertia`s can be transformed in similar fashion. # You can also ask for the homogeneous transform to world: transform_to_root(state, frame_after(elbow)) # Or a relative transform: relative_transform(state, frame_after(elbow), frame_after(shoulder)) # and here's the center of mass of the double pendulum: center_of_mass(state) # ## Dynamics # A `MechanismState` can also be used to compute quantities related to the dynamics of the `Mechanism`. Here we compute the mass matrix: mass_matrix(state) # Note that there is also a zero-allocation version, `mass_matrix!` (the `!` at the end of a method is a Julia convention signifying that the function is 'in-place', i.e. modifies its input data). # We can do inverse dynamics as follows (note again that there is a non-allocating version of this method as well): v̇ = similar(velocity(state)) # the joint acceleration vector, i.e., the time derivative of the joint velocity vector v v̇[shoulder][1] = 1 v̇[elbow][1] = 2 inverse_dynamics(state, v̇) # ## Simulation # Let's simulate the double pendulum for 5 seconds, starting from the state we defined earlier. For this, we can use the basic `simulate` function: ts, qs, vs = simulate(state, 5., Δt = 1e-3); # `simulate` returns a vector of times (`ts`) and associated joint configurations (`qs`) and velocities (`vs`). You can of course plot the trajectories using your favorite plotting package (see e.g. [Plots.jl](https://github.com/JuliaPlots/Plots.jl)). The [MeshCatMechanisms](https://github.com/JuliaRobotics/MeshCatMechanisms.jl) or [RigidBodyTreeInspector](https://github.com/rdeits/RigidBodyTreeInspector.jl) packages can also be used for 3D animation of the double pendulum in action. See also [RigidBodySim.jl](https://github.com/JuliaRobotics/RigidBodySim.jl) for a more full-fledge simulation environment. # A lower level interface for simulation/ODE integration with more options is also available. # Consult the documentation for more information. # In addition, [RigidBodySim.jl](https://github.com/JuliaRobotics/RigidBodySim.jl) offers a more full-featured simulation environment.
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
2233
# # @__NAME__ # PREAMBLE # PKG_SETUP # Please note that [RigidBodySim.jl](https://github.com/JuliaRobotics/RigidBodySim.jl) now provides a more capable simulation environment. # ## Setup using RigidBodyDynamics # ## Model definition # We'll just use the double pendulum model, loaded from a URDF: srcdir = dirname(pathof(RigidBodyDynamics)) urdf = joinpath(srcdir, "..", "test", "urdf", "Acrobot.urdf") mechanism = parse_urdf(urdf) # ## Controller # Let's write a simple controller that just applies $10 \sin(t)$ at the elbow joint and adds some damping at the shoulder joint: shoulder, elbow = joints(mechanism) function simple_control!(torques::AbstractVector, t, state::MechanismState) torques[velocity_range(state, shoulder)] .= -1 .* velocity(state, shoulder) torques[velocity_range(state, elbow)] .= 10 * sin(t) end; # ## Simulation # Basic simulation can be done using the `simulate` function. We'll first create a `MechanismState` object, and set the initial joint configurations and velocities: state = MechanismState(mechanism) zero_velocity!(state) set_configuration!(state, shoulder, 0.7) set_configuration!(state, elbow, -0.8); # Now we can simply call `simulate`, which will return a tuple consisting of: # * simulation times (a `Vector` of numbers) # * joint configuration vectors (a `Vector` of `Vector`s) # * joint velocity vectors (a `Vector` of `Vector`s) final_time = 10. ts, qs, vs = simulate(state, final_time, simple_control!; Δt = 1e-3); # For access to lower-level functionality, such as different ways of storing or visualizing the data generated during the simulation, it is advised to simply pattern match the basic `simulate` function. # ## Visualization # For visualization, we'll use [`MeshCatMechanisms`](https://github.com/JuliaRobotics/MeshCatMechanisms.jl), an external package based on RigidBodyDynamics.jl. using MeshCatMechanisms # Create a `MechanismVisualizer` and open it in a new browser tab # (see [`MeshCat.jl`](https://github.com/rdeits/MeshCat.jl) for other options): mvis = MechanismVisualizer(mechanism, URDFVisuals(urdf)); #- #nb ##NBSKIP #nb open(mvis) #md ## open(mvis) # And animate: MeshCatMechanisms.animate(mvis, ts, qs; realtimerate = 1.);
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
5046
# # @__NAME__ # PREAMBLE # PKG_SETUP # This example is a (slightly modified) contribution by [Aykut Satici](https://github.com/symplectomorphism). # ## Setup using Pkg # hide Pkg.activate(@__DIR__) # hide Pkg.instantiate() # hide using LinearAlgebra using RigidBodyDynamics using StaticArrays # ## Model definition # We're going to create a [four-bar linkage](https://en.wikipedia.org/wiki/Four-bar_linkage) that looks like this: # ![fourbar](fourbar.jpg) # # We'll 'cut' the mechanism at joint 4: joints 1, 2, and 3 will be part of the spanning tree of the mechanism, but joint 4 will be a 'loop joint' (see e.g. Featherstone's 'Rigid Body Dynamics Algorithms'), for which the dynamics will be enforced using Lagrange multipliers. # # First, we'll define some relevant constants: ## gravitational acceleration g = -9.81 ## link lengths l_0 = 1.10 l_1 = 0.5 l_2 = 1.20 l_3 = 0.75 ## link masses m_1 = 0.5 m_2 = 1.0 m_3 = 0.75 ## link center of mass offsets from the preceding joint axes c_1 = 0.25 c_2 = 0.60 c_3 = 0.375 ## moments of inertia about the center of mass of each link I_1 = 0.333 I_2 = 0.537 I_3 = 0.4 ## Rotation axis: negative y-axis axis = SVector(0., -1., 0.); # Construct the world rigid body and create a new mechanism: world = RigidBody{Float64}("world") fourbar = Mechanism(world; gravity = SVector(0., 0., g)) # Next, we'll construct the spanning tree of the mechanism, # consisting of bodies 1, 2, and 3 connected by joints 1, 2, and 3. # Note the use of the `moment_about_com` keyword (as opposed to `moment`): # Link 1 and joint 1: joint1 = Joint("joint1", Revolute(axis)) inertia1 = SpatialInertia(frame_after(joint1), com=SVector(c_1, 0, 0), moment_about_com=I_1*axis*transpose(axis), mass=m_1) link1 = RigidBody(inertia1) before_joint1_to_world = one(Transform3D, frame_before(joint1), default_frame(world)) attach!(fourbar, world, link1, joint1, joint_pose = before_joint1_to_world) # Link 2 and joint 2: joint2 = Joint("joint2", Revolute(axis)) inertia2 = SpatialInertia(frame_after(joint2), com=SVector(c_2, 0, 0), moment_about_com=I_2*axis*transpose(axis), mass=m_2) link2 = RigidBody(inertia2) before_joint2_to_after_joint1 = Transform3D( frame_before(joint2), frame_after(joint1), SVector(l_1, 0., 0.)) attach!(fourbar, link1, link2, joint2, joint_pose = before_joint2_to_after_joint1) # Link 3 and joint 3: joint3 = Joint("joint3", Revolute(axis)) inertia3 = SpatialInertia(frame_after(joint3), com=SVector(l_0, 0., 0.), moment_about_com=I_3*axis*transpose(axis), mass=m_3) link3 = RigidBody(inertia3) before_joint3_to_world = Transform3D( frame_before(joint3), default_frame(world), SVector(l_0, 0., 0.)) attach!(fourbar, world, link3, joint3, joint_pose = before_joint3_to_world) # Finally, we'll add joint 4 in almost the same way we did the other joints, # with the following exceptions: # 1. both `link2` and `link3` are already part of the `Mechanism`, so the `attach!` # function will figure out that `joint4` will be a loop joint. # 2. instead of using the default (identity) for the argument that specifies the # transform from the successor of joint 4 (i.e., link 3) to the frame directly after # joint 4, we'll specify a transform that incorporates the $l_3$ offset. ## joint between link2 and link3 joint4 = Joint("joint4", Revolute(axis)) before_joint4_to_joint2 = Transform3D( frame_before(joint4), frame_after(joint2), SVector(l_2, 0., 0.)) joint3_to_after_joint4 = Transform3D( frame_after(joint3), frame_after(joint4), SVector(-l_3, 0., 0.)) attach!(fourbar, link2, link3, joint4, joint_pose = before_joint4_to_joint2, successor_pose = joint3_to_after_joint4) # Note the additional non-tree joint in the printed `Mechanism` summary. # ## Simulation # As usual, we'll now construct a `MechanismState` and `DynamicsResult` for the # four-bar `Mechanism`. We'll set some initial conditions for a simulation, which # were solved for a priori using a nonlinear program (not shown here). state = MechanismState(fourbar) result = DynamicsResult(fourbar); set_configuration!(state, joint1, 1.6707963267948966) # θ set_configuration!(state, joint2, -1.4591054166649482) # γ set_configuration!(state, joint3, 1.5397303602625536) # ϕ set_velocity!(state, joint1, 0.5) set_velocity!(state, joint2, -0.47295) set_velocity!(state, joint3, 0.341) # Next, we'll do a 3-second simulation: ts, qs, vs = simulate(state, 3., Δt = 1e-2); # ## Visualization # For visualization, we'll use [`MeshCatMechanisms`](https://github.com/JuliaRobotics/MeshCatMechanisms.jl), # an external package based on RigidBodyDynamics.jl. using MeshCatMechanisms # Create a `MechanismVisualizer` for the four-bar linkage and open it in a new browser tab # (see [`MeshCat.jl`](https://github.com/rdeits/MeshCat.jl) for other options): mvis = MechanismVisualizer(fourbar, Skeleton(inertias=false)); #- #nb ##NBSKIP #nb open(mvis) #md ## open(mvis) # And animate: MeshCatMechanisms.animate(mvis, ts, qs; realtimerate = 1.);
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
7459
# # @__NAME__ # PREAMBLE # PKG_SETUP # In this notebook, we'll demonstrate an extremely simple approach for computing basic inverse kinematics (IK) and controlling the position of some point on our robot using the Jacobian transpose. # # For a brief technical introduction, see <https://groups.csail.mit.edu/drl/journal_club/papers/033005/buss-2004.pdf> or <https://homes.cs.washington.edu/~todorov/courses/cseP590/06_JacobianMethods.pdf> # ## Setup using Pkg # hide Pkg.activate(@__DIR__) # hide Pkg.instantiate() # hide using RigidBodyDynamics using StaticArrays using MeshCat, MeshCatMechanisms using Electron: Application # Fix the random seed, so we get repeatable results using Random Random.seed!(42); # First we'll load our double pendulum robot from URDF: srcdir = dirname(pathof(RigidBodyDynamics)) urdf = joinpath(srcdir, "..", "test", "urdf", "Acrobot.urdf") mechanism = parse_urdf(urdf) state = MechanismState(mechanism) mechanism # Now we choose a point on the robot to control. We'll pick the end of the second link, which is located 2m from the origin of the `lower_link` body: body = findbody(mechanism, "lower_link") point = Point3D(default_frame(body), 0., 0, -2) # Let's visualize the mechanism and its attached point. For visualization, we'll use [MeshCatMechanisms.jl](https://github.com/JuliaRobotics/MeshCatMechanisms.jl) with [Electron.jl](https://github.com/davidanthoff/Electron.jl). ## Create the visualizer vis = MechanismVisualizer(mechanism, URDFVisuals(urdf)) ## Render our target point attached to the robot as a sphere with radius 0.07 setelement!(vis, point, 0.07) # Open the visualizer in a new Electron window: #nb ##NBSKIP #nb open(vis, Application()); #md ## open(vis, Application()); # ## Inverse Kinematics # First, let's use the point jacobian to solve a simple inverse kinematics problem. Given a target location `desired` expressed in world frame, we want to find the joint angles `q` such that the `point` attached to the robot is at the desired location. # # To do that, we'll iteratively update `q` by applying: # # \begin{align} # \Delta q = \alpha \, J_p^\top \, \Delta p # \end{align} # # where $\alpha$ is our step size (equivalent to a learning rate in gradient descent) and $\Delta p$ is the error in the position of our target point. function jacobian_transpose_ik!(state::MechanismState, body::RigidBody, point::Point3D, desired::Point3D; α=0.1, iterations=100) mechanism = state.mechanism world = root_frame(mechanism) ## Compute the joint path from world to our target body p = path(mechanism, root_body(mechanism), body) ## Allocate the point jacobian (we'll update this in-place later) Jp = point_jacobian(state, p, transform(state, point, world)) q = copy(configuration(state)) for i in 1:iterations ## Update the position of the point point_in_world = transform(state, point, world) ## Update the point's jacobian point_jacobian!(Jp, state, p, point_in_world) ## Compute an update in joint coordinates using the jacobian transpose Δq = α * Array(Jp)' * (transform(state, desired, world) - point_in_world).v ## Apply the update q .= configuration(state) .+ Δq set_configuration!(state, q) end state end # To use our IK method, we just have to set our current state and choose a desired location for the tip of the robot's arm: rand!(state) set_configuration!(vis, configuration(state)) # Choose a desired location. We'll move the tip of the arm to # [0.5, 0, 2] desired_tip_location = Point3D(root_frame(mechanism), 0.5, 0, 2) # Run the IK, updating `state` in place jacobian_transpose_ik!(state, body, point, desired_tip_location) set_configuration!(vis, configuration(state)) # We asked for our point to be close to [0.5, 0, 2], # but since the arm cannot move in the y direction at all # we end up near [0.5, 0.25, 2] instead transform(state, point, root_frame(mechanism)) # We can try varying the target and watching the IK solution change: qs = typeof(configuration(state))[] # Vary the desired x position from -1 to 1 for x in range(-1, stop=1, length=100) desired = Point3D(root_frame(mechanism), x, 0, 2) jacobian_transpose_ik!(state, body, point, desired) push!(qs, copy(configuration(state))) end ts = collect(range(0, stop=1, length=length(qs))) setanimation!(vis, Animation(vis, ts, qs)) # ## Control # Now let's use the same principle to generate torques and actually control the robot. To make things more interesting, let's get the end of the robot's arm to trace out a circle. circle_origin = SVector(0., 0.25, 2) radius = 0.5 ω = 1.0 # radians per second at which the point should move in its circle using GeometryTypes: Point ## Draw the circle in the viewer θ = repeat(range(0, stop=2π, length=100), inner=(2,))[2:end] cx, cy, cz = circle_origin geometry = PointCloud(Point.(cx .+ radius .* sin.(θ), cy, cz .+ 0.5 .* cos.(θ))) setobject!(vis[:circle], LineSegments(geometry, LineBasicMaterial())) # This function will take in the parameters of the circle # and the target point and return a function we can use # as the controller. By wrapping the construction of the # controller in this way, we avoid any issues with accessing # non-const global variables. function make_circle_controller(state::MechanismState, body::RigidBody, point::Point3D, circle_origin::AbstractVector, radius, ω) mechanism = state.mechanism world = root_frame(mechanism) joint_path = path(mechanism, root_body(mechanism), body) point_world = transform(state, point, root_frame(mechanism)) Jp = point_jacobian(state, joint_path, point_world) v̇ = similar(velocity(state)) function controller!(τ, t, state) desired = Point3D(world, circle_origin .+ radius .* SVector(sin(t / ω), 0, cos(t / ω))) point_in_world = transform_to_root(state, body) * point point_jacobian!(Jp, state, joint_path, point_in_world) Kp = 200 Kd = 20 Δp = desired - point_in_world v̇ .= Kp * Array(Jp)' * Δp.v .- 20 .* velocity(state) τ .= inverse_dynamics(state, v̇) end end controller! = make_circle_controller(state, body, point, circle_origin, radius, ω) ts, qs, vs = simulate(state, 10, controller!); # Animate the resulting trajectory: setanimation!(vis, Animation(vis, ts, qs)) # Now we can plot the behavior of the controller. The initial state is quite far from the target, so there's some significant overshoot early in the trajectory, but the controller eventually settles into tracking the desired circular path. This controller isn't very well-tuned, and we could certainly do better with a more advanced approach, but this is still a nice demonstration of a very simple control policy. using Plots: plot xs = Float64[] zs = Float64[] ## Downsample by 100 just so the plot doesn't become a huge file: for q in qs[1:100:end] set_configuration!(state, q) p = transform(state, point, root_frame(mechanism)) push!(xs, p.v[1]) push!(zs, p.v[3]) end plot(xs, zs, xlim=(-1, 1), ylim=(1, 3), aspect_ratio=:equal, legend=nothing)
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
8046
# # @__NAME__ # PREAMBLE # PKG_SETUP # ## Setup using Pkg # hide Pkg.activate(@__DIR__) # hide Pkg.instantiate() # hide using RigidBodyDynamics, StaticArrays, ForwardDiff using Test, Random Random.seed!(1); # to get repeatable results # ## Jacobians with respect to $q$ and $v$ - the naive way # First, we'll load our trusty double pendulum from a URDF: srcdir = dirname(pathof(RigidBodyDynamics)) urdf = joinpath(srcdir, "..", "test", "urdf", "Acrobot.urdf") mechanism = parse_urdf(urdf) # Of course, we can create a `MechanismState` for the double pendulum, and compute its momentum in some random state: float64state = MechanismState(mechanism) rand!(float64state) momentum(float64state) # But now suppose we want the Jacobian of momentum with respect to the joint velocity vector $v$. # We can do this using the `ForwardDiff.Dual` type and the `ForwardDiff.jacobian` function. # The ForwardDiff package implements forward-mode [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation). # To use `ForwardDiff.jacobian` we'll create a function that maps `v` (as a `Vector`) to momentum (as a `Vector`): q = configuration(float64state) function momentum_vec(v::AbstractVector{T}) where T ## create a `MechanismState` that can handle the element type of `v` (which will be some `ForwardDiff.Dual`): state = MechanismState{T}(mechanism) ## set the state variables: set_configuration!(state, q) set_velocity!(state, v) ## return momentum converted to an `SVector` (as ForwardDiff expects an `AbstractVector`) Vector(SVector(momentum(state))) end # Let's first check that the function returns the same thing we got from `float64state`: v = velocity(float64state) @test momentum_vec(v) == SVector(momentum(float64state)) # That works, so now let's compute the Jacobian with `ForwardDiff`: J = ForwardDiff.jacobian(momentum_vec, v) # At this point we note that the matrix `J` is simply the momentum matrix (in world frame) of the `Mechanism`. In this case, RigidBodyDynamics.jl has a specialized algorithm for computing this matrix, so let's verify the results: A = momentum_matrix(float64state) @test J ≈ Array(A) atol = 1e-12 # Gradients with respect to $q$ can be computed in similar fashion. # ## Improving performance # Ignoring the fact that we have a specialized method available, let's look at the performance of using `ForwardDiff.jacobian`. using BenchmarkTools @benchmark ForwardDiff.jacobian($momentum_vec, $v) # That's not great. Note all the allocations. We can do better by making the following modifications: # # 1. use an in-place version of the `jacobian` function, `ForwardDiff.jacobian!` # 2. reimplement our `momentum_vec` function to be in-place as well # 3. don't create a new `MechanismState` every time # # The third point is especially important; creating a `MechanismState` is expensive! # # Regarding the second point, we could also just stop converting momentum from a `StaticArrays.SVector` to a `Vector` to avoid allocations. However, the solution of making the function in-place also applies when the size of the output vector is not known statically (e.g., for `dynamics_bias!`). # To facillitate reuse of `MechanismState`s while keeping the code nice and generic, we can use a `StateCache` object. # `StateCache` is a container that stores `MechanismState`s of various types (associated with one `Mechanism`), and will ease the process of using `ForwardDiff`. # Creating one is easy: const statecache = StateCache(mechanism) # `MechanismState`s of a given type can be accessed as follows (note that if a `MechanismState` of a certain type is already available, it will be reused): float32state = statecache[Float32] @test float32state === statecache[Float32] # Now we'll use the `StateCache` to reimplement `momentum_vec`, making it in-place as well: function momentum_vec!(out::AbstractVector, v::AbstractVector{T}) where T ## retrieve a `MechanismState` that can handle the element type of `v`: state = statecache[T] ## set the state variables: set_configuration!(state, q) set_velocity!(state, v) ## compute momentum and store it in `out` m = momentum(state) copyto!(out, SVector(m)) end # Check that the in-place version works as expected on `Float64` inputs: const out = zeros(6) # where we'll be storing our results momentum_vec!(out, v) @test out == SVector(momentum(float64state)) # And use `ForwardDiff.jacobian!` to compute the Jacobian: const result = DiffResults.JacobianResult(out, v) const config = ForwardDiff.JacobianConfig(momentum_vec!, out, v) ForwardDiff.jacobian!(result, momentum_vec!, out, v, config) J = DiffResults.jacobian(result) @test J ≈ Array(A) atol = 1e-12 # Let's check the performance again: @benchmark ForwardDiff.jacobian!($result, $momentum_vec!, $out, $v, $config) # That's much better. Do note that the specialized algorithm is still faster: q = copy(configuration(float64state)) @benchmark begin set_configuration!($float64state, $q) momentum_matrix!($A, $float64state) end # ## Time derivatives # We can also use ForwardDiff to compute time derivatives. Let's verify that energy is conserved for the double pendulum in the absence of nonconservative forces (like damping). That is, we expect that the time derivative of the pendulum's total energy is zero when its state evolves according to the passive dynamics. # Let's first compute the joint acceleration vector $\dot{v}$ using the passive dynamics: dynamicsresult = DynamicsResult(mechanism) set_configuration!(float64state, q) set_velocity!(float64state, v) dynamics!(dynamicsresult, float64state) v̇ = dynamicsresult.v̇ # Now for the time derivative of total energy. ForwardDiff has a `derivative` function that can be used to take derivatives of functions that map a scalar to a scalar. But in this example, we'll instead use ForwardDiff's `Dual` type directly. `ForwardDiff.Dual` represents a (potentially multidimensional) dual number, i.e., a type that stores both the value of a function evaluated at a certain point, as well as the partial derivatives of the function, again evaluated at the same point. See the [ForwardDiff documentation](http://www.juliadiff.org/ForwardDiff.jl/stable/dev/how_it_works.html) for more information. # We'll create a vector of `Dual`s representing the value and derivative of $q(t)$: q̇ = v q_dual = ForwardDiff.Dual.(q, q̇) # **Note**: for the double pendulum, $\dot{q} = v$, but this is not the case in general for `Mechanism`s created using RigidBodyDynamics.jl. For example, the `QuaternionSpherical` joint type uses a unit quaternion to represent the joint configuration, but angular velocity (in body frame) to represent velocity. In general $\dot{q}$ can be computed from the velocity vector $v$ stored in a `MechanismState` using # # ```julia # configuration_derivative(::MechanismState) # ``` # # or its in-place variant, `configuration_derivative!`. # We'll do the same thing for $v(t)$: v_dual = ForwardDiff.Dual.(v, v̇) # Now we're ready to compute the total energy (kinetic + potential) using these `ForwardDiff.Dual` inputs. We'll use our `StateCache` again: T = eltype(q_dual) state = statecache[T] set_configuration!(state, q_dual) set_velocity!(state, v_dual) energy_dual = kinetic_energy(state) + gravitational_potential_energy(state) # Note that the result type of `energy_dual` is again a `ForwardDiff.Dual`. We can extract the energy and its time derivative (mechanical power) from `energy_dual` as follows: energy = ForwardDiff.value(energy_dual) partials = ForwardDiff.partials(energy_dual) power = partials[1]; # So the total energy in the system is: energy # **Note**: the total energy is negative because the origin of the world frame is used as a reference for computing gravitational potential energy, i.e., the center of mass of the double pendulum is somewhere below this origin. # And we can verify that, indeed, there is no power flow into or out of the system: @test power ≈ 0 atol = 1e-14
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
2778
# # @__NAME__ # PREAMBLE # PKG_SETUP # ## Setup using RigidBodyDynamics using StaticArrays using Symbolics # ## Create symbolic parameters # * Masses: $m_1, m_2$ # * Mass moments of inertia (about center of mass): $I_1, I_2$ # * Link lengths: $l_1, l_2$ # * Center of mass locations (w.r.t. preceding joint axis): $c_1, c_2$ # * Gravitational acceleration: $g$ inertias = @variables m_1 m_2 I_1 I_2 positive = true lengths = @variables l_1 l_2 c_1 c_2 real = true gravitational_acceleration = @variables g real = true params = [inertias..., lengths..., gravitational_acceleration...] transpose(params) # ## Create double pendulum `Mechanism` # A `Mechanism` contains the joint layout and inertia parameters, but no state information. T = Num # the 'scalar type' of the Mechanism we'll construct axis = SVector(zero(T), one(T), zero(T)) # axis of rotation for each of the joints double_pendulum = Mechanism(RigidBody{T}("world"); gravity=SVector(zero(T), zero(T), g)) world = root_body(double_pendulum) # the fixed 'world' rigid body # Attach the first (upper) link to the world via a revolute joint named 'shoulder' inertia1 = SpatialInertia(CartesianFrame3D("upper_link"), moment=I_1 * axis * transpose(axis), com=SVector(zero(T), zero(T), c_1), mass=m_1) body1 = RigidBody(inertia1) joint1 = Joint("shoulder", Revolute(axis)) joint1_to_world = one(Transform3D{T}, frame_before(joint1), default_frame(world)); attach!(double_pendulum, world, body1, joint1, joint_pose=joint1_to_world); # Attach the second (lower) link to the world via a revolute joint named 'elbow' inertia2 = SpatialInertia(CartesianFrame3D("lower_link"), moment=I_2 * axis * transpose(axis), com=SVector(zero(T), zero(T), c_2), mass=m_2) body2 = RigidBody(inertia2) joint2 = Joint("elbow", Revolute(axis)) joint2_to_body1 = Transform3D( frame_before(joint2), default_frame(body1), SVector(zero(T), zero(T), l_1)) attach!(double_pendulum, body1, body2, joint2, joint_pose=joint2_to_body1) # ## Create `MechanismState` associated with the double pendulum `Mechanism` # A `MechanismState` stores all state-dependent information associated with a `Mechanism`. x = MechanismState(double_pendulum); # Set the joint configuration vector of the MechanismState to a new vector of symbolic variables q = configuration(x) for i in eachindex(q) q[i] = symbols("q_$i", real=true) end # Set the joint velocity vector of the MechanismState to a new vector of symbolic variables v = velocity(x) for i in eachindex(v) v[i] = symbols("v_$i", real=true) end # ## Compute dynamical quantities in symbolic form # Mass matrix simplify.(mass_matrix(x)) # Kinetic energy simplify(kinetic_energy(x)) # Potential energy simplify(gravitational_potential_energy(x))
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
4011
# # @__NAME__ # PREAMBLE # PKG_SETUP # ## Floating-point error # In computers, real numbers are commonly approximated using floating-point numbers, such as Julia's `Float64`. Unfortunately, not all real numbers can be exactly represented as a finite-size floating-point number, and the results of operations on floating-point numbers can only approximate the results of applying the operation to a true real number. This results in peculiarities like: 2.6 - 0.7 - 1.9 # IntervalArithmetic.jl can be used to quantify floating point error, by computing _rigorous_ worst-case bounds on floating point error, within which the true result is _guaranteed_ to lie. using Pkg # hide Pkg.activate(@__DIR__) # hide Pkg.instantiate() # hide using IntervalArithmetic # IntervalArithmetic.jl provides the `Interval` type, which stores an upper and a lower bound: i = Interval(1.0, 2.0) #- dump(i) # IntervalArithmetic.jl provides overloads for most common Julia functions that take these bounds into account. For example: i + i #- sin(i) # Note that the bounds computed by IntervalArithmetic.jl take floating point error into account. Also note that a given real number, once converted to (approximated by) a floating-point number may not be equal to the original real number. To rigorously construct an `Interval` that contains a given real number as an input, IntervalArithmetic.jl provides the `@interval` macro: i = @interval(2.9) i.lo === i.hi #- dump(i) # Compare this to i = Interval(2.9) i.lo === i.hi #- dump(i) # As an example, consider again the peculiar result from before, now using interval arithmetic: i = @interval(2.6) - @interval(0.7) - @interval(1.9) # showing that the true result, `0`, is indeed in the guaranteed interval, and indeed: using Test @test (2.6 - 0.7 - 1.9) ∈ i # ## Accuracy of RigidBodyDynamics.jl's `mass_matrix` # Let's use IntervalArithmetic.jl to establish rigorous bounds on the accuracy of the accuracy of the `mass_matrix` algorithm for the Acrobot (double pendulum) in a certain configuration. Let's get started. using RigidBodyDynamics # We'll create a `Mechanism` by parsing the Acrobot URDF, passing in `Interval{Float64}` as the type used to store the parameters (inertias, link lengths, etc.) of the mechanism. Note that the parameters parsed from the URDF are treated as floating point numbers (i.e., like `Interval(2.9)` instead of `@interval(2.9)` above). const T = Interval{Float64} srcdir = dirname(pathof(RigidBodyDynamics)) urdf = joinpath(srcdir, "..", "test", "urdf", "Acrobot.urdf") const mechanism = parse_urdf(urdf; scalar_type=T) state = MechanismState(mechanism) # Let's set the initial joint angle of the shoulder joint to the smallest `Interval{Float64}` containing the real number $1$, and similarly for the elbow joint: shoulder, elbow = joints(mechanism) set_configuration!(state, shoulder, @interval(1)) set_configuration!(state, elbow, @interval(2)); # And now we can compute the mass matrix as normal: M = mass_matrix(state) # Woah, those bounds look pretty big. RigidBodyDynamics.jl must not be very accurate! Actually, things aren't so bad; the issue is just that IntervalArithmetic.jl isn't kidding when it comes to guaranteed bounds, and that includes printing the numbers in shortened form. Here are the lengths of the intervals: err = map(x -> x.hi - x.lo, M) #- @test maximum(abs, err) ≈ 0 atol = 1e-14 # ## Rigorous (worst-case) uncertainty propagation # IntervalArithmetic.jl can also be applied to propagate uncertainty in a rigorous way when the inputs themselves are uncertain. Consider for example the case that we only know the joint angles up to $\pm 0.05$ radians: set_configuration!(state, shoulder, @interval(0.95, 1.05)) set_configuration!(state, elbow, @interval(1.95, 2.05)); # and let's compute bounds on the center of mass position: center_of_mass(state) # Note that the bounds on the $y$-coordinate are very tight, since our mechanism only lives in the $x$-$z$ plane.
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
5886
using Pkg Pkg.activate(@__DIR__) Pkg.instantiate() using RigidBodyDynamics using RigidBodyDynamics.OdeIntegrators using Random using Profile using BenchmarkTools using LinearAlgebra # Due to https://github.com/JuliaRobotics/RigidBodyDynamics.jl/issues/500: BLAS.set_num_threads(1) const ScalarType = Float64 # const ScalarType = Float32 function create_floating_atlas() url = "https://raw.githubusercontent.com/RobotLocomotion/drake/6e3ca768cbaabf15d0f2bed0fb5bd703fa022aa5/drake/examples/Atlas/urdf/atlas_minimal_contact.urdf" urdf = RigidBodyDynamics.cached_download(url, "atlas.urdf") atlas = parse_urdf(urdf, scalar_type=ScalarType, floating=true) atlas end function create_benchmark_suite() suite = BenchmarkGroup() mechanism = create_floating_atlas() remove_fixed_tree_joints!(mechanism) state = MechanismState{ScalarType}(mechanism) result = DynamicsResult{ScalarType}(mechanism) nv = num_velocities(state) mat = MomentumMatrix(root_frame(mechanism), Matrix{ScalarType}(undef, 3, nv), Matrix{ScalarType}(undef, 3, nv)) torques = similar(velocity(state)) rfoot = findbody(mechanism, "r_foot") lhand = findbody(mechanism, "l_hand") p = path(mechanism, rfoot, lhand) jac = GeometricJacobian(default_frame(lhand), default_frame(rfoot), root_frame(mechanism), Matrix{ScalarType}(undef, 3, nv), Matrix{ScalarType}(undef, 3, nv)) suite["mass_matrix!"] = @benchmarkable(begin setdirty!($state) mass_matrix!($(result.massmatrix), $state) end, setup = rand!($state), evals = 10) suite["dynamics_bias!"] = @benchmarkable(begin setdirty!($state) dynamics_bias!($result, $state) end, setup = begin rand!($state) end, evals = 10) suite["inverse_dynamics!"] = @benchmarkable(begin setdirty!($state) inverse_dynamics!($torques, $(result.jointwrenches), $(result.accelerations), $state, v̇, externalwrenches) end, setup = begin v̇ = similar(velocity($state)) rand!(v̇) externalwrenches = RigidBodyDynamics.BodyDict(convert(BodyID, body) => rand(Wrench{ScalarType}, root_frame($mechanism)) for body in bodies($mechanism)) rand!($state) end, evals = 10) suite["dynamics!"] = @benchmarkable(begin setdirty!($state) dynamics!($result, $state, τ, externalwrenches) end, setup = begin rand!($state) τ = similar(velocity($state)) rand!(τ) externalwrenches = RigidBodyDynamics.BodyDict(convert(BodyID, body) => rand(Wrench{ScalarType}, root_frame($mechanism)) for body in bodies($mechanism)) end, evals = 10) suite["momentum_matrix!"] = @benchmarkable(begin setdirty!($state) momentum_matrix!($mat, $state) end, setup = rand!($state), evals = 10) suite["geometric_jacobian!"] = @benchmarkable(begin setdirty!($state) geometric_jacobian!($jac, $state, $p) end, setup = rand!($state), evals = 10) suite["mass_matrix! and geometric_jacobian!"] = @benchmarkable(begin setdirty!($state) mass_matrix!($(result.massmatrix), $state) geometric_jacobian!($jac, $state, $p) end, setup = begin rand!($state) end, evals = 10) suite["momentum"] = @benchmarkable(begin setdirty!($state) momentum($state) end, setup = rand!($state), evals = 10) suite["momentum_rate_bias"] = @benchmarkable(begin setdirty!($state) momentum_rate_bias($state) end, setup = rand!($state), evals = 10) suite["kinetic_energy"] = @benchmarkable(begin setdirty!($state) kinetic_energy($state) end, setup = rand!($state), evals = 10) suite["gravitational_potential_energy"] = @benchmarkable(begin setdirty!($state) gravitational_potential_energy($state) end, setup = rand!($state), evals = 10) suite["center_of_mass"] = @benchmarkable(begin setdirty!($state) center_of_mass($state) end, setup = rand!($state), evals = 10) let Δt = 1e-4 final_time = 0.1 tableau = runge_kutta_4(ScalarType) storage = RingBufferStorage{ScalarType}(state, ceil(Int64, final_time / Δt * 1.001)) # very rough overestimate of number of time steps passive_dynamics! = let result=result # https://github.com/JuliaLang/julia/issues/15276 function (v̇::AbstractArray, ṡ::AbstractArray, t, state) dynamics!(result, state) copyto!(v̇, result.v̇) copyto!(ṡ, result.ṡ) nothing end end integrator = MuntheKaasIntegrator(state, passive_dynamics!, tableau, storage) suite["simulate tree"] = @benchmarkable(begin integrate($integrator, $final_time, $Δt) end, setup = rand!($state), evals = 10) end mcmechanism = maximal_coordinates(mechanism) mcstate = MechanismState{ScalarType}(mcmechanism) mcresult = DynamicsResult{ScalarType}(mcmechanism) suite["constraint_jacobian!"] = @benchmarkable(begin setdirty!($mcstate) RigidBodyDynamics.constraint_jacobian!($(mcresult.constraintjacobian), $(mcresult.constraintrowranges), $mcstate) end, setup = rand!($mcstate), evals = 10) suite["constraint_bias!"] = @benchmarkable(begin setdirty!($mcstate) RigidBodyDynamics.constraint_bias!($(mcresult.constraintbias), $mcstate) end, setup = rand!($mcstate), evals = 10) suite end function runbenchmarks() suite = create_benchmark_suite() Profile.clear_malloc_data() overhead = BenchmarkTools.estimate_overhead() Random.seed!(1) results = run(suite, verbose=true, overhead=overhead, gctrial=false) for result in results println("$(first(result)):") display(last(result)) println() end end runbenchmarks()
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
4448
module RigidBodyDynamics using Random using LinearAlgebra using StaticArrays using Rotations using TypeSortedCollections using DocStringExtensions using Reexport using Base.Iterators: filter, flatten using Base: @propagate_inbounds, promote_eltype # mechanism-related types export RigidBody, Joint, JointType, Mechanism, MechanismState, DynamicsResult, StateCache, DynamicsResultCache, SegmentedVectorCache # specific joint types export QuaternionFloating, SPQuatFloating, Revolute, Prismatic, Fixed, Planar, QuaternionSpherical, SinCosRevolute # basic functionality related to mechanism structure export has_defined_inertia, mass, default_frame, frame_before, frame_after, joint_type, add_frame!, root_frame, root_body, non_root_bodies, isroot, bodies, path, joints, tree_joints, non_tree_joints, successor, predecessor, in_joints, out_joints, joints_to_children, joint_to_parent, num_bodies, num_positions, num_velocities, num_additional_states, num_constraints, isfloating, configuration_range, velocity_range, has_fixed_subspaces, spatial_inertia!, # TODO: rename to set_spatial_inertia! add_body_fixed_frame!, fixed_transform, findbody, findjoint, body_fixed_frame_to_body, position_bounds, velocity_bounds, effort_bounds # mechanism creation and modification export rand_chain_mechanism, rand_tree_mechanism, rand_floating_tree_mechanism, attach!, remove_joint!, replace_joint!, maximal_coordinates, submechanism, remove_fixed_tree_joints!, remove_subtree! # contact-related functionality export # note: contact-related functionality may be changed significantly in the future contact_points, add_contact_point!, add_environment_primitive! # state-dependent functionality export local_coordinates!, global_coordinates!, configuration_derivative!, configuration_derivative, velocity_to_configuration_derivative!, # TODO: consider merging with configuration_derivative! configuration_derivative_to_velocity!, configuration_derivative_to_velocity_adjoint!, configuration, velocity, additional_state, joint_transform, motion_subspace, constraint_wrench_subspace, bias_acceleration, spatial_inertia, crb_inertia, twist_wrt_world, relative_twist, transform_to_root, relative_transform, setdirty!, rand_configuration!, zero_configuration!, rand_velocity!, zero_velocity!, set_configuration!, set_velocity!, set_additional_state!, zero!, # TODO: remove normalize_configuration!, principal_value!, center_of_mass, geometric_jacobian, geometric_jacobian!, point_velocity, point_acceleration, point_jacobian, point_jacobian!, relative_acceleration, kinetic_energy, gravitational_potential_energy, spatial_accelerations!, mass_matrix!, mass_matrix, momentum, momentum_matrix!, momentum_matrix, momentum_rate_bias, inverse_dynamics!, inverse_dynamics, dynamics_bias!, dynamics_bias, dynamics!, simulate # Utility export SegmentedVector, JointDict, BodyDict, JointID, BodyID, segments # Type aliases const ModifiedRodriguesParam = Rotations.MRP include(joinpath("custom_collections", "custom_collections.jl")) include(joinpath("graphs", "Graphs.jl")) include(joinpath("spatial", "Spatial.jl")) include("contact.jl") include("pdcontrol.jl") @reexport using .Spatial using .CustomCollections using .Contact using .Graphs using .PDControl import .Spatial: rotation, translation, transform, center_of_mass, newton_euler, kinetic_energy include("util.jl") include("joint.jl") include(joinpath("joint_types", "joint_types.jl")) include("rigid_body.jl") include("mechanism.jl") include("mechanism_modification.jl") include("mechanism_state.jl") include("dynamics_result.jl") include("caches.jl") include("mechanism_algorithms.jl") include("ode_integrators.jl") include("simulate.jl") include(joinpath("urdf", "URDF.jl")) @reexport using .URDF # import these for MechanismGeometries compatibility. TODO: stop importing these after updating MechanismGeometries. import .URDF: parse_scalar, parse_vector, parse_pose end # module
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
3552
abstract type AbstractTypeDict end function valuetype end function makevalue end function Base.getindex(c::C, ::Type{T}) where {C<:AbstractTypeDict, T} ReturnType = valuetype(C, T) key = objectid(T) @inbounds for i in eachindex(c.keys) if c.keys[i] === key return c.values[i]::ReturnType end end value = makevalue(c, T)::ReturnType push!(c.keys, key) push!(c.values, value) value::ReturnType end """ $(TYPEDEF) A container that manages the creation and storage of [`MechanismState`](@ref) objects of various scalar types, associated with a given `Mechanism`. A `StateCache` can be used to write generic functions that use `MechanismState` objects, while avoiding overhead due to the construction of a new `MechanismState` with a given scalar type every time the function is called. # Examples ```julia-repl julia> mechanism = rand_tree_mechanism(Float64, Revolute{Float64}, Prismatic{Float64}, QuaternionFloating{Float64}); julia> cache = StateCache(mechanism) StateCache{…} julia> state32 = cache[Float32] MechanismState{Float32, Float64, Float64, …}(…) julia> cache[Float32] === state32 true julia> cache[Float64] MechanismState{Float64, Float64, Float64, …}(…) ``` """ struct StateCache{M, JointCollection} <: AbstractTypeDict mechanism::Mechanism{M} keys::Vector{UInt} values::Vector{MechanismState} end function StateCache(mechanism::Mechanism{M}) where M JointCollection = typeof(TypeSortedCollection(joints(mechanism))) StateCache{M, JointCollection}(mechanism, [], []) end Base.show(io::IO, ::StateCache) = print(io, "StateCache{…}(…)") @inline function valuetype(::Type{StateCache{M, JC}}, ::Type{X}) where {M, JC, X} C = promote_type(X, M) MechanismState{X, M, C, JC} end @inline makevalue(c::StateCache, ::Type{X}) where X = MechanismState{X}(c.mechanism) """ $(TYPEDEF) A container that manages the creation and storage of [`DynamicsResult`](@ref) objects of various scalar types, associated with a given `Mechanism`. Similar to [`StateCache`](@ref). """ struct DynamicsResultCache{M} <: AbstractTypeDict mechanism::Mechanism{M} keys::Vector{UInt} values::Vector{DynamicsResult{<:Any, M}} end Base.show(io::IO, ::DynamicsResultCache{M}) where {M} = print(io, "DynamicsResultCache{$M}(…)") DynamicsResultCache(mechanism::Mechanism{M}) where {M} = DynamicsResultCache{M}(mechanism, [], []) @inline valuetype(::Type{DynamicsResultCache{M}}, ::Type{T}) where {M, T} = DynamicsResult{T, M} @inline makevalue(c::DynamicsResultCache, ::Type{T}) where {T} = DynamicsResult{T}(c.mechanism) """ $(TYPEDEF) A container that manages the creation and storage of heterogeneously typed [`SegmentedVector`](@ref) objects. Similar to [`StateCache`](@ref). """ struct SegmentedVectorCache{K, KeyRange<:AbstractUnitRange{K}} <: AbstractTypeDict ranges::IndexDict{K, KeyRange, UnitRange{Int}} length::Int keys::Vector{UInt} values::Vector{SegmentedVector} end function SegmentedVectorCache(ranges::IndexDict{K, KeyRange, UnitRange{Int}}) where {K, KeyRange<:AbstractUnitRange{K}} SegmentedVectorCache(ranges, sum(length, values(ranges)), Vector{UInt}(), Vector{SegmentedVector}()) end @inline function valuetype(::Type{SegmentedVectorCache{K, KeyRange}}, ::Type{T}) where {K, T, KeyRange} SegmentedVector{K, T, KeyRange, Vector{T}} end @inline function makevalue(c::SegmentedVectorCache{K, KeyRange}, ::Type{T}) where {K, T, KeyRange} SegmentedVector{K, T, KeyRange}(Vector{T}(undef, c.length), c.ranges) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
9384
module Contact using LinearAlgebra using RigidBodyDynamics.Spatial using StaticArrays using Base: promote_eltype # base types export SoftContactModel, SoftContactState, SoftContactStateDeriv, ContactPoint, ContactEnvironment, HalfSpace3D # interface functions export num_states, location, contact_model, contact_dynamics!, reset!, point_inside, separation, detect_contact # specific models export HuntCrossleyModel, hunt_crossley_hertz export ViscoelasticCoulombModel, ViscoelasticCoulombState, ViscoelasticCoulombStateDeriv # defaults export DefaultContactPoint, DefaultSoftContactState, DefaultSoftContactStateDeriv # Normal force model/state/state derivative interface: # * `normal_force(model, state, z::Number, ż::Number)`: return the normal force given penetration `z` and penetration velocity `ż` # * `num_states(model)`: return the number of state variables associated with the model # * `state(model, statevec, frame)`: create a new state associated with the model # * `state_derivative(model, statederivvec, frame)`: create a new state derivative associated with the model # * `reset!(state)`: resets the contact state # * `dynamics!(state_deriv, model, state, fnormal)`: sets state_deriv given the current state and the normal force # Friction model/state/state derivative interface: # * `friction_force(model, state, fnormal::Number, tangential_velocity::FreeVector3D)`: return the friction force given normal force `fnormal` and tangential velocity `tangential_velocity` # * `num_states(model)`: return the number of state variables associated with the model # * `state(model, statevec, frame)`: create a new state associated with the model # * `state_derivative(model, statederivvec, frame)`: create a new state derivative associated with the model # * `reset!(state)`: resets the contact state # * `dynamics!(state_deriv, model, state, ftangential)`: sets state_deriv given the current state and the tangential force force ## SoftContactModel and related types. struct SoftContactModel{N, F} normal::N friction::F end struct SoftContactState{N, F} normal::N friction::F end struct SoftContactStateDeriv{N, F} normal::N friction::F end normal_force_model(model::SoftContactModel) = model.normal friction_model(model::SoftContactModel) = model.friction normal_force_state(state::SoftContactState) = state.normal friction_state(state::SoftContactState) = state.friction normal_force_state_deriv(deriv::SoftContactStateDeriv) = deriv.normal friction_state_deriv(deriv::SoftContactStateDeriv) = deriv.friction num_states(model::SoftContactModel) = num_states(normal_force_model(model)) + num_states(friction_model(model)) for (fun, returntype) in [(:state, :SoftContactState), (:state_derivative, :SoftContactStateDeriv)] @eval function $returntype(model::SoftContactModel, vec::AbstractVector, frame::CartesianFrame3D) nnormal = num_states(normal_force_model(model)) nfriction = num_states(friction_model(model)) vecnormal = view(vec, 1 : nnormal - 1) vecfriction = view(vec, 1 + nnormal : nnormal + nfriction) $returntype($fun(normal_force_model(model), vecnormal, frame), $fun(friction_model(model), vecfriction, frame)) end end reset!(state::SoftContactState) = (reset!(normal_force_state(state)); reset!(friction_state(state))) zero!(deriv::SoftContactStateDeriv) = (zero!(friction_state_deriv(deriv)); zero!(friction_state_deriv(deriv))) ## ContactPoint mutable struct ContactPoint{T, M <: SoftContactModel} location::Point3D{SVector{3, T}} model::M end location(point::ContactPoint) = point.location contact_model(point::ContactPoint) = point.model function contact_dynamics!(state_deriv::SoftContactStateDeriv, state::SoftContactState, model::SoftContactModel, penetration::Number, velocity::FreeVector3D, normal::FreeVector3D) @boundscheck penetration >= 0 || error("penetration must be nonnegative") z = penetration ż = -dot(velocity, normal) # penetration velocity fnormal = max(normal_force(normal_force_model(model), normal_force_state(state), z, ż), 0) dynamics!(normal_force_state_deriv(state_deriv), normal_force_model(model), normal_force_state(state), fnormal) tangential_velocity = velocity + ż * normal ftangential = friction_force(friction_model(model), friction_state(state), fnormal, tangential_velocity) dynamics!(friction_state_deriv(state_deriv), friction_model(model), friction_state(state), ftangential) fnormal * normal + ftangential end ## Models with no state reset!(::Nothing) = nothing zero!(::Nothing) = nothing ## Normal contact models struct HuntCrossleyModel{T} # (2) in Marhefka, Orin, "A Compliant Contact Model with Nonlinear Damping for Simulation of Robotic Systems" k::T λ::T n::T end function hunt_crossley_hertz(; k = 50e3, α = 0.2) λ = 3/2 * α * k # (12) in Marhefka, Orin HuntCrossleyModel(k, λ, 3/2) end num_states(::HuntCrossleyModel) = 0 state(::HuntCrossleyModel, ::AbstractVector, ::CartesianFrame3D) = nothing state_derivative(::HuntCrossleyModel, ::AbstractVector, ::CartesianFrame3D) = nothing function normal_force(model::HuntCrossleyModel, ::Nothing, z, ż) zn = z^model.n f = model.λ * zn * ż + model.k * zn # (2) in Marhefka, Orin (note: z is penetration, returning repelling force) end dynamics!(ẋ::Nothing, model::HuntCrossleyModel, state::Nothing, fnormal::Number) = nothing # Friction models struct ViscoelasticCoulombModel{T} # See section 11.8 of Featherstone, "Rigid Body Dynamics Algorithms", 2008 μ::T k::T b::T end mutable struct ViscoelasticCoulombState{V} tangential_displacement::FreeVector3D{V} # Use a 3-vector; technically only need one state for each tangential direction, but this is easier to work with. end mutable struct ViscoelasticCoulombStateDeriv{V} deriv::FreeVector3D{V} end num_states(::ViscoelasticCoulombModel) = 3 function state(::ViscoelasticCoulombModel, statevec::AbstractVector, frame::CartesianFrame3D) ViscoelasticCoulombState(FreeVector3D(frame, statevec)) end function state_derivative(::ViscoelasticCoulombModel, statederivvec::AbstractVector, frame::CartesianFrame3D) ViscoelasticCoulombStateDeriv(FreeVector3D(frame, statederivvec)) end reset!(state::ViscoelasticCoulombState) = fill!(state.tangential_displacement.v, 0) zero!(deriv::ViscoelasticCoulombStateDeriv) = fill!(deriv.deriv.v, 0) function friction_force(model::ViscoelasticCoulombModel, state::ViscoelasticCoulombState, fnormal, tangential_velocity::FreeVector3D) T = typeof(fnormal) μ = model.μ k = model.k b = model.b x = convert(FreeVector3D{SVector{3, T}}, state.tangential_displacement) v = tangential_velocity # compute friction force that would be needed to avoid slip fstick = -k * x - b * v # limit friction force to lie within friction cone fstick_norm² = dot(fstick, fstick) fstick_max_norm² = (μ * fnormal)^2 ftangential = if fstick_norm² > fstick_max_norm² fstick * sqrt(fstick_max_norm² / fstick_norm²) else fstick end end function dynamics!(ẋ::ViscoelasticCoulombStateDeriv, model::ViscoelasticCoulombModel, state::ViscoelasticCoulombState, ftangential::FreeVector3D) k = model.k b = model.b x = state.tangential_displacement @framecheck ẋ.deriv.frame x.frame ẋ.deriv.v .= (-k .* x.v .- ftangential.v) ./ b end ## VectorSegment: type of a view of a vector const VectorSegment{T} = SubArray{T,1,Array{T, 1},Tuple{UnitRange{Int64}},true} # TODO: a bit too specific const DefaultContactPoint{T} = ContactPoint{T,SoftContactModel{HuntCrossleyModel{T},ViscoelasticCoulombModel{T}}} const DefaultSoftContactState{T} = SoftContactState{Nothing, ViscoelasticCoulombState{VectorSegment{T}}} const DefaultSoftContactStateDeriv{T} = SoftContactStateDeriv{Nothing, ViscoelasticCoulombStateDeriv{VectorSegment{T}}} # Contact detection # TODO: should probably move this somewhere else mutable struct HalfSpace3D{T} point::Point3D{SVector{3, T}} outward_normal::FreeVector3D{SVector{3, T}} function HalfSpace3D(point::Point3D{SVector{3, T}}, outward_normal::FreeVector3D{SVector{3, T}}) where {T} @framecheck point.frame outward_normal.frame new{T}(point, normalize(outward_normal)) end end frame(halfspace::HalfSpace3D) = halfspace.point.frame function HalfSpace3D(point::Point3D, outward_normal::FreeVector3D) T = promote_eltype(point, outward_normal) HalfSpace3D(convert(Point3D{SVector{3, T}}, point), convert(FreeVector3D{SVector{3, T}}, outward_normal)) end Base.eltype(::Type{HalfSpace3D{T}}) where {T} = T separation(halfspace::HalfSpace3D, p::Point3D) = dot(p - halfspace.point, halfspace.outward_normal) point_inside(halfspace::HalfSpace3D, p::Point3D) = separation(halfspace, p) <= 0 detect_contact(halfspace::HalfSpace3D, p::Point3D) = separation(halfspace, p), halfspace.outward_normal # ContactEnvironment mutable struct ContactEnvironment{T} halfspaces::Vector{HalfSpace3D{T}} ContactEnvironment{T}() where {T} = new{T}(HalfSpace3D{T}[]) end Base.push!(environment::ContactEnvironment, halfspace::HalfSpace3D) = push!(environment.halfspaces, halfspace) Base.length(environment::ContactEnvironment) = length(environment.halfspaces) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
5239
""" $(TYPEDEF) Stores variables related to the dynamics of a `Mechanism`, e.g. the `Mechanism`'s mass matrix and joint acceleration vector. Type parameters: * `T`: the scalar type of the dynamics-related variables. * `M`: the scalar type of the `Mechanism`. """ mutable struct DynamicsResult{T, M} mechanism::Mechanism{M} massmatrix::Symmetric{T, Matrix{T}} dynamicsbias::SegmentedVector{JointID, T, Base.OneTo{JointID}, Vector{T}} constraintjacobian::Matrix{T} constraintbias::SegmentedVector{JointID, T, UnitRange{JointID}, Vector{T}} constraintrowranges::IndexDict{JointID, UnitRange{JointID}, UnitRange{Int}} q̇::SegmentedVector{JointID, T, Base.OneTo{JointID}, Vector{T}} v̇::SegmentedVector{JointID, T, Base.OneTo{JointID}, Vector{T}} ṡ::Vector{T} λ::Vector{T} contactwrenches::BodyDict{Wrench{T}} totalwrenches::BodyDict{Wrench{T}} accelerations::BodyDict{SpatialAcceleration{T}} jointwrenches::BodyDict{Wrench{T}} # TODO: index by joint tree index? contact_state_derivatives::BodyDict{Vector{Vector{DefaultSoftContactStateDeriv{T}}}} # see solve_dynamics! for meaning of the following variables: L::Matrix{T} # lower triangular A::Matrix{T} # symmetric z::Vector{T} Y::Matrix{T} function DynamicsResult{T}(mechanism::Mechanism{M}) where {T, M} nq = num_positions(mechanism) nv = num_velocities(mechanism) nc = num_constraints(mechanism) massmatrix = Symmetric(Matrix{T}(undef, nv, nv), :L) dynamicsbias = SegmentedVector(Vector{T}(undef, nv), tree_joints(mechanism), num_velocities) constraintjacobian = Matrix{T}(undef, nc, nv) constraintbias = SegmentedVector{JointID, T, UnitRange{JointID}}( Vector{T}(undef, nc), non_tree_joints(mechanism), num_constraints) constraintrowranges = ranges(constraintbias) q̇ = SegmentedVector(Vector{T}(undef, nq), tree_joints(mechanism), num_positions) v̇ = SegmentedVector(Vector{T}(undef, nv), tree_joints(mechanism), num_velocities) ṡ = Vector{T}(undef, num_additional_states(mechanism)) λ = Vector{T}(undef, nc) rootframe = root_frame(mechanism) contactwrenches = BodyDict{Wrench{T}}(b => zero(Wrench{T}, rootframe) for b in bodies(mechanism)) totalwrenches = BodyDict{Wrench{T}}(b => zero(Wrench{T}, rootframe) for b in bodies(mechanism)) accelerations = BodyDict{SpatialAcceleration{T}}( b => zero(SpatialAcceleration{T}, rootframe, rootframe, rootframe) for b in bodies(mechanism)) jointwrenches = BodyDict{Wrench{T}}(b => zero(Wrench{T}, rootframe) for b in bodies(mechanism)) contact_state_derivs = BodyDict{Vector{Vector{DefaultSoftContactStateDeriv{T}}}}( b => Vector{Vector{DefaultSoftContactStateDeriv{T}}}() for b in bodies(mechanism)) startind = Ref(1) for body in bodies(mechanism) for point::DefaultContactPoint{M} in contact_points(body) model = contact_model(point) n = num_states(model) push!(contact_state_derivs[body], collect(begin ṡ_part = view(ṡ, startind[] : startind[] + n - 1) contact_state_deriv = SoftContactStateDeriv(model, ṡ_part, root_frame(mechanism)) startind[] += n contact_state_deriv end for j = 1 : length(mechanism.environment))) end end L = Matrix{T}(undef, nv, nv) A = Matrix{T}(undef, nc, nc) z = Vector{T}(undef, nv) Y = Matrix{T}(undef, nc, nv) new{T, M}(mechanism, massmatrix, dynamicsbias, constraintjacobian, constraintbias, constraintrowranges, q̇, v̇, ṡ, λ, contactwrenches, totalwrenches, accelerations, jointwrenches, contact_state_derivs, L, A, z, Y) end end DynamicsResult(mechanism::Mechanism{M}) where {M} = DynamicsResult{M}(mechanism) function Base.copyto!(ẋ::AbstractVector, result::DynamicsResult) nq = length(result.q̇) nv = length(result.v̇) ns = length(result.ṡ) @boundscheck length(ẋ) == nq + nv + ns || throw(DimensionMismatch()) @inbounds copyto!(ẋ, 1, result.q̇, 1, nq) @inbounds copyto!(ẋ, nq + 1, result.v̇, 1, nv) @inbounds copyto!(ẋ, nq + nv + 1, result.ṡ, 1, ns) ẋ end contact_state_derivatives(result::DynamicsResult, body::Union{<:RigidBody, BodyID}) = result.contact_state_derivatives[body] contact_wrench(result::DynamicsResult, body::Union{<:RigidBody, BodyID}) = result.contactwrenches[body] set_contact_wrench!(result::DynamicsResult, body::Union{<:RigidBody, BodyID}, wrench::Wrench) = (result.contactwrenches[body] = wrench) acceleration(result::DynamicsResult, body::Union{<:RigidBody, BodyID}) = result.accelerations[body] set_acceleration!(result::DynamicsResult, body::Union{<:RigidBody, BodyID}, accel::SpatialAcceleration) = (result.accelerations[body] = accel) joint_wrench(result::DynamicsResult, body::Union{<:RigidBody, BodyID}) = result.jointwrenches[body] set_joint_wrench!(result::DynamicsResult, body::Union{<:RigidBody, BodyID}, wrench::Wrench) = (result.jointwrenches[body] = wrench)
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
17467
@indextype JointID """ $(TYPEDEF) The abstract supertype of all concrete joint types. """ abstract type JointType{T} end Base.eltype(::Type{<:JointType{T}}) where {T} = T isfloating(::T) where {T<:JointType} = isfloating(T) num_velocities(::T) where {T<:JointType} = num_velocities(T) num_positions(::T) where {T<:JointType} = num_positions(T) num_constraints(::Type{T}) where {T<:JointType} = 6 - num_velocities(T) """ $(TYPEDEF) A joint represents a kinematic restriction of the relative twist between two rigid bodies to a linear subspace of dimension ``k``. A joint has a direction. The rigid body before the joint is called the joint's predecessor, and the rigid body after the joint is its successor. The state related to the joint is parameterized by two sets of variables, namely * a vector ``q \\in \\mathcal{Q}``, parameterizing the relative homogeneous transform. * a vector ``v \\in \\mathbb{R}^k``, parameterizing the relative twist. The twist of the successor with respect to the predecessor is a linear function of ``v``. For some joint types (notably those using a redundant representation of relative orientation, such as a unit quaternion), ``\\dot{q}``, the time derivative of ``q``, may not be the same as ``v``. However, an invertible linear transformation exists between ``\\dot{q}`` and ``v``. See also: * Definition 2.9 in Duindam, "Port-Based Modeling and Control for Efficient Bipedal Walking Robots", 2006. * Section 4.4 of Featherstone, "Rigid Body Dynamics Algorithms", 2008. """ struct Joint{T, JT<:JointType{T}} name::String frame_before::CartesianFrame3D frame_after::CartesianFrame3D joint_type::JT id::Base.RefValue{JointID} joint_to_predecessor::Base.RefValue{Transform3D{T}} joint_to_successor::Base.RefValue{Transform3D{T}} position_bounds::Vector{Bounds{T}} velocity_bounds::Vector{Bounds{T}} effort_bounds::Vector{Bounds{T}} function Joint(name::String, frame_before::CartesianFrame3D, frame_after::CartesianFrame3D, joint_type::JointType{T}; position_bounds::Vector{Bounds{T}}=fill(Bounds{T}(), num_positions(joint_type)), velocity_bounds::Vector{Bounds{T}}=fill(Bounds{T}(), num_velocities(joint_type)), effort_bounds::Vector{Bounds{T}}=fill(Bounds{T}(), num_velocities(joint_type))) where {T} JT = typeof(joint_type) id = Ref(JointID(-1)) joint_to_predecessor = Ref(one(Transform3D{T}, frame_before)) joint_to_successor = Ref(one(Transform3D{T}, frame_after)) new{T, JT}(name, frame_before, frame_after, joint_type, id, joint_to_predecessor, joint_to_successor, position_bounds, velocity_bounds, effort_bounds) end end function Joint(name::String, jtype::JointType; kw...) Joint(name, CartesianFrame3D(string("before_", name)), CartesianFrame3D(string("after_", name)), jtype; kw...) end Base.print(io::IO, joint::Joint) = print(io, joint.name) frame_before(joint::Joint) = joint.frame_before frame_after(joint::Joint) = joint.frame_after joint_type(joint::Joint) = joint.joint_type joint_to_predecessor(joint::Joint) = joint.joint_to_predecessor[] joint_to_successor(joint::Joint) = joint.joint_to_successor[] """ $(SIGNATURES) Return a `Vector{Bounds{T}}` giving the upper and lower bounds of the configuration for `joint` """ position_bounds(joint::Joint) = joint.position_bounds """ $(SIGNATURES) Return a `Vector{Bounds{T}}` giving the upper and lower bounds of the velocity for `joint` """ velocity_bounds(joint::Joint) = joint.velocity_bounds """ $(SIGNATURES) Return a `Vector{Bounds{T}}` giving the upper and lower bounds of the effort for `joint` """ effort_bounds(joint::Joint) = joint.effort_bounds JointID(joint::Joint) = joint.id[] Base.convert(::Type{JointID}, joint::Joint) = JointID(joint) @inline RigidBodyDynamics.Graphs.edge_id_type(::Type{<:Joint}) = JointID @inline RigidBodyDynamics.Graphs.edge_id(joint::Joint) = convert(JointID, joint) @inline RigidBodyDynamics.Graphs.set_edge_id!(joint::Joint, id::JointID) = (joint.id[] = id) function RigidBodyDynamics.Graphs.flip_direction(joint::Joint) jtype = RigidBodyDynamics.flip_direction(joint_type(joint)) Joint(string(joint), frame_after(joint), frame_before(joint), jtype; position_bounds = .-joint.position_bounds, velocity_bounds = .-joint.velocity_bounds, effort_bounds = .-joint.effort_bounds) end function set_joint_to_predecessor!(joint::Joint, tf::Transform3D) @framecheck tf.from frame_before(joint) joint.joint_to_predecessor[] = tf joint end function set_joint_to_successor!(joint::Joint, tf::Transform3D) @framecheck tf.from frame_after(joint) joint.joint_to_successor[] = tf joint end function Base.show(io::IO, joint::Joint) if get(io, :compact, false) print(io, joint) else print(io, "Joint \"$(string(joint))\": $(joint.joint_type)") end end num_positions(itr) = reduce((val, joint) -> val + num_positions(joint), 0, itr) num_velocities(itr) = reduce((val, joint) -> val + num_velocities(joint), 0, itr) @inline function check_num_positions(joint::Joint, vec::AbstractVector) length(vec) == num_positions(joint) || error("wrong size") nothing end @inline function check_num_velocities(joint::Joint, vec::AbstractVector) length(vec) == num_velocities(joint) || error("wrong size") nothing end @propagate_inbounds function set_configuration!(q::AbstractVector, joint::Joint, config::AbstractVector) @boundscheck check_num_positions(joint, q) copyto!(q, config) q end @propagate_inbounds function set_velocity!(v::AbstractVector, joint::Joint, vel::AbstractVector) @boundscheck check_num_velocities(joint, v) copyto!(v, vel) v end """ $(SIGNATURES) Return the length of the configuration vector of `joint`. """ @inline num_positions(joint::Joint) = num_positions(joint.joint_type) """ $(SIGNATURES) Return the length of the velocity vector of `joint`. """ @inline num_velocities(joint::Joint) = num_velocities(joint.joint_type) """ $(SIGNATURES) Return the number of constraints imposed on the relative twist between the joint's predecessor and successor """ @inline num_constraints(joint::Joint) = 6 - num_velocities(joint) """ $(SIGNATURES) Return a `Transform3D` representing the homogeneous transform from the frame after the joint to the frame before the joint for joint configuration vector ``q``. """ @propagate_inbounds function joint_transform(joint::Joint, q::AbstractVector) @boundscheck check_num_positions(joint, q) @inbounds return joint_transform(joint.joint_type, frame_after(joint), frame_before(joint), q) end """ $(SIGNATURES) Return a basis for the motion subspace of the joint in configuration ``q``. The motion subspace basis is a ``6 \\times k`` matrix, where ``k`` is the dimension of the velocity vector ``v``, that maps ``v`` to the twist of the joint's successor with respect to its predecessor. The returned motion subspace is expressed in the frame after the joint, which is attached to the joint's successor. """ @propagate_inbounds function motion_subspace(joint::Joint, q::AbstractVector) @boundscheck check_num_positions(joint, q) @inbounds return motion_subspace(joint.joint_type, frame_after(joint), joint_to_predecessor(joint).to, q) end """ $(SIGNATURES) Return a basis for the constraint wrench subspace of the joint, where `joint_transform` is the transform from the frame after the joint to the frame before the joint. The constraint wrench subspace is a ``6 \\times (6 - k)`` matrix, where ``k`` is the dimension of the velocity vector ``v``, that maps a vector of Lagrange multipliers ``\\lambda`` to the constraint wrench exerted across the joint onto its successor. The constraint wrench subspace is orthogonal to the motion subspace. """ @propagate_inbounds function constraint_wrench_subspace(joint::Joint, joint_transform::Transform3D) @framecheck joint_transform.from frame_after(joint) @framecheck joint_transform.to frame_before(joint) @inbounds return constraint_wrench_subspace(joint.joint_type, joint_transform) end """ $(SIGNATURES) Return the acceleration of the joint's successor with respect to its predecessor in configuration ``q`` and at velocity ``v``, when the joint acceleration ``\\dot{v}`` is zero. """ @propagate_inbounds function bias_acceleration(joint::Joint, q::AbstractVector, v::AbstractVector) @boundscheck check_num_positions(joint, q) @boundscheck check_num_velocities(joint, v) @inbounds return bias_acceleration(joint.joint_type, frame_after(joint), joint_to_predecessor(joint).to, q, v) end """ $(SIGNATURES) Whether the joint's motion subspace and constraint wrench subspace depend on ``q``. """ has_fixed_subspaces(joint::Joint) = has_fixed_subspaces(joint.joint_type) """ $(SIGNATURES) Compute joint velocity vector ``v`` given the joint configuration vector ``q`` and its time derivative ``\\dot{q}`` (in place). Note that this mapping is linear. See also [`velocity_to_configuration_derivative!`](@ref), the inverse mapping. """ @propagate_inbounds function configuration_derivative_to_velocity!(v::AbstractVector, joint::Joint, q::AbstractVector, q̇::AbstractVector) @boundscheck check_num_velocities(joint, v) @boundscheck check_num_positions(joint, q) @boundscheck check_num_positions(joint, q̇) @inbounds return configuration_derivative_to_velocity!(v, joint.joint_type, q, q̇) end """ $(SIGNATURES) Given a linear function ```math f(v) = \\langle f_v, v \\rangle ``` where ``v`` is the joint velocity vector, return a vector ``f_q`` such that ```math \\langle f_v, v \\rangle = \\langle f_q, \\dot{q}(v) \\rangle. ``` Note: since ``v`` is a linear function of ``\\dot{q}`` (see [`configuration_derivative_to_velocity!`](@ref)), we can write ``v = J_{\\dot{q} \\rightarrow v} \\dot{q}``, so ```math \\langle f_v, v \\rangle = \\langle f_v, J_{\\dot{q} \\rightarrow v} \\dot{q} \\rangle = \\langle J_{\\dot{q} \\rightarrow v}^{*} f_v, \\dot{q} \\rangle ``` so ``f_q = J_{\\dot{q} \\rightarrow v}^{*} f_v``. To compute ``J_{\\dot{q} \\rightarrow v}`` see [`configuration_derivative_to_velocity_jacobian`](@ref). """ @propagate_inbounds function configuration_derivative_to_velocity_adjoint!(fq, joint::Joint, q::AbstractVector, fv) @boundscheck check_num_positions(joint, fq) @boundscheck check_num_positions(joint, q) @boundscheck check_num_velocities(joint, fv) @inbounds return configuration_derivative_to_velocity_adjoint!(fq, joint_type(joint), q, fv) end """ $(SIGNATURES) Compute the time derivative ``\\dot{q}`` of the joint configuration vector ``q`` given ``q`` and the joint velocity vector ``v`` (in place). Note that this mapping is linear. See also [`configuration_derivative_to_velocity!`](@ref), the inverse mapping. """ @propagate_inbounds function velocity_to_configuration_derivative!(q̇::AbstractVector, joint::Joint, q::AbstractVector, v::AbstractVector) @boundscheck check_num_positions(joint, q̇) @boundscheck check_num_positions(joint, q) @boundscheck check_num_velocities(joint, v) @inbounds return velocity_to_configuration_derivative!(q̇, joint.joint_type, q, v) end """ $(SIGNATURES) Compute the jacobian ``J_{v \\rightarrow \\dot{q}}`` which maps joint velocity to configuration derivative for the given joint: ```math \\dot{q} = J_{v \\rightarrow \\dot{q}} v ``` """ @propagate_inbounds function velocity_to_configuration_derivative_jacobian(joint::Joint, q::AbstractVector) @boundscheck check_num_positions(joint, q) @inbounds return velocity_to_configuration_derivative_jacobian(joint.joint_type, q) end """ $(SIGNATURES) Compute the jacobian ``J_{\\dot{q} \\rightarrow v}`` which maps joint configuration derivative to velocity for the given joint: ```math v = J_{\\dot{q} \\rightarrow v} \\dot{q} ``` """ @propagate_inbounds function configuration_derivative_to_velocity_jacobian(joint::Joint, q::AbstractVector) @boundscheck check_num_positions(joint, q) @inbounds return configuration_derivative_to_velocity_jacobian(joint.joint_type, q) end """ $(SIGNATURES) Set ``q`` to the 'zero' configuration, corresponding to an identity joint transform. """ @propagate_inbounds function zero_configuration!(q::AbstractVector, joint::Joint) @boundscheck check_num_positions(joint, q) @inbounds return zero_configuration!(q, joint.joint_type) end """ $(SIGNATURES) Set ``q`` to a random configuration. The distribution used depends on the joint type. """ @propagate_inbounds function rand_configuration!(q::AbstractVector, joint::Joint) @boundscheck check_num_positions(joint, q) @inbounds return rand_configuration!(q, joint.joint_type) end """ $(SIGNATURES) Return the twist of `joint`'s successor with respect to its predecessor, expressed in the frame after the joint. Note that this is the same as `Twist(motion_subspace(joint, q), v)`. """ @propagate_inbounds function joint_twist(joint::Joint, q::AbstractVector, v::AbstractVector) @boundscheck check_num_positions(joint, q) @boundscheck check_num_velocities(joint, v) @inbounds return joint_twist(joint.joint_type, frame_after(joint), joint_to_predecessor(joint).to, q, v) end """ $(SIGNATURES) Return the spatial acceleration of `joint`'s successor with respect to its predecessor, expressed in the frame after the joint. """ @propagate_inbounds function joint_spatial_acceleration(joint::Joint, q::AbstractVector, v::AbstractVector, vd::AbstractVector) @boundscheck check_num_positions(joint, q) @boundscheck check_num_velocities(joint, v) @boundscheck check_num_velocities(joint, vd) @inbounds return joint_spatial_acceleration(joint.joint_type, frame_after(joint), joint_to_predecessor(joint).to, q, v, vd) end """ $(SIGNATURES) Given the wrench exerted across the joint on the joint's successor, compute the vector of joint torques ``\\tau`` (in place), in configuration `q`. """ @propagate_inbounds function joint_torque!(τ::AbstractVector, joint::Joint, q::AbstractVector, joint_wrench::Wrench) @boundscheck check_num_velocities(joint, τ) @boundscheck check_num_positions(joint, q) @framecheck(joint_wrench.frame, frame_after(joint)) @inbounds return joint_torque!(τ, joint.joint_type, q, joint_wrench) end """ $(SIGNATURES) Compute a vector of local coordinates ``\\phi`` around configuration ``q_0`` corresponding to configuration ``q`` (in place). Also compute the time derivative ``\\dot{\\phi}`` of ``\\phi`` given the joint velocity vector ``v``. The local coordinate vector ``\\phi`` must be zero if and only if ``q = q_0``. For revolute or prismatic joint types, the local coordinates can just be ``\\phi = q - q_0``, but for joint types with configuration vectors that are restricted to a manifold (e.g. when unit quaternions are used to represent orientation), elementwise subtraction may not make sense. For such joints, exponential coordinates could be used as the local coordinate vector ``\\phi``. See also [`global_coordinates!`](@ref). """ @propagate_inbounds function local_coordinates!(ϕ::AbstractVector, ϕ̇::AbstractVector, joint::Joint, q0::AbstractVector, q::AbstractVector, v::AbstractVector) @boundscheck check_num_velocities(joint, ϕ) @boundscheck check_num_velocities(joint, ϕ̇) @boundscheck check_num_positions(joint, q0) @boundscheck check_num_positions(joint, q) @boundscheck check_num_velocities(joint, v) @inbounds return local_coordinates!(ϕ, ϕ̇, joint.joint_type, q0, q, v) end """ $(SIGNATURES) Compute the global parameterization of the joint's configuration, ``q``, given a 'base' orientation ``q_0`` and a vector of local coordinates ``ϕ`` centered around ``q_0``. See also [`local_coordinates!`](@ref). """ @propagate_inbounds function global_coordinates!(q::AbstractVector, joint::Joint, q0::AbstractVector, ϕ::AbstractVector) @boundscheck check_num_positions(joint, q) @boundscheck check_num_positions(joint, q0) @boundscheck check_num_velocities(joint, ϕ) @inbounds return global_coordinates!(q, joint.joint_type, q0, ϕ) end """ $(SIGNATURES) Whether the joint is a floating joint, i.e., whether it imposes no constraints on the relative motions of its successor and predecessor bodies. """ isfloating(joint::Joint) = isfloating(joint.joint_type) """ $(SIGNATURES) Renormalize the configuration vector ``q`` associated with `joint` so that it lies on the joint's configuration manifold. """ @propagate_inbounds function normalize_configuration!(q::AbstractVector, joint::Joint) @boundscheck check_num_positions(joint, q) @inbounds return normalize_configuration!(q, joint.joint_type) end @propagate_inbounds function is_configuration_normalized(joint::Joint, q::AbstractVector{X}; rtol::Real = sqrt(eps(X)), atol::Real = zero(X)) where {X} @boundscheck check_num_positions(joint, q) @inbounds return is_configuration_normalized(joint.joint_type, q, rtol, atol) end """ $(SIGNATURES) Applies the principal_value functions from [Rotations.jl](https://github.com/FugroRoames/Rotations.jl/blob/d080990517f89b56c37962ad53a7fd24bd94b9f7/src/principal_value.jl) to joint angles. This currently only applies to `SPQuatFloating` joints. """ @propagate_inbounds function principal_value!(q::AbstractVector, joint::Joint) @boundscheck check_num_positions(joint, q) @inbounds return principal_value!(q, joint.joint_type) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
9562
const DEFAULT_GRAVITATIONAL_ACCELERATION = SVector(0.0, 0.0, -9.81) """ $(TYPEDEF) A `Mechanism` represents an interconnection of rigid bodies and joints. `Mechanism`s store the joint layout and inertia parameters, but no state-dependent information. """ mutable struct Mechanism{T} graph::DirectedGraph{RigidBody{T}, Joint{T}} tree::SpanningTree{RigidBody{T}, Joint{T}} environment::ContactEnvironment{T} gravitational_acceleration::FreeVector3D{SVector{3, T}} # TODO: consider removing modcount::Int @doc """ $(SIGNATURES) Create a new `Mechanism` containing only a root body, to which other bodies can be attached with joints. The `gravity` keyword argument can be used to set the gravitational acceleration (a 3-vector expressed in the `Mechanism`'s root frame). Default: `$(DEFAULT_GRAVITATIONAL_ACCELERATION)`. """ -> function Mechanism(root_body::RigidBody{T}; gravity::AbstractVector=DEFAULT_GRAVITATIONAL_ACCELERATION) where {T} graph = DirectedGraph{RigidBody{T}, Joint{T}}() add_vertex!(graph, root_body) tree = SpanningTree(graph, root_body) gravitational_acceleration = FreeVector3D(default_frame(root_body), convert(SVector{3, T}, gravity)) environment = ContactEnvironment{T}() new{T}(graph, tree, environment, gravitational_acceleration, 0) end end Base.eltype(::Type{Mechanism{T}}) where {T} = T """ $(SIGNATURES) Return the `Joint`s that are part of the `Mechanism` as an iterable collection. """ joints(mechanism::Mechanism) = edges(mechanism.graph) """ $(SIGNATURES) Return the `Joint`s that are part of the `Mechanism`'s spanning tree as an iterable collection. """ tree_joints(mechanism::Mechanism) = edges(mechanism.tree) """ $(SIGNATURES) Return the `Joint`s that are not part of the `Mechanism`'s spanning tree as an iterable collection. """ non_tree_joints(mechanism::Mechanism) = setdiff(edges(mechanism.graph), edges(mechanism.tree)) """ $(SIGNATURES) Return the `RigidBody`s that are part of the `Mechanism` as an iterable collection. """ bodies(mechanism::Mechanism) = vertices(mechanism.graph) """ $(SIGNATURES) Return the root (stationary 'world') body of the `Mechanism`. """ root_body(mechanism::Mechanism) = first(bodies(mechanism)) """ $(SIGNATURES) Return the default frame of the root body. """ root_frame(mechanism::Mechanism) = default_frame(root_body(mechanism)) """ $(SIGNATURES) Return the path from rigid body `from` to `to` along edges of the `Mechanism`'s kinematic tree. """ path(mechanism::Mechanism, from::RigidBody, to::RigidBody) = TreePath(from, to, mechanism.tree) has_loops(mechanism::Mechanism) = num_edges(mechanism.graph) > num_edges(mechanism.tree) @inline modcount(mechanism::Mechanism) = mechanism.modcount register_modification!(mechanism::Mechanism) = mechanism.modcount += 1 function Base.show(io::IO, mechanism::Mechanism) println(io, "Spanning tree:") print(io, mechanism.tree) nontreejoints = non_tree_joints(mechanism) println(io) if isempty(nontreejoints) print(io, "No non-tree joints.") else print(io, "Non-tree joints:") for joint in nontreejoints println(io) show(IOContext(io, :compact => true), joint) print(io, ", predecessor: ") show(IOContext(io, :compact => true), predecessor(joint, mechanism)) print(io, ", successor: ") show(IOContext(io, :compact => true), successor(joint, mechanism)) end end end isroot(b::RigidBody{T}, mechanism::Mechanism{T}) where {T} = b == root_body(mechanism) non_root_bodies(mechanism::Mechanism) = Base.unsafe_view(bodies(mechanism), 2 : length(bodies(mechanism))) num_bodies(mechanism::Mechanism) = num_vertices(mechanism.graph) """ $(SIGNATURES) Return the dimension of the joint configuration vector ``q``. """ num_positions(mechanism::Mechanism)::Int = mapreduce(num_positions, +, tree_joints(mechanism); init=0) """ $(SIGNATURES) Return the dimension of the joint velocity vector ``v``. """ num_velocities(mechanism::Mechanism)::Int = mapreduce(num_velocities, +, tree_joints(mechanism); init=0) """ $(SIGNATURES) Return the number of constraints imposed by the mechanism's non-tree joints (i.e., the number of rows of the constraint Jacobian). """ num_constraints(mechanism::Mechanism)::Int = mapreduce(num_constraints, +, non_tree_joints(mechanism); init=0) """ $(SIGNATURES) Return the dimension of the vector of additional states ``s`` (used for stateful contact models). """ function num_additional_states(mechanism::Mechanism) num_states_per_environment_element = 0 for body in bodies(mechanism), point in contact_points(body) num_states_per_environment_element += num_states(contact_model(point)) end num_states_per_environment_element * length(mechanism.environment) end """ $(SIGNATURES) Return the `RigidBody` to which `frame` is attached. Note: this function is linear in the number of bodies and is not meant to be called in tight loops. """ function body_fixed_frame_to_body(mechanism::Mechanism, frame::CartesianFrame3D) for body in bodies(mechanism) if is_fixed_to_body(body, frame) return body end end error("Unable to determine to what body $(frame) is attached") end """ $(SIGNATURES) Return the definition of body-fixed frame `frame`, i.e., the `Transform3D` from `frame` to the default frame of the body to which it is attached. Note: this function is linear in the number of bodies and is not meant to be called in tight loops. See also [`default_frame`](@ref), [`frame_definition`](@ref). """ function body_fixed_frame_definition(mechanism::Mechanism, frame::CartesianFrame3D) frame_definition(body_fixed_frame_to_body(mechanism, frame), frame) end """ $(SIGNATURES) Return the transform from `CartesianFrame3D` `from` to `to`, both of which are rigidly attached to the same `RigidBody`. Note: this function is linear in the number of bodies and is not meant to be called in tight loops. """ function fixed_transform(mechanism::Mechanism, from::CartesianFrame3D, to::CartesianFrame3D) fixed_transform(body_fixed_frame_to_body(mechanism, from), from, to) end """ $(SIGNATURES) Return the body 'before' the joint, i.e. the 'tail' of the joint interpreted as an arrow in the `Mechanism`'s kinematic graph. See [`Joint`](@ref). """ predecessor(joint::Joint, mechanism::Mechanism) = source(joint, mechanism.graph) """ $(SIGNATURES) Return the body 'after' the joint, i.e. the 'head' of the joint interpreted as an arrow in the `Mechanism`'s kinematic graph. See [`Joint`](@ref). """ successor(joint::Joint, mechanism::Mechanism) = target(joint, mechanism.graph) """ $(SIGNATURES) Return the joints that have `body` as their [`predecessor`](@ref). """ out_joints(body::RigidBody, mechanism::Mechanism) = out_edges(body, mechanism.graph) """ $(SIGNATURES) Return the joints that have `body` as their [`successor`](@ref). """ in_joints(body::RigidBody, mechanism::Mechanism) = in_edges(body, mechanism.graph) """ $(SIGNATURES) Return the joints that are part of the mechanism's kinematic tree and have `body` as their predecessor. """ joints_to_children(body::RigidBody, mechanism::Mechanism) = edges_to_children(body, mechanism.tree) """ $(SIGNATURES) Return the joint that is part of the mechanism's kinematic tree and has `body` as its successor. """ joint_to_parent(body::RigidBody, mechanism::Mechanism) = edge_to_parent(body, mechanism.tree) function add_body_fixed_frame!(mechanism::Mechanism{T}, transform::Transform3D) where {T} add_frame!(body_fixed_frame_to_body(mechanism, transform.to), transform) end function canonicalize_frame_definitions!(mechanism::Mechanism{T}, body::RigidBody{T}) where {T} if !isroot(body, mechanism) change_default_frame!(body, frame_after(joint_to_parent(body, mechanism))) end for joint in in_joints(body, mechanism) set_joint_to_successor!(joint, frame_definition(body, frame_after(joint))) end for joint in out_joints(body, mechanism) set_joint_to_predecessor!(joint, frame_definition(body, frame_before(joint))) end end function canonicalize_frame_definitions!(mechanism::Mechanism) for body in bodies(mechanism) canonicalize_frame_definitions!(mechanism, body) end end function gravitational_spatial_acceleration(mechanism::Mechanism) frame = mechanism.gravitational_acceleration.frame SpatialAcceleration(frame, frame, frame, zero(SVector{3, eltype(mechanism)}), mechanism.gravitational_acceleration.v) end """ $(SIGNATURES) Return the `RigidBody` with the given name. Errors if there is no body with the given name, or if there's more than one. """ findbody(mechanism::Mechanism, name::String) = findunique(b -> string(b) == name, bodies(mechanism)) """ $(SIGNATURES) Return the `Joint` with the given name. Errors if there is no joint with the given name, or if there's more than one. """ findjoint(mechanism::Mechanism, name::String) = findunique(j -> string(j) == name, joints(mechanism)) """ $(SIGNATURES) Return the `RigidBody` with the given `BodyID`. """ function findbody(mechanism::Mechanism, id::BodyID) ret = bodies(mechanism)[id] BodyID(ret) == id || error() # should never happen ret end """ $(SIGNATURES) Return the `Joint` with the given `JointID`. """ function findjoint(mechanism::Mechanism, id::JointID) ret = joints(mechanism)[id] JointID(ret) == id || error() # should never happen ret end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
32850
const noalloc_doc = """This method does its computation in place, performing no dynamic memory allocation.""" """ $(SIGNATURES) Return the mass of a subtree of a `Mechanism`, rooted at `base` (including the mass of `base`). """ function subtree_mass(base::RigidBody{T}, mechanism::Mechanism{T}) where {T} result = isroot(base, mechanism) ? zero(T) : spatial_inertia(base).mass for joint in joints_to_children(base, mechanism) result += subtree_mass(successor(joint, mechanism), mechanism) end result end """ $(SIGNATURES) Return the total mass of the `Mechanism`. """ mass(m::Mechanism) = subtree_mass(root_body(m), m) """ $(SIGNATURES) Compute the center of mass of an iterable subset of a `Mechanism`'s bodies in the given state. Ignores the root body of the mechanism. """ function center_of_mass(state::MechanismState, itr) update_transforms!(state) T = cache_eltype(state) mechanism = state.mechanism frame = root_frame(mechanism) com = Point3D(frame, zero(SVector{3, T})) mass = zero(T) for body in itr if body.inertia !== nothing inertia = spatial_inertia(body) if inertia.mass > 0 bodycom = transform_to_root(state, body, false) * center_of_mass(inertia) com += inertia.mass * FreeVector3D(bodycom) mass += inertia.mass end end end com /= mass com end """ $(SIGNATURES) Compute the center of mass of the whole `Mechanism` in the given state. """ center_of_mass(state::MechanismState) = center_of_mass(state, bodies(state.mechanism)) const geometric_jacobian_doc = """Compute a geometric Jacobian (also known as a basic, or spatial Jacobian) associated with a directed path in the `Mechanism`'s spanning tree, (a collection of `Joint`s and traversal directions) in the given state. A geometric Jacobian maps the `Mechanism`'s joint velocity vector ``v`` to the twist of the target of the joint path (the body succeeding the last joint in the path) with respect to the source of the joint path (the body preceding the first joint in the path). See also [`path`](@ref), [`GeometricJacobian`](@ref), [`Twist`](@ref). """ """ $(SIGNATURES) $geometric_jacobian_doc `transformfun` is a callable that may be used to transform the individual motion subspaces of each of the joints to the frame in which `out` is expressed. $noalloc_doc """ function geometric_jacobian!(jac::GeometricJacobian, state::MechanismState, path::TreePath, transformfun) @boundscheck num_velocities(state) == size(jac, 2) || throw(DimensionMismatch()) @framecheck jac.body default_frame(target(path)) @framecheck jac.base default_frame(source(path)) update_motion_subspaces!(state) fill!(jac.angular, 0) fill!(jac.linear, 0) for i in eachindex(path.edges) # TODO: just use @inbounds here; currently messes with frame check in set_col! @inbounds joint = path.edges[i] vrange = velocity_range(state, joint) @inbounds direction = directions(path)[i] for col in eachindex(vrange) @inbounds vindex = vrange[col] @inbounds Scol = transformfun(state.motion_subspaces.data[vindex]) direction == PathDirections.up && (Scol = -Scol) set_col!(jac, vindex, Scol) end end jac end """ $(SIGNATURES) $geometric_jacobian_doc `root_to_desired` is the transform from the `Mechanism`'s root frame to the frame in which `out` is expressed. $noalloc_doc """ function geometric_jacobian!(out::GeometricJacobian, state::MechanismState, path::TreePath, root_to_desired::Transform3D) geometric_jacobian!(out, state, path, S -> transform(S, root_to_desired)) end """ $(SIGNATURES) $geometric_jacobian_doc See [`geometric_jacobian!(out, state, path, root_to_desired)`](@ref). Uses `state` to compute the transform from the `Mechanism`'s root frame to the frame in which `out` is expressed. $noalloc_doc """ function geometric_jacobian!(out::GeometricJacobian, state::MechanismState, path::TreePath) if out.frame == root_frame(state.mechanism) geometric_jacobian!(out, state, path, identity) else geometric_jacobian!(out, state, path, inv(transform_to_root(state, out.frame))) end end """ $(SIGNATURES) $geometric_jacobian_doc The Jacobian is computed in the `Mechanism`'s root frame. See [`geometric_jacobian!(out, state, path)`](@ref). """ function geometric_jacobian(state::MechanismState{X, M, C}, path::TreePath{RigidBody{M}, Joint{M}}) where {X, M, C} nv = num_velocities(state) angular = Matrix{C}(undef, 3, nv) linear = Matrix{C}(undef, 3, nv) bodyframe = default_frame(target(path)) baseframe = default_frame(source(path)) jac = GeometricJacobian(bodyframe, baseframe, root_frame(state.mechanism), angular, linear) geometric_jacobian!(jac, state, path, identity) end const point_jacobian_doc = """ Compute the Jacobian mapping the `Mechanism`'s joint velocity vector ``v`` to the velocity of a point fixed to the target of the joint path (the body succeeding the last joint in the path) with respect to the source of the joint path (the body preceding the first joint in the path). """ """ $(SIGNATURES) $point_jacobian_doc $noalloc_doc """ function _point_jacobian!(Jp::PointJacobian, state::MechanismState, path::TreePath, point::Point3D, transformfun) @framecheck Jp.frame point.frame update_motion_subspaces!(state) fill!(Jp.J, 0) p̂ = Spatial.hat(point.v) @inbounds for i in eachindex(path.edges) joint = path.edges[i] vrange = velocity_range(state, joint) direction = path.directions[i] for col in eachindex(vrange) vindex = vrange[col] Scol = transformfun(state.motion_subspaces.data[vindex]) direction == PathDirections.up && (Scol = -Scol) newcol = -p̂ * angular(Scol) + linear(Scol) for row in 1:3 Jp.J[row, vindex] = newcol[row] end end end Jp end """ $(SIGNATURES) $point_jacobian_doc Uses `state` to compute the transform from the `Mechanism`'s root frame to the frame in which `out` is expressed if necessary. $noalloc_doc """ function point_jacobian!(out::PointJacobian, state::MechanismState, path::TreePath, point::Point3D) if out.frame == root_frame(state.mechanism) _point_jacobian!(out, state, path, point, identity) else root_to_desired = inv(transform_to_root(state, out.frame)) let root_to_desired = root_to_desired _point_jacobian!(out, state, path, point, S -> transform(S, root_to_desired)) end end end """ $(SIGNATURES) $point_jacobian_doc """ function point_jacobian(state::MechanismState{X, M, C}, path::TreePath{RigidBody{M}, Joint{M}}, point::Point3D) where {X, M, C} Jp = PointJacobian(point.frame, Matrix{C}(undef, 3, num_velocities(state))) point_jacobian!(Jp, state, path, point) Jp end const mass_matrix_doc = """Compute the joint-space mass matrix (also known as the inertia matrix) of the `Mechanism` in the given state, i.e., the matrix ``M(q)`` in the unconstrained joint-space equations of motion ```math M(q) \\dot{v} + c(q, v, w_\\text{ext}) = \\tau ``` This method implements the composite rigid body algorithm. """ """ $(SIGNATURES) $mass_matrix_doc $noalloc_doc The `out` argument must be an ``n_v \\times n_v`` lower triangular `Symmetric` matrix, where ``n_v`` is the dimension of the `Mechanism`'s joint velocity vector ``v``. """ function mass_matrix!(M::Symmetric, state::MechanismState) nv = num_velocities(state) @boundscheck size(M, 1) == nv || throw(DimensionMismatch("mass matrix has wrong size")) @boundscheck M.uplo == 'L' || throw(ArgumentError(("expected a lower triangular symmetric matrix"))) update_motion_subspaces!(state) update_crb_inertias!(state) motion_subspaces = state.motion_subspaces.data @inbounds for i in Base.OneTo(nv) jointi = velocity_index_to_joint_id(state, i) bodyi = successorid(jointi, state) Ici = crb_inertia(state, bodyi, false) Si = motion_subspaces[i] Fi = Ici * Si for j in Base.OneTo(i) jointj = velocity_index_to_joint_id(state, j) M.data[i, j] = if supports(jointj, bodyi, state) Sj = motion_subspaces[j] (transpose(Fi) * Sj)[1] else zero(eltype(M)) end end end M end mass_matrix!(result::DynamicsResult, state::MechanismState) = mass_matrix!(result.massmatrix, state) """ $(SIGNATURES) $mass_matrix_doc """ function mass_matrix(state::MechanismState{X, M, C}) where {X, M, C} nv = num_velocities(state) ret = Symmetric(Matrix{C}(undef, nv, nv), :L) mass_matrix!(ret, state) ret end const momentum_matrix_doc = """Compute the momentum matrix ``A(q)`` of the `Mechanism` in the given state. The momentum matrix maps the `Mechanism`'s joint velocity vector ``v`` to its total momentum. See also [`MomentumMatrix`](@ref). """ const momentum_matrix!_doc = """$momentum_matrix_doc The `out` argument must be a mutable `MomentumMatrix` with as many columns as the dimension of the `Mechanism`'s joint velocity vector ``v``. """ """ $(SIGNATURES) $momentum_matrix!_doc `transformfun` is a callable that may be used to transform the individual momentum matrix blocks associated with each of the joints to the frame in which `out` is expressed. $noalloc_doc """ function momentum_matrix!(mat::MomentumMatrix, state::MechanismState, transformfun) nv = num_velocities(state) @boundscheck size(mat, 2) == nv || throw(DimensionMismatch()) update_motion_subspaces!(state) update_crb_inertias!(state) @inbounds for i in 1 : nv jointi = velocity_index_to_joint_id(state, i) bodyi = successorid(jointi, state) Ici = crb_inertia(state, bodyi) Si = state.motion_subspaces.data[i] Fi = transformfun(Ici * Si) set_col!(mat, i, Fi) end mat end """ $(SIGNATURES) $momentum_matrix!_doc `root_to_desired` is the transform from the `Mechanism`'s root frame to the frame in which `out` is expressed. $noalloc_doc """ function momentum_matrix!(mat::MomentumMatrix, state::MechanismState, root_to_desired::Transform3D) momentum_matrix!(mat, state, F -> transform(F, root_to_desired)) end """ $(SIGNATURES) $momentum_matrix!_doc See [`momentum_matrix!(out, state, root_to_desired)`](@ref). Uses `state` to compute the transform from the `Mechanism`'s root frame to the frame in which `out` is expressed. $noalloc_doc """ function momentum_matrix!(out::MomentumMatrix, state::MechanismState) if out.frame == root_frame(state.mechanism) momentum_matrix!(out, state, identity) else momentum_matrix!(out, state, inv(transform_to_root(state, out.frame))) end end """ $(SIGNATURES) $momentum_matrix_doc See [`momentum_matrix!(out, state)`](@ref). """ function momentum_matrix(state::MechanismState) ncols = num_velocities(state) T = cache_eltype(state) ret = MomentumMatrix(root_frame(state.mechanism), Matrix{T}(undef, 3, ncols), Matrix{T}(undef, 3, ncols)) momentum_matrix!(ret, state, identity) ret end function bias_accelerations!(out::AbstractDict{BodyID, SpatialAcceleration{T}}, state::MechanismState{X, M}) where {T, X, M} update_bias_accelerations_wrt_world!(state) gravitybias = convert(SpatialAcceleration{T}, -gravitational_spatial_acceleration(state.mechanism)) for jointid in state.treejointids bodyid = successorid(jointid, state) out[bodyid] = gravitybias + bias_acceleration(state, bodyid, false) end nothing end function spatial_accelerations!(out::AbstractDict{BodyID, SpatialAcceleration{T}}, state::MechanismState, v̇::SegmentedVector{JointID}) where T update_transforms!(state) update_twists_wrt_world!(state) # Compute joint accelerations joints = state.treejoints qs = values(segments(state.q)) vs = values(segments(state.v)) v̇s = values(segments(v̇)) foreach_with_extra_args(state, out, joints, qs, vs, v̇s) do state, accels, joint, qjoint, vjoint, v̇joint bodyid = successorid(JointID(joint), state) accels[bodyid] = joint_spatial_acceleration(joint, qjoint, vjoint, v̇joint) end # Recursive propagation # TODO: manual frame changes. Find a way to not avoid the frame checks here. mechanism = state.mechanism root = root_body(mechanism) out[root] = convert(SpatialAcceleration{T}, -gravitational_spatial_acceleration(mechanism)) @inbounds for jointid in state.treejointids parentbodyid, bodyid = predsucc(jointid, state) toroot = transform_to_root(state, bodyid, false) parenttwist = twist_wrt_world(state, parentbodyid, false) bodytwist = twist_wrt_world(state, bodyid, false) jointaccel = out[bodyid] jointaccel = SpatialAcceleration(jointaccel.body, parenttwist.body, toroot.to, Spatial.transform_spatial_motion(jointaccel.angular, jointaccel.linear, rotation(toroot), translation(toroot))...) out[bodyid] = out[parentbodyid] + (-bodytwist) × parenttwist + jointaccel end nothing end spatial_accelerations!(result::DynamicsResult, state::MechanismState) = spatial_accelerations!(result.accelerations, state, result.v̇) function relative_acceleration(accels::AbstractDict{BodyID, SpatialAcceleration{T}}, body::RigidBody{M}, base::RigidBody{M}) where {T, M} -accels[BodyID(base)] + accels[BodyID(body)] end # TODO: ensure that accelerations are up-to-date relative_acceleration(result::DynamicsResult, body::RigidBody, base::RigidBody) = relative_acceleration(result.accelerations, body, base) function newton_euler!( out::AbstractDict{BodyID, Wrench{T}}, state::MechanismState{X, M}, accelerations::AbstractDict{BodyID, SpatialAcceleration{T}}, externalwrenches::AbstractDict{BodyID, Wrench{W}}) where {T, X, M, W} update_twists_wrt_world!(state) update_spatial_inertias!(state) for jointid in state.treejointids bodyid = successorid(jointid, state) wrench = newton_euler(state, bodyid, accelerations[bodyid], false) out[bodyid] = haskey(externalwrenches, bodyid) ? wrench - externalwrenches[bodyid] : wrench end end function joint_wrenches_and_torques!( torquesout::SegmentedVector{JointID}, net_wrenches_in_joint_wrenches_out::AbstractDict{BodyID, <:Wrench}, # TODO: consider having a separate Associative{Joint{M}, Wrench{T}} for joint wrenches state::MechanismState) update_motion_subspaces!(state) # Note: pass in net wrenches as wrenches argument. wrenches argument is modified to be joint wrenches @boundscheck length(torquesout) == num_velocities(state) || error("length of torque vector is wrong") wrenches = net_wrenches_in_joint_wrenches_out for jointid in reverse(state.treejointids) parentbodyid, bodyid = predsucc(jointid, state) jointwrench = wrenches[bodyid] wrenches[parentbodyid] += jointwrench # action = -reaction for vindex in velocity_range(state, jointid) Scol = state.motion_subspaces.data[vindex] torquesout[vindex] = (transpose(Scol) * jointwrench)[1] end end end const dynamics_bias_doc = """Compute the 'dynamics bias term', i.e. the term ```math c(q, v, w_\\text{ext}) ``` in the unconstrained joint-space equations of motion ```math M(q) \\dot{v} + c(q, v, w_\\text{ext}) = \\tau ``` given joint configuration vector ``q``, joint velocity vector ``v``, joint acceleration vector ``\\dot{v}`` and (optionally) external wrenches ``w_\\text{ext}``. The `externalwrenches` argument can be used to specify additional wrenches that act on the `Mechanism`'s bodies. """ """ $(SIGNATURES) $dynamics_bias_doc $noalloc_doc """ function dynamics_bias!( torques::SegmentedVector{JointID}, biasaccelerations::AbstractDict{BodyID, <:SpatialAcceleration}, wrenches::AbstractDict{BodyID, <:Wrench}, state::MechanismState{X}, externalwrenches::AbstractDict{BodyID, <:Wrench} = NullDict{BodyID, Wrench{X}}()) where X bias_accelerations!(biasaccelerations, state) newton_euler!(wrenches, state, biasaccelerations, externalwrenches) joint_wrenches_and_torques!(torques, wrenches, state) torques end function dynamics_bias!(result::DynamicsResult, state::MechanismState) dynamics_bias!(result.dynamicsbias, result.accelerations, result.jointwrenches, state, result.totalwrenches) end """ $(SIGNATURES) $dynamics_bias_doc """ function dynamics_bias( state::MechanismState{X, M}, externalwrenches::AbstractDict{BodyID, Wrench{W}} = NullDict{BodyID, Wrench{X}}()) where {X, M, W} T = promote_type(X, M, W) mechanism = state.mechanism torques = similar(velocity(state), T) rootframe = root_frame(mechanism) jointwrenches = BodyDict(BodyID(b) => zero(Wrench{T}, rootframe) for b in bodies(mechanism)) accelerations = BodyDict(BodyID(b) => zero(SpatialAcceleration{T}, rootframe, rootframe, rootframe) for b in bodies(mechanism)) dynamics_bias!(torques, accelerations, jointwrenches, state, externalwrenches) torques end const inverse_dynamics_doc = """Do inverse dynamics, i.e. compute ``\\tau`` in the unconstrained joint-space equations of motion ```math M(q) \\dot{v} + c(q, v, w_\\text{ext}) = \\tau ``` given joint configuration vector ``q``, joint velocity vector ``v``, joint acceleration vector ``\\dot{v}`` and (optionally) external wrenches ``w_\\text{ext}``. The `externalwrenches` argument can be used to specify additional wrenches that act on the `Mechanism`'s bodies. This method implements the recursive Newton-Euler algorithm. Currently doesn't support `Mechanism`s with cycles. """ """ $(SIGNATURES) $inverse_dynamics_doc $noalloc_doc """ function inverse_dynamics!( torquesout::SegmentedVector{JointID}, jointwrenchesout::AbstractDict{BodyID, Wrench{T}}, accelerations::AbstractDict{BodyID, SpatialAcceleration{T}}, state::MechanismState, v̇::SegmentedVector{JointID}, externalwrenches::AbstractDict{BodyID, <:Wrench} = NullDict{BodyID, Wrench{T}}()) where T @boundscheck length(tree_joints(state.mechanism)) == length(joints(state.mechanism)) || error("This method can currently only handle tree Mechanisms.") spatial_accelerations!(accelerations, state, v̇) newton_euler!(jointwrenchesout, state, accelerations, externalwrenches) joint_wrenches_and_torques!(torquesout, jointwrenchesout, state) end """ $(SIGNATURES) $inverse_dynamics_doc """ function inverse_dynamics( state::MechanismState{X, M}, v̇::SegmentedVector{JointID, V}, externalwrenches::AbstractDict{BodyID, Wrench{W}} = NullDict{BodyID, Wrench{X}}()) where {X, M, V, W} T = promote_type(X, M, V, W) mechanism = state.mechanism torques = similar(velocity(state), T) rootframe = root_frame(mechanism) jointwrenches = BodyDict(BodyID(b) => zero(Wrench{T}, rootframe) for b in bodies(mechanism)) accelerations = BodyDict(BodyID(b) => zero(SpatialAcceleration{T}, rootframe, rootframe, rootframe) for b in bodies(mechanism)) inverse_dynamics!(torques, jointwrenches, accelerations, state, v̇, externalwrenches) torques end function constraint_jacobian!(jac::AbstractMatrix, rowranges, state::MechanismState) # TODO: traversing jac in the wrong order update_motion_subspaces!(state) update_constraint_wrench_subspaces!(state) fill!(jac, 0) @inbounds for nontreejointid in state.nontreejointids path = state.constraint_jacobian_structure[nontreejointid] for cindex in constraint_range(state, nontreejointid) Tcol = state.constraint_wrench_subspaces.data[cindex] for i in eachindex(path.edges) treejoint = path.edges[i] vrange = velocity_range(state, treejoint) direction = directions(path)[i] sign = ifelse(direction == PathDirections.up, -1, 1) for col in eachindex(vrange) vindex = vrange[col] Scol = state.motion_subspaces.data[vindex] jacelement = flipsign((transpose(Tcol) * Scol)[1], sign) jac[cindex, vindex] = jacelement end end end end jac end function constraint_jacobian!(result::DynamicsResult, state::MechanismState) constraint_jacobian!(result.constraintjacobian, result.constraintrowranges, state) end """ $(SIGNATURES) Return the default Baumgarte constraint stabilization gains. These gains result in critical damping, and correspond to ``T_{stab} = 0.1`` in Featherstone (2008), section 8.3. """ function default_constraint_stabilization_gains(scalar_type::Type{T}) where T ConstDict{JointID}(SE3PDGains(PDGains(T(100), T(20)), PDGains(T(100), T(20)))) end const stabilization_gains_doc = """ The `stabilization_gains` keyword argument can be used to set PD gains for Baumgarte stabilization, which can be used to prevent separation of non-tree (loop) joints. See Featherstone (2008), section 8.3 for more information. There are several options for specifying gains: * `nothing` can be used to completely disable Baumgarte stabilization. * Gains can be specifed on a per-joint basis using any `AbstractDict{JointID, <:RigidBodyDynamics.PDControl.SE3PDGains}`, which maps the `JointID` for the non-tree joints of the mechanism to the gains for that joint. * As a special case of the second option, the same gains can be used for all joints by passing in a `RigidBodyDynamics.CustomCollections.ConstDict{JointID}`. The [`default_constraint_stabilization_gains`](@ref) function is called to produce the default gains, which use the last option. """ function constraint_bias!(bias::SegmentedVector, state::MechanismState{X}; stabilization_gains::Union{AbstractDict{JointID, <:SE3PDGains}, Nothing}=default_constraint_stabilization_gains(X)) where X update_transforms!(state) update_twists_wrt_world!(state) update_bias_accelerations_wrt_world!(state) update_constraint_wrench_subspaces!(state) constraint_wrench_subspaces = state.constraint_wrench_subspaces.data for nontreejointid in state.nontreejointids predid, succid = predsucc(nontreejointid, state) predtwist = twist_wrt_world(state, predid, false) succtwist = twist_wrt_world(state, succid, false) crossterm = succtwist × predtwist succbias = bias_acceleration(state, succid, false) predbias = bias_acceleration(state, predid, false) jointbias = -predbias + succbias biasaccel = crossterm + jointbias # what's inside parentheses in 8.47 in Featherstone if stabilization_gains !== nothing # TODO: make this nicer (less manual frame juggling and no manual transformations) jointtransform = joint_transform(state, nontreejointid, false) jointtwist = -predtwist + succtwist jointtwist = Twist(jointtransform.from, jointtransform.to, jointtwist.frame, jointtwist.angular, jointtwist.linear) # make frames line up successor_to_root = transform_to_root(state, jointtransform.from) # TODO: expensive jointtwist = transform(jointtwist, inv(successor_to_root)) # twist needs to be in successor frame for pd method stabaccel = pd(stabilization_gains[nontreejointid], jointtransform, jointtwist, SE3PDMethod{:Linearized}()) # in successor frame stabaccel = SpatialAcceleration(stabaccel.body, stabaccel.base, biasaccel.frame, Spatial.transform_spatial_motion(stabaccel.angular, stabaccel.linear, rotation(successor_to_root), translation(successor_to_root))...) # back to world frame. TODO: ugly way to do this stabaccel = SpatialAcceleration(biasaccel.body, biasaccel.body, stabaccel.frame, stabaccel.angular, stabaccel.linear) # make frames line up @inbounds biasaccel = biasaccel + -stabaccel end for cindex in constraint_range(state, nontreejointid) Tcol = constraint_wrench_subspaces[cindex] # TODO: make nicer: @framecheck Tcol.frame biasaccel.frame bias[cindex] = (transpose(Tcol.angular) * biasaccel.angular + transpose(Tcol.linear) * biasaccel.linear)[1] end end bias end function constraint_bias!(result::DynamicsResult, state::MechanismState{X}; stabilization_gains::Union{AbstractDict{JointID, <:SE3PDGains}, Nothing}=default_constraint_stabilization_gains(X)) where X constraint_bias!(result.constraintbias, state; stabilization_gains=stabilization_gains) end function contact_dynamics!(result::DynamicsResult{T, M}, state::MechanismState{X, M, C}) where {X, M, C, T} update_transforms!(state) update_twists_wrt_world!(state) mechanism = state.mechanism root = root_body(mechanism) frame = default_frame(root) for body in bodies(mechanism) bodyid = BodyID(body) wrench = zero(Wrench{T}, frame) points = contact_points(body) if !isempty(points) # TODO: AABB body_to_root = transform_to_root(state, bodyid, false) twist = twist_wrt_world(state, bodyid, false) states_for_body = contact_states(state, bodyid) state_derivs_for_body = contact_state_derivatives(result, bodyid) for i = 1 : length(points) @inbounds c = points[i] point = body_to_root * location(c) velocity = point_velocity(twist, point) states_for_point = states_for_body[i] state_derivs_for_point = state_derivs_for_body[i] for j = 1 : length(mechanism.environment.halfspaces) primitive = mechanism.environment.halfspaces[j] contact_state = states_for_point[j] contact_state_deriv = state_derivs_for_point[j] model = contact_model(c) # TODO: would be good to move this to Contact module # arguments: model, state, state_deriv, point, velocity, primitive if point_inside(primitive, point) separation, normal = Contact.detect_contact(primitive, point) force = Contact.contact_dynamics!(contact_state_deriv, contact_state, model, -separation, velocity, normal) wrench += Wrench(point, force) else Contact.reset!(contact_state) Contact.zero!(contact_state_deriv) end end end end set_contact_wrench!(result, body, wrench) end end function dynamics_solve!(result::DynamicsResult, τ::AbstractVector) # version for general scalar types # TODO: make more efficient M = result.massmatrix c = parent(result.dynamicsbias) v̇ = parent(result.v̇) K = result.constraintjacobian k = result.constraintbias λ = result.λ nv = size(M, 1) nl = size(K, 1) G = [Matrix(M) K'; # TODO: Matrix because of https://github.com/JuliaLang/julia/issues/21332 K zeros(nl, nl)] r = [τ - c; -k] v̇λ = G \ r v̇ .= view(v̇λ, 1 : nv) λ .= view(v̇λ, nv + 1 : nv + nl) nothing end function dynamics_solve!(result::DynamicsResult{T, S}, τ::AbstractVector{T}) where {S, T<:LinearAlgebra.BlasReal} # optimized version for BLAS floats M = result.massmatrix c = parent(result.dynamicsbias) v̇ = parent(result.v̇) K = result.constraintjacobian k = result.constraintbias λ = result.λ L = result.L A = result.A z = result.z Y = result.Y L .= M.data uplo = M.uplo LinearAlgebra.LAPACK.potrf!(uplo, L) # L <- Cholesky decomposition of M; M == L Lᵀ (note: Featherstone, page 151 uses M == Lᵀ L instead) τbiased = v̇ τbiased .= τ .- c if size(K, 1) > 0 # Loops. # Basic math: # DAE: # [M Kᵀ] [v̇] = [τ - c] # [K 0 ] [λ] = [-k] # Solve for v̇: # v̇ = M⁻¹ (τ - c - Kᵀ λ) # Plug into λ equation: # K M⁻¹ (τ - c - Kᵀ λ) = -k # K M⁻¹ Kᵀ λ = K M⁻¹(τ - c) + k # which can be solved for λ, after which λ can be used to solve for v̇. # Implementation loosely follows page 151 of Featherstone, Rigid Body Dynamics Algorithms. # It is slightly different because Featherstone uses M = Lᵀ L, whereas BLAS uses M = L Lᵀ. # M = L Lᵀ (Cholesky decomposition) # Y = K L⁻ᵀ, so that Y Yᵀ = K L⁻ᵀ L⁻¹ Kᵀ = K M⁻¹ Kᵀ = A # z = L⁻¹ (τ - c) # b = Y z + k # solve A λ = b for λ # solve M v̇ = τ - c for v̇ # Compute Y = K L⁻ᵀ Y .= K LinearAlgebra.BLAS.trsm!('R', uplo, 'T', 'N', one(T), L, Y) # Compute z = L⁻¹ (τ - c) z .= τbiased LinearAlgebra.BLAS.trsv!(uplo, 'N', 'N', L, z) # z <- L⁻¹ (τ - c) # Compute A = Y Yᵀ == K * M⁻¹ * Kᵀ LinearAlgebra.BLAS.gemm!('N', 'T', one(T), Y, Y, zero(T), A) # A <- K * M⁻¹ * Kᵀ # Compute b = Y z + k b = λ b .= k LinearAlgebra.BLAS.gemv!('N', one(T), Y, z, one(T), b) # b <- Y z + k # Compute λ = A⁻¹ b == (K * M⁻¹ * Kᵀ)⁻¹ * (K * M⁻¹ * (τ - c) + k) # LinearAlgebra.LAPACK.posv!(uplo, A, b) # NOTE: doesn't work in general because A is only guaranteed to be positive semidefinite singular_value_zero_tolerance = 1e-10 # TODO: more principled choice # TODO: https://github.com/JuliaLang/julia/issues/22242 b[:], _ = LinearAlgebra.LAPACK.gelsy!(A, b, singular_value_zero_tolerance) # b == λ <- (K * M⁻¹ * Kᵀ)⁻¹ * (K * M⁻¹ * (τ - c) + k) # Update τbiased: subtract Kᵀ * λ LinearAlgebra.BLAS.gemv!('T', -one(T), K, λ, one(T), τbiased) # τbiased <- τ - c - Kᵀ * λ # Solve for v̇ = M⁻¹ * (τ - c - Kᵀ * λ) LinearAlgebra.LAPACK.potrs!(uplo, L, τbiased) # τbiased ==v̇ <- M⁻¹ * (τ - c - Kᵀ * λ) else # No loops. LinearAlgebra.LAPACK.potrs!(uplo, L, τbiased) # τbiased == v̇ <- M⁻¹ * (τ - c) end nothing end """ $(SIGNATURES) Compute the joint acceleration vector ``\\dot{v}`` and Lagrange multipliers ``\\lambda`` that satisfy the joint-space equations of motion ```math M(q) \\dot{v} + c(q, v, w_\\text{ext}) = \\tau - K(q)^{T} \\lambda ``` and the constraint equations ```math K(q) \\dot{v} = -k ``` given joint configuration vector ``q``, joint velocity vector ``v``, and (optionally) joint torques ``\\tau`` and external wrenches ``w_\\text{ext}``. The `externalwrenches` argument can be used to specify additional wrenches that act on the `Mechanism`'s bodies. $stabilization_gains_doc """ function dynamics!(result::DynamicsResult, state::MechanismState{X}, torques::AbstractVector = ConstVector(zero(X), num_velocities(state)), externalwrenches::AbstractDict{BodyID, <:Wrench} = NullDict{BodyID, Wrench{X}}(); stabilization_gains=default_constraint_stabilization_gains(X)) where X configuration_derivative!(result.q̇, state) contact_dynamics!(result, state) for jointid in state.treejointids bodyid = successorid(jointid, state) contactwrench = result.contactwrenches[bodyid] result.totalwrenches[bodyid] = haskey(externalwrenches, bodyid) ? externalwrenches[bodyid] + contactwrench : contactwrench end dynamics_bias!(result, state) mass_matrix!(result, state) if has_loops(state.mechanism) constraint_jacobian!(result, state) constraint_bias!(result, state; stabilization_gains=stabilization_gains) end dynamics_solve!(result, parent(torques)) nothing end """ $(SIGNATURES) Convenience function for use with standard ODE integrators that takes a `Vector` argument ```math x = \\left(\\begin{array}{c} q\\\\ v \\end{array}\\right) ``` and returns a `Vector` ``\\dot{x}``. """ function dynamics!(ẋ::StridedVector{X}, result::DynamicsResult, state::MechanismState{X}, x::AbstractVector{X}, torques::AbstractVector = ConstVector(zero(X), num_velocities(state)), externalwrenches::AbstractDict{BodyID, <:Wrench} = NullDict{BodyID, Wrench{X}}(); stabilization_gains=default_constraint_stabilization_gains(X)) where X copyto!(state, x) dynamics!(result, state, torques, externalwrenches; stabilization_gains=stabilization_gains) copyto!(ẋ, result) ẋ end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
17482
""" $(SIGNATURES) Attach `successor` to `predecessor` using `joint`. See [`Joint`](@ref) for definitions of the terms successor and predecessor. The `Transform3D`s `joint_pose` and `successor_pose` define where `joint` is attached to each body. `joint_pose` should define `frame_before(joint)` with respect to any frame fixed to `predecessor`, and likewise `successor_pose` should define any frame fixed to `successor` with respect to `frame_after(joint)`. `predecessor` is required to already be among the bodies of the `Mechanism`. If `successor` is not yet a part of the `Mechanism`, it will be added to the `Mechanism`. Otherwise, the `joint` will be treated as a non-tree edge in the `Mechanism`, effectively creating a loop constraint that will be enforced using Lagrange multipliers (as opposed to using recursive algorithms). """ function attach!(mechanism::Mechanism{T}, predecessor::RigidBody{T}, successor::RigidBody{T}, joint::Joint{T}; joint_pose::Transform3D = one(Transform3D{T}, frame_before(joint), default_frame(predecessor)), successor_pose::Transform3D = one(Transform3D{T}, default_frame(successor), frame_after(joint))) where {T} @assert joint_pose.from == frame_before(joint) @assert successor_pose.to == frame_after(joint) @assert predecessor ∈ bodies(mechanism) @assert joint ∉ joints(mechanism) # define where joint is attached on predecessor joint.joint_to_predecessor[] = joint_pose add_frame!(predecessor, joint_pose) # define where child is attached to joint joint.joint_to_successor[] = inv(successor_pose) add_frame!(successor, joint.joint_to_successor[]) # update graph if successor ∈ bodies(mechanism) add_edge!(mechanism.graph, predecessor, successor, joint) else add_edge!(mechanism.tree, predecessor, successor, joint) canonicalize_frame_definitions!(mechanism, successor) end register_modification!(mechanism) mechanism end function _copyjoint!(dest::Mechanism{T}, src::Mechanism{T}, srcjoint::Joint{T}, bodymap::AbstractDict{RigidBody{T}, RigidBody{T}}, jointmap::AbstractDict{Joint{T}, Joint{T}}) where {T} srcpredecessor = source(srcjoint, src.graph) srcsuccessor = target(srcjoint, src.graph) joint_to_predecessor = fixed_transform(srcpredecessor, frame_before(srcjoint), default_frame(srcpredecessor)) successor_to_joint = fixed_transform(srcsuccessor, default_frame(srcsuccessor), frame_after(srcjoint)) destpredecessor = get!(() -> deepcopy(srcpredecessor), bodymap, srcpredecessor) destsuccessor = get!(() -> deepcopy(srcsuccessor), bodymap, srcsuccessor) destjoint = jointmap[srcjoint] = deepcopy(srcjoint) attach!(dest, destpredecessor, destsuccessor, destjoint; joint_pose = joint_to_predecessor, successor_pose = successor_to_joint) end const bodymap_jointmap_doc = """ * `bodymap::AbstractDict{RigidBody{T}, RigidBody{T}}`: will be populated with the mapping from input mechanism's bodies to output mechanism's bodies * `jointmap::AbstractDict{<:Joint{T}, <:Joint{T}}`: will be populated with the mapping from input mechanism's joints to output mechanism's joints where `T` is the element type of `mechanism`. """ """ $(SIGNATURES) Attach a copy of `childmechanism` to `mechanism`. Essentially replaces the root body of a copy of `childmechanism` with `parentbody` (which belongs to `mechanism`). Note: gravitational acceleration for `childmechanism` is ignored. Keyword arguments: * `child_root_pose`: pose of the default frame of the root body of `childmechanism` relative to that of `parentbody`. Default: the identity transformation. $bodymap_jointmap_doc """ function attach!(mechanism::Mechanism{T}, parentbody::RigidBody{T}, childmechanism::Mechanism{T}; child_root_pose = one(Transform3D{T}, default_frame(root_body(childmechanism)), default_frame(parentbody)), bodymap::AbstractDict{RigidBody{T}, RigidBody{T}}=Dict{RigidBody{T}, RigidBody{T}}(), jointmap::AbstractDict{<:Joint{T}, <:Joint{T}}=Dict{Joint{T}, Joint{T}}()) where {T} # FIXME: test with cycles @assert mechanism != childmechanism # infinite loop otherwise empty!(bodymap) empty!(jointmap) # Define where child root body is located w.r.t parent body and add frames that were attached to childroot to parentbody. childroot = root_body(childmechanism) add_frame!(parentbody, child_root_pose) for transform in frame_definitions(childroot) add_frame!(parentbody, transform) end bodymap[childroot] = parentbody # Insert childmechanism's non-root vertices and joints, starting with the tree joints (to preserve order). for joint in flatten((tree_joints(childmechanism), non_tree_joints(childmechanism))) _copyjoint!(mechanism, childmechanism, joint, bodymap, jointmap) end canonicalize_frame_definitions!(mechanism, parentbody) mechanism end """ $(SIGNATURES) Create a new `Mechanism` from the subtree of `mechanism` rooted at `submechanismroot`. Any non-tree joint in `mechanism` will appear in the returned `Mechanism` if and only if both its successor and its predecessor are part of the subtree. Keyword arguments: $bodymap_jointmap_doc """ function submechanism(mechanism::Mechanism{T}, submechanismroot::RigidBody{T}; bodymap::AbstractDict{RigidBody{T}, RigidBody{T}}=Dict{RigidBody{T}, RigidBody{T}}(), jointmap::AbstractDict{<:Joint{T}, <:Joint{T}}=Dict{Joint{T}, Joint{T}}()) where {T} # FIXME: test with cycles empty!(bodymap) empty!(jointmap) # Create Mechanism root = bodymap[submechanismroot] = deepcopy(submechanismroot) ret = Mechanism(root; gravity = mechanism.gravitational_acceleration.v) # Add tree joints, preserving order in input mechanism. for joint in tree_joints(mechanism) # assumes toposort if haskey(bodymap, predecessor(joint, mechanism)) _copyjoint!(ret, mechanism, joint, bodymap, jointmap) end end # Add non-tree joints. for joint in non_tree_joints(mechanism) if haskey(bodymap, predecessor(joint, mechanism)) && haskey(bodymap, successor(joint, mechanism)) _copyjoint!(ret, mechanism, joint, bodymap, jointmap) end end ret end """ Remove all bodies in the subtree rooted at `subtree_root`, including `subtree_root` itself, as well as all joints connected to these bodies. The ordering of the joints that remain in the mechanism is retained. """ function remove_subtree!(mechanism::Mechanism{T}, subtree_root::RigidBody{T}) where {T} @assert subtree_root != root_body(mechanism) tree = mechanism.tree graph = mechanism.graph bodies_to_remove = subtree_vertices(subtree_root, tree) new_tree_joints = copy(edges(tree)) for body in bodies_to_remove # Remove the tree joint from our new ordered list of joints. tree_joint = edge_to_parent(body, tree) deleteat!(new_tree_joints, findfirst(isequal(tree_joint), new_tree_joints)) end for body in bodies_to_remove # Remove all edges to and from the vertex in the graph. for joint in copy(in_edges(body, graph)) remove_edge!(graph, joint) end for joint in copy(out_edges(body, graph)) remove_edge!(graph, joint) end # Remove the vertex itself. remove_vertex!(graph, body) end # Construct a new spanning tree with the new list of tree joints. mechanism.tree = SpanningTree(graph, root_body(mechanism), new_tree_joints) canonicalize_graph!(mechanism) mechanism end """ $(SIGNATURES) Reconstruct the mechanism's spanning tree. Optionally, the `flipped_joint_map` keyword argument can be used to pass in an associative container that will be populated with a mapping from original joints to flipped joints, if the rebuilding process required the polarity of some joints to be flipped. Also optionally, `next_edge` can be used to select which joints should become part of the new spanning tree. """ function rebuild_spanning_tree!(mechanism::Mechanism{M}, flipped_joint_map::Union{AbstractDict, Nothing} = nothing; next_edge = first #= breadth first =#) where {M} mechanism.tree = SpanningTree(mechanism.graph, root_body(mechanism), flipped_joint_map; next_edge = next_edge) register_modification!(mechanism) canonicalize_frame_definitions!(mechanism) mechanism end """ $(SIGNATURES) Remove a joint from the mechanism. Rebuilds the spanning tree if the joint is part of the current spanning tree. Optionally, the `flipped_joint_map` keyword argument can be used to pass in an associative container that will be populated with a mapping from original joints to flipped joints, if removing `joint` requires rebuilding the spanning tree of `mechanism` and the polarity of some joints needed to be changed in the process. Also optionally, `spanning_tree_next_edge` can be used to select which joints should become part of the new spanning tree, if rebuilding the spanning tree is required. """ function remove_joint!(mechanism::Mechanism{M}, joint::Joint{M}; flipped_joint_map::Union{AbstractDict, Nothing} = nothing, spanning_tree_next_edge = first #= breadth first =#) where {M} istreejoint = joint ∈ tree_joints(mechanism) remove_edge!(mechanism.graph, joint) register_modification!(mechanism) if istreejoint rebuild_spanning_tree!(mechanism, flipped_joint_map, next_edge=spanning_tree_next_edge) # also recanonicalizes frame definitions canonicalize_graph!(mechanism) end nothing end function replace_joint!(mechanism::Mechanism, oldjoint::Joint, newjoint::Joint) # TODO: can hopefully remove this again once Joint is mutable again @assert frame_before(newjoint) == frame_before(oldjoint) @assert frame_after(newjoint) == frame_after(oldjoint) set_joint_to_predecessor!(newjoint, oldjoint.joint_to_predecessor[]) set_joint_to_successor!(newjoint, oldjoint.joint_to_successor[]) if oldjoint ∈ tree_joints(mechanism) replace_edge!(mechanism.tree, oldjoint, newjoint) else replace_edge!(mechanism.graph, oldjoint, newjoint) end register_modification!(mechanism) nothing end """ $(SIGNATURES) Remove any fixed joints present as tree edges in `mechanism` by merging the rigid bodies that these fixed joints join together into bodies with equivalent inertial properties. """ function remove_fixed_tree_joints!(mechanism::Mechanism{T}) where T # FIXME: test with cycles graph = mechanism.graph # Update graph. fixedjoints = filter(j -> joint_type(j) isa Fixed, tree_joints(mechanism)) newtreejoints = setdiff(tree_joints(mechanism), fixedjoints) for fixedjoint in fixedjoints pred = source(fixedjoint, graph) succ = target(fixedjoint, graph) # Add identity joint transform as a body-fixed frame definition. jointtransform = one(Transform3D{T}, frame_after(fixedjoint), frame_before(fixedjoint)) add_frame!(pred, jointtransform) # Migrate body fixed frames to parent body. for tf in frame_definitions(succ) add_frame!(pred, tf) end # Migrate contact points to parent body. for point in contact_points(succ) add_contact_point!(pred, point) end # Add inertia to parent body. if has_defined_inertia(pred) inertia = spatial_inertia(succ) parentinertia = spatial_inertia(pred) toparent = fixed_transform(pred, inertia.frame, parentinertia.frame) spatial_inertia!(pred, parentinertia + transform(inertia, toparent)) end # Merge vertex into parent. for joint in copy(in_edges(succ, graph)) if joint == fixedjoint remove_edge!(graph, joint) else rewire!(graph, joint, source(joint, graph), pred) end end for joint in copy(out_edges(succ, graph)) rewire!(graph, joint, pred, target(joint, graph)) end remove_vertex!(mechanism.graph, succ) end # Recompute spanning tree (preserves order for non-fixed joints) mechanism.tree = SpanningTree(graph, root_body(mechanism), newtreejoints) # Recanonicalize graph and frames canonicalize_frame_definitions!(mechanism) canonicalize_graph!(mechanism) register_modification!(mechanism) mechanism end # TODO: remove floating_non_tree_joints """ $(SIGNATURES) Return a dynamically equivalent `Mechanism`, but with a flat tree structure: all bodies are attached to the root body via a floating joint, and the tree joints of the input `Mechanism` are transformed into non-tree joints (with joint constraints enforced using Lagrange multipliers in `dynamics!`). Keyword arguments: * `floating_joint_type::Type{<:JointType{T}}`: which floating joint type to use for the joints between each body and the root. Default: `QuaternionFloating{T}` $bodymap_jointmap_doc """ function maximal_coordinates(mechanism::Mechanism{T}; floating_joint_type::Type{<:JointType{T}}=QuaternionFloating{T}, bodymap::AbstractDict{RigidBody{T}, RigidBody{T}}=Dict{RigidBody{T}, RigidBody{T}}(), jointmap::AbstractDict{<:Joint{T}, <:Joint{T}}=Dict{Joint{T}, Joint{T}}()) where T @assert isfloating(floating_joint_type) empty!(bodymap) empty!(jointmap) # Copy root. root = bodymap[root_body(mechanism)] = deepcopy(root_body(mechanism)) ret = Mechanism(root, gravity = mechanism.gravitational_acceleration.v) # Copy non-root bodies and attach them to the root with a floating joint. for srcbody in non_root_bodies(mechanism) framebefore = default_frame(root) frameafter = default_frame(srcbody) body = bodymap[srcbody] = deepcopy(srcbody) floatingjoint = Joint(string(body), framebefore, frameafter, floating_joint_type()) attach!(ret, root, body, floatingjoint, joint_pose = one(Transform3D{T}, framebefore), successor_pose = one(Transform3D{T}, frameafter)) end # Copy input Mechanism's joints. for joint in flatten((tree_joints(mechanism), non_tree_joints(mechanism))) _copyjoint!(ret, mechanism, joint, bodymap, jointmap) end ret end function canonicalize_graph!(mechanism::Mechanism) root = root_body(mechanism) treejoints = copy(tree_joints(mechanism)) edges = vcat(treejoints, non_tree_joints(mechanism)) vertices = append!([root], successor(joint, mechanism) for joint in treejoints) reindex!(mechanism.graph, vertices, edges) mechanism.tree = SpanningTree(mechanism.graph, root, treejoints) # otherwise tree.edge_tree_indices can go out of sync register_modification!(mechanism) mechanism end add_environment_primitive!(mechanism::Mechanism, halfspace::HalfSpace3D) = push!(mechanism.environment, halfspace) """ $(SIGNATURES) Create a random tree `Mechanism` with the given joint types. Each new body is attached to a parent selected using the `parentselector` function. """ function rand_tree_mechanism(::Type{T}, parentselector::Function, jointtypes::Vararg{Type{<:JointType{T}}}) where {T} parentbody = RigidBody{T}("world") mechanism = Mechanism(parentbody) for (i, jointtype) in enumerate(jointtypes) joint = Joint("joint$i", rand(jointtype)) joint_to_parent_body = rand(Transform3D{T}, frame_before(joint), default_frame(parentbody)) body = RigidBody(rand(SpatialInertia{T}, CartesianFrame3D("body$i"))) body_to_joint = one(Transform3D{T}, default_frame(body), frame_after(joint)) attach!(mechanism, parentbody, body, joint, joint_pose = joint_to_parent_body, successor_pose = body_to_joint) parentbody = parentselector(mechanism) end return mechanism end rand_tree_mechanism(parentselector::Function, jointtypes::Vararg{Type{<:JointType{T}}}) where {T} = rand_tree_mechanism(T, parentselector, jointtypes...) """ $(SIGNATURES) Create a random chain `Mechanism` with the given joint types. """ rand_chain_mechanism(::Type{T}, jointtypes::Vararg{Type{<:JointType{T}}}) where {T} = rand_tree_mechanism(T, mechanism::Mechanism -> last(bodies(mechanism)), jointtypes...) rand_chain_mechanism(jointtypes::Vararg{Type{<:JointType{T}}}) where {T} = rand_chain_mechanism(T, jointtypes...) """ $(SIGNATURES) Create a random tree `Mechanism`. """ rand_tree_mechanism(::Type{T}, jointtypes::Vararg{Type{<:JointType{T}}}) where {T} = rand_tree_mechanism(T, mechanism::Mechanism -> rand(bodies(mechanism)), jointtypes...) rand_tree_mechanism(jointtypes::Vararg{Type{<:JointType{T}}}) where {T} = rand_tree_mechanism(T, jointtypes...) """ $(SIGNATURES) Create a random tree `Mechanism`, with a quaternion floating joint as the first joint (between the root body and the first non-root body). """ function rand_floating_tree_mechanism(::Type{T}, nonfloatingjointtypes::Vararg{Type{<:JointType{T}}}) where {T} parentselector = (mechanism::Mechanism) -> begin only_root = length(bodies(mechanism)) == 1 only_root ? root_body(mechanism) : rand(collect(non_root_bodies(mechanism))) end rand_tree_mechanism(parentselector, QuaternionFloating{T}, nonfloatingjointtypes...) end rand_floating_tree_mechanism(nonfloatingjointtypes::Vararg{Type{<:JointType{T}}}) where {T} = rand_floating_tree_mechanism(T, nonfloatingjointtypes...)
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
41374
## BodyDict, JointDict const BodyDict{V} = IndexDict{BodyID, Base.OneTo{BodyID}, V} const BodyCacheDict{V} = CacheIndexDict{BodyID, Base.OneTo{BodyID}, V} @propagate_inbounds Base.getindex(d::AbstractIndexDict{BodyID}, key::RigidBody) = d[BodyID(key)] @propagate_inbounds Base.setindex!(d::AbstractIndexDict{BodyID}, value, key::RigidBody) = d[BodyID(key)] = value const JointDict{V} = IndexDict{JointID, Base.OneTo{JointID}, V} const JointCacheDict{V} = CacheIndexDict{JointID, Base.OneTo{JointID}, V} @propagate_inbounds Base.getindex(d::AbstractIndexDict{JointID}, key::Joint) = d[JointID(key)] @propagate_inbounds Base.setindex!(d::AbstractIndexDict{JointID}, value, key::Joint) = d[JointID(key)] = value ## SegmentedVector method overloads @propagate_inbounds Base.getindex(v::SegmentedVector{JointID}, joint::Joint) = v[JointID(joint)] @propagate_inbounds Base.view(v::SegmentedVector{JointID}, joint::Joint) = Base.view(v, JointID(joint)) function SegmentedVector(parent::AbstractVector{T}, joints::AbstractVector{<:Joint}, viewlengthfun) where T SegmentedVector{JointID, T, Base.OneTo{JointID}}(parent, joints, viewlengthfun) end """ $(TYPEDEF) A `MechanismState` stores state information for an entire `Mechanism`. It contains the joint configuration and velocity vectors ``q`` and ``v``, and a vector of additional states ``s``. In addition, it stores cache variables that depend on ``q`` and ``v`` and are aimed at preventing double work. Type parameters: * `X`: the scalar type of the ``q``, ``v``, and ``s`` vectors. * `M`: the scalar type of the `Mechanism` * `C`: the scalar type of the cache variables (`== promote_type(X, M)`) * `JointCollection`: the type of the `treejoints` and `nontreejoints` members (a `TypeSortedCollection` subtype) """ struct MechanismState{X, M, C, JointCollection} modcount::Int # mechanism layout mechanism::Mechanism{M} nonrootbodies::Vector{RigidBody{M}} # TODO: remove once https://github.com/JuliaLang/julia/issues/14955 is fixed treejoints::JointCollection nontreejoints::JointCollection jointids::Base.OneTo{JointID} treejointids::Base.OneTo{JointID} nontreejointids::UnitRange{JointID} predecessor_and_successor_ids::JointDict{Pair{BodyID, BodyID}} qranges::JointDict{UnitRange{Int}} vranges::JointDict{UnitRange{Int}} constraintranges::IndexDict{JointID, UnitRange{JointID}, UnitRange{Int}} support_set_masks::BodyDict{JointDict{Bool}} # TODO: use a Matrix-backed type constraint_jacobian_structure::JointDict{TreePath{RigidBody{M}, Joint{M}}} # TODO: use a Matrix-backed type q_index_to_joint_id::Vector{JointID} v_index_to_joint_id::Vector{JointID} # minimal representation of state q::SegmentedVector{JointID, X, Base.OneTo{JointID}, Vector{X}} # configurations v::SegmentedVector{JointID, X, Base.OneTo{JointID}, Vector{X}} # velocities s::Vector{X} # additional state # joint-related cache joint_transforms::JointCacheDict{Transform3D{C}} joint_twists::JointCacheDict{Twist{C}} joint_bias_accelerations::JointCacheDict{SpatialAcceleration{C}} tree_joint_transforms::VectorSegment{Transform3D{C}} non_tree_joint_transforms::VectorSegment{Transform3D{C}} # motion_subspaces::CacheElement{Vector{GeometricJacobian{SMatrix{3, 1, C, 3}}}} # TODO: use CacheIndexDict? constraint_wrench_subspaces::CacheElement{Vector{WrenchMatrix{SMatrix{3, 1, C, 3}}}} # TODO: use CacheIndexDict? # body-related cache transforms_to_root::BodyCacheDict{Transform3D{C}} twists_wrt_world::BodyCacheDict{Twist{C}} bias_accelerations_wrt_world::BodyCacheDict{SpatialAcceleration{C}} inertias::BodyCacheDict{SpatialInertia{C}} crb_inertias::BodyCacheDict{SpatialInertia{C}} contact_states::BodyCacheDict{Vector{Vector{DefaultSoftContactState{X}}}} # TODO: consider moving to separate type function MechanismState{X, M, C, JointCollection}(m::Mechanism{M}, q::Vector{X}, v::Vector{X}, s::Vector{X}) where {X, M, C, JointCollection} @assert length(q) == num_positions(m) @assert length(v) == num_velocities(m) @assert length(s) == num_additional_states(m) # mechanism layout nonrootbodies = collect(non_root_bodies(m)) treejoints = JointCollection(tree_joints(m)) nontreejoints = JointCollection(non_tree_joints(m)) lastjointid = isempty(joints(m)) ? JointID(0) : JointID(last(joints(m))) lasttreejointid = isempty(tree_joints(m)) ? JointID(0) : JointID(last(tree_joints(m))) jointids = Base.OneTo(lastjointid) treejointids = Base.OneTo(lasttreejointid) nontreejointids = lasttreejointid + 1 : lastjointid predecessor_and_successor_ids = JointDict{Pair{BodyID, BodyID}}( JointID(j) => (BodyID(predecessor(j, m)) => BodyID(successor(j, m))) for j in joints(m)) support_set = function (b::RigidBody) JointDict{Bool}(JointID(j) => (j ∈ tree_joints(m) ? j ∈ path(m, b, root_body(m)) : false) for j in joints(m)) end support_set_masks = BodyDict{JointDict{Bool}}(b => support_set(b) for b in bodies(m)) constraint_jacobian_structure = JointDict{TreePath{RigidBody{M}, Joint{M}}}( JointID(j) => path(m, predecessor(j, m), successor(j, m)) for j in joints(m)) qsegmented = SegmentedVector(q, tree_joints(m), num_positions) vsegmented = SegmentedVector(v, tree_joints(m), num_velocities) qranges = ranges(qsegmented) vranges = ranges(vsegmented) constraintranges = let start = 1 rangevec = UnitRange{Int}[start : (start += num_constraints(j)) - 1 for j in non_tree_joints(m)] IndexDict(nontreejointids, rangevec) end q_index_to_joint_id = Vector{JointID}(undef, length(q)) v_index_to_joint_id = Vector{JointID}(undef, length(v)) for jointid in treejointids for qindex in qranges[jointid] q_index_to_joint_id[qindex] = jointid end for vindex in vranges[jointid] v_index_to_joint_id[vindex] = jointid end end # joint-related cache joint_transforms = JointCacheDict{Transform3D{C}}(jointids) joint_twists = JointCacheDict{Twist{C}}(treejointids) joint_bias_accelerations = JointCacheDict{SpatialAcceleration{C}}(treejointids) tree_joint_transforms = view(values(joint_transforms), 1 : Int(lasttreejointid)) non_tree_joint_transforms = view(values(joint_transforms), Int(lasttreejointid) + 1 : Int(lastjointid)) # motion subspaces, constraint wrench subspaces motion_subspaces = CacheElement(Vector{GeometricJacobian{SMatrix{3, 1, C, 3}}}(undef, num_velocities(m))) constraint_wrench_subspaces = CacheElement(Vector{WrenchMatrix{SMatrix{3, 1, C, 3}}}(undef, num_constraints(m))) # body-related cache bodyids = Base.OneTo(BodyID(last(bodies(m)))) transforms_to_root = BodyCacheDict{Transform3D{C}}(bodyids) twists_wrt_world = BodyCacheDict{Twist{C}}(bodyids) bias_accelerations_wrt_world = BodyCacheDict{SpatialAcceleration{C}}(bodyids) inertias = BodyCacheDict{SpatialInertia{C}}(bodyids) crb_inertias = BodyCacheDict{SpatialInertia{C}}(bodyids) # contact. TODO: move out of MechanismState: contact_states = BodyCacheDict{Vector{Vector{DefaultSoftContactState{X}}}}( BodyID(b) => Vector{Vector{DefaultSoftContactState{X}}}() for b in bodies(m)) startind = 1 for body in bodies(m), point in contact_points(body) model = contact_model(point) n = num_states(model) push!(contact_states[body], collect(begin s_part = view(s, startind : startind + n - 1) contact_state = SoftContactState(model, s_part, root_frame(m)) startind += n contact_state end for j = 1 : length(m.environment))) end # initialize state-independent cache data for root bodies: root = root_body(m) rootframe = default_frame(root) transforms_to_root[root] = one(Transform3D{C}, rootframe) twists_wrt_world[root] = zero(Twist{C}, rootframe, rootframe, rootframe) bias_accelerations_wrt_world[root] = zero(SpatialAcceleration{C}, rootframe, rootframe, rootframe) inertias[root] = zero(SpatialInertia{C}, rootframe) new{X, M, C, JointCollection}( modcount(m), m, nonrootbodies, treejoints, nontreejoints, jointids, treejointids, nontreejointids, predecessor_and_successor_ids, qranges, vranges, constraintranges, support_set_masks, constraint_jacobian_structure, q_index_to_joint_id, v_index_to_joint_id, qsegmented, vsegmented, s, joint_transforms, joint_twists, joint_bias_accelerations, tree_joint_transforms, non_tree_joint_transforms, motion_subspaces, constraint_wrench_subspaces, transforms_to_root, twists_wrt_world, bias_accelerations_wrt_world, inertias, crb_inertias, contact_states) end function MechanismState{X, M, C}(mechanism::Mechanism{M}, q::Vector{X}, v::Vector{X}, s::Vector{X}) where {X, M, C} JointCollection = typeof(TypeSortedCollection(joints(mechanism))) MechanismState{X, M, C, JointCollection}(mechanism, q, v, s) end function MechanismState{X, M}(mechanism::Mechanism{M}, q::Vector{X}, v::Vector{X}, s::Vector{X}) where {X, M} C = promote_type(X, M) MechanismState{X, M, C}(mechanism, q, v, s) end function MechanismState{X}(mechanism::Mechanism{M}) where {X, M} q = Vector{X}(undef, num_positions(mechanism)) v = Vector{X}(undef, num_velocities(mechanism)) s = Vector{X}(undef, num_additional_states(mechanism)) state = MechanismState{X, M}(mechanism, q, v, s) zero!(state) state end end function MechanismState(mechanism::Mechanism{M}, q::Vector{X}, v::Vector{X}, s=zeros(X, num_additional_states(mechanism))) where {X, M} MechanismState{X, M}(mechanism, q, v, s) end MechanismState(mechanism::Mechanism{M}) where {M} = MechanismState{M}(mechanism) Base.broadcastable(x::MechanismState) = Ref(x) Base.show(io::IO, ::MechanismState{X, M, C}) where {X, M, C} = print(io, "MechanismState{$X, $M, $C, …}(…)") modcount(state::MechanismState) = state.modcount @propagate_inbounds predsucc(id::JointID, state::MechanismState) = state.predecessor_and_successor_ids[id] @propagate_inbounds successorid(id::JointID, state::MechanismState) = last(state.predecessor_and_successor_ids[id]) """ $(SIGNATURES) Return the length of the joint configuration vector ``q``. """ num_positions(state::MechanismState) = length(state.q) """ $(SIGNATURES) Return the length of the joint velocity vector ``v``. """ num_velocities(state::MechanismState) = length(state.v) """ $(SIGNATURES) Return the length of the vector of additional states ``s`` (currently used for stateful contact models). """ num_additional_states(state::MechanismState) = length(state.s) state_vector_eltype(state::MechanismState{X, M, C}) where {X, M, C} = X mechanism_eltype(state::MechanismState{X, M, C}) where {X, M, C} = M cache_eltype(state::MechanismState{X, M, C}) where {X, M, C} = C """ $(SIGNATURES) Return the part of the configuration vector ``q`` associated with `joint`. """ configuration(state::MechanismState, joint::Union{<:Joint, JointID}) = state.q[joint] """ $(SIGNATURES) Return the part of the velocity vector ``v`` associated with `joint`. """ velocity(state::MechanismState, joint::Union{<:Joint, JointID}) = state.v[joint] """ $(SIGNATURES) Invalidate all cache variables. """ function setdirty!(state::MechanismState) CustomCollections.setdirty!(state.joint_transforms) CustomCollections.setdirty!(state.joint_twists) CustomCollections.setdirty!(state.joint_bias_accelerations) CustomCollections.setdirty!(state.motion_subspaces) CustomCollections.setdirty!(state.constraint_wrench_subspaces) CustomCollections.setdirty!(state.transforms_to_root) CustomCollections.setdirty!(state.twists_wrt_world) CustomCollections.setdirty!(state.bias_accelerations_wrt_world) CustomCollections.setdirty!(state.inertias) CustomCollections.setdirty!(state.crb_inertias) nothing end """ $(SIGNATURES) Reset all contact state variables. """ function reset_contact_state!(state::MechanismState) for states_for_body in values(state.contact_states) for states_for_point in states_for_body for contact_state in states_for_point reset!(contact_state) end end end end """ $(SIGNATURES) 'Zero' the configuration vector ``q``. Invalidates cache variables. Note that when the `Mechanism` contains e.g. quaternion-parameterized joints, ``q`` may not actually be set to all zeros; the quaternion part of the configuration vector would be set to identity. The contract is that each of the joint transforms should be an identity transform. """ function zero_configuration!(state::MechanismState) foreach(state.treejoints, values(segments(state.q))) do joint, qjoint zero_configuration!(qjoint, joint) end reset_contact_state!(state) setdirty!(state) end """ $(SIGNATURES) Zero the velocity vector ``v``. Invalidates cache variables. """ function zero_velocity!(state::MechanismState) state.v .= 0 reset_contact_state!(state) setdirty!(state) end """ $(SIGNATURES) Zero both the configuration and velocity. Invalidates cache variables. See [`zero_configuration!`](@ref), [`zero_velocity!`](@ref). """ zero!(state::MechanismState) = (zero_configuration!(state); zero_velocity!(state)) """ $(SIGNATURES) Randomize the configuration vector ``q``. The distribution depends on the particular joint types present in the associated `Mechanism`. The resulting ``q`` is guaranteed to be on the `Mechanism`'s configuration manifold. Invalidates cache variables. """ function rand_configuration!(state::MechanismState) foreach(state.treejoints, values(segments(state.q))) do joint, qjoint rand_configuration!(qjoint, joint) end reset_contact_state!(state) setdirty!(state) end """ $(SIGNATURES) Randomize the velocity vector ``v``. Invalidates cache variables. """ function rand_velocity!(state::MechanismState) rand!(state.v) reset_contact_state!(state) setdirty!(state) end """ $(SIGNATURES) Randomize both the configuration and velocity. Invalidates cache variables. """ Random.rand!(state::MechanismState) = begin rand_configuration!(state); rand_velocity!(state) end """ $(SIGNATURES) Return the configuration vector ``q``. Note that this returns a reference to the underlying data in `state`. The user is responsible for calling [`setdirty!`](@ref) after modifying this vector to ensure that dependent cache variables are invalidated. """ configuration(state::MechanismState) = state.q """ $(SIGNATURES) Return the velocity vector ``v``. Note that this function returns a read-write reference to a field in `state`. The user is responsible for calling [`setdirty!`](@ref) after modifying this vector to ensure that dependent cache variables are invalidated. """ velocity(state::MechanismState) = state.v """ $(SIGNATURES) Return the vector of additional states ``s``. """ additional_state(state::MechanismState) = state.s for fun in (:num_velocities, :num_positions) @eval function $fun(p::TreePath{RigidBody{T}, <:Joint{T}} where {T}) mapreduce($fun, +, p; init=0) end end """ $(SIGNATURES) Set the part of the configuration vector associated with `joint`. Invalidates cache variables. """ function set_configuration!(state::MechanismState, joint::Joint, config) set_configuration!(configuration(state, joint), joint, config) reset_contact_state!(state) setdirty!(state) end """ $(SIGNATURES) Set the part of the velocity vector associated with `joint`. Invalidates cache variables. """ function set_velocity!(state::MechanismState, joint::Joint, vel) set_velocity!(velocity(state, joint), joint, vel) reset_contact_state!(state) setdirty!(state) end """ $(SIGNATURES) Set the configuration vector ``q``. Invalidates cache variables. """ function set_configuration!(state::MechanismState, q::AbstractVector) copyto!(state.q, q) setdirty!(state) end """ $(SIGNATURES) Set the velocity vector ``v``. Invalidates cache variables. """ function set_velocity!(state::MechanismState, v::AbstractVector) copyto!(state.v, v) setdirty!(state) end """ $(SIGNATURES) Set the vector of additional states ``s``. """ function set_additional_state!(state::MechanismState, s::AbstractVector) copyto!(state.s, s) # note: setdirty! is currently not needed because no cache variables depend on s end """ $(SIGNATURES) Copy (minimal representation of) state `src` to state `dest`. """ function Base.copyto!(dest::MechanismState, src::MechanismState) dest.mechanism == src.mechanism || throw(ArgumentError("States are not associated with the same Mechanism.")) @modcountcheck dest src copyto!(dest.q, src.q) copyto!(dest.v, src.v) copyto!(dest.s, src.s) setdirty!(dest) dest end """ $(SIGNATURES) Copy state information in vector `src` (ordered `[q; v; s]`) to state `dest`. """ function Base.copyto!(dest::MechanismState, src::AbstractVector) nq = num_positions(dest) nv = num_velocities(dest) ns = num_additional_states(dest) @boundscheck length(src) == nq + nv + ns || throw(DimensionMismatch()) @inbounds copyto!(parent(dest.q), 1, src, 1, nq) @inbounds copyto!(parent(dest.v), 1, src, nq + 1, nv) @inbounds copyto!(dest.s, 1, src, nq + nv + 1, ns) setdirty!(dest) dest end """ $(SIGNATURES) Copy state information in state `dest` to vector `src` (ordered `[q; v; s]`). """ function Base.copyto!(dest::AbstractVector, src::MechanismState) nq = num_positions(src) nv = num_velocities(src) ns = num_additional_states(src) length(dest) == nq + nv + ns || throw(DimensionMismatch()) @inbounds copyto!(dest, 1, src.q, 1, nq) @inbounds copyto!(dest, nq + 1, src.v, 1, nv) @inbounds copyto!(dest, nq + nv + 1, src.s, 1, ns) dest end """ $(SIGNATURES) Create a `Vector` that represents the same state as `state` (ordered `[q; v; s]`). """ function Base.Vector{T}(state::MechanismState) where T dest = Vector{T}(undef, num_positions(state) + num_velocities(state) + num_additional_states(state)) copyto!(dest, state) end Base.Vector(state::MechanismState{X}) where {X} = Vector{X}(state) Base.Array{T}(state::MechanismState) where {T} = Vector{T}(state) Base.Array(state::MechanismState{X}) where {X} = Array{X}(state) Base.convert(::Type{T}, state::MechanismState) where {T<:Array} = T(state) """ $(SIGNATURES) Project the configuration vector ``q`` onto the configuration manifold. For example: * for a part of ``q`` corresponding to a revolute joint, this method is a no-op; * for a part of ``q`` corresponding to a spherical joint that uses a unit quaternion to parameterize the orientation of its successor with respect to its predecessor, `normalize_configuration!` will renormalize the quaternion so that it is indeed of unit length. !!! warning This method does not ensure that the configuration or velocity satisfy joint configuration or velocity limits/bounds. """ function normalize_configuration!(state::MechanismState) foreach(state.treejoints, values(segments(state.q))) do joint, qjoint normalize_configuration!(qjoint, joint) end end """ $(SIGNATURES) Applies the principal_value functions from [Rotations.jl](https://github.com/FugroRoames/Rotations.jl/blob/d080990517f89b56c37962ad53a7fd24bd94b9f7/src/principal_value.jl) to joint angles. This currently only applies to `SPQuatFloating` joints. For example: * for a part of ``q`` corresponding to a revolute joint, this method is a no-op; * for a part of ``q`` corresponding to a `SPQuatFloating` joint this function applies `principal_value the orientation. """ function principal_value!(state::MechanismState) foreach(state.treejoints, values(segments(state.q))) do joint, qjoint principal_value!(qjoint, joint) end end """ $(SIGNATURES) Return the range of indices into the joint configuration vector ``q`` corresponding to joint `joint`. """ @propagate_inbounds configuration_range(state::MechanismState, joint::Union{<:Joint, JointID}) = state.qranges[joint] """ $(SIGNATURES) Return the range of indices into the joint velocity vector ``v`` corresponding to joint `joint`. """ @propagate_inbounds velocity_range(state::MechanismState, joint::Union{<:Joint, JointID}) = state.vranges[joint] """ $(SIGNATURES) Return the `JointID` of the joint associated with the given index into the configuration vector ``q``. """ @propagate_inbounds configuration_index_to_joint_id(state::MechanismState, qindex::Integer) = state.q_index_to_joint_id[qindex] """ $(SIGNATURES) Return the `JointID` of the joint associated with the given index into the velocity vector ``v``. """ @propagate_inbounds velocity_index_to_joint_id(state::MechanismState, qindex::Integer) = state.v_index_to_joint_id[qindex] """ $(SIGNATURES) Return the range of row indices into the constraint Jacobian corresponding to joint `joint`. """ @propagate_inbounds constraint_range(state::MechanismState, joint::Union{<:Joint, JointID}) = state.constraintranges[joint] """ $(SIGNATURES) Return whether `joint` supports `body`, i.e., `joint` is a tree joint on the path between `body` and the root. """ @propagate_inbounds function supports(joint::Union{<:Joint, JointID}, body::Union{<:RigidBody, BodyID}, state::MechanismState) state.support_set_masks[body][joint] end ## Accessor functions for cached variables """ $(SIGNATURES) Return the joint transform for the given joint, i.e. the transform from `frame_after(joint)` to `frame_before(joint)`. """ @propagate_inbounds function joint_transform(state::MechanismState, joint::Union{<:Joint, JointID}, safe=true) safe && update_transforms!(state) state.joint_transforms[joint] end """ $(SIGNATURES) Return the joint twist for the given joint, i.e. the twist of `frame_after(joint)` with respect to `frame_before(joint)`, expressed in the root frame of the mechanism. """ @propagate_inbounds function twist(state::MechanismState, joint::Union{<:Joint, JointID}, safe=true) safe && update_joint_twists!(state) state.joint_twists[joint] end """ $(SIGNATURES) Return the bias acceleration across the given joint, i.e. the spatial acceleration of `frame_after(joint)` with respect to `frame_before(joint)`, expressed in the root frame of the mechanism when all joint accelerations are zero. """ @propagate_inbounds function bias_acceleration(state::MechanismState, joint::Union{<:Joint, JointID}, safe=true) safe && update_joint_bias_accelerations!(state) state.joint_bias_accelerations[joint] end """ $(SIGNATURES) Return the transform from `default_frame(body)` to the root frame of the mechanism. """ @propagate_inbounds function transform_to_root(state::MechanismState, body::Union{<:RigidBody, BodyID}, safe=true) safe && update_transforms!(state) state.transforms_to_root[body] end """ $(SIGNATURES) Return the twist of `default_frame(body)` with respect to the root frame of the mechanism, expressed in the root frame. """ @propagate_inbounds function twist_wrt_world(state::MechanismState, body::Union{<:RigidBody, BodyID}, safe=true) safe && update_twists_wrt_world!(state) state.twists_wrt_world[body] end """ $(SIGNATURES) Return the bias acceleration of the given body with respect to the world, i.e. the spatial acceleration of `default_frame(body)` with respect to the root frame of the mechanism, expressed in the root frame, when all joint accelerations are zero. """ @propagate_inbounds function bias_acceleration(state::MechanismState, body::Union{<:RigidBody, BodyID}, safe=true) safe && update_bias_accelerations_wrt_world!(state) state.bias_accelerations_wrt_world[body] end """ $(SIGNATURES) Return the spatial inertia of `body` expressed in the root frame of the mechanism. """ @propagate_inbounds function spatial_inertia(state::MechanismState, body::Union{<:RigidBody, BodyID}, safe=true) safe && update_spatial_inertias!(state) state.inertias[body] end """ $(SIGNATURES) Return the composite rigid body inertia `body` expressed in the root frame of the mechanism. """ @propagate_inbounds function crb_inertia(state::MechanismState, body::Union{<:RigidBody, BodyID}, safe=true) safe && update_crb_inertias!(state) state.crb_inertias[body] end # Cache variable update functions @inline update_transforms!(state::MechanismState) = isdirty(state.transforms_to_root) && _update_transforms!(state) @noinline function _update_transforms!(state::MechanismState) @modcountcheck state state.mechanism # update tree joint transforms qs = values(segments(state.q)) @inbounds map!(joint_transform, state.tree_joint_transforms, state.treejoints, qs) # update transforms to root transforms_to_root = state.transforms_to_root for joint in tree_joints(state.mechanism) jointid = JointID(joint) parentid, bodyid = predsucc(jointid, state) transforms_to_root[bodyid] = transforms_to_root[parentid] * joint_to_predecessor(joint) * state.joint_transforms[jointid] end state.transforms_to_root.dirty = false # update non-tree joint transforms if !isempty(state.nontreejointids) broadcast!(state.non_tree_joint_transforms, state, state.nontreejoints) do state, joint predid, succid = predsucc(JointID(joint), state) before_to_root = state.transforms_to_root[predid] * joint_to_predecessor(joint) after_to_root = state.transforms_to_root[succid] * joint_to_successor(joint) inv(before_to_root) * after_to_root end end state.joint_transforms.dirty = false nothing end @inline function update_joint_twists!(state::MechanismState) isdirty(state.joint_twists) && _update_joint_twists!(state) nothing end @noinline function _update_joint_twists!(state::MechanismState) qs = values(segments(state.q)) vs = values(segments(state.v)) @inbounds map!(joint_twist, values(state.joint_twists), state.treejoints, qs, vs) state.joint_twists.dirty = false nothing end @inline function update_joint_bias_accelerations!(state::MechanismState) isdirty(state.joint_bias_accelerations) && _update_joint_bias_accelerations!(state) nothing end @noinline function _update_joint_bias_accelerations!(state::MechanismState) qs = values(segments(state.q)) vs = values(segments(state.v)) @inbounds map!(bias_acceleration, values(state.joint_bias_accelerations), state.treejoints, qs, vs) state.joint_bias_accelerations.dirty = false nothing end @inline function update_motion_subspaces!(state::MechanismState) isdirty(state.motion_subspaces) && _update_motion_subspaces!(state) nothing end @inline function _motion_subspace(state::MechanismState, joint::Joint, qjoint::AbstractVector) jointid = JointID(joint) bodyid = successorid(jointid, state) transform(motion_subspace(joint, qjoint), transform_to_root(state, bodyid, false)) end @noinline function _update_motion_subspaces!(state::MechanismState) update_transforms!(state) qs = values(segments(state.q)) foreach_with_extra_args(state, state.treejoints, qs) do state, joint, qjoint S = _motion_subspace(state, joint, qjoint) @inbounds vrange = velocity_range(state, joint) @inbounds for col = Base.OneTo(size(S, 2)) Scol = GeometricJacobian(S.body, S.base, S.frame, SMatrix{3, 1}(S.angular[:, col]), SMatrix{3, 1}(S.linear[:, col])) vindex = vrange[col] state.motion_subspaces.data[vindex] = Scol end end state.motion_subspaces.dirty = false nothing end @inline function update_twists_wrt_world!(state::MechanismState) isdirty(state.twists_wrt_world) && _update_twists_wrt_world!(state) nothing end @noinline function _update_twists_wrt_world!(state::MechanismState) update_transforms!(state) update_joint_twists!(state) twists = state.twists_wrt_world @inbounds for jointid in state.treejointids parentbodyid, bodyid = predsucc(jointid, state) jointtwist = state.joint_twists[jointid] twists[bodyid] = twists[parentbodyid] + transform(jointtwist, transform_to_root(state, bodyid, false)) end state.twists_wrt_world.dirty = false nothing end @inline function update_constraint_wrench_subspaces!(state::MechanismState) isdirty(state.constraint_wrench_subspaces) && _update_constraint_wrench_subspaces!(state) nothing end @inline function _constraint_wrench_subspace(state::MechanismState, joint::Joint) jointid = JointID(joint) tf = state.joint_transforms[jointid] T = constraint_wrench_subspace(joint, tf) bodyid = successorid(jointid, state) toroot = state.transforms_to_root[bodyid] * joint_to_successor(joint) transform(T, toroot) end @noinline function _update_constraint_wrench_subspaces!(state::MechanismState) update_transforms!(state) foreach_with_extra_args(state, state.nontreejoints) do state, joint T = _constraint_wrench_subspace(state, joint) @inbounds crange = constraint_range(state, joint) @inbounds for col = Base.OneTo(size(T, 2)) Tcol = WrenchMatrix(T.frame, SMatrix{3, 1}(T.angular[:, col]), SMatrix{3, 1}(T.linear[:, col])) cindex = crange[col] state.constraint_wrench_subspaces.data[cindex] = Tcol end end state.constraint_wrench_subspaces.dirty = false nothing end @inline function update_bias_accelerations_wrt_world!(state::MechanismState) isdirty(state.bias_accelerations_wrt_world) && _update_bias_accelerations_wrt_world!(state) nothing end @noinline function _update_bias_accelerations_wrt_world!(state::MechanismState) # TODO: make more efficient update_transforms!(state) update_twists_wrt_world!(state) update_joint_bias_accelerations!(state) biasaccels = state.bias_accelerations_wrt_world for jointid in state.treejointids parentbodyid, bodyid = predsucc(jointid, state) jointbias = bias_acceleration(state, jointid) # TODO: awkward way of doing this: toroot = transform_to_root(state, bodyid, false) twistwrtworld = transform(twist_wrt_world(state, bodyid), inv(toroot)) jointtwist = twist(state, jointid) biasaccels[bodyid] = biasaccels[parentbodyid] + transform(jointbias, toroot, twistwrtworld, jointtwist) end state.bias_accelerations_wrt_world.dirty = false nothing end @inline function update_spatial_inertias!(state::MechanismState) isdirty(state.inertias) && _update_spatial_inertias!(state) nothing end @noinline function _update_spatial_inertias!(state::MechanismState) update_transforms!(state) mechanism = state.mechanism inertias = state.inertias @inbounds for body in state.nonrootbodies bodyid = BodyID(body) inertias[bodyid] = transform(spatial_inertia(body), transform_to_root(state, bodyid, false)) end state.inertias.dirty = false nothing end @inline function update_crb_inertias!(state::MechanismState) isdirty(state.crb_inertias) && _update_crb_inertias!(state) nothing end @noinline function _update_crb_inertias!(state::MechanismState) update_spatial_inertias!(state) mechanism = state.mechanism crb_inertias = state.crb_inertias rootbodyid = BodyID(root_body(mechanism)) crb_inertias[rootbodyid] = state.inertias[rootbodyid] for jointid in state.treejointids bodyid = successorid(jointid, state) crb_inertias[bodyid] = state.inertias[bodyid] end for jointid in reverse(state.treejointids)# TODO: reverse is kind of expensive parentbodyid, bodyid = predsucc(jointid, state) crb_inertias[parentbodyid] += crb_inertias[bodyid] end state.crb_inertias.dirty = false nothing end contact_states(state::MechanismState, body::Union{<:RigidBody, BodyID}) = state.contact_states[body] @propagate_inbounds function newton_euler(state::MechanismState, body::Union{<:RigidBody, BodyID}, accel::SpatialAcceleration, safe=true) inertia = spatial_inertia(state, body, safe) twist = twist_wrt_world(state, body, safe) newton_euler(inertia, accel, twist) end @propagate_inbounds function momentum(state::MechanismState, body::Union{<:RigidBody, BodyID}, safe=true) spatial_inertia(state, body, safe) * twist_wrt_world(state, body, safe) end @propagate_inbounds function momentum_rate_bias(state::MechanismState, body::Union{<:RigidBody, BodyID}, safe=true) newton_euler(state, body, bias_acceleration(state, body, safe), safe) end @propagate_inbounds function kinetic_energy(state::MechanismState, body::Union{<:RigidBody, BodyID}, safe=true) kinetic_energy(spatial_inertia(state, body, safe), twist_wrt_world(state, body, safe)) end """ $(SIGNATURES) Return the gravitational potential energy in the given state, computed as the negation of the dot product of the gravitational force and the center of mass expressed in the `Mechanism`'s root frame. """ @propagate_inbounds function gravitational_potential_energy(state::MechanismState, body::Union{<:RigidBody, BodyID}, safe=true) inertia = spatial_inertia(body) m = inertia.mass m > 0 || return zero(cache_eltype(state)) com = transform_to_root(state, body, safe) * center_of_mass(inertia) -m * dot(state.mechanism.gravitational_acceleration, FreeVector3D(com)) end function configuration_derivative!(q̇::SegmentedVector{JointID}, state::MechanismState) q̇s = values(segments(q̇)) qs = values(segments(state.q)) vs = values(segments(state.v)) foreach((joint, q̇, q, v) -> velocity_to_configuration_derivative!(q̇, joint, q, v), state.treejoints, q̇s, qs, vs) end function configuration_derivative_to_velocity_adjoint!( fq::SegmentedVector{JointID}, state::MechanismState, fv::SegmentedVector{JointID}) fqs = values(segments(fq)) qs = values(segments(state.q)) fvs = values(segments(fv)) foreach((joint, fq, q, fv) -> configuration_derivative_to_velocity_adjoint!(fq, joint, q, fv), state.treejoints, fqs, qs, fvs) end function configuration_derivative(state::MechanismState{X}) where {X} ret = SegmentedVector(Vector{X}(undef, num_positions(state.mechanism)), tree_joints(state.mechanism), num_positions) configuration_derivative!(ret, state) ret end function velocity_to_configuration_derivative_jacobian!(J::SegmentedBlockDiagonalMatrix, state::MechanismState) qs = values(segments(state.q)) foreach(state.treejoints, qs, CustomCollections.blocks(J)) do joint, qjoint, block copyto!(block, velocity_to_configuration_derivative_jacobian(joint, qjoint)) end nothing end function velocity_to_configuration_derivative_jacobian(state::MechanismState{X, M, C}) where {X, M, C} q_ranges = values(ranges(configuration(state))) v_ranges = values(ranges(velocity(state))) J = SegmentedBlockDiagonalMatrix(zeros(C, num_positions(state), num_velocities(state)), zip(q_ranges, v_ranges)) velocity_to_configuration_derivative_jacobian!(J, state) J end function configuration_derivative_to_velocity_jacobian!(J::SegmentedBlockDiagonalMatrix, state::MechanismState) qs = values(segments(state.q)) foreach(state.treejoints, qs, CustomCollections.blocks(J)) do joint, qjoint, block copyto!(block, configuration_derivative_to_velocity_jacobian(joint, qjoint)) end nothing end function configuration_derivative_to_velocity_jacobian(state::MechanismState{X, M, C}) where {X, M, C} q_ranges = values(ranges(configuration(state))) v_ranges = values(ranges(velocity(state))) J = SegmentedBlockDiagonalMatrix(zeros(C, num_velocities(state), num_positions(state)), zip(v_ranges, q_ranges)) configuration_derivative_to_velocity_jacobian!(J, state) J end function transform_to_root(state::MechanismState, frame::CartesianFrame3D, safe=true) body = body_fixed_frame_to_body(state.mechanism, frame) # FIXME: expensive tf = transform_to_root(state, body, safe) if tf.from != frame tf = tf * body_fixed_frame_definition(state.mechanism, frame) # TODO: consider caching end tf end @propagate_inbounds function statesum(fun::F, state::MechanismState, itr, init, safe=true) where F ret = init for x in itr ret += fun(state, x, safe) end ret end @propagate_inbounds function momentum(state::MechanismState, body_itr) T = cache_eltype(state) update_twists_wrt_world!(state) update_spatial_inertias!(state) statesum(momentum, state, body_itr, zero(Momentum{T}, root_frame(state.mechanism)), false) end @propagate_inbounds function momentum_rate_bias(state::MechanismState, body_itr) T = cache_eltype(state) update_bias_accelerations_wrt_world!(state) update_spatial_inertias!(state) statesum(momentum_rate_bias, state, body_itr, zero(Wrench{T}, root_frame(state.mechanism)), false) end @propagate_inbounds function kinetic_energy(state::MechanismState, body_itr) T = cache_eltype(state) update_twists_wrt_world!(state) update_spatial_inertias!(state) statesum(kinetic_energy, state, body_itr, zero(T), false) end @propagate_inbounds function gravitational_potential_energy(state::MechanismState, body_itr) T = cache_eltype(state) update_transforms!(state) statesum(gravitational_potential_energy, state, body_itr, zero(T), false) end for fun in (:momentum, :momentum_rate_bias, :kinetic_energy, :gravitational_potential_energy) @eval $fun(state::MechanismState) = @inbounds return $fun(state, state.nonrootbodies) end """ $(SIGNATURES) Return the homogeneous transform from `from` to `to`. """ function relative_transform(state::MechanismState, from::CartesianFrame3D, to::CartesianFrame3D) update_transforms!(state) inv(transform_to_root(state, to, false)) * transform_to_root(state, from, false) end """ $(SIGNATURES) Return the twist of `body` with respect to `base`, expressed in the `Mechanism`'s root frame. """ function relative_twist(state::MechanismState, body::Union{<:RigidBody, BodyID}, base::Union{<:RigidBody, BodyID}) update_twists_wrt_world!(state) -twist_wrt_world(state, base, false) + twist_wrt_world(state, body, false) end """ $(SIGNATURES) Return the twist of `body_frame` with respect to `base_frame`, expressed in the `Mechanism`'s root frame. """ function relative_twist(state::MechanismState, body_frame::CartesianFrame3D, base_frame::CartesianFrame3D) body = body_fixed_frame_to_body(state.mechanism, body_frame) base = body_fixed_frame_to_body(state.mechanism, base_frame) twist = relative_twist(state, body, base) Twist(body_frame, base_frame, twist.frame, angular(twist), linear(twist)) end for VectorType in (:Point3D, :FreeVector3D, :Twist, :Momentum, :Wrench) @eval begin function transform(state::MechanismState, v::$VectorType, to::CartesianFrame3D) # TODO: consider transforming in steps, so that computing the relative transform is not necessary transform(v, relative_transform(state, v.frame, to)) end end end function transform(state::MechanismState, accel::SpatialAcceleration, to::CartesianFrame3D) old_to_root = transform_to_root(state, accel.frame) root_to_old = inv(old_to_root) twist_of_body_wrt_base = transform(relative_twist(state, accel.body, accel.base), root_to_old) twist_of_old_wrt_new = transform(relative_twist(state, accel.frame, to), root_to_old) old_to_new = inv(transform_to_root(state, to)) * old_to_root transform(accel, old_to_new, twist_of_old_wrt_new, twist_of_body_wrt_base) end """ $(SIGNATURES) Compute local coordinates ``\\phi`` centered around (global) configuration vector ``q_0``, as well as their time derivatives ``\\dot{\\phi}``. """ # TODO: refer to the method that takes a joint once it's moved to its own Joints module function local_coordinates!( ϕ::SegmentedVector{JointID}, ϕd::SegmentedVector{JointID}, state::MechanismState, q0::SegmentedVector{JointID}) ϕs = values(segments(ϕ)) ϕds = values(segments(ϕd)) q0s = values(segments(q0)) qs = values(segments(state.q)) vs = values(segments(state.v)) foreach((joint, ϕ, ϕ̇, q0, q, v) -> local_coordinates!(ϕ, ϕ̇, joint, q0, q, v), state.treejoints, ϕs, ϕds, q0s, qs, vs) end """ $(SIGNATURES) Convert local coordinates ``\\phi`` centered around ``q_0`` to (global) configuration vector ``q``. """ # TODO: refer to the method that takes a joint once it's moved to its own Joints module function global_coordinates!(state::MechanismState, q0::SegmentedVector{JointID}, ϕ::SegmentedVector{JointID}) qs = values(segments(state.q)) q0s = values(segments(q0)) ϕs = values(segments(ϕ)) foreach((joint, q, q0, ϕ) -> global_coordinates!(q, joint, q0, ϕ), state.treejoints, qs, q0s, ϕs) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
11412
module OdeIntegrators using LinearAlgebra using RigidBodyDynamics using StaticArrays using DocStringExtensions using LoopThrottle export runge_kutta_4, MuntheKaasIntegrator, ButcherTableau, OdeResultsSink, RingBufferStorage, ExpandingStorage, integrate, step """ $(TYPEDEF) A [Butcher tableau](https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods#Explicit_Runge.E2.80.93Kutta_methods). """ struct ButcherTableau{N, T, L} a::SMatrix{N, N, T, L} b::SVector{N, T} c::SVector{N, T} explicit::Bool function ButcherTableau(a::AbstractMatrix{T}, b::AbstractVector{T}) where {T} N = size(a, 1) L = N^2 @assert N > 0 @assert size(a, 2) == N @assert length(b) == N c = vec(sum(a, dims=2)) explicit = all(triu(a) .== 0) new{N, T, L}(SMatrix{N, N}(a), SVector{N}(b), SVector{N}(c), explicit) end end num_stages(::ButcherTableau{N}) where {N} = N isexplicit(tableau::ButcherTableau) = tableau.explicit """ $(SIGNATURES) Return the Butcher tableau for the standard fourth order Runge-Kutta integrator. """ function runge_kutta_4(scalar_type::Type{T}) where {T} a = zeros(T, 4, 4) a[2, 1] = 1/2 a[3, 2] = 1/2 a[4, 3] = 1 b = T[1/6, 1/3, 1/3, 1/6] ButcherTableau(a, b) end """ $(TYPEDEF) Does 'something' with the results of an ODE integration (e.g. storing results, visualizing, etc.). Subtypes must implement: * `initialize(sink, state)`: called with the initial state when integration begins. * `process(sink, t, state)`: called at every integration time step with the current state and time. """ abstract type OdeResultsSink end initialize(::OdeResultsSink, state) = error("concrete subtypes must implement") process(::OdeResultsSink, t, state) = error("concrete subtypes must implement") """ $(TYPEDEF) An `OdeResultsSink` that stores the state at each integration time step in a ring buffer. """ mutable struct RingBufferStorage{T, Q<:AbstractVector, V<:AbstractVector} <: OdeResultsSink ts::Vector{T} qs::Vector{Q} vs::Vector{V} last_index::Int64 function RingBufferStorage{T}(state, n) where {T} Q = typeof(configuration(state)) V = typeof(velocity(state)) ts = Vector{T}(undef, n) qs = [similar(configuration(state)) for i in 1 : n] vs = [similar(velocity(state)) for i in 1 : n] new{T, Q, V}(ts, qs, vs, 0) end end Base.eltype(storage::RingBufferStorage{T}) where {T} = T Base.length(storage::RingBufferStorage) = length(storage.ts) function initialize(storage::RingBufferStorage, t, state) process(storage, t, state) end function process(storage::RingBufferStorage, t, state) index = storage.last_index % length(storage) + 1 storage.ts[index] = t copyto!(storage.qs[index], configuration(state)) copyto!(storage.vs[index], velocity(state)) storage.last_index = index nothing end """ $(TYPEDEF) An `OdeResultsSink` that stores the state at each integration time step in `Vectors` that may expand. """ mutable struct ExpandingStorage{T, Q<:AbstractVector, V<:AbstractVector} <: OdeResultsSink ts::Vector{T} qs::Vector{Q} vs::Vector{V} function ExpandingStorage{T}(state, n) where {T} Q = typeof(configuration(state)) V = typeof(velocity(state)) ts = T[]; sizehint!(ts, n) qs = Q[]; sizehint!(qs, n) vs = V[]; sizehint!(vs, n) new{T, Q, V}(ts, qs, vs) end end Base.eltype(storage::ExpandingStorage{T}) where {T} = T Base.length(storage::ExpandingStorage) = length(storage.ts) initialize(storage::ExpandingStorage, t, state) = process(storage, t, state) function process(storage::ExpandingStorage, t, state) push!(storage.ts, t) q = similar(configuration(state)) copyto!(q, configuration(state)) push!(storage.qs, q) v = similar(velocity(state)) copyto!(v, velocity(state)) push!(storage.vs, v) nothing end mutable struct MuntheKaasStageCache{N, T, Q<:AbstractVector, V<:AbstractVector, S<:AbstractVector} q0::Q # global coordinates vs::SVector{N, V} # velocity vector for each stage vds::SVector{N, V} # time derivatives of vs ϕs::SVector{N, V} # local coordinates around q0 for each stage ϕds::SVector{N, V} # time derivatives of ϕs ss::SVector{N, S} # additional state for each stage sds::SVector{N, S} # time derivatives of ss ϕstep::V # local coordinates around q0 after complete step vstep::V # velocity after complete step sstep::S # additional state after complete step function MuntheKaasStageCache{N, T}(state) where {N, T} q0 = similar(configuration(state), T) vs = SVector{N}((similar(velocity(state), T) for i in 1 : N)...) vds = SVector{N}((similar(velocity(state), T) for i in 1 : N)...) ϕs = SVector{N}((similar(velocity(state), T) for i in 1 : N)...) ϕds = SVector{N}((similar(velocity(state), T) for i in 1 : N)...) ss = SVector{N}((similar(additional_state(state), T) for i in 1 : N)...) sds = SVector{N}((similar(additional_state(state), T) for i in 1 : N)...) ϕstep = similar(velocity(state), T) vstep = similar(velocity(state), T) sstep = similar(additional_state(state), T) new{N, T, typeof(q0), typeof(ϕstep), typeof(sstep)}(q0, vs, vds, ϕs, ϕds, ss, sds, ϕstep, vstep, sstep) end end """ $(TYPEDEF) A Lie-group-aware ODE integrator. `MuntheKaasIntegrator` is used to properly integrate the dynamics of globally parameterized rigid joints (Duindam, Port-Based Modeling and Control for Efficient Bipedal Walking Robots, 2006, Definition 2.9). Global parameterizations of e.g. ``SO(3)`` are needed to avoid singularities, but this leads to the problem that the tangent space no longer has the same dimension as the ambient space of the global parameterization. A Munthe-Kaas integrator solves this problem by converting back and forth between local and global coordinates at every integration time step. The idea is to do the dynamics and compute the stages of the integration scheme in terms of local coordinates centered around the global parameterization of the configuration at the end of the previous time step (e.g. exponential coordinates), combine the stages into a new set of local coordinates as usual for Runge-Kutta methods, and then convert the local coordinates back to global coordinates. From [Iserles et al., 'Lie-group methods' (2000)](https://hal.archives-ouvertes.fr/hal-01328729). Another useful reference is [Park and Chung, 'Geometric Integration on Euclidean Group with Application to Articulated Multibody Systems' (2005)](http://www.ent.mrt.ac.lk/iml/paperbase/TRO%20Collection/TRO/2005/october/7.pdf). """ struct MuntheKaasIntegrator{N, T, F, S<:OdeResultsSink, X, L, M<:MuntheKaasStageCache{N, T}} dynamics!::F # dynamics!(vd, sd, t, state), sets vd (time derivative of v) and sd (time derivative of s) given time t and state tableau::ButcherTableau{N, T, L} sink::S state::X stages::M @doc """ $(SIGNATURES) Create a `MuntheKaasIntegrator` given: * a callable `dynamics!(vd, t, state)` that updates the joint acceleration vector `vd` at time `t` and in state `state`; * a [`ButcherTableau`](@ref) `tableau`, specifying the integrator coefficients; * an [`OdeResultsSink`](@ref) `sink` which processes the results of the integration procedure at each time step. `state` must be of a type for which the following functions are defined: * `configuration(state)`, returns the configuration vector in global coordinates; * `velocity(state)`, returns the velocity vector; * `additional_state(state)`, returns the vector of additional states; * `set_velocity!(state, v)`, sets velocity vector to `v`; * `set_additional_state!(state, s)`, sets vector of additional states to `s`; * `global_coordinates!(state, q0, ϕ)`, sets global coordinates in state based on local coordinates `ϕ` centered around global coordinates `q0`; * `local_coordinates!(ϕ, ϕd, state, q0)`, converts state's global configuration `q` and velocity `v` to local coordinates centered around global coordinates `q0`. """ -> function MuntheKaasIntegrator(state::X, dynamics!::F, tableau::ButcherTableau{N, T, L}, sink::S) where {N, T, F, S<:OdeResultsSink, X, L} @assert isexplicit(tableau) stages = MuntheKaasStageCache{N, T}(state) new{N, T, F, S, X, L, typeof(stages)}(dynamics!, tableau, sink, state, stages) end end num_stages(::MuntheKaasIntegrator{N}) where {N} = N Base.eltype(::MuntheKaasIntegrator{N, T}) where {N, T} = T """ $(SIGNATURES) Take a single integration step. """ function step(integrator::MuntheKaasIntegrator, t::Real, Δt::Real) tableau = integrator.tableau stages = integrator.stages n = num_stages(integrator) # Use current configuration as the configuration around which the local coordinates for this step will be centered. q0, v0, s0 = stages.q0, stages.vstep, stages.sstep state = integrator.state q0 .= configuration(state) v0 .= velocity(state) s0 .= additional_state(state) # Compute integrator stages. for i = 1 : n # Update local coordinates and velocities ϕ = stages.ϕs[i] v = stages.vs[i] s = stages.ss[i] ϕ .= 0 v .= v0 s .= s0 for j = 1 : i - 1 aij = tableau.a[i, j] if aij != zero(aij) weight = Δt * aij ϕ .= muladd.(weight, stages.ϕds[j], ϕ) v .= muladd.(weight, stages.vds[j], v) s .= muladd.(weight, stages.sds[j], s) end end # Convert from local to global coordinates and set state # TODO: multiple setdirty! calls when using MechanismState: global_coordinates!(state, q0, ϕ) set_velocity!(state, v) set_additional_state!(state, s) # Dynamics in global coordinates vd = stages.vds[i] sd = stages.sds[i] integrator.dynamics!(vd, sd, muladd(tableau.c[i], Δt, t), state) # Convert back to local coordinates ϕd = stages.ϕds[i] # TODO: ϕ not actually needed, just ϕd! local_coordinates!(ϕ, ϕd, state, q0) end # Combine stages ϕ = stages.ϕstep ϕ .= 0 v = stages.vstep # already initialized to v0 s = stages.sstep # already initialized to s0 for i = 1 : n weight = tableau.b[i] * Δt ϕ .= muladd.(weight, stages.ϕds[i], ϕ) v .= muladd.(weight, stages.vds[i], v) s .= muladd.(weight, stages.sds[i], s) end # Convert from local to global coordinates # TODO: multiple setdirty! calls when using MechanismState: global_coordinates!(state, q0, ϕ) set_velocity!(state, v) set_additional_state!(state, s) nothing end """ $(SIGNATURES) Integrate dynamics from the initial state at time ``0`` to `final_time` using step size `Δt`. """ function integrate(integrator::MuntheKaasIntegrator, final_time, Δt; max_realtime_rate::Float64 = Inf) t = zero(eltype(integrator)) state = integrator.state initialize(integrator.sink, t, state) @throttle t while t < final_time step(integrator, t, Δt) t += Δt process(integrator.sink, t, state) end max_rate=max_realtime_rate min_sleep_time=1/60. end end # module
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
4598
module PDControl using RigidBodyDynamics.Spatial using StaticArrays using Rotations # functions export pd # gain types export PDGains, FramePDGains, SE3PDGains # pd control methods export SE3PDMethod abstract type AbstractPDGains end group_error(x, xdes) = x - xdes group_error(x::Rotation, xdes::Rotation) = inv(xdes) * x group_error(x::Transform3D, xdes::Transform3D) = inv(xdes) * x pd(gains::AbstractPDGains, x, xdes, ẋ, ẋdes) = pd(gains, group_error(x, xdes), -ẋdes + ẋ) pd(gains::AbstractPDGains, x, xdes, ẋ, ẋdes, method) = pd(gains, group_error(x, xdes), -ẋdes + ẋ, method) struct PDGains{K, D} <: AbstractPDGains k::K d::D end pd(gains::PDGains, e, ė) = -gains.k * e - gains.d * ė pd(gains::PDGains, e::RotationVec, ė::AbstractVector) = pd(gains, SVector(e.sx, e.sy, e.sz), ė) pd(gains::PDGains, e::Rotation{3}, ė::AbstractVector) = pd(gains, RotationVec(e), ė) rotategain(gain::Number, R::Rotation) = gain rotategain(gain::AbstractMatrix, R::Rotation) = R * gain * R' function Spatial.transform(gains::PDGains, tf::Transform3D) R = rotation(tf) PDGains(rotategain(gains.k, R), rotategain(gains.d, R)) end # Gains with a frame annotation struct FramePDGains{K, D} <: AbstractPDGains frame::CartesianFrame3D gains::PDGains{K, D} end function pd(fgains::FramePDGains, e::FreeVector3D, ė::FreeVector3D) @framecheck fgains.frame e.frame @framecheck fgains.frame ė.frame FreeVector3D(fgains.frame, pd(fgains.gains, e.v, ė.v)) end function Spatial.transform(fgains::FramePDGains, tf::Transform3D) @framecheck tf.from fgains.frame FramePDGains(tf.to, transform(fgains.gains, tf)) end # PD control on the special Euclidean group struct SE3PDGains{A<:Union{PDGains, FramePDGains}, L<:Union{PDGains, FramePDGains}} <: AbstractPDGains angular::A linear::L end function SE3PDGains(frame::CartesianFrame3D, angular::PDGains, linear::PDGains) SE3PDGains(FramePDGains(frame, angular), FramePDGains(frame, linear)) end Spatial.angular(gains::SE3PDGains) = gains.angular Spatial.linear(gains::SE3PDGains) = gains.linear function Spatial.transform(gains::SE3PDGains, t::Transform3D) SE3PDGains(transform(gains.angular, t), transform(gains.linear, t)) end struct SE3PDMethod{T} end pd(gains::SE3PDGains, e::Transform3D, ė::Twist) = pd(gains, e, ė, SE3PDMethod{:DoubleGeodesic}()) function pd(gains::SE3PDGains, e::Transform3D, ė::Twist, ::SE3PDMethod{:DoubleGeodesic}) # Theorem 12 in Bullo, Murray, "Proportional derivative (PD) control on the Euclidean group", 1995 (4.6 in the Technical Report). # Note: in Theorem 12, even though the twist and spatial acceleration are expressed in body frame, the gain Kv is expressed in base (or desired) frame, # since it acts on the translation part of the transform from body frame to base frame (i.e. the definition of body frame expressed in base frame), # and force Kv * p needs to be rotated back to body frame to match the spatial acceleration in body frame. # Instead, we express Kv in body frame by performing a similarity transform on Kv: R * Kv * R', where R is the rotation from actual body frame to desired body frame. # This turns the linear and proportional part of the PD law into R' * R * Kv * R' * p = Kv * R' * p # Note also that in Theorem 12, the frame in which the orientation gain Kω must be expressed is ambiguous, since R' * log(R) = log(R). # This explains why the Kω used here is the same as the Kω in Theorem 12. # Gains should be expressed in actual body frame. bodyframe = ė.body @framecheck e.from bodyframe @framecheck ė.base e.to @framecheck ė.frame bodyframe R = rotation(e) p = translation(e) ψ = RotationVec(R) ang = pd(angular(gains), FreeVector3D(bodyframe, ψ.sx, ψ.sy, ψ.sz), FreeVector3D(bodyframe, angular(ė))) lin = pd(linear(gains), FreeVector3D(bodyframe, R' * p), FreeVector3D(bodyframe, linear(ė))) SpatialAcceleration(ė.body, ė.base, ang, lin) end function pd(gains::SE3PDGains, e::Transform3D, ė::Twist, ::SE3PDMethod{:Linearized}) bodyframe = ė.body @framecheck e.from bodyframe @framecheck ė.base e.to @framecheck ė.frame bodyframe R = rotation(e) p = translation(e) ψ = linearized_rodrigues_vec(R) ang = pd(angular(gains), FreeVector3D(bodyframe, ψ.sx, ψ.sy, ψ.sz), FreeVector3D(bodyframe, angular(ė))) lin = pd(linear(gains), FreeVector3D(bodyframe, R' * p), FreeVector3D(bodyframe, linear(ė))) SpatialAcceleration(ė.body, ė.base, ang, lin) end end # module
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
5797
@indextype BodyID """ $(TYPEDEF) A non-deformable body. A `RigidBody` has inertia (represented as a [`SpatialInertia`](@ref)), unless it represents a root (world) body. A `RigidBody` additionally stores a list of definitions of coordinate systems that are rigidly attached to it. """ mutable struct RigidBody{T} name::String inertia::Union{SpatialInertia{T}, Nothing} frame_definitions::Vector{Transform3D{T}} contact_points::Vector{DefaultContactPoint{T}} # TODO: allow different contact models id::BodyID # inertia undefined; can be used for the root of a kinematic tree function RigidBody{T}(name::String) where {T} frame = CartesianFrame3D(name) new{T}(name, nothing, [one(Transform3D{T}, frame)], DefaultContactPoint{T}[], BodyID(-1)) end # other bodies function RigidBody(name::String, inertia::SpatialInertia{T}) where {T} new{T}(name, inertia, [one(Transform3D{T}, inertia.frame)], DefaultContactPoint{T}[], BodyID(-1)) end end Base.eltype(::Type{RigidBody{T}}) where {T} = T Base.eltype(body::RigidBody) = eltype(typeof(body)) RigidBody(inertia::SpatialInertia) = RigidBody(string(inertia.frame), inertia) Base.print(io::IO, b::RigidBody) = print(io, b.name) function Base.show(io::IO, b::RigidBody) if get(io, :compact, false) print(io, b) else print(io, "RigidBody: \"$(string(b))\"") end end BodyID(b::RigidBody) = b.id Base.convert(::Type{BodyID}, b::RigidBody) = BodyID(b) @inline RigidBodyDynamics.Graphs.vertex_id_type(::Type{<:RigidBody}) = BodyID @inline RigidBodyDynamics.Graphs.vertex_id(b::RigidBody) = convert(BodyID, b) @inline RigidBodyDynamics.Graphs.set_vertex_id!(b::RigidBody, id::BodyID) = (b.id = id) """ $(SIGNATURES) Whether the body has a defined inertia. """ has_defined_inertia(b::RigidBody) = b.inertia !== nothing """ $(SIGNATURES) Return the spatial inertia of the body. If the inertia is undefined, calling this method will result in an error. """ spatial_inertia(b::RigidBody{T}) where {T} = b.inertia::SpatialInertia{T} """ $(SIGNATURES) Set the spatial inertia of the body. """ function spatial_inertia!(body::RigidBody, inertia::SpatialInertia) body.inertia = transform(inertia, frame_definition(body, inertia.frame)) end """ frame_definitions(body) Return the list of homogeneous transforms ([`Transform3D`](@ref)s) that define the coordinate systems attached to `body` with respect to a single common frame ([`default_frame(body)`](@ref)). """ frame_definitions(body::RigidBody) = body.frame_definitions """ $(SIGNATURES) Whether `frame` is attached to `body` (i.e. whether it is among [`frame_definitions(body)`](@ref)). """ is_fixed_to_body(body::RigidBody, frame::CartesianFrame3D) = any((t) -> t.from == frame, frame_definitions(body)) """ $(SIGNATURES) The [`CartesianFrame3D`](@ref) with respect to which all other frames attached to `body` are defined. See [`frame_definitions(body)`](@ref), [`frame_definition(body, frame)`](@ref). """ default_frame(body::RigidBody) = body.frame_definitions[1].to # allows standardization on a frame to reduce number of transformations required """ $(SIGNATURES) Return the [`Transform3D`](@ref) defining `frame` (attached to `body`) with respect to [`default_frame(body)`](@ref). Throws an error if `frame` is not attached to `body`. """ function frame_definition(body::RigidBody, frame::CartesianFrame3D) for transform in body.frame_definitions transform.from == frame && return transform end error("$frame not found among body fixed frame definitions for $body") end """ $(SIGNATURES) Return the transform from `CartesianFrame3D` `from` to `to`, both of which are rigidly attached to `body`. """ function fixed_transform(body::RigidBody, from::CartesianFrame3D, to::CartesianFrame3D) transform = frame_definition(body, from) if transform.to != to transform = inv(frame_definition(body, to)) * transform end transform end """ $(SIGNATURES) Add a new frame definition to `body`, represented by a homogeneous transform from the `CartesianFrame3D` to be added to any other frame that is already attached to `body`. """ function add_frame!(body::RigidBody, transform::Transform3D) # note: overwrites any existing frame definition # transform.to needs to be among (transform.from for transform in frame_definitions(body)) definitions = body.frame_definitions if transform.to != default_frame(body) transform = frame_definition(body, transform.to) * transform end filter!(t -> t.from != transform.from, definitions) push!(definitions, transform) transform end """ $(SIGNATURES) Change the default frame of `body` to `frame` (which should already be among `body`'s frame definitions). """ function change_default_frame!(body::RigidBody, new_default_frame::CartesianFrame3D) if new_default_frame != default_frame(body) old_to_new = inv(frame_definition(body, new_default_frame)) map!(tf -> old_to_new * tf, body.frame_definitions, body.frame_definitions) if has_defined_inertia(body) body.inertia = transform(spatial_inertia(body), old_to_new) end for point in contact_points(body) point.location = old_to_new * point.location end end end """ $(SIGNATURES) Add a new contact point to the rigid body """ function add_contact_point!(body::RigidBody{T}, point::DefaultContactPoint{T}) where {T} loc = location(point) tf = fixed_transform(body, loc.frame, default_frame(body)) point.location = tf * loc push!(body.contact_points, point) nothing end """ $(SIGNATURES) Return the contact points attached to the body as an ordered collection. """ contact_points(body::RigidBody) = body.contact_points
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
2258
using RigidBodyDynamics.OdeIntegrators """ $(SIGNATURES) A trivial controller that simply sets the torques to zero. """ function zero_torque!(torques::AbstractVector, t, state::MechanismState) torques .= 0 end """ $(SIGNATURES) Basic `Mechanism` simulation: integrate the state from time ``0`` to `final_time` starting from the initial state `state0`. Return a `Vector` of times, as well as `Vector`s of configuration vectors and velocity vectors at these times. Optionally, a function (or other callable) can be passed in as the third argument (`control!`). `control!` will be called at each time step of the simulation and allows you to specify joint torques given the time and the state of the `Mechanism`. It should look like this: ```julia function control!(torques::AbstractVector, t, state::MechanismState) rand!(torques) # for example end ``` The integration time step can be specified using the `Δt` keyword argument (defaults to `1e-4`). $stabilization_gains_doc Uses `MuntheKaasIntegrator`. See [`RigidBodyDynamics.OdeIntegrators.MuntheKaasIntegrator`](@ref) for a lower level interface with more options. """ function simulate(state0::MechanismState{X}, final_time, control! = zero_torque!; Δt = 1e-4, stabilization_gains=default_constraint_stabilization_gains(X)) where X T = cache_eltype(state0) result = DynamicsResult{T}(state0.mechanism) control_torques = similar(velocity(state0)) closed_loop_dynamics! = let result=result, control_torques=control_torques, stabilization_gains=stabilization_gains # https://github.com/JuliaLang/julia/issues/15276 function (v̇::AbstractArray, ṡ::AbstractArray, t, state) control!(control_torques, t, state) dynamics!(result, state, control_torques; stabilization_gains=stabilization_gains) copyto!(v̇, result.v̇) copyto!(ṡ, result.ṡ) nothing end end tableau = runge_kutta_4(T) storage = ExpandingStorage{T}(state0, ceil(Int64, final_time / Δt * 1.001)) # very rough overestimate of number of time steps integrator = MuntheKaasIntegrator(state0, closed_loop_dynamics!, tableau, storage) integrate(integrator, final_time, Δt) storage.ts, storage.qs, storage.vs end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
4376
# TODO: higher level abstraction once it's as fast for T in (:GeometricJacobian, :MomentumMatrix) @eval @inline function set_col!(dest::$T, col::Integer, src::$T) @framecheck dest.frame src.frame @boundscheck size(src, 2) == 1 || throw(ArgumentError()) @boundscheck col ∈ Base.OneTo(size(dest, 2)) || throw(DimensionMismatch()) @inbounds begin start = LinearIndices(dest.angular)[1, col] dest.angular[start] = src.angular[1] dest.angular[start + 1] = src.angular[2] dest.angular[start + 2] = src.angular[3] dest.linear[start] = src.linear[1] dest.linear[start + 1] = src.linear[2] dest.linear[start + 2] = src.linear[3] end end end ## findunique function findunique(f, A::AbstractArray) i = findfirst(f, A) i === nothing && error("No results found.") findnext(f, A, i + 1) === nothing || error("Multiple results found.") @inbounds return A[i] end # Cached download const module_tempdir = joinpath(Base.tempdir(), string(nameof(@__MODULE__))) function cached_download(url::String, local_file_name::String, cache_dir::String = joinpath(module_tempdir, string(hash(url)))) if !ispath(cache_dir) mkpath(cache_dir) end full_cache_path = joinpath(cache_dir, local_file_name) if !isfile(full_cache_path) download(url, full_cache_path) end full_cache_path end ## VectorSegment: type of a view of a vector const VectorSegment{T} = SubArray{T,1,Array{T, 1},Tuple{UnitRange{Int64}},true} # TODO: a bit too specific function quatnorm(quat::QuatRotation) w, x, y, z = Rotations.params(quat) sqrt(w^2 + x^2 + y^2 + z^2) end ## Modification count stuff function modcount end struct ModificationCountMismatch <: Exception msg::String end Base.showerror(io::IO, ex::ModificationCountMismatch) = print(io, "ModificationCountMismatch: $(ex.msg)") macro modcountcheck(a, b) quote modcount($(esc(a))) == modcount($(esc(b))) || modcount_check_fail($(QuoteNode(a)), $(QuoteNode(b)), $(esc(a)), $(esc(b))) end end @noinline function modcount_check_fail(asym, bsym, a, b) amod = modcount(a) bmod = modcount(b) msg = "Modification count of '$(string(asym))' ($amod) does not match modification count of '$(string(bsym))' ($bmod)." throw(ModificationCountMismatch(msg)) end # Bounds """ $(TYPEDEF) Bounds is a scalar-like type representing a closed interval from ``lower`` to ``upper``. To indicate that a vector of values falls with some range, use a ``Vector{Bounds{T}}``. """ struct Bounds{T} lower::T upper::T function Bounds{T}(lower, upper) where T @assert lower <= upper new{T}(lower, upper) end Bounds{T}() where {T} = new{T}(typemin(T), typemax(T)) end Bounds(lower::T1, upper::T2) where {T1, T2} = Bounds{promote_type(T1, T2)}(lower, upper) upper(b::Bounds) = b.upper lower(b::Bounds) = b.lower Base.:(==)(b1::Bounds, b2::Bounds) = b1.lower == b2.lower && b1.upper == b2.upper Base.:-(b::Bounds) = Bounds(-b.upper, -b.lower) Base.show(io::IO, b::Bounds) = print(io, "(", lower(b), ", ", upper(b), ")") Base.convert(::Type{Bounds{T1}}, b::Bounds{T2}) where {T1, T2} = Bounds{T1}(convert(T1, lower(b)), convert(T1, upper(b))) Base.broadcastable(b::Bounds) = Ref(b) """ $(SIGNATURES) Return the closest value to ``x`` within the interval described by ``b``. """ Base.clamp(x, b::Bounds) = clamp(x, b.lower, b.upper) Base.intersect(b1::Bounds, b2::Bounds) = Bounds(max(b1.lower, b2.lower), min(b1.upper, b2.upper)) # Create a new Int-backed index type, along with necessary methods to support creating ranges macro indextype(ID) esc(quote struct $ID <: Integer value::Int end $ID(id::$ID) = id Base.hash(i::$ID, h::UInt) = hash(i.value, h) Base.convert(::Type{Int}, i::$ID) = i.value Base.Integer(i::$ID) = i.value Base.Int(i::$ID) = i.value Base.convert(::Type{$ID}, i::Integer) = $ID(i) Base.promote_type(::Type{Int}, ::Type{$ID}) = $ID Base.promote_type(::Type{$ID}, ::Type{Int}) = $ID Base.:<(x::$ID, y::$ID) = x.value < y.value Base.:<=(x::$ID, y::$ID) = x.value <= y.value Base.:-(x::$ID, y::$ID) = x.value - y.value Base.:+(x::$ID, y::Int) = $ID(x.value + y) end) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
267
## CacheElement mutable struct CacheElement{T} data::T dirty::Bool CacheElement(data::T) where {T} = new{T}(data, true) end @inline setdirty!(element::CacheElement) = (element.dirty = true; nothing) @inline isdirty(element::CacheElement) = element.dirty
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
454
## ConstDict """ An immutable `AbstractDict` for which the value is the same, no matter what the key is. """ struct ConstDict{K, V} <: AbstractDict{K, V} val::V ConstDict{K}(val::V) where {K, V} = new{K, V}(val) end Base.getindex(d::ConstDict{K}, key) where K = d.val Base.show(io::IO, ::MIME"text/plain", d::ConstDict{K}) where {K} = show(io, d) Base.show(io::IO, d::ConstDict{K}) where {K} = print(io, "$(typeof(d)) with fixed value $(d.val)")
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
488
## ConstVector """ $(TYPEDEF) An immutable `AbstractVector` for which all elements are the same, represented compactly and as a bitstype if the element type is a bitstype. """ struct ConstVector{T} <: AbstractVector{T} val::T length::Int64 end Base.size(A::ConstVector) = (A.length, ) @propagate_inbounds Base.getindex(A::ConstVector, i::Int) = (@boundscheck checkbounds(A, i); A.val) Base.IndexStyle(::Type{<:ConstVector}) = IndexLinear() Base.unalias(dest, x::ConstVector) = x
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
4211
## IndexDicts abstract type AbstractIndexDict{K, V} <: AbstractDict{K, V} end makekeys(::Type{UnitRange{K}}, start::K, stop::K) where {K} = start : stop function makekeys(::Type{Base.OneTo{K}}, start::K, stop::K) where {K} @boundscheck start === K(1) || error() Base.OneTo(stop) end """ $(TYPEDEF) An associative type whose keys are an `AbstractUnitRange`, and whose values are stored in a `Vector`. `IndexDict` is an ordered associative collection, with the order determined by key range. The nature of the keys enables very fast lookups and stores. # Examples ```julia-repl julia> IndexDict(2 : 4, [4, 5, 6]) RigidBodyDynamics.CustomCollections.IndexDict{Int64,UnitRange{Int64},Int64} with 3 entries: 2 => 4 3 => 5 4 => 6 julia> IndexDict{Int32, UnitRange{Int32}}(i => 3 * i for i in Int32[4, 2, 3]) RigidBodyDynamics.CustomCollections.IndexDict{Int32,UnitRange{Int32},Int64} with 3 entries: 2 => 6 3 => 9 4 => 12 ``` """ struct IndexDict{K, KeyRange<:AbstractUnitRange{K}, V} <: AbstractIndexDict{K, V} keys::KeyRange values::Vector{V} end Base.broadcastable(x::IndexDict) = Ref(x) """ $(TYPEDEF) Like [`IndexDict`](@ref), but contains an additional `Bool` dirty bit to be used in algorithms involving cached data. """ mutable struct CacheIndexDict{K, KeyRange<:AbstractUnitRange{K}, V} <: AbstractIndexDict{K, V} keys::KeyRange values::Vector{V} dirty::Bool function CacheIndexDict{K, KeyRange, V}(keys::KeyRange, values::Vector{V}) where {K, V, KeyRange<:AbstractUnitRange{K}} @boundscheck length(keys) == length(values) || error("Mismatch between keys and values.") new{K, KeyRange, V}(keys, values, true) end end setdirty!(d::CacheIndexDict) = (d.dirty = true; nothing) isdirty(d::CacheIndexDict) = d.dirty # Constructors for IDict in (:IndexDict, :CacheIndexDict) @eval begin function $IDict{K, KeyRange, V}(keys::KeyRange) where {K, KeyRange<:AbstractUnitRange{K}, V} $IDict{K, KeyRange, V}(keys, Vector{V}(undef, length(keys))) end function $IDict{K, KeyRange, V}(kv::Vector{Pair{K, V}}) where {K, KeyRange<:AbstractUnitRange{K}, V} if !issorted(kv, by = first) sort!(kv; by = first) end start, stop = if isempty(kv) K(1), K(0) else first(first(kv)), first(last(kv)) end keys = makekeys(KeyRange, start, stop) for i in eachindex(kv) keys[i] === first(kv[i]) || error() end values = map(last, kv) $IDict{K, KeyRange, V}(keys, values) end function $IDict{K, KeyRange}(kv::Vector{Pair{K, V}}) where {K, KeyRange<:AbstractUnitRange{K}, V} $IDict{K, KeyRange, V}(kv) end function $IDict{K, KeyRange, V}(itr) where {K, KeyRange<:AbstractUnitRange{K}, V} kv = Pair{K, V}[] for x in itr push!(kv, convert(K, first(x)) => convert(V, last(x))) end $IDict{K, KeyRange, V}(kv) end function $IDict{K, KeyRange}(itr) where {K, KeyRange<:AbstractUnitRange{K}} kv = [convert(K, first(x)) => last(x) for x in itr] $IDict{K, KeyRange}(kv) end end end @inline Base.isempty(d::AbstractIndexDict) = isempty(d.values) @inline Base.length(d::AbstractIndexDict) = length(d.values) @inline Base.iterate(d::AbstractIndexDict, i = 1) = i > length(d) ? nothing : (d.keys[i] => d.values[i], i + 1) @inline Base.keys(d::AbstractIndexDict{K}) where {K} = d.keys @inline Base.values(d::AbstractIndexDict) = d.values @inline Base.haskey(d::AbstractIndexDict, key) = key ∈ d.keys @inline keyindex(key::K, keyrange::Base.OneTo{K}) where {K} = Int(key) @inline keyindex(key::K, keyrange::UnitRange{K}) where {K} = Int(key - first(keyrange) + 1) @propagate_inbounds Base.getindex(d::AbstractIndexDict{K}, key::K) where {K} = d.values[keyindex(key, d.keys)] @propagate_inbounds Base.setindex!(d::AbstractIndexDict{K}, value, key::K) where {K} = d.values[keyindex(key, d.keys)] = value @propagate_inbounds Base.get(d::AbstractIndexDict{K}, key::K, default) where {K} = d[key]
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
277
## NullDict """ $(TYPEDEF) An immutable associative type that signifies an empty dictionary and does not allocate any memory. """ struct NullDict{K, V} <: AbstractDict{K, V} end Base.haskey(::NullDict, k) = false Base.length(::NullDict) = 0 Base.iterate(::NullDict) = nothing
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
3824
const AbstractMatrixBlock{T, M} = SubArray{T,2,M,Tuple{UnitRange{Int},UnitRange{Int}},false} """ $(TYPEDEF) `SegmentedBlockDiagonalMatrix` is an `AbstractMatrix` backed by a parent `AbstractMatrix`, which additionally stores a sequence of views into the diagonal blocks of the parent matrix. This type is useful for storing and updating block-diagonal matrices whose block contents may change but whose overall structure is fixed, such as configuration derivative <-> velocity jacobians. """ struct SegmentedBlockDiagonalMatrix{T, M<:AbstractMatrix{T}} <: AbstractMatrix{T} parent::M blocks::Vector{AbstractMatrixBlock{T, M}} function SegmentedBlockDiagonalMatrix{T, M}(parent::M, block_indices) where {T, M<:AbstractMatrix{T}} check_contiguous_block_ranges(parent, block_indices) blocks = collect(view(parent, indices...) for indices in block_indices) new{T, M}(parent, blocks) end end SegmentedBlockDiagonalMatrix(parent::M, block_indices) where {T, M<:AbstractMatrix{T}} = SegmentedBlockDiagonalMatrix{T, M}(parent, block_indices) function SegmentedBlockDiagonalMatrix{T}(initializer, rows::Integer, cols::Integer, block_indices) where T parent = Matrix{T}(initializer, rows, cols) SegmentedBlockDiagonalMatrix{T}(parent, block_indices) end Base.parent(m::SegmentedBlockDiagonalMatrix) = m.parent Base.size(m::SegmentedBlockDiagonalMatrix) = size(m.parent) @propagate_inbounds Base.getindex(v::SegmentedBlockDiagonalMatrix, i::Int) = v.parent[i] @propagate_inbounds Base.setindex!(v::SegmentedBlockDiagonalMatrix, value, i::Int) = v.parent[i] = value Base.IndexStyle(::Type{<:SegmentedBlockDiagonalMatrix}) = IndexLinear() blocks(m::SegmentedBlockDiagonalMatrix) = m.blocks function check_contiguous_block_ranges(parent::AbstractMatrix, block_indices) if !_is_contiguous_and_diagonal(parent, block_indices) throw(ArgumentError("The `block_indices` should be a vector of index ranges corresponding to non-overlapping contiguous diagonal blocks")) end end function _is_contiguous_and_diagonal(parent::AbstractMatrix, block_indices) expected_starts = first.(axes(parent)) for inds in block_indices if first.(inds) !== expected_starts return false end expected_starts = last.(inds) .+ 1 end if expected_starts !== last.(axes(parent)) .+ 1 return false end return true end function LinearAlgebra.mul!(C::Matrix, A::Matrix, B::SegmentedBlockDiagonalMatrix) # TODO: coordination with BLAS threads @boundscheck size(C) == (size(A, 1), size(B, 2)) || throw(DimensionMismatch("Output size mismatch.")) A′ = Base.unalias(C, A) Threads.@threads for block in blocks(B) # allocates 32 bytes (see https://github.com/JuliaLang/julia/issues/29748) @inbounds begin Acols, Ccols = parentindices(block) Aview = uview(A′, :, Acols) Cview = uview(C, :, Ccols) if block == I copyto!(Cview, Aview) else mul!(Cview, Aview, block) end end end return C end function LinearAlgebra.mul!(C::Matrix, A::SegmentedBlockDiagonalMatrix, B::Matrix) # TODO: coordination with BLAS threads @boundscheck size(C) == (size(A, 1), size(B, 2)) || throw(DimensionMismatch("Output size mismatch.")) B′ = Base.unalias(C, B) Threads.@threads for block in blocks(A) # allocates 32 bytes (see https://github.com/JuliaLang/julia/issues/29748) @inbounds begin Crows, Brows = parentindices(block) Bview = uview(B, Brows, :) Cview = uview(C, Crows, :) if block == I copyto!(Cview, Bview) else mul!(Cview, block, Bview) end end end return C end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
4403
## SegmentedVector const VectorSegment{T} = SubArray{T,1,Array{T, 1},Tuple{UnitRange{Int}},true} # type of a n:m view into a Vector """ $(TYPEDEF) `SegmentedVector` is an `AbstractVector` backed by another `AbstractVector` (its parent), which additionally stores an [`IndexDict`](@ref) containing views into the parent. Together, these views cover the parent. # Examples ```julia-repl julia> x = [1., 2., 3., 4.] 4-element Array{Float64,1}: 1.0 2.0 3.0 4.0 julia> viewlength(i) = 2 viewlength (generic function with 1 method) julia> xseg = SegmentedVector{Int}(x, 1 : 2, viewlength) 4-element RigidBodyDynamics.CustomCollections.SegmentedVector{Int64,Float64,Base.OneTo{Int64},Array{Float64,1}}: 1.0 2.0 3.0 4.0 julia> segments(xseg)[1] 2-element SubArray{Float64,1,Array{Float64,1},Tuple{UnitRange{Int64}},true}: 1.0 2.0 julia> yseg = similar(xseg, Int32); yseg .= 1 : 4 # same view ranges, different element type 4-element RigidBodyDynamics.CustomCollections.SegmentedVector{Int64,Int32,Base.OneTo{Int64},Array{Int32,1}}: 1 2 3 4 julia> segments(yseg)[2] 2-element SubArray{Int32,1,Array{Int32,1},Tuple{UnitRange{Int64}},true}: 3 4 ``` """ struct SegmentedVector{K, T, KeyRange<:AbstractRange{K}, P<:AbstractVector{T}} <: AbstractVector{T} parent::P segments::IndexDict{K, KeyRange, VectorSegment{T}} function SegmentedVector{K, T, KeyRange, P}(p::P, segments::IndexDict{K, KeyRange, VectorSegment{T}}) where {K, T, KeyRange<:AbstractRange{K}, P<:AbstractVector{T}} @boundscheck begin firstsegment = true start = 0 l = 0 for segment in values(segments) parent(segment) === parent(p) || error() indices = first(parentindices(segment)) if firstsegment start = first(indices) firstsegment = false else first(indices) === start || error() end start = last(indices) + 1 l += length(indices) end l == length(p) || error("Segments do not cover input data.") end new{K, T, KeyRange, P}(p, segments) end end function SegmentedVector(p::P, segments::IndexDict{K, KeyRange, VectorSegment{T}}) where {K, T, KeyRange<:AbstractRange{K}, P<:AbstractVector{T}} SegmentedVector{K, T, KeyRange, P}(p, segments) end function SegmentedVector{K, T, KeyRange}(parent::P, keys, viewlengthfun) where {K, T, KeyRange<:AbstractRange{K}, P<:AbstractVector{T}} views = Vector{Pair{K, VectorSegment{T}}}() start = 1 for key in keys stop = start[] + viewlengthfun(key) - 1 push!(views, convert(K, key) => view(parent, start : stop)) start = stop + 1 end SegmentedVector{K, T, KeyRange, P}(parent, IndexDict{K, KeyRange, VectorSegment{T}}(views)) end function SegmentedVector{K}(parent::P, keys, viewlengthfun) where {K, T, P<:AbstractVector{T}} SegmentedVector{K, T, Base.OneTo{K}}(parent, keys, viewlengthfun) end function SegmentedVector{K, T, KeyRange}(parent::P, ranges::AbstractDict{K, UnitRange{Int}}) where {K, T, KeyRange, P<:AbstractVector{T}} segs = IndexDict{K, KeyRange, VectorSegment{T}}(keys(ranges), [view(parent, range) for range in values(ranges)]) SegmentedVector{K, T, KeyRange, P}(parent, IndexDict{K, KeyRange, VectorSegment{T}}(segs)) end Base.size(v::SegmentedVector) = size(v.parent) @propagate_inbounds Base.getindex(v::SegmentedVector, i::Int) = v.parent[i] @propagate_inbounds Base.getindex(v::SegmentedVector{K}, key::K) where {K} = v.segments[key] # TODO: deprecate in favor of view? @propagate_inbounds Base.setindex!(v::SegmentedVector, value, i::Int) = v.parent[i] = value Base.dataids(x::SegmentedVector) = Base.dataids(x.parent) @propagate_inbounds Base.view(v::SegmentedVector{K}, key::K) where {K} = v.segments[key] Base.parent(v::SegmentedVector) = v.parent segments(v::SegmentedVector) = v.segments function ranges(v::SegmentedVector{K, <:Any, KeyRange}) where {K, KeyRange} segments = v.segments IndexDict{K, KeyRange, UnitRange{Int}}(segments.keys, map(segment -> first(parentindices(segment))::UnitRange{Int}, segments.values)) end function Base.similar(v::SegmentedVector{K, T, KeyRange}, ::Type{S} = T) where {K, T, KeyRange, S} SegmentedVector{K, S, KeyRange}(similar(parent(v), S), ranges(v)) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
236
struct UnorderedPair{T} a::T b::T end Base.hash(p::UnorderedPair, h::UInt) = hash(p.a, h) + hash(p.b, h) function Base.:(==)(x::UnorderedPair, y::UnorderedPair) (x.a == y.a && x.b == y.b) || (x.a == y.b && x.b == y.a) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
708
module CustomCollections export ConstVector, ConstDict, NullDict, CacheElement, AbstractIndexDict, IndexDict, CacheIndexDict, SegmentedVector, SegmentedBlockDiagonalMatrix, UnorderedPair export foreach_with_extra_args, isdirty, segments, ranges using TypeSortedCollections using DocStringExtensions using LinearAlgebra using UnsafeArrays using Base: @propagate_inbounds include("foreach_with_extra_args.jl") include("ConstVector.jl") include("ConstDict.jl") include("NullDict.jl") include("CacheElement.jl") include("IndexDict.jl") include("SegmentedVector.jl") include("SegmentedBlockDiagonalMatrix.jl") include("UnorderedPair.jl") end # module
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
1597
## TypeSortedCollections addendum # `foreach_with_extra_args` below is a hack to avoid allocations associated with creating closures over # heap-allocated variables. Hopefully this will not be necessary in a future version of Julia. for num_extra_args = 1 : 5 extra_arg_syms = [Symbol("arg", i) for i = 1 : num_extra_args] @eval begin @generated function foreach_with_extra_args(f, $(extra_arg_syms...), A1::TypeSortedCollection{<:Any, N}, As::Union{<:TypeSortedCollection{<:Any, N}, AbstractVector}...) where {N} extra_args = $extra_arg_syms expr = Expr(:block) push!(expr.args, :(Base.@_inline_meta)) # required to achieve zero allocation push!(expr.args, :(leading_tsc = A1)) push!(expr.args, :(@boundscheck TypeSortedCollections.lengths_match(A1, As...) || TypeSortedCollections.lengths_match_fail())) for i = 1 : N vali = Val(i) push!(expr.args, quote let inds = leading_tsc.indices[$i] @boundscheck TypeSortedCollections.indices_match($vali, inds, A1, As...) || TypeSortedCollections.indices_match_fail() @inbounds for j in LinearIndices(inds) vecindex = inds[j] f($(extra_args...), TypeSortedCollections._getindex_all($vali, j, vecindex, A1, As...)...) end end end) end quote $expr nothing end end end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
833
module Graphs # modules export PathDirections # types export DirectedGraph, SpanningTree, TreePath, Edge, Vertex # functions export vertextype, edgetype, vertices, edges, source, target, out_edges, in_edges, out_neighbors, in_neighbors, num_vertices, num_edges, add_vertex!, add_edge!, remove_vertex!, remove_edge!, rewire!, replace_edge!, reindex!, root, edge_to_parent, edges_to_children, tree_index, ancestors, lowest_common_ancestor, subtree_vertices, direction, directions using Base.Iterators: flatten import SparseArrays: sparsevec include("abstract.jl") include("directed_graph.jl") include("spanning_tree.jl") include("tree_path.jl") include("edge_vertex_wrappers.jl") end # module
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
1980
# Vertex interface """ vertex_id(vertex) Return an identifier of the vertex. The identifier must be of a type that can be converted from and to an Int. """ function vertex_id end """ set_vertex_id!(vertex, id) Set the vertex identifier. The identifier must be of a type that can be converted from and to an Int. """ function set_vertex_id! end """ vertex_id_type(V) Return the identifier type used by vertex type `V`. The identifier type must be convertible from and to an Int. """ vertex_id_type(::Type) = Int # fallback, can be specialized @inline vertex_index(x) = Int(vertex_id(x)) @inline vertex_index!(x::T, index::Int) where {T} = set_vertex_id!(x, vertex_id_type(T)(index)) # Edge interface """ edge_id(edge) Return an identifier of the edge. The identifier must be of a type that can be converted from and to an Int. """ function edge_id end """ set_edge_id!(edge, id) Set the edge identifier. The identifier must be of a type that can be converted from and to an Int. """ function set_edge_id! end """ edge_id_type(V) Return the identifier type used by edge type `V`. The identifier type must be convertible from and to an Int. """ edge_id_type(::Type) = Int # fallback, can be specialized @inline edge_index(x) = Int(edge_id(x)) @inline edge_index!(x::T, index::Int) where {T} = set_edge_id!(x, edge_id_type(T)(index)) flip_direction(x::Any) = deepcopy(x) abstract type AbstractGraph{V, E} end vertextype(::Type{<:AbstractGraph{V, E}}) where {V, E} = V vertextype(g::AbstractGraph) = vertextype(typeof(g)) edgetype(::Type{<:AbstractGraph{V, E}}) where {V, E} = E edgetype(g::AbstractGraph) = edgetype(typeof(g)) num_vertices(g::AbstractGraph) = length(vertices(g)) num_edges(g::AbstractGraph) = length(edges(g)) out_neighbors(vertex::V, g::AbstractGraph{V, E}) where {V, E} = (target(e, g) for e in out_edges(vertex, g)) in_neighbors(vertex::V, g::AbstractGraph{V, E}) where {V, E} = (source(e, g) for e in in_edges(vertex, g))
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
5061
mutable struct DirectedGraph{V, E} <: AbstractGraph{V, E} vertices::Vector{V} edges::Vector{E} sources::Vector{V} targets::Vector{V} inedges::Vector{Vector{E}} outedges::Vector{Vector{E}} end DirectedGraph{V, E}() where {V, E} = DirectedGraph{V, E}(V[], E[], V[], V[], Set{E}[], Set{E}[]) function DirectedGraph(vertexfun::Base.Callable, edgefun::Base.Callable, other::DirectedGraph) vertices = map(vertexfun, other.vertices) edges = map(edgefun, other.edges) vertexmap = Dict(zip(other.vertices, vertices)) edgemap = Dict(zip(other.edges, edges)) sources = [vertexmap[v] for v in other.sources] targets = [vertexmap[v] for v in other.targets] inedges = [[edgemap[e] for e in vec] for vec in other.inedges] outedges = [[edgemap[e] for e in vec] for vec in other.outedges] DirectedGraph(vertices, edges, sources, targets, inedges, outedges) end # AbstractGraph interface vertices(g::DirectedGraph) = g.vertices edges(g::DirectedGraph) = g.edges source(edge, g::DirectedGraph{V, E}) where {V, E} = g.sources[edge_index(edge)] target(edge, g::DirectedGraph{V, E}) where {V, E} = g.targets[edge_index(edge)] in_edges(vertex::V, g::DirectedGraph{V, E}) where {V, E} = g.inedges[vertex_index(vertex)] out_edges(vertex::V, g::DirectedGraph{V, E}) where {V, E} = g.outedges[vertex_index(vertex)] Base.show(io::IO, ::DirectedGraph{V, E}) where {V, E} = print(io, "DirectedGraph{$V, $E}(…)") function Base.empty!(g::DirectedGraph) empty!(g.vertices) empty!(g.edges) empty!(g.sources) empty!(g.targets) empty!(g.inedges) empty!(g.outedges) g end function add_vertex!(g::DirectedGraph{V, E}, vertex::V) where {V, E} @assert vertex ∉ vertices(g) vertex_index!(vertex, num_vertices(g) + 1) push!(g.vertices, vertex) push!(g.outedges, E[]) push!(g.inedges, E[]) g end function add_edge!(g::DirectedGraph{V, E}, source::V, target::V, edge::E) where {V, E} @assert edge ∉ edges(g) source ∈ vertices(g) || add_vertex!(g, source) target ∈ vertices(g) || add_vertex!(g, target) edge_index!(edge, num_edges(g) + 1) push!(g.edges, edge) push!(g.sources, source) push!(g.targets, target) push!(out_edges(source, g), edge) push!(in_edges(target, g), edge) g end function remove_vertex!(g::DirectedGraph{V, E}, vertex::V) where {V, E} disconnected = isempty(in_edges(vertex, g)) && isempty(out_edges(vertex, g)) disconnected || error("Vertex must be disconnected from the rest of the graph before it can be removed.") index = vertex_index(vertex) deleteat!(g.vertices, index) deleteat!(g.inedges, index) deleteat!(g.outedges, index) for i = index : num_vertices(g) vertex_index!(g.vertices[i], i) end vertex_index!(vertex, -1) g end function remove_edge!(g::DirectedGraph{V, E}, edge::E) where {V, E} target_inedges = in_edges(target(edge, g), g) deleteat!(target_inedges, findfirst(isequal(edge), target_inedges)) source_outedges = out_edges(source(edge, g), g) deleteat!(source_outedges, findfirst(isequal(edge), source_outedges)) index = edge_index(edge) deleteat!(g.edges, index) deleteat!(g.sources, index) deleteat!(g.targets, index) for i = index : num_edges(g) edge_index!(g.edges[i], i) end edge_index!(edge, -1) g end function rewire!(g::DirectedGraph{V, E}, edge::E, newsource::V, newtarget::V) where {V, E} oldsource = source(edge, g) oldtarget = target(edge, g) g.sources[edge_index(edge)] = newsource g.targets[edge_index(edge)] = newtarget oldtarget_inedges = in_edges(oldtarget, g) deleteat!(oldtarget_inedges, findfirst(isequal(edge), oldtarget_inedges)) oldsource_outedges = out_edges(oldsource, g) deleteat!(oldsource_outedges, findfirst(isequal(edge), oldsource_outedges)) push!(out_edges(newsource, g), edge) push!(in_edges(newtarget, g), edge) g end function replace_edge!(g::DirectedGraph{V, E}, old_edge::E, new_edge::E) where {V, E} if new_edge !== old_edge src = source(old_edge, g) dest = target(old_edge, g) index = edge_index(old_edge) edge_index!(new_edge, index) g.edges[index] = new_edge out_edge_index = findfirst(isequal(old_edge), out_edges(src, g)) out_edges(src, g)[out_edge_index] = new_edge in_edge_index = findfirst(isequal(old_edge), in_edges(dest, g)) in_edges(dest, g)[in_edge_index] = new_edge edge_index!(old_edge, -1) end g end function reindex!(g::DirectedGraph{V, E}, vertices_in_order, edges_in_order) where {V, E} @assert isempty(setdiff(vertices(g), vertices_in_order)) @assert isempty(setdiff(edges(g), edges_in_order)) sources = source.(edges_in_order, Ref(g)) targets = target.(edges_in_order, Ref(g)) empty!(g) for v in vertices_in_order add_vertex!(g, v) end for (source, target, e) in zip(sources, targets, edges_in_order) add_edge!(g, source, target, e) end g end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
599
# Vertex and Edge types; useful for wrapping an existing type with the edge interface. # Note that DirectedGraph does not require using these types; just implement the edge interface. for typename in (:Edge, :Vertex) getid = Symbol(lowercase(string(typename)) * "_id") setid = Symbol("set_" * lowercase(string(typename)) * "_id!") @eval begin mutable struct $typename{T} data::T id::Int64 end $typename(data) = $typename(data, -1) $getid(x::$typename) = x.id $setid(x::$typename, index::Int64) = (x.id = index) end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
6389
mutable struct SpanningTree{V, E} <: AbstractGraph{V, E} graph::DirectedGraph{V, E} root::V edges::Vector{E} inedges::Vector{E} outedges::Vector{Vector{E}} edge_tree_indices::Vector{Int64} # mapping from edge_index(edge) to index into edges(tree) end # AbstractGraph interface vertices(tree::SpanningTree) = vertices(tree.graph) edges(tree::SpanningTree) = tree.edges source(edge, tree::SpanningTree{V, E}) where {V, E} = source(edge, tree.graph) # note: doesn't check that edge is in spanning tree! target(edge, tree::SpanningTree{V, E}) where {V, E} = target(edge, tree.graph) # note: doesn't check that edge is in spanning tree! in_edges(vertex::V, tree::SpanningTree{V, E}) where {V, E} = (tree.inedges[vertex_index(vertex)],) out_edges(vertex::V, tree::SpanningTree{V, E}) where {V, E} = tree.outedges[vertex_index(vertex)] root(tree::SpanningTree) = tree.root edge_to_parent(vertex::V, tree::SpanningTree{V, E}) where {V, E} = tree.inedges[vertex_index(vertex)] edges_to_children(vertex::V, tree::SpanningTree{V, E}) where {V, E} = out_edges(vertex, tree) tree_index(edge, tree::SpanningTree{V, E}) where {V, E} = tree.edge_tree_indices[edge_index(edge)] tree_index(vertex::V, tree::SpanningTree{V, E}) where {V, E} = vertex === root(tree) ? 1 : tree_index(edge_to_parent(vertex, tree), tree) + 1 function SpanningTree(g::DirectedGraph{V, E}, root::V, edges::AbstractVector{E}) where {V, E} n = num_vertices(g) length(edges) == n - 1 || error("Expected n - 1 edges.") inedges = Vector{E}(undef, n) outedges = [E[] for i = 1 : n] edge_tree_indices = Int64[] treevertices = V[] for (i, edge) in enumerate(edges) parent = source(edge, g) child = target(edge, g) isempty(treevertices) && push!(treevertices, parent) @assert parent ∈ treevertices inedges[vertex_index(child)] = edge push!(outedges[vertex_index(parent)], edge) push!(treevertices, child) resize!(edge_tree_indices, max(edge_index(edge), length(edge_tree_indices))) edge_tree_indices[edge_index(edge)] = i end SpanningTree(g, root, edges, inedges, outedges, edge_tree_indices) end function SpanningTree(g::DirectedGraph{V, E}, root::V, flipped_edge_map::Union{AbstractDict, Nothing} = nothing; next_edge = first #= breadth first =#) where {V, E} tree_edges = E[] tree_vertices = [root] frontier = E[] append!(frontier, out_edges(root, g)) append!(frontier, in_edges(root, g)) while !isempty(frontier) # select a new edge e = next_edge(frontier) # remove edges from frontier flip = source(e, g) ∉ tree_vertices child = flip ? source(e, g) : target(e, g) filter!(x -> x ∉ in_edges(child, g), frontier) filter!(x -> x ∉ out_edges(child, g), frontier) # flip current edge if necessary if flip rewire!(g, e, target(e, g), source(e, g)) newedge = flip_direction(e) replace_edge!(g, e, newedge) if flipped_edge_map !== nothing flipped_edge_map[e] = newedge end e = newedge end # update tree push!(tree_edges, e) push!(tree_vertices, child) # add new edges to frontier append!(frontier, x for x in out_edges(child, g) if target(x, g) ∉ tree_vertices) append!(frontier, x for x in in_edges(child, g) if source(x, g) ∉ tree_vertices) end length(tree_vertices) == num_vertices(g) || error("Graph is not connected.") SpanningTree(g, root, tree_edges) end """ Add an edge and vertex to both the tree and the underlying graph. """ function add_edge!(tree::SpanningTree{V, E}, source::V, target::V, edge::E) where {V, E} @assert target ∉ vertices(tree) add_edge!(tree.graph, source, target, edge) push!(tree.edges, edge) push!(tree.inedges, edge) push!(tree.outedges, E[]) push!(out_edges(source, tree), edge) resize!(tree.edge_tree_indices, max(edge_index(edge), length(tree.edge_tree_indices))) tree.edge_tree_indices[edge_index(edge)] = num_edges(tree) tree end """ Replace an edge in both the tree and the underlying graph. """ function replace_edge!(tree::SpanningTree{V, E}, old_edge::E, new_edge::E) where {V, E} @assert old_edge ∈ edges(tree) src = source(old_edge, tree) dest = target(old_edge, tree) tree.edges[tree_index(old_edge, tree)] = new_edge tree.inedges[vertex_index(dest)] = new_edge out_edge_index = findfirst(isequal(old_edge), out_edges(src, tree)) out_edges(src, tree)[out_edge_index] = new_edge replace_edge!(tree.graph, old_edge, new_edge) tree end function Base.show(io::IO, tree::SpanningTree, vertex = root(tree), level::Int64 = 0) for i = 1 : level print(io, " ") end print(io, "Vertex: ") show(IOContext(io, :compact => true), vertex) if vertex == root(tree) print(io, " (root)") else print(io, ", ") print(io, "Edge: ") show(IOContext(io, :compact => true), edge_to_parent(vertex, tree)) end for edge in edges_to_children(vertex, tree) print(io, "\n") child = target(edge, tree) show(io, tree, child, level + 1) end end function ancestors(vertex::V, tree::SpanningTree{V, E}) where {V, E} ret = [vertex] while vertex != root(tree) vertex = source(edge_to_parent(vertex, tree), tree) push!(ret, vertex) end ret end function lowest_common_ancestor(v1::V, v2::V, tree::SpanningTree{V, E}) where {V, E} while v1 != v2 if tree_index(v1, tree) > tree_index(v2, tree) v1 = source(edge_to_parent(v1, tree), tree) else v2 = source(edge_to_parent(v2, tree), tree) end end v1 end """ Return a list of vertices in the subtree rooted at `subtree_root`, including `subtree_root` itself. The list is guaranteed to be topologically sorted. """ function subtree_vertices(subtree_root::V, tree::SpanningTree{V, E}) where {V, E} @assert subtree_root ∈ vertices(tree) frontier = [subtree_root] subtree_vertices = V[] while !isempty(frontier) parent = pop!(frontier) push!(subtree_vertices, parent) for child in out_neighbors(parent, tree) push!(frontier, child) end end return subtree_vertices end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
2425
module PathDirections export PathDirection @enum PathDirection::Bool begin up # going towards the root of the tree down # going away from the root of the tree end end using .PathDirections struct TreePath{V, E} source::V target::V edges::Vector{E} # in order directions::Vector{PathDirection} indexmap::Vector{Int} end source(path::TreePath) = path.source target(path::TreePath) = path.target @inline Base.findfirst(path::TreePath{<:Any, E}, edge::E) where {E} = path.indexmap[edge_index(edge)] # TODO: remove, use equalto @inline Base.in(edge::E, path::TreePath{<:Any, E}) where {E} = findfirst(path, edge) != 0 # TODO: findfirst update @inline directions(path::TreePath) = path.directions @inline direction(edge::E, path::TreePath{<:Any, E}) where {E} = path.directions[findfirst(path, edge)] # TODO: findfirst update Base.iterate(path::TreePath) = iterate(path.edges) Base.iterate(path::TreePath, state) = iterate(path.edges, state) Base.eltype(path::TreePath) = eltype(path.edges) Base.length(path::TreePath) = length(path.edges) function Base.show(io::IO, path::TreePath) println(io, "Path from $(path.source) to $(path.target):") for edge in path directionchar = ifelse(direction(edge, path) == PathDirections.up, '↑', '↓') print(io, "$directionchar ") show(IOContext(io, :compact => true), edge) println(io) end end function TreePath(src::V, target::V, tree::SpanningTree{V, E}) where {V, E} source_to_lca = E[] lca_to_target = E[] source_current = src target_current = target while source_current != target_current if tree_index(source_current, tree) > tree_index(target_current, tree) edge = edge_to_parent(source_current, tree) push!(source_to_lca, edge) source_current = source(edge, tree) else edge = edge_to_parent(target_current, tree) push!(lca_to_target, edge) target_current = source(edge, tree) end end reverse!(lca_to_target) edges = collect(E, flatten((source_to_lca, lca_to_target))) directions = collect(PathDirection, flatten(((PathDirections.up for e in source_to_lca), (PathDirections.down for e in lca_to_target)))) indexmap = Vector(sparsevec(Dict(edge_index(e) => i for (i, e) in enumerate(edges)), num_edges(tree))) TreePath{V, E}(src, target, edges, directions, indexmap) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
2884
""" $(TYPEDEF) The `Fixed` joint type is a degenerate joint type, in the sense that it allows no motion between its predecessor and successor rigid bodies. """ struct Fixed{T} <: JointType{T} end Base.show(io::IO, jt::Fixed) = print(io, "Fixed joint") Random.rand(::Type{Fixed{T}}) where {T} = Fixed{T}() RigidBodyDynamics.flip_direction(jt::Fixed) = deepcopy(jt) num_positions(::Type{<:Fixed}) = 0 num_velocities(::Type{<:Fixed}) = 0 has_fixed_subspaces(jt::Fixed) = true isfloating(::Type{<:Fixed}) = false @inline function joint_transform(jt::Fixed, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) S = promote_eltype(jt, q) one(Transform3D{S}, frame_after, frame_before) end @inline function joint_twist(jt::Fixed, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) zero(Twist{S}, frame_after, frame_before, frame_after) end @inline function joint_spatial_acceleration(jt::Fixed, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector, vd::AbstractVector) S = promote_eltype(jt, q, v, vd) zero(SpatialAcceleration{S}, frame_after, frame_before, frame_after) end @inline function motion_subspace(jt::Fixed, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) S = promote_eltype(jt, q) GeometricJacobian(frame_after, frame_before, frame_after, zero(SMatrix{3, 0, S}), zero(SMatrix{3, 0, S})) end @inline function constraint_wrench_subspace(jt::Fixed, joint_transform::Transform3D) S = promote_eltype(jt, joint_transform) angular = hcat(one(SMatrix{3, 3, S}), zero(SMatrix{3, 3, S})) linear = hcat(zero(SMatrix{3, 3, S}), one(SMatrix{3, 3, S})) WrenchMatrix(joint_transform.from, angular, linear) end @inline zero_configuration!(q::AbstractVector, ::Fixed) = nothing @inline rand_configuration!(q::AbstractVector, ::Fixed) = nothing @inline function bias_acceleration(jt::Fixed, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) zero(SpatialAcceleration{S}, frame_after, frame_before, frame_after) end @inline configuration_derivative_to_velocity!(v::AbstractVector, ::Fixed, q::AbstractVector, q̇::AbstractVector) = nothing @inline velocity_to_configuration_derivative!(q̇::AbstractVector, ::Fixed, q::AbstractVector, v::AbstractVector) = nothing @inline joint_torque!(τ::AbstractVector, jt::Fixed, q::AbstractVector, joint_wrench::Wrench) = nothing @inline function velocity_to_configuration_derivative_jacobian(::Fixed{T}, ::AbstractVector) where T SMatrix{0, 0, T}() end @inline function configuration_derivative_to_velocity_jacobian(::Fixed{T}, ::AbstractVector) where T SMatrix{0, 0, T}() end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
1601
# TODO: document which methods are needed for a new JointType. # Default implementations function flip_direction(jt::JointType{T}) where {T} error("Flipping direction is not supported for $(typeof(jt))") end @propagate_inbounds zero_configuration!(q::AbstractVector, ::JointType) = (q .= 0; nothing) @propagate_inbounds function local_coordinates!(ϕ::AbstractVector, ϕ̇::AbstractVector, jt::JointType, q0::AbstractVector, q::AbstractVector, v::AbstractVector) ϕ .= q .- q0 velocity_to_configuration_derivative!(ϕ̇, jt, q, v) nothing end @propagate_inbounds function global_coordinates!(q::AbstractVector, jt::JointType, q0::AbstractVector, ϕ::AbstractVector) q .= q0 .+ ϕ end @propagate_inbounds function configuration_derivative_to_velocity_adjoint!(out, jt::JointType, q::AbstractVector, f) out .= f end @propagate_inbounds function configuration_derivative_to_velocity!(v::AbstractVector, ::JointType, q::AbstractVector, q̇::AbstractVector) v .= q̇ nothing end @propagate_inbounds function velocity_to_configuration_derivative!(q̇::AbstractVector, ::JointType, q::AbstractVector, v::AbstractVector) q̇ .= v nothing end normalize_configuration!(q::AbstractVector, ::JointType) = nothing is_configuration_normalized(::JointType, q::AbstractVector, rtol, atol) = true principal_value!(q::AbstractVector, ::JointType) = nothing include("quaternion_floating.jl") include("spquat_floating.jl") include("prismatic.jl") include("revolute.jl") include("fixed.jl") include("planar.jl") include("quaternion_spherical.jl") include("sin_cos_revolute.jl")
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
6331
""" $(TYPEDEF) The `Planar` joint type allows translation along two orthogonal vectors, referred to as ``x`` and ``y``, as well as rotation about an axis ``z = x \\times y``. The components of the 3-dimensional configuration vector ``q`` associated with a `Planar` joint are the ``x``- and ``y``-coordinates of the translation, and the angle of rotation ``\\theta`` about ``z``, in that order. The components of the 3-dimension velocity vector ``v`` associated with a `Planar` joint are the ``x``- and ``y``-coordinates of the linear part of the joint twist, expressed in the frame after the joint, followed by the ``z``-component of the angular part of this joint twist. !!! warning For the `Planar` joint type, ``v \\neq \\dot{q}``! Although the angular parts of ``v`` and ``\\dot{q}`` are the same, their linear parts differ. The linear part of ``v`` is the linear part of ``\\dot{q}``, rotated to the frame after the joint. This parameterization was chosen to allow the translational component of the joint transform to be independent of the rotation angle ``\\theta`` (i.e., the rotation is applied **after** the translation), while still retaining a constant motion subspace expressed in the frame after the joint. """ struct Planar{T} <: JointType{T} x_axis::SVector{3, T} y_axis::SVector{3, T} rot_axis::SVector{3, T} @doc """ $(SIGNATURES) Construct a new `Planar` joint type with the ``xy``-plane in which translation is allowed defined by 3-vectors `x` and `y` expressed in the frame before the joint. """ -> function Planar{T}(x_axis::AbstractVector, y_axis::AbstractVector) where {T} x, y = map(axis -> normalize(SVector{3}(axis)), (x_axis, y_axis)) @assert isapprox(x ⋅ y, 0; atol = 100 * eps(T)) new{T}(x, y, x × y) end end Planar(x_axis::AbstractVector, y_axis::AbstractVector) = Planar{promote_eltype(x_axis, y_axis)}(x_axis, y_axis) Base.show(io::IO, jt::Planar) = print(io, "Planar joint with x-axis $(jt.x_axis) and y-axis $(jt.y_axis)") function Random.rand(::Type{Planar{T}}) where {T} x = normalize(randn(SVector{3, T})) y = normalize(randn(SVector{3, T})) y = normalize(y - (x ⋅ y) * x) Planar(x, y) end num_positions(::Type{<:Planar}) = 3 num_velocities(::Type{<:Planar}) = 3 has_fixed_subspaces(jt::Planar) = true isfloating(::Type{<:Planar}) = false @propagate_inbounds function rand_configuration!(q::AbstractVector, ::Planar) T = eltype(q) q[1] = rand() - T(0.5) q[2] = rand() - T(0.5) q[3] = randn() nothing end @propagate_inbounds function joint_transform(jt::Planar, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) rot = RotMatrix(AngleAxis(q[3], jt.rot_axis[1], jt.rot_axis[2], jt.rot_axis[3], false)) trans = jt.x_axis * q[1] + jt.y_axis * q[2] Transform3D(frame_after, frame_before, rot, trans) end @propagate_inbounds function joint_twist(jt::Planar, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) angular = jt.rot_axis * v[3] linear = jt.x_axis * v[1] + jt.y_axis * v[2] Twist(frame_after, frame_before, frame_after, angular, linear) end @propagate_inbounds function joint_spatial_acceleration(jt::Planar, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector, vd::AbstractVector) S = promote_eltype(jt, q, v, vd) angular = jt.rot_axis * vd[3] linear = jt.x_axis * vd[1] + jt.y_axis * vd[2] SpatialAcceleration{S}(frame_after, frame_before, frame_after, angular, linear) end @inline function motion_subspace(jt::Planar, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) S = promote_eltype(jt, q) angular = hcat(zero(SMatrix{3, 2, S}), jt.rot_axis) linear = hcat(jt.x_axis, jt.y_axis, zero(SVector{3, S})) GeometricJacobian(frame_after, frame_before, frame_after, angular, linear) end @inline function constraint_wrench_subspace(jt::Planar, joint_transform::Transform3D) S = promote_eltype(jt, joint_transform) angular = hcat(zero(SVector{3, S}), jt.x_axis, jt.y_axis) linear = hcat(jt.rot_axis, zero(SMatrix{3, 2, S})) WrenchMatrix(joint_transform.from, angular, linear) end @inline function bias_acceleration(jt::Planar, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) zero(SpatialAcceleration{S}, frame_after, frame_before, frame_after) end @propagate_inbounds function joint_torque!(τ::AbstractVector, jt::Planar, q::AbstractVector, joint_wrench::Wrench) τ[1] = dot(linear(joint_wrench), jt.x_axis) τ[2] = dot(linear(joint_wrench), jt.y_axis) τ[3] = dot(angular(joint_wrench), jt.rot_axis) nothing end @propagate_inbounds function configuration_derivative_to_velocity!(v::AbstractVector, jt::Planar, q::AbstractVector, q̇::AbstractVector) vlinear = RotMatrix(-q[3]) * SVector(q̇[1], q̇[2]) v[1] = vlinear[1] v[2] = vlinear[2] v[3] = q̇[3] nothing end @propagate_inbounds function velocity_to_configuration_derivative!(q̇::AbstractVector, jt::Planar, q::AbstractVector, v::AbstractVector) q̇linear = RotMatrix(q[3]) * SVector(v[1], v[2]) q̇[1] = q̇linear[1] q̇[2] = q̇linear[2] q̇[3] = v[3] nothing end @propagate_inbounds function configuration_derivative_to_velocity_adjoint!(out, jt::Planar, q::AbstractVector, f) outlinear = RotMatrix(q[3]) * SVector(f[1], f[2]) out[1] = outlinear[1] out[2] = outlinear[2] out[3] = f[3] nothing end @propagate_inbounds function velocity_to_configuration_derivative_jacobian(::Planar, q::AbstractVector) # TODO: use SMatrix(RotZ(q[3]) once it's as fast rot = RotMatrix(q[3]) @inbounds return @SMatrix([rot[1] rot[3] 0; rot[2] rot[4] 0; 0 0 1]) end @propagate_inbounds function configuration_derivative_to_velocity_jacobian(::Planar, q::AbstractVector) # TODO: use SMatrix(RotZ(-q[3]) once it's as fast rot = RotMatrix(-q[3]) @inbounds return @SMatrix([rot[1] rot[3] 0; rot[2] rot[4] 0; 0 0 1]) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
3854
""" $(TYPEDEF) A `Prismatic` joint type allows translation along a fixed axis. """ struct Prismatic{T} <: JointType{T} axis::SVector{3, T} rotation_from_z_aligned::RotMatrix3{T} @doc """ $(SIGNATURES) Construct a new `Prismatic` joint type, allowing translation along `axis` (expressed in the frame before the joint). """ -> function Prismatic(axis::AbstractVector{T}) where {T} a = normalize(axis) new{T}(a, rotation_between(SVector(zero(T), zero(T), one(T)), SVector{3, T}(a))) end end Base.show(io::IO, jt::Prismatic) = print(io, "Prismatic joint with axis $(jt.axis)") function Random.rand(::Type{Prismatic{T}}) where {T} axis = normalize(randn(SVector{3, T})) Prismatic(axis) end num_positions(::Type{<:Prismatic}) = 1 num_velocities(::Type{<:Prismatic}) = 1 has_fixed_subspaces(jt::Prismatic) = true isfloating(::Type{<:Prismatic}) = false RigidBodyDynamics.flip_direction(jt::Prismatic) = Prismatic(-jt.axis) @propagate_inbounds function set_configuration!(q::AbstractVector, joint::Joint{<:Any, <:Prismatic}, pos::Number) @boundscheck check_num_positions(joint, q) @inbounds q[1] = pos q end @propagate_inbounds function set_velocity!(v::AbstractVector, joint::Joint{<:Any, <:Prismatic}, vel::Number) @boundscheck check_num_velocities(joint, v) @inbounds v[1] = vel v end @propagate_inbounds function rand_configuration!(q::AbstractVector, ::Prismatic) randn!(q) nothing end @inline function bias_acceleration(jt::Prismatic, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) zero(SpatialAcceleration{S}, frame_after, frame_before, frame_after) end @inline function velocity_to_configuration_derivative_jacobian(jt::Prismatic, q::AbstractVector) T = promote_eltype(jt, q) @SMatrix([one(T)]) end @inline function configuration_derivative_to_velocity_jacobian(jt::Prismatic, q::AbstractVector) T = promote_eltype(jt, q) @SMatrix([one(T)]) end @propagate_inbounds function joint_transform(jt::Prismatic, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) translation = q[1] * jt.axis Transform3D(frame_after, frame_before, translation) end @propagate_inbounds function joint_twist(jt::Prismatic, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) linear = jt.axis * v[1] Twist(frame_after, frame_before, frame_after, zero(linear), linear) end @propagate_inbounds function joint_spatial_acceleration(jt::Prismatic, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector, vd::AbstractVector) S = promote_eltype(jt, q, v, vd) linear = convert(SVector{3, S}, jt.axis * vd[1]) SpatialAcceleration(frame_after, frame_before, frame_after, zero(linear), linear) end @inline function motion_subspace(jt::Prismatic, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) S = promote_eltype(jt, q) angular = zero(SMatrix{3, 1, S}) linear = SMatrix{3, 1, S}(jt.axis) GeometricJacobian(frame_after, frame_before, frame_after, angular, linear) end @inline function constraint_wrench_subspace(jt::Prismatic, joint_transform::Transform3D) S = promote_eltype(jt, joint_transform) R = convert(RotMatrix3{S}, jt.rotation_from_z_aligned) Rcols12 = R[:, SVector(1, 2)] angular = hcat(R, zero(SMatrix{3, 2, S})) linear = hcat(zero(SMatrix{3, 3, S}), Rcols12) WrenchMatrix(joint_transform.from, angular, linear) end @propagate_inbounds function joint_torque!(τ::AbstractVector, jt::Prismatic, q::AbstractVector, joint_wrench::Wrench) τ[1] = dot(linear(joint_wrench), jt.axis) nothing end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
10889
""" $(TYPEDEF) A floating joint type that uses a unit quaternion representation for orientation. Floating joints are 6-degree-of-freedom joints that are in a sense degenerate, as they impose no constraints on the relative motion between two bodies. The full, 7-dimensional configuration vector of a `QuaternionFloating` joint type consists of a unit quaternion representing the orientation that rotates vectors from the frame 'directly after' the joint to the frame 'directly before' it, and a 3D position vector representing the origin of the frame after the joint in the frame before the joint. The 6-dimensional velocity vector of a `QuaternionFloating` joint is the twist of the frame after the joint with respect to the frame before it, expressed in the frame after the joint. """ struct QuaternionFloating{T} <: JointType{T} end Base.show(io::IO, jt::QuaternionFloating) = print(io, "Quaternion floating joint") Random.rand(::Type{QuaternionFloating{T}}) where {T} = QuaternionFloating{T}() num_positions(::Type{<:QuaternionFloating}) = 7 num_velocities(::Type{<:QuaternionFloating}) = 6 has_fixed_subspaces(jt::QuaternionFloating) = true isfloating(::Type{<:QuaternionFloating}) = true @propagate_inbounds function rotation(jt::QuaternionFloating, q::AbstractVector, normalize::Bool = true) quat = QuatRotation(q[1], q[2], q[3], q[4], normalize) quat end @propagate_inbounds function set_rotation!(q::AbstractVector, jt::QuaternionFloating, rot::Rotation{3}) T = eltype(rot) quat = convert(QuatRotation{T}, rot) w, x, y, z = Rotations.params(quat) q[1] = w q[2] = x q[3] = y q[4] = z nothing end @propagate_inbounds function set_rotation!(q::AbstractVector, jt::QuaternionFloating, rot::AbstractVector) q[1] = rot[1] q[2] = rot[2] q[3] = rot[3] q[4] = rot[4] nothing end @propagate_inbounds translation(jt::QuaternionFloating, q::AbstractVector) = SVector(q[5], q[6], q[7]) @propagate_inbounds set_translation!(q::AbstractVector, jt::QuaternionFloating, trans::AbstractVector) = copyto!(q, 5, trans, 1, 3) @propagate_inbounds angular_velocity(jt::QuaternionFloating, v::AbstractVector) = SVector(v[1], v[2], v[3]) @propagate_inbounds set_angular_velocity!(v::AbstractVector, jt::QuaternionFloating, ω::AbstractVector) = copyto!(v, 1, ω, 1, 3) @propagate_inbounds linear_velocity(jt::QuaternionFloating, v::AbstractVector) = SVector(v[4], v[5], v[6]) @propagate_inbounds set_linear_velocity!(v::AbstractVector, jt::QuaternionFloating, ν::AbstractVector) = copyto!(v, 4, ν, 1, 3) @propagate_inbounds function set_configuration!(q::AbstractVector, joint::Joint{<:Any, <:QuaternionFloating}, config::Transform3D) @boundscheck check_num_positions(joint, q) @framecheck config.from frame_after(joint) @framecheck config.to frame_before(joint) set_rotation!(q, joint_type(joint), rotation(config)) set_translation!(q, joint_type(joint), translation(config)) q end @propagate_inbounds function set_velocity!(v::AbstractVector, joint::Joint{<:Any, <:QuaternionFloating}, twist::Twist) @boundscheck check_num_velocities(joint, v) @framecheck twist.base frame_before(joint) @framecheck twist.body frame_after(joint) @framecheck twist.frame frame_after(joint) set_angular_velocity!(v, joint_type(joint), angular(twist)) set_linear_velocity!(v, joint_type(joint), linear(twist)) v end @propagate_inbounds function joint_transform(jt::QuaternionFloating, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) Transform3D(frame_after, frame_before, rotation(jt, q, false), translation(jt, q)) end @inline function motion_subspace(jt::QuaternionFloating, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) S = promote_eltype(jt, q) angular = hcat(one(SMatrix{3, 3, S}), zero(SMatrix{3, 3, S})) linear = hcat(zero(SMatrix{3, 3, S}), one(SMatrix{3, 3, S})) GeometricJacobian(frame_after, frame_before, frame_after, angular, linear) end @inline function constraint_wrench_subspace(jt::QuaternionFloating, joint_transform::Transform3D) S = promote_eltype(jt, joint_transform) WrenchMatrix(joint_transform.from, zero(SMatrix{3, 0, S}), zero(SMatrix{3, 0, S})) end @inline function bias_acceleration(jt::QuaternionFloating, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(q, v) zero(SpatialAcceleration{S}, frame_after, frame_before, frame_after) end @propagate_inbounds function configuration_derivative_to_velocity!(v::AbstractVector, jt::QuaternionFloating, q::AbstractVector, q̇::AbstractVector) quat = rotation(jt, q, false) quatdot = SVector(q̇[1], q̇[2], q̇[3], q̇[4]) ω = angular_velocity_in_body(quat, quatdot) posdot = translation(jt, q̇) linear = inv(quat) * posdot set_angular_velocity!(v, jt, ω) set_linear_velocity!(v, jt, linear) nothing end @propagate_inbounds function configuration_derivative_to_velocity_adjoint!(fq, jt::QuaternionFloating, q::AbstractVector, fv) quatnorm = sqrt(q[1]^2 + q[2]^2 + q[3]^2 + q[4]^2) # TODO: make this nicer quat = QuatRotation(q[1] / quatnorm, q[2] / quatnorm, q[3] / quatnorm, q[4] / quatnorm, false) rot = (velocity_jacobian(angular_velocity_in_body, quat)' * angular_velocity(jt, fv)) ./ quatnorm trans = quat * linear_velocity(jt, fv) set_rotation!(fq, jt, rot) set_translation!(fq, jt, trans) nothing end @propagate_inbounds function velocity_to_configuration_derivative!(q̇::AbstractVector, jt::QuaternionFloating, q::AbstractVector, v::AbstractVector) quat = rotation(jt, q, false) ω = angular_velocity(jt, v) linear = linear_velocity(jt, v) quatdot = quaternion_derivative(quat, ω) transdot = quat * linear set_rotation!(q̇, jt, quatdot) set_translation!(q̇, jt, transdot) nothing end @propagate_inbounds function velocity_to_configuration_derivative_jacobian(jt::QuaternionFloating, q::AbstractVector) quat = rotation(jt, q, false) vj = velocity_jacobian(quaternion_derivative, quat) R = RotMatrix(quat) # TODO: use hvcat once it's as fast @SMatrix( [vj[1] vj[5] vj[9] 0 0 0; vj[2] vj[6] vj[10] 0 0 0; vj[3] vj[7] vj[11] 0 0 0; vj[4] vj[8] vj[12] 0 0 0; 0 0 0 R[1] R[4] R[7]; 0 0 0 R[2] R[5] R[8]; 0 0 0 R[3] R[6] R[9]]) end @propagate_inbounds function configuration_derivative_to_velocity_jacobian(jt::QuaternionFloating, q::AbstractVector) quat = rotation(jt, q, false) vj = velocity_jacobian(angular_velocity_in_body, quat) R_inv = RotMatrix(inv(quat)) # TODO: use hvcat once it's as fast @SMatrix( [vj[1] vj[4] vj[7] vj[10] 0 0 0; vj[2] vj[5] vj[8] vj[11] 0 0 0; vj[3] vj[6] vj[9] vj[12] 0 0 0; 0 0 0 0 R_inv[1] R_inv[4] R_inv[7]; 0 0 0 0 R_inv[2] R_inv[5] R_inv[8]; 0 0 0 0 R_inv[3] R_inv[6] R_inv[9]]) end @propagate_inbounds function zero_configuration!(q::AbstractVector, jt::QuaternionFloating) T = eltype(q) set_rotation!(q, jt, one(QuatRotation{T})) set_translation!(q, jt, zero(SVector{3, T})) nothing end @propagate_inbounds function rand_configuration!(q::AbstractVector, jt::QuaternionFloating) T = eltype(q) set_rotation!(q, jt, rand(QuatRotation{T})) set_translation!(q, jt, rand(SVector{3, T}) .- 0.5) nothing end @propagate_inbounds function joint_twist(jt::QuaternionFloating, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) angular = convert(SVector{3, S}, angular_velocity(jt, v)) linear = convert(SVector{3, S}, linear_velocity(jt, v)) Twist(frame_after, frame_before, frame_after, angular, linear) end @propagate_inbounds function joint_spatial_acceleration(jt::QuaternionFloating, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector, vd::AbstractVector) S = promote_eltype(jt, q, v, vd) angular = convert(SVector{3, S}, angular_velocity(jt, vd)) linear = convert(SVector{3, S}, linear_velocity(jt, vd)) SpatialAcceleration(frame_after, frame_before, frame_after, angular, linear) end @propagate_inbounds function joint_torque!(τ::AbstractVector, jt::QuaternionFloating, q::AbstractVector, joint_wrench::Wrench) set_angular_velocity!(τ, jt, angular(joint_wrench)) set_linear_velocity!(τ, jt, linear(joint_wrench)) nothing end # uses exponential coordinates centered around q0 @propagate_inbounds function local_coordinates!(ϕ::AbstractVector, ϕ̇::AbstractVector, jt::QuaternionFloating, q0::AbstractVector, q::AbstractVector, v::AbstractVector) # anonymous helper frames # FIXME frame_before = CartesianFrame3D() frame0 = CartesianFrame3D() frame_after = CartesianFrame3D() quat0 = rotation(jt, q0, false) quat = rotation(jt, q, false) p0 = translation(jt, q0) p = translation(jt, q) quat0inv = inv(quat0) δquat = quat0inv * quat δp = quat0inv * (p - p0) relative_transform = Transform3D(frame_after, frame0, δquat, δp) twist = joint_twist(jt, frame_after, frame0, q, v) # (q_0 is assumed not to change) ξ, ξ̇ = log_with_time_derivative(relative_transform, twist) copyto!(ϕ, 1, angular(ξ), 1, 3) copyto!(ϕ, 4, linear(ξ), 1, 3) copyto!(ϕ̇, 1, angular(ξ̇), 1, 3) copyto!(ϕ̇, 4, linear(ξ̇), 1, 3) nothing end @propagate_inbounds function global_coordinates!(q::AbstractVector, jt::QuaternionFloating, q0::AbstractVector, ϕ::AbstractVector) # anonymous helper frames #FIXME frame_before = CartesianFrame3D() frame0 = CartesianFrame3D() frame_after = CartesianFrame3D() t0 = joint_transform(jt, frame0, frame_before, q0) ξrot = SVector(ϕ[1], ϕ[2], ϕ[3]) ξtrans = SVector(ϕ[4], ϕ[5], ϕ[6]) ξ = Twist(frame_after, frame0, frame0, ξrot, ξtrans) relative_transform = exp(ξ) t = t0 * relative_transform set_rotation!(q, jt, rotation(t)) set_translation!(q, jt, translation(t)) nothing end @propagate_inbounds normalize_configuration!(q::AbstractVector, jt::QuaternionFloating) = set_rotation!(q, jt, rotation(jt, q, true)) @propagate_inbounds function is_configuration_normalized(jt::QuaternionFloating, q::AbstractVector, rtol, atol) isapprox(quatnorm(rotation(jt, q, false)), one(eltype(q)); rtol = rtol, atol = atol) end @propagate_inbounds function principal_value!(q::AbstractVector, jt::QuaternionFloating) quat = rotation(jt, q, false) set_rotation!(q, jt, principal_value(quat)) nothing end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
6862
""" $(TYPEDEF) The `QuaternionSpherical` joint type allows rotation in any direction. It is an implementation of a ball-and-socket joint. The 4-dimensional configuration vector ``q`` associated with a `QuaternionSpherical` joint is the unit quaternion that describes the orientation of the frame after the joint with respect to the frame before the joint. In other words, it is the quaternion that can be used to rotate vectors from the frame after the joint to the frame before the joint. The 3-dimensional velocity vector ``v`` associated with a `QuaternionSpherical` joint is the angular velocity of the frame after the joint with respect to the frame before the joint, expressed in the frame after the joint (body frame). """ struct QuaternionSpherical{T} <: JointType{T} end Base.show(io::IO, jt::QuaternionSpherical) = print(io, "Quaternion spherical joint") Random.rand(::Type{QuaternionSpherical{T}}) where {T} = QuaternionSpherical{T}() num_positions(::Type{<:QuaternionSpherical}) = 4 num_velocities(::Type{<:QuaternionSpherical}) = 3 has_fixed_subspaces(jt::QuaternionSpherical) = true isfloating(::Type{<:QuaternionSpherical}) = false @propagate_inbounds function rotation(jt::QuaternionSpherical, q::AbstractVector, normalize::Bool = true) QuatRotation(q[1], q[2], q[3], q[4], normalize) end @propagate_inbounds function set_rotation!(q::AbstractVector, jt::QuaternionSpherical, rot::Rotation{3}) T = eltype(rot) quat = convert(QuatRotation{T}, rot) w, x, y, z = Rotations.params(quat) q[1] = w q[2] = x q[3] = y q[4] = z nothing end @propagate_inbounds function set_configuration!(q::AbstractVector, joint::Joint{<:Any, <:QuaternionSpherical}, rot::Rotation{3}) @boundscheck check_num_positions(joint, q) @inbounds set_rotation!(q, joint_type(joint), rot) q end @propagate_inbounds function joint_transform(jt::QuaternionSpherical, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) quat = rotation(jt, q, false) Transform3D(frame_after, frame_before, quat) end @inline function motion_subspace(jt::QuaternionSpherical, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) S = promote_eltype(jt, q) angular = one(SMatrix{3, 3, S}) linear = zero(SMatrix{3, 3, S}) GeometricJacobian(frame_after, frame_before, frame_after, angular, linear) end @inline function constraint_wrench_subspace(jt::QuaternionSpherical, joint_transform::Transform3D) S = promote_eltype(jt, joint_transform) angular = zero(SMatrix{3, 3, S}) linear = one(SMatrix{3, 3, S}) WrenchMatrix(joint_transform.from, angular, linear) end @inline function bias_acceleration(jt::QuaternionSpherical, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) zero(SpatialAcceleration{S}, frame_after, frame_before, frame_after) end @propagate_inbounds function configuration_derivative_to_velocity!(v::AbstractVector, jt::QuaternionSpherical, q::AbstractVector, q̇::AbstractVector) quat = rotation(jt, q, false) quatdot = SVector(q̇[1], q̇[2], q̇[3], q̇[4]) v .= angular_velocity_in_body(quat, quatdot) nothing end @propagate_inbounds function configuration_derivative_to_velocity_adjoint!(fq, jt::QuaternionSpherical, q::AbstractVector, fv) quatnorm = sqrt(q[1]^2 + q[2]^2 + q[3]^2 + q[4]^2) # TODO: make this nicer quat = QuatRotation(q[1] / quatnorm, q[2] / quatnorm, q[3] / quatnorm, q[4] / quatnorm, false) fq .= (velocity_jacobian(angular_velocity_in_body, quat)' * fv) ./ quatnorm nothing end @propagate_inbounds function velocity_to_configuration_derivative!(q̇::AbstractVector, jt::QuaternionSpherical, q::AbstractVector, v::AbstractVector) quat = rotation(jt, q, false) q̇ .= quaternion_derivative(quat, v) nothing end @propagate_inbounds function velocity_to_configuration_derivative_jacobian(jt::QuaternionSpherical, q::AbstractVector) quat = rotation(jt, q, false) velocity_jacobian(quaternion_derivative, quat) end @propagate_inbounds function configuration_derivative_to_velocity_jacobian(jt::QuaternionSpherical, q::AbstractVector) quat = rotation(jt, q, false) velocity_jacobian(angular_velocity_in_body, quat) end @propagate_inbounds function zero_configuration!(q::AbstractVector, jt::QuaternionSpherical) T = eltype(q) set_rotation!(q, jt, one(QuatRotation{T})) nothing end @propagate_inbounds function rand_configuration!(q::AbstractVector, jt::QuaternionSpherical) T = eltype(q) set_rotation!(q, jt, rand(QuatRotation{T})) nothing end @propagate_inbounds function joint_twist(jt::QuaternionSpherical, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) angular = SVector{3, S}(v) linear = zero(SVector{3, S}) Twist(frame_after, frame_before, frame_after, angular, linear) end @propagate_inbounds function joint_spatial_acceleration(jt::QuaternionSpherical, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector, vd::AbstractVector) S = promote_eltype(jt, q, v, vd) angular = SVector{3, S}(vd) linear = zero(SVector{3, S}) SpatialAcceleration(frame_after, frame_before, frame_after, angular, linear) end @propagate_inbounds function joint_torque!(τ::AbstractVector, jt::QuaternionSpherical, q::AbstractVector, joint_wrench::Wrench) τ .= angular(joint_wrench) nothing end # uses exponential coordinates centered around q0 @propagate_inbounds function local_coordinates!(ϕ::AbstractVector, ϕ̇::AbstractVector, jt::QuaternionSpherical, q0::AbstractVector, q::AbstractVector, v::AbstractVector) quat = inv(rotation(jt, q0, false)) * rotation(jt, q, false) rv = RotationVec(quat) ϕstatic = SVector(rv.sx, rv.sy, rv.sz) ϕ .= ϕstatic ϕ̇ .= rotation_vector_rate(ϕstatic, v) nothing end @propagate_inbounds function global_coordinates!(q::AbstractVector, jt::QuaternionSpherical, q0::AbstractVector, ϕ::AbstractVector) quat0 = rotation(jt, q0, false) quat = quat0 * QuatRotation(RotationVec(ϕ[1], ϕ[2], ϕ[3])) set_rotation!(q, jt, quat) nothing end @propagate_inbounds normalize_configuration!(q::AbstractVector, jt::QuaternionSpherical) = set_rotation!(q, jt, rotation(jt, q, true)) @propagate_inbounds function is_configuration_normalized(jt::QuaternionSpherical, q::AbstractVector, rtol, atol) isapprox(quatnorm(rotation(jt, q, false)), one(eltype(q)); rtol = rtol, atol = atol) end @propagate_inbounds function principal_value!(q::AbstractVector, jt::QuaternionSpherical) quat = rotation(jt, q, false) set_rotation!(q, jt, principal_value(quat)) nothing end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
4138
""" $(TYPEDEF) A `Revolute` joint type allows rotation about a fixed axis. The configuration vector for the `Revolute` joint type simply consists of the angle of rotation about the specified axis. The velocity vector consists of the angular rate, and is thus the time derivative of the configuration vector. """ struct Revolute{T} <: JointType{T} axis::SVector{3, T} rotation_from_z_aligned::RotMatrix3{T} function Revolute{T}(axis::AbstractVector) where {T} a = normalize(axis) new{T}(a, rotation_between(SVector(zero(T), zero(T), one(T)), SVector{3, T}(a))) end end """ $(SIGNATURES) Construct a new `Revolute` joint type, allowing rotation about `axis` (expressed in the frame before the joint). """ Revolute(axis::AbstractVector{T}) where {T} = Revolute{T}(axis) Base.show(io::IO, jt::Revolute) = print(io, "Revolute joint with axis $(jt.axis)") function Random.rand(::Type{Revolute{T}}) where {T} axis = normalize(randn(SVector{3, T})) Revolute(axis) end RigidBodyDynamics.flip_direction(jt::Revolute) = Revolute(-jt.axis) num_positions(::Type{<:Revolute}) = 1 num_velocities(::Type{<:Revolute}) = 1 has_fixed_subspaces(jt::Revolute) = true isfloating(::Type{<:Revolute}) = false @propagate_inbounds function set_configuration!(q::AbstractVector, joint::Joint{<:Any, <:Revolute}, θ::Number) @boundscheck check_num_positions(joint, q) @inbounds q[1] = θ q end @propagate_inbounds function set_velocity!(v::AbstractVector, joint::Joint{<:Any, <:Revolute}, θ̇::Number) check_num_velocities(joint, v) @inbounds v[1] = θ̇ v end @propagate_inbounds function rand_configuration!(q::AbstractVector, ::Revolute) q[1] = randn() nothing end @propagate_inbounds function joint_transform(jt::Revolute, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) aa = AngleAxis(q[1], jt.axis[1], jt.axis[2], jt.axis[3], false) Transform3D(frame_after, frame_before, convert(RotMatrix3{eltype(aa)}, aa)) end @propagate_inbounds function joint_twist(jt::Revolute, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) angular = jt.axis * v[1] Twist(frame_after, frame_before, frame_after, angular, zero(angular)) end @inline function bias_acceleration(jt::Revolute, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) zero(SpatialAcceleration{S}, frame_after, frame_before, frame_after) end @propagate_inbounds function joint_spatial_acceleration(jt::Revolute, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector, vd::AbstractVector) S = promote_eltype(jt, q, v, vd) angular = convert(SVector{3, S}, jt.axis * vd[1]) SpatialAcceleration(frame_after, frame_before, frame_after, angular, zero(angular)) end @inline function motion_subspace(jt::Revolute, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) S = promote_eltype(jt, q) angular = SMatrix{3, 1, S}(jt.axis) linear = zero(SMatrix{3, 1, S}) GeometricJacobian(frame_after, frame_before, frame_after, angular, linear) end @inline function constraint_wrench_subspace(jt::Revolute, joint_transform::Transform3D) S = promote_eltype(jt, joint_transform) R = convert(RotMatrix3{S}, jt.rotation_from_z_aligned) Rcols12 = R[:, SVector(1, 2)] angular = hcat(Rcols12, zero(SMatrix{3, 3, S})) linear = hcat(zero(SMatrix{3, 2, S}), R) WrenchMatrix(joint_transform.from, angular, linear) end @propagate_inbounds function joint_torque!(τ::AbstractVector, jt::Revolute, q::AbstractVector, joint_wrench::Wrench) τ[1] = dot(angular(joint_wrench), jt.axis) nothing end @inline function velocity_to_configuration_derivative_jacobian(jt::Revolute, q::AbstractVector) T = promote_eltype(jt, q) @SMatrix([one(T)]) end @inline function configuration_derivative_to_velocity_jacobian(jt::Revolute, q::AbstractVector) T = promote_eltype(jt, q) @SMatrix([one(T)]) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
7263
""" $(TYPEDEF) A `SinCosRevolute` joint type allows rotation about a fixed axis. In contrast to the [`Revolute`](@ref) joint type, the configuration vector for the `SinCosRevolute` joint type consists of the sine and cosine of the angle of rotation about the specified axis (in that order). The velocity vector for the `SinCosRevolute` joint type is the same as for the `Revolute` joint type, i.e., the time derivative of the angle about the axis. """ struct SinCosRevolute{T} <: JointType{T} axis::SVector{3, T} rotation_from_z_aligned::RotMatrix3{T} function SinCosRevolute{T}(axis::AbstractVector) where {T} a = normalize(axis) new{T}(a, rotation_between(SVector(zero(T), zero(T), one(T)), SVector{3, T}(a))) end end """ $(SIGNATURES) Construct a new `SinCosRevolute` joint type, allowing rotation about `axis` (expressed in the frame before the joint). """ SinCosRevolute(axis::AbstractVector{T}) where {T} = SinCosRevolute{T}(axis) Base.show(io::IO, jt::SinCosRevolute) = print(io, "SinCosRevolute joint with axis $(jt.axis)") function Random.rand(::Type{SinCosRevolute{T}}) where {T} axis = normalize(randn(SVector{3, T})) SinCosRevolute(axis) end RigidBodyDynamics.flip_direction(jt::SinCosRevolute) = SinCosRevolute(-jt.axis) num_positions(::Type{<:SinCosRevolute}) = 2 num_velocities(::Type{<:SinCosRevolute}) = 1 has_fixed_subspaces(jt::SinCosRevolute) = true isfloating(::Type{<:SinCosRevolute}) = false @propagate_inbounds function set_configuration!(q::AbstractVector, joint::Joint{<:Any, <:SinCosRevolute}, θ::Number) @boundscheck check_num_positions(joint, q) s, c = sincos(θ) @inbounds q[1] = s @inbounds q[2] = c q end @propagate_inbounds function set_velocity!(v::AbstractVector, joint::Joint{<:Any, <:SinCosRevolute}, θ̇::Number) @boundscheck check_num_velocities(joint, v) @inbounds v[1] = θ̇ v end @propagate_inbounds function rand_configuration!(q::AbstractVector, jt::SinCosRevolute) q .= normalize(@SVector(randn(2))) nothing end @propagate_inbounds function zero_configuration!(q::AbstractVector, jt::SinCosRevolute) T = eltype(q) q[1] = zero(T) q[2] = one(T) nothing end @propagate_inbounds function joint_transform(jt::SinCosRevolute, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) # from https://github.com/FugroRoames/Rotations.jl/blob/8d77152a76950665302b5a730b420973bb397f41/src/angleaxis_types.jl#L50 T = eltype(q) axis = jt.axis s, c = q[1], q[2] c1 = one(T) - c c1x2 = c1 * axis[1]^2 c1y2 = c1 * axis[2]^2 c1z2 = c1 * axis[3]^2 c1xy = c1 * axis[1] * axis[2] c1xz = c1 * axis[1] * axis[3] c1yz = c1 * axis[2] * axis[3] sx = s * axis[1] sy = s * axis[2] sz = s * axis[3] # Note that the RotMatrix constructor argument order makes this look transposed: rot = RotMatrix( one(T) - c1y2 - c1z2, c1xy + sz, c1xz - sy, c1xy - sz, one(T) - c1x2 - c1z2, c1yz + sx, c1xz + sy, c1yz - sx, one(T) - c1x2 - c1y2) Transform3D(frame_after, frame_before, rot) end @propagate_inbounds function joint_twist(jt::SinCosRevolute, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) angular = jt.axis * v[1] Twist(frame_after, frame_before, frame_after, angular, zero(angular)) end @inline function bias_acceleration(jt::SinCosRevolute, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) zero(SpatialAcceleration{S}, frame_after, frame_before, frame_after) end @propagate_inbounds function joint_spatial_acceleration(jt::SinCosRevolute, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector, vd::AbstractVector) S = promote_eltype(jt, q, v, vd) angular = convert(SVector{3, S}, jt.axis * vd[1]) SpatialAcceleration(frame_after, frame_before, frame_after, angular, zero(angular)) end @inline function motion_subspace(jt::SinCosRevolute, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) S = promote_eltype(jt, q) angular = SMatrix{3, 1, S}(jt.axis) linear = zero(SMatrix{3, 1, S}) GeometricJacobian(frame_after, frame_before, frame_after, angular, linear) end @inline function constraint_wrench_subspace(jt::SinCosRevolute, joint_transform::Transform3D) S = promote_eltype(jt, joint_transform) R = convert(RotMatrix3{S}, jt.rotation_from_z_aligned) Rcols12 = R[:, SVector(1, 2)] angular = hcat(Rcols12, zero(SMatrix{3, 3, S})) linear = hcat(zero(SMatrix{3, 2, S}), R) WrenchMatrix(joint_transform.from, angular, linear) end @propagate_inbounds function joint_torque!(τ::AbstractVector, jt::SinCosRevolute, q::AbstractVector, joint_wrench::Wrench) τ[1] = dot(angular(joint_wrench), jt.axis) nothing end @propagate_inbounds function configuration_derivative_to_velocity!(v::AbstractVector, jt::SinCosRevolute, q::AbstractVector, q̇::AbstractVector) # q̇ = [c; -s] * v # [c -s] * [c; -s] = c^2 + s^2 = 1 # v = [c -s] * q̇ s, c = q[1], q[2] v[1] = c * q̇[1] - s * q̇[2] nothing end @propagate_inbounds function configuration_derivative_to_velocity_jacobian(jt::SinCosRevolute, q::AbstractVector) s, c = q[1], q[2] @SMatrix [c -s] end @propagate_inbounds function configuration_derivative_to_velocity_adjoint!(fq, jt::SinCosRevolute, q::AbstractVector, fv) qnorm = sqrt(q[1]^2 + q[2]^2) qnormalized = @SVector([q[1], q[2]]) / qnorm fq .= (configuration_derivative_to_velocity_jacobian(jt, qnormalized)' * fv) ./ qnorm nothing end @propagate_inbounds function velocity_to_configuration_derivative!(q̇::AbstractVector, jt::SinCosRevolute, q::AbstractVector, v::AbstractVector) s, c = q[1], q[2] q̇[1] = c * v[1] q̇[2] = -s * v[1] nothing end @propagate_inbounds function velocity_to_configuration_derivative_jacobian(jt::SinCosRevolute, q::AbstractVector) s, c = q[1], q[2] @SMatrix [c; -s] end # uses exponential coordinates centered around q0 (i.e, the relative joint angle) @propagate_inbounds function local_coordinates!(ϕ::AbstractVector, ϕd::AbstractVector, jt::SinCosRevolute, q0::AbstractVector, q::AbstractVector, v::AbstractVector) # RΔ = R₀ᵀ * R s0, c0 = q0[1], q0[2] s, c = q[1], q[2] sΔ = c0 * s - s0 * c cΔ = c0 * c + s0 * s θ = atan(sΔ, cΔ) ϕ[1] = θ ϕd[1] = v[1] nothing end @propagate_inbounds function global_coordinates!(q::AbstractVector, jt::SinCosRevolute, q0::AbstractVector, ϕ::AbstractVector) # R = R₀ * RΔ: s0, c0 = q0[1], q0[2] θ = ϕ[1] sΔ, cΔ = sincos(θ) s = s0 * cΔ + c0 * sΔ c = c0 * cΔ - s0 * sΔ q[1] = s q[2] = c nothing end @propagate_inbounds function normalize_configuration!(q::AbstractVector, jt::SinCosRevolute) q ./= sqrt(q[1]^2 + q[2]^2) q end @propagate_inbounds function is_configuration_normalized(jt::SinCosRevolute, q::AbstractVector, rtol, atol) # TODO: base off of norm squared qnorm = sqrt(q[1]^2 + q[2]^2) isapprox(qnorm, one(eltype(q)); rtol = rtol, atol = atol) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
8555
""" $(TYPEDEF) A floating joint type that uses a modified Rodrigues parameter (`Rotations.MRP`, previously known as `Rotations.SPQuat`) representation for orientation. Floating joints are 6-degree-of-freedom joints that are in a sense degenerate, as they impose no constraints on the relative motion between two bodies. The 6-dimensional configuration vector of a `SPQuatFloating` joint type consists of a SPQuat representing the orientation that rotates vectors from the frame 'directly after' the joint to the frame 'directly before' it, and a 3D position vector representing the origin of the frame after the joint in the frame before the joint. The 6-dimensional velocity vector of a `SPQuatFloating` joint is the twist of the frame after the joint with respect to the frame before it, expressed in the frame after the joint. """ struct SPQuatFloating{T} <: JointType{T} end Base.show(io::IO, jt::SPQuatFloating) = print(io, "SPQuat floating joint") Random.rand(::Type{SPQuatFloating{T}}) where {T} = SPQuatFloating{T}() num_positions(::Type{<:SPQuatFloating}) = 6 num_velocities(::Type{<:SPQuatFloating}) = 6 has_fixed_subspaces(jt::SPQuatFloating) = true isfloating(::Type{<:SPQuatFloating}) = true @propagate_inbounds function rotation(jt::SPQuatFloating, q::AbstractVector) ModifiedRodriguesParam(q[1], q[2], q[3]) end @propagate_inbounds function set_rotation!(q::AbstractVector, jt::SPQuatFloating, rot::Rotation{3}) T = eltype(rot) spq = convert(ModifiedRodriguesParam{T}, rot) q[1] = spq.x q[2] = spq.y q[3] = spq.z nothing end @propagate_inbounds function set_rotation!(q::AbstractVector, jt::SPQuatFloating, rot::AbstractVector) q[1] = rot[1] q[2] = rot[2] q[3] = rot[3] nothing end @propagate_inbounds translation(jt::SPQuatFloating, q::AbstractVector) = SVector(q[4], q[5], q[6]) @propagate_inbounds set_translation!(q::AbstractVector, jt::SPQuatFloating, trans::AbstractVector) = copyto!(q, 4, trans, 1, 3) @propagate_inbounds angular_velocity(jt::SPQuatFloating, v::AbstractVector) = SVector(v[1], v[2], v[3]) @propagate_inbounds set_angular_velocity!(v::AbstractVector, jt::SPQuatFloating, ω::AbstractVector) = copyto!(v, 1, ω, 1, 3) @propagate_inbounds linear_velocity(jt::SPQuatFloating, v::AbstractVector) = SVector(v[4], v[5], v[6]) @propagate_inbounds set_linear_velocity!(v::AbstractVector, jt::SPQuatFloating, ν::AbstractVector) = copyto!(v, 4, ν, 1, 3) @inline function set_configuration!(q::AbstractVector, joint::Joint{<:Any, <:SPQuatFloating}, config::Transform3D) @boundscheck check_num_positions(joint, q) @framecheck config.from frame_after(joint) @framecheck config.to frame_before(joint) @inbounds set_rotation!(q, joint_type(joint), rotation(config)) @inbounds set_translation!(q, joint_type(joint), translation(config)) q end @propagate_inbounds function set_velocity!(v::AbstractVector, joint::Joint{<:Any, <:SPQuatFloating}, twist::Twist) @boundscheck check_num_velocities(joint, v) @framecheck twist.base frame_before(joint) @framecheck twist.body frame_after(joint) @framecheck twist.frame frame_after(joint) @inbounds set_angular_velocity!(v, joint_type(joint), angular(twist)) @inbounds set_linear_velocity!(v, joint_type(joint), linear(twist)) v end @propagate_inbounds function joint_transform(jt::SPQuatFloating, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) Transform3D(frame_after, frame_before, rotation(jt, q), translation(jt, q)) end @inline function motion_subspace(jt::SPQuatFloating, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector) S = promote_eltype(jt, q) angular = hcat(one(SMatrix{3, 3, S}), zero(SMatrix{3, 3, S})) linear = hcat(zero(SMatrix{3, 3, S}), one(SMatrix{3, 3, S})) GeometricJacobian(frame_after, frame_before, frame_after, angular, linear) end @inline function constraint_wrench_subspace(jt::SPQuatFloating, joint_transform::Transform3D) S = promote_eltype(jt, joint_transform) WrenchMatrix(joint_transform.from, zero(SMatrix{3, 0, S}), zero(SMatrix{3, 0, S})) end @propagate_inbounds function bias_acceleration(jt::SPQuatFloating, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) zero(SpatialAcceleration{S}, frame_after, frame_before, frame_after) end @propagate_inbounds function configuration_derivative_to_velocity!(v::AbstractVector, jt::SPQuatFloating, q::AbstractVector, q̇::AbstractVector) spq = rotation(jt, q) spqdot = SVector(q̇[1], q̇[2], q̇[3]) ω = angular_velocity_in_body(spq, spqdot) posdot = translation(jt, q̇) linear = inv(spq) * posdot set_angular_velocity!(v, jt, ω) set_linear_velocity!(v, jt, linear) nothing end @propagate_inbounds function configuration_derivative_to_velocity_adjoint!(fq, jt::SPQuatFloating, q::AbstractVector, fv) spq = ModifiedRodriguesParam(q[1], q[2], q[3]) rot = velocity_jacobian(angular_velocity_in_body, spq)' * angular_velocity(jt, fv) trans = spq * linear_velocity(jt, fv) set_rotation!(fq, jt, rot) set_translation!(fq, jt, trans) nothing end @propagate_inbounds function velocity_to_configuration_derivative!(q̇::AbstractVector, jt::SPQuatFloating, q::AbstractVector, v::AbstractVector) spq = rotation(jt, q) ω = angular_velocity(jt, v) linear = linear_velocity(jt, v) spqdot = spquat_derivative(spq, ω) transdot = spq * linear set_rotation!(q̇, jt, spqdot) set_translation!(q̇, jt, transdot) nothing end @propagate_inbounds function velocity_to_configuration_derivative_jacobian(jt::SPQuatFloating, q::AbstractVector) spq = rotation(jt, q) vj = velocity_jacobian(spquat_derivative, spq) R = RotMatrix(spq) # TODO: use hvcat once it's as fast @SMatrix( [vj[1] vj[4] vj[7] 0 0 0; vj[2] vj[5] vj[8] 0 0 0; vj[3] vj[6] vj[9] 0 0 0; 0 0 0 R[1] R[4] R[7]; 0 0 0 R[2] R[5] R[8]; 0 0 0 R[3] R[6] R[9]]) end @propagate_inbounds function configuration_derivative_to_velocity_jacobian(jt::SPQuatFloating, q::AbstractVector) spq = rotation(jt, q) vj = velocity_jacobian(angular_velocity_in_body, spq) R_inv = RotMatrix(inv(spq)) # TODO: use hvcat once it's as fast @SMatrix( [vj[1] vj[4] vj[7] 0 0 0; vj[2] vj[5] vj[8] 0 0 0; vj[3] vj[6] vj[9] 0 0 0; 0 0 0 R_inv[1] R_inv[4] R_inv[7]; 0 0 0 R_inv[2] R_inv[5] R_inv[8]; 0 0 0 R_inv[3] R_inv[6] R_inv[9]]) end @propagate_inbounds function zero_configuration!(q::AbstractVector, jt::SPQuatFloating) T = eltype(q) set_rotation!(q, jt, one(ModifiedRodriguesParam{T})) set_translation!(q, jt, zero(SVector{3, T})) nothing end @propagate_inbounds function rand_configuration!(q::AbstractVector, jt::SPQuatFloating) T = eltype(q) set_rotation!(q, jt, rand(ModifiedRodriguesParam{T})) set_translation!(q, jt, rand(SVector{3, T}) .- 0.5) nothing end @propagate_inbounds function joint_twist(jt::SPQuatFloating, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector) S = promote_eltype(jt, q, v) angular = convert(SVector{3, S}, angular_velocity(jt, v)) linear = convert(SVector{3, S}, linear_velocity(jt, v)) Twist(frame_after, frame_before, frame_after, angular, linear) end @propagate_inbounds function joint_spatial_acceleration(jt::SPQuatFloating, frame_after::CartesianFrame3D, frame_before::CartesianFrame3D, q::AbstractVector, v::AbstractVector, vd::AbstractVector) S = promote_eltype(jt, q, v, vd) angular = convert(SVector{3, S}, angular_velocity(jt, vd)) linear = convert(SVector{3, S}, linear_velocity(jt, vd)) SpatialAcceleration(frame_after, frame_before, frame_after, angular, linear) end @propagate_inbounds function joint_torque!(τ::AbstractVector, jt::SPQuatFloating, q::AbstractVector, joint_wrench::Wrench) set_angular_velocity!(τ, jt, angular(joint_wrench)) set_linear_velocity!(τ, jt, linear(joint_wrench)) nothing end @propagate_inbounds function principal_value!(q::AbstractVector, jt::SPQuatFloating) spq = rotation(jt, q) set_rotation!(q, jt, principal_value(spq)) nothing end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
1155
module Spatial # types export CartesianFrame3D, Transform3D, FreeVector3D, Point3D, GeometricJacobian, PointJacobian, Twist, SpatialAcceleration, MomentumMatrix, # TODO: consider combining with WrenchMatrix WrenchMatrix, # TODO: consider combining with MomentumMatrix Momentum, Wrench, SpatialInertia # functions export transform, rotation, translation, angular, linear, point_velocity, point_acceleration, change_base, log_with_time_derivative, center_of_mass, newton_euler, torque, torque!, kinetic_energy, rotation_vector_rate, quaternion_derivative, spquat_derivative, angular_velocity_in_body, velocity_jacobian, linearized_rodrigues_vec # macros export @framecheck using LinearAlgebra using Random using StaticArrays using Rotations using DocStringExtensions using Base: promote_eltype include("frame.jl") include("util.jl") include("transform3d.jl") include("threevectors.jl") include("spatialmotion.jl") include("spatialforce.jl") include("motion_force_interaction.jl") include("common.jl") end # module
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
2092
for SpatialVector in (:Twist, :SpatialAcceleration, :Momentum, :Wrench) @eval begin # Basics Base.eltype(::Type{$SpatialVector{T}}) where {T} = T angular(v::$SpatialVector) = v.angular linear(v::$SpatialVector) = v.linear # Construct/convert given another spatial vector $SpatialVector{T}(v::$SpatialVector{T}) where {T} = v Base.convert(::Type{V}, v::$SpatialVector) where {V<:$SpatialVector} = V(v) # Construct/convert to SVector StaticArrays.SVector{6, T}(v::$SpatialVector) where {T} = convert(SVector{6, T}, [angular(v); linear(v)]) StaticArrays.SVector{6}(v::$SpatialVector{X}) where {X} = SVector{6, X}(v) StaticArrays.SVector(v::$SpatialVector) = SVector{6}(v) StaticArrays.SArray(v::$SpatialVector) = SVector(v) Base.convert(::Type{SA}, v::$SpatialVector) where {SA <: SArray} = SA(v) function Base.Array(v::$SpatialVector) Base.depwarn("Array(v) has been deprecated. Please use SVector(v) instead.", :Array) SVector(v) end end end for SpatialMatrix in (:GeometricJacobian, :MomentumMatrix, :WrenchMatrix) @eval begin # Basics Base.eltype(::Type{$SpatialMatrix{A}}) where {T, A<:AbstractMatrix{T}} = T Base.size(m::$SpatialMatrix) = (6, size(angular(m), 2)) Base.size(m::$SpatialMatrix, d) = size(m)[d] Base.transpose(m::$SpatialMatrix) = Transpose(m) angular(m::$SpatialMatrix) = m.angular linear(m::$SpatialMatrix) = m.linear # Construct/convert given another spatial matrix $SpatialMatrix(m::$SpatialMatrix{A}) where {A} = SpatialMatrix{A}(m) Base.convert(::Type{$SpatialMatrix{A}}, m::$SpatialMatrix) where {A} = $SpatialMatrix{A}(m) Base.convert(::Type{$SpatialMatrix{A}}, m::$SpatialMatrix{A}) where {A} = m # Construct/convert to Matrix (::Type{A})(m::$SpatialMatrix) where {A<:Array} = convert(A, [angular(m); linear(m)]) Base.convert(::Type{A}, m::$SpatialMatrix) where {A<:Array} = A(m) end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
2884
# NOTE: The `next_frame_id' and `frame_names' globals below are a hack, but they # enable a significant reduction in allocations. # Storing the names of all CartesianFrame3D objects in this frame_names vector instead # of in the CartesianFrame3D and having CartesianFrame3D only contain an integer ID # makes CartesianFrame3D an isbits (pointer free) type. # This in turn makes it so that a lot of the geometry/dynamics types become isbits # types, making them stack allocated and allowing all sorts of # optimizations. const next_frame_id = Ref(0) const frame_names = Dict{Int64, String}() """ $(TYPEDEF) A `CartesianFrame3D` identifies a three-dimensional Cartesian coordinate system. `CartesianFrame3D`s are typically used to annotate the frame in which certain quantities are expressed. """ struct CartesianFrame3D id::Int64 @doc """ $(SIGNATURES) Create a `CartesianFrame3D` with the given name. """ -> function CartesianFrame3D(name::String) ret = new(next_frame_id.x) next_frame_id.x = Base.Checked.checked_add(next_frame_id.x, 1) frame_names[ret.id] = name ret end @doc """ $(SIGNATURES) Create an anonymous `CartesianFrame3D`. """ -> function CartesianFrame3D() ret = new(next_frame_id.x) next_frame_id.x = Base.Checked.checked_add(next_frame_id.x, 1) ret end end Base.print(io::IO, frame::CartesianFrame3D) = print(io, get(frame_names, frame.id, "anonymous")) name_and_id(frame::CartesianFrame3D) = "\"$frame\" (id = $(frame.id))" Base.show(io::IO, frame::CartesianFrame3D) = print(io, "CartesianFrame3D: $(name_and_id(frame))") Base.in(x::CartesianFrame3D, y::CartesianFrame3D) = x == y """ $(SIGNATURES) Check that `CartesianFrame3D` `f1` is one of `f2s`. Note that if `f2s` is a `CartesianFrame3D`, then `f1` and `f2s` are simply checked for equality. Throws an `ArgumentError` if `f1` is not among `f2s` when bounds checks are enabled. `@framecheck` is a no-op when bounds checks are disabled. """ macro framecheck(f1, f2s) quote @boundscheck begin $(esc(f1)) ∉ $(esc(f2s)) && framecheck_fail($(QuoteNode(f1)), $(QuoteNode(f2s)), $(esc(f1)), $(esc(f2s))) end end end framecheck_string(expr, frame::CartesianFrame3D) = "$expr: $(name_and_id(frame))" @noinline function framecheck_fail(expr1, expr2, f1::CartesianFrame3D, f2::CartesianFrame3D) throw(ArgumentError("$(framecheck_string(expr1, f1)) ≠ $(framecheck_string(expr2, f2))")) end @noinline function framecheck_fail(expr1, expr2, f1::CartesianFrame3D, f2s) buf = IOBuffer() print(buf, '(') first = true for f2 in f2s first || print(buf, ", ") first = false print(buf, name_and_id(f2)) end print(buf, ')') throw(ArgumentError("$(framecheck_string(expr1, f1)) ∉ $(expr2): $(String(take!(buf)))")) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
13162
""" $(TYPEDEF) A spatial inertia, or inertia matrix, represents the mass distribution of a rigid body. A spatial inertia expressed in frame ``i`` is defined as: ```math I^i = \\int_{B}\\rho\\left(x\\right)\\left[\\begin{array}{cc} \\hat{p}^{T}\\left(x\\right)\\hat{p}\\left(x\\right) & \\hat{p}\\left(x\\right)\\\\ \\hat{p}^{T}\\left(x\\right) & I \\end{array}\\right]dx=\\left[\\begin{array}{cc} J & \\hat{c}\\\\ \\hat{c}^{T} & mI \\end{array}\\right] ``` where ``\\rho(x)`` is the density of point ``x``, and ``p(x)`` are the coordinates of point ``x`` expressed in frame ``i``. ``J`` is the mass moment of inertia, ``m`` is the total mass, and ``c`` is the 'cross part', center of mass position scaled by ``m``. !!! warning The `moment` field of a `SpatialInertia` is the moment of inertia **about the origin of its `frame`**, not about the center of mass. """ struct SpatialInertia{T} frame::CartesianFrame3D moment::SMatrix{3, 3, T, 9} cross_part::SVector{3, T} # mass times center of mass mass::T @inline function SpatialInertia{T}(frame::CartesianFrame3D, moment::AbstractMatrix, cross_part::AbstractVector, mass) where T new{T}(frame, moment, cross_part, mass) end end """ $(SIGNATURES) Construct a `SpatialInertia` by specifying: * `frame`: the frame in which the spatial inertia is expressed. * `moment`: the moment of inertia expressed in `frame` (i.e., in `frame`'s axes and about the origin of `frame`). * `cross_part`: the center of mass expressed in `frame`, multiplied by the mass. * `mass`: the total mass. For more convenient construction of `SpatialInertia`s, consider using the keyword argument constructor instead. """ @inline function SpatialInertia(frame::CartesianFrame3D, moment::AbstractMatrix, cross_part::AbstractVector, mass) T = promote_eltype(moment, cross_part, mass) SpatialInertia{T}(frame, moment, cross_part, mass) end """ $(SIGNATURES) Construct a `SpatialInertia` by specifying: * `frame`: the frame in which the spatial inertia is expressed. * one of: * `moment`: the moment of inertia expressed in `frame` (i.e., about the origin of `frame` and in `frame`'s axes). * `moment_about_com`: the moment of inertia about the center of mass, in `frame`'s axes. * `com`: the center of mass expressed in `frame`. * `mass`: the total mass. The `com` and `mass` keyword arguments are required, as well as exactly one of `moment` and `moment_about_com` """ @inline function SpatialInertia(frame::CartesianFrame3D; moment::Union{AbstractMatrix, Nothing}=nothing, moment_about_com::Union{AbstractMatrix, Nothing}=nothing, com::AbstractVector, mass) if !((moment isa AbstractMatrix) ⊻ (moment_about_com isa AbstractMatrix)) throw(ArgumentError("Exactly one of `moment` or `moment_about_com` is required.")) end _com = SVector{3}(com) if moment !== nothing _moment = moment else _moment = SMatrix{3, 3}(moment_about_com) _moment -= mass * hat_squared(_com) # parallel axis theorem end SpatialInertia(frame, _moment, mass * _com, mass) end # SpatialInertia-specific functions Base.eltype(::Type{SpatialInertia{T}}) where {T} = T # Construct/convert given another SpatialInertia SpatialInertia{T}(inertia::SpatialInertia{T}) where {T} = inertia @inline function SpatialInertia{T}(inertia::SpatialInertia) where {T} SpatialInertia{T}(inertia.frame, SMatrix{3, 3, T}(inertia.moment), SVector{3, T}(inertia.cross_part), T(inertia.mass)) end @inline Base.convert(::Type{S}, inertia::SpatialInertia) where {S<:SpatialInertia} = S(inertia) # Construct/convert to SMatrix function StaticArrays.SMatrix{6, 6, T, 36}(inertia::SpatialInertia) where {T} J = SMatrix{3, 3, T}(inertia.moment) C = hat(SVector{3, T}(inertia.cross_part)) m = T(inertia.mass) [[J C]; [C' SMatrix{3, 3}(m * I)]] end StaticArrays.SMatrix{6, 6, T}(inertia::SpatialInertia) where {T} = SMatrix{6, 6, T, 36}(inertia) StaticArrays.SMatrix{6, 6}(inertia::SpatialInertia{T}) where {T} = SMatrix{6, 6, T}(inertia) StaticArrays.SMatrix(inertia::SpatialInertia) = SMatrix{6, 6}(inertia) StaticArrays.SArray(inertia::SpatialInertia) = SMatrix(inertia) Base.convert(::Type{A}, inertia::SpatialInertia) where {A<:SArray} = A(inertia) function Base.convert(::Type{Matrix}, inertia::SpatialInertia) Base.depwarn("This convert method is deprecated. Please use `Matrix(SMatrix(inertia))` instead or reconsider whether conversion to Matrix is necessary.", :convert) Matrix(SMatrix(inertia)) end function Base.Array(inertia::SpatialInertia) Base.depwarn("This Array constructor is deprecated. Please use `Matrix(SMatrix(inertia))` instead or reconsider whether conversion to Matrix is necessary.", :Array) Matrix(SMatrix(inertia)) end """ $(SIGNATURES) Return the center of mass of the `SpatialInertia` as a [`Point3D`](@ref). """ center_of_mass(inertia::SpatialInertia) = Point3D(inertia.frame, inertia.cross_part / inertia.mass) function Base.show(io::IO, inertia::SpatialInertia) println(io, "SpatialInertia expressed in $(name_and_id(inertia.frame)):") println(io, "mass: $(inertia.mass)") println(io, "center of mass: $(center_of_mass(inertia))") print(io, "moment of inertia (about origin of $(name_and_id(inertia.frame)):\n$(inertia.moment)") end Base.zero(::Type{SpatialInertia{T}}, frame::CartesianFrame3D) where {T} = SpatialInertia(frame, zero(SMatrix{3, 3, T}), zero(SVector{3, T}), zero(T)) Base.zero(inertia::SpatialInertia) = zero(typeof(inertia), inertia.frame) function Base.isapprox(x::SpatialInertia, y::SpatialInertia; atol = 1e-12) x.frame == y.frame && isapprox(x.moment, y.moment; atol = atol) && isapprox(x.cross_part, y.cross_part; atol = atol) && isapprox(x.mass, y.mass; atol = atol) end @inline function Base.:+(inertia1::SpatialInertia, inertia2::SpatialInertia) @framecheck(inertia1.frame, inertia2.frame) SpatialInertia(inertia1.frame, inertia1.moment + inertia2.moment, inertia1.cross_part + inertia2.cross_part, inertia1.mass + inertia2.mass) end """ $(SIGNATURES) Transform the `SpatialInertia` to a different frame. """ @inline function transform(inertia::SpatialInertia, t::Transform3D) @framecheck(t.from, inertia.frame) J = inertia.moment mc = inertia.cross_part m = inertia.mass R = rotation(t) p = translation(t) Rmc = R * mc mp = m * p mcnew = Rmc + mp X = Rmc * transpose(p) Y = X + transpose(X) + mp * transpose(p) Jnew = R * J * transpose(R) - Y + tr(Y) * I SpatialInertia(t.to, Jnew, mcnew, m) end function Random.rand(::Type{<:SpatialInertia{T}}, frame::CartesianFrame3D) where {T} # Try to generate a random but physical moment of inertia by constructing it from its eigendecomposition. # Create random principal moments of inertia (about the center of mass). # Scale the inertias to make the length scale of the equivalent inertial ellipsoid roughly ~1 unit ixx = rand(T) / 10. iyy = rand(T) / 10. # Ensure that the principal moments of inertia obey the triangle inequalities: # http://www.mathworks.com/help/physmod/sm/mech/vis/about-body-color-and-geometry.html lb = abs(ixx - iyy) ub = ixx + iyy izz = rand(T) * (ub - lb) + lb # Randomly rotate the principal axes. R = rand(RotMatrix3{T}) moment_about_com = R * Diagonal(SVector(ixx, iyy, izz)) * R' SpatialInertia(frame, moment_about_com=moment_about_com, com=rand(SVector{3, T}) .- T(0.5), mass=rand(T)) end """ $(SIGNATURES) Compute the mechanical power associated with a pairing of a wrench and a twist. """ LinearAlgebra.dot(w::Wrench, t::Twist) = begin @framecheck(w.frame, t.frame); dot(angular(w), angular(t)) + dot(linear(w), linear(t)) end LinearAlgebra.dot(t::Twist, w::Wrench) = dot(w, t) for (ForceSpaceMatrix, ForceSpaceElement) in (:MomentumMatrix => :Momentum, :MomentumMatrix => :Wrench, :WrenchMatrix => :Wrench) # MomentumMatrix * velocity vector --> Momentum # MomentumMatrix * acceleration vector --> Wrench # WrenchMatrix * dimensionless multipliers --> Wrench @eval function $ForceSpaceElement(mat::$ForceSpaceMatrix, x::AbstractVector) $ForceSpaceElement(mat.frame, SVector{3}(angular(mat) * x), SVector{3}(linear(mat) * x)) end end @inline function Base.:*(inertia::SpatialInertia, twist::Twist) @framecheck(inertia.frame, twist.frame) ang, lin = mul_inertia(inertia.moment, inertia.cross_part, inertia.mass, angular(twist), linear(twist)) Momentum(inertia.frame, ang, lin) end @inline function Base.:*(inertia::SpatialInertia, jac::GeometricJacobian) @framecheck(inertia.frame, jac.frame) Jω = angular(jac) Jv = linear(jac) J = inertia.moment m = inertia.mass c = inertia.cross_part ang = J * Jω + colwise(×, c, Jv) lin = m * Jv - colwise(×, c, Jω) MomentumMatrix(inertia.frame, ang, lin) end """ $(SIGNATURES) Apply the Newton-Euler equations to find the external wrench required to make a body with spatial inertia ``I``, which has twist ``T`` with respect to an inertial frame, achieve spatial acceleration ``\\dot{T}``. This wrench is also equal to the rate of change of momentum of the body. """ @inline function newton_euler(inertia::SpatialInertia, spatial_accel::SpatialAcceleration, twist::Twist) I = inertia T = twist Ṫ = spatial_accel body = Ṫ.body base = Ṫ.base # TODO: should assert that this is an inertial frame somehow frame = Ṫ.frame @framecheck(I.frame, frame) @framecheck(T.body, body) @framecheck(T.base, base) @framecheck(T.frame, frame) ang, lin = mul_inertia(I.moment, I.cross_part, I.mass, angular(Ṫ), linear(Ṫ)) angular_momentum, linear_momentum = mul_inertia(I.moment, I.cross_part, I.mass, angular(T), linear(T)) ang += angular(T) × angular_momentum + linear(T) × linear_momentum lin += angular(T) × linear_momentum Wrench(frame, ang, lin) end @inline torque!(τ::AbstractVector, jac::GeometricJacobian, wrench::Wrench) = mul!(τ, transpose(jac), wrench) @inline function torque(jac::GeometricJacobian, wrench::Wrench) T = promote_eltype(jac, wrench) τ = Vector{T}(undef, size(jac, 2)) torque!(τ, jac, wrench) τ end for (MatrixType, VectorType) in (:WrenchMatrix => :(Union{Twist, SpatialAcceleration}), :GeometricJacobian => :(Union{Momentum, Wrench})) @eval begin @inline function LinearAlgebra.mul!( dest::AbstractVector{T}, transposed_mat::LinearAlgebra.Transpose{<:Any, <:$MatrixType}, vec::$VectorType) where T mat = parent(transposed_mat) @boundscheck length(dest) == size(mat, 2) || throw(DimensionMismatch()) @framecheck mat.frame vec.frame mat_angular = angular(mat) mat_linear = linear(mat) vec_angular = angular(vec) vec_linear = linear(vec) @inbounds begin @simd for row in eachindex(dest) dest[row] = mat_angular[1, row] * vec_angular[1] + mat_angular[2, row] * vec_angular[2] + mat_angular[3, row] * vec_angular[3] end @simd for row in eachindex(dest) dest[row] += mat_linear[1, row] * vec_linear[1] + mat_linear[2, row] * vec_linear[2] + mat_linear[3, row] * vec_linear[3] end end dest end function Base.:*(transposed_mat::LinearAlgebra.Transpose{<:Any, <:$MatrixType}, vec::$VectorType) mat = parent(transposed_mat) @framecheck mat.frame vec.frame transpose(angular(mat)) * angular(vec) + transpose(linear(mat)) * linear(vec) end end end for ForceSpaceMatrix in (:MomentumMatrix, :WrenchMatrix) for (A, B) in ((ForceSpaceMatrix, :GeometricJacobian), (:GeometricJacobian, ForceSpaceMatrix)) @eval begin function Base.:*(at::LinearAlgebra.Transpose{<:Any, <:$A}, b::$B) a = parent(at) @framecheck a.frame b.frame transpose(angular(a)) * angular(b) + transpose(linear(a)) * linear(b) end function Base.:*(a::$A, bt::LinearAlgebra.Transpose{<:Any, <:$B}) b = parent(bt) @framecheck a.frame b.frame angular(a) * transpose(angular(b)) + linear(a) * transpose(linear(b)) end end end end """ $(SIGNATURES) Compute the kinetic energy of a body with spatial inertia ``I``, which has twist ``T`` with respect to an inertial frame. """ @inline function kinetic_energy(inertia::SpatialInertia, twist::Twist) @framecheck(inertia.frame, twist.frame) # TODO: should assert that twist.base is an inertial frame somehow ω = angular(twist) v = linear(twist) J = inertia.moment c = inertia.cross_part m = inertia.mass (ω ⋅ (J * ω) + v ⋅ (m * v + 2 * (ω × c))) / 2 end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
6634
for ForceSpaceMatrix in (:MomentumMatrix, :WrenchMatrix) @eval struct $ForceSpaceMatrix{A<:AbstractMatrix} frame::CartesianFrame3D angular::A linear::A @inline function $ForceSpaceMatrix{A}(frame::CartesianFrame3D, angular::AbstractMatrix, linear::AbstractMatrix) where {A<:AbstractMatrix} @boundscheck size(angular, 1) == 3 || throw(DimensionMismatch()) @boundscheck size(linear, 1) == 3 || throw(DimensionMismatch()) @boundscheck size(angular, 2) == size(linear, 2) || throw(DimensionMismatch()) new{A}(frame, angular, linear) end end end """ $(TYPEDEF) A momentum matrix maps a joint velocity vector to momentum. This is a slight generalization of the centroidal momentum matrix (Orin, Goswami, "Centroidal momentum matrix of a humanoid robot: Structure and properties.") in that the matrix (and hence the corresponding total momentum) need not be expressed in a centroidal frame. """ MomentumMatrix for ForceSpaceMatrix in (:MomentumMatrix, :WrenchMatrix) @eval begin @inline function $ForceSpaceMatrix(frame::CartesianFrame3D, angular::A, linear::A) where {A<:AbstractMatrix} $ForceSpaceMatrix{A}(frame, angular, linear) end @inline function $ForceSpaceMatrix(frame::CartesianFrame3D, angular::A1, linear::A2) where {A1<:AbstractMatrix, A2<:AbstractMatrix} $ForceSpaceMatrix(frame, promote(angular, linear)...) end @inline function $ForceSpaceMatrix{A}(mat::$ForceSpaceMatrix) where A $ForceSpaceMatrix(mat.frame, A(angular(mat)), A(linear(mat))) end function Base.show(io::IO, m::$ForceSpaceMatrix) print(io, "$($(string(ForceSpaceMatrix))) expressed in \"$(string(m.frame))\":\n$(Array(m))") end @inline function transform(mat::$ForceSpaceMatrix, tf::Transform3D) @framecheck(mat.frame, tf.from) R = rotation(tf) Av = R * linear(mat) Aω = R * angular(mat) + colwise(×, translation(tf), Av) $ForceSpaceMatrix(tf.to, Aω, Av) end end end """ $(TYPEDEF) A `Momentum` is the product of a `SpatialInertia` and a `Twist`, i.e. ```math h^i = \\left(\\begin{array}{c} k^{i}\\\\ l^{i} \\end{array}\\right) = I^i T^{i, j}_k ``` where ``I^i`` is the spatial inertia of a given body expressed in frame ``i``, and ``T^{i, j}_k`` is the twist of frame ``k`` (attached to the body) with respect to inertial frame ``j``, expressed in frame ``i``. ``k^i`` is the angular momentum and ``l^i`` is the linear momentum. """ struct Momentum{T} frame::CartesianFrame3D angular::SVector{3, T} linear::SVector{3, T} @inline function Momentum{T}(frame::CartesianFrame3D, angular::AbstractVector, linear::AbstractVector) where T new{T}(frame, angular, linear) end end """ $(TYPEDEF) A wrench represents a system of forces. The wrench ``w^i`` expressed in frame ``i`` is defined as ```math w^{i} = \\left(\\begin{array}{c} \\tau^{i}\\\\ f^{i} \\end{array}\\right) = \\sum_{j}\\left(\\begin{array}{c} r_{j}^{i}\\times f_{j}^{i}\\\\ f_{j}^{i} \\end{array}\\right) ``` where the ``f_{j}^{i}`` are forces expressed in frame ``i``, exerted at positions ``r_{j}^{i}``. ``\\tau^i`` is the total torque and ``f^i`` is the total force. """ struct Wrench{T} frame::CartesianFrame3D angular::SVector{3, T} linear::SVector{3, T} @inline function Wrench{T}(frame::CartesianFrame3D, angular::AbstractVector, linear::AbstractVector) where T new{T}(frame, angular, linear) end end for ForceSpaceElement in (:Momentum, :Wrench) @eval begin # Construct with possibly eltype-heterogeneous inputs @inline function $ForceSpaceElement(frame::CartesianFrame3D, angular::AbstractVector, linear::AbstractVector) T = promote_eltype(angular, linear) $ForceSpaceElement{T}(frame, angular, linear) end """ $(SIGNATURES) Create a $($(string(ForceSpaceElement))) given the angular and linear components, which should be expressed in the same frame. """ function $ForceSpaceElement(angular::FreeVector3D, linear::FreeVector3D) @framecheck angular.frame linear.frame $ForceSpaceElement(angular.frame, angular.v, linear.v) end function Base.show(io::IO, f::$ForceSpaceElement) print(io, "$($(string(ForceSpaceElement))) expressed in \"$(string(f.frame))\":\nangular: $(angular(f)), linear: $(linear(f))") end function Base.zero(::Type{$ForceSpaceElement{T}}, frame::CartesianFrame3D) where {T} $ForceSpaceElement(frame, zero(SVector{3, T}), zero(SVector{3, T})) end Base.zero(f::$ForceSpaceElement) = zero(typeof(f), f.frame) function Random.rand(::Type{$ForceSpaceElement{T}}, frame::CartesianFrame3D) where {T} $ForceSpaceElement(frame, rand(SVector{3, T}), rand(SVector{3, T})) end """ $(SIGNATURES) Transform the $($(string(ForceSpaceElement))) to a different frame. """ @inline function transform(f::$ForceSpaceElement, tf::Transform3D) @framecheck(f.frame, tf.from) rot = rotation(tf) lin = rot * linear(f) ang = rot * angular(f) + translation(tf) × lin $ForceSpaceElement(tf.to, ang, lin) end @inline function Base.:+(f1::$ForceSpaceElement, f2::$ForceSpaceElement) @framecheck(f1.frame, f2.frame) $ForceSpaceElement(f1.frame, angular(f1) + angular(f2), linear(f1) + linear(f2)) end @inline function Base.:-(f1::$ForceSpaceElement, f2::$ForceSpaceElement) @framecheck(f1.frame, f2.frame) $ForceSpaceElement(f1.frame, angular(f1) - angular(f2), linear(f1) - linear(f2)) end @inline Base.:-(f::$ForceSpaceElement) = $ForceSpaceElement(f.frame, -angular(f), -linear(f)) function Base.isapprox(x::$ForceSpaceElement, y::$ForceSpaceElement; atol = 1e-12) x.frame == y.frame && isapprox(angular(x), angular(y), atol = atol) && isapprox(linear(x), linear(y), atol = atol) end end end # Wrench-specific functions """ $(SIGNATURES) Create a Wrench from a force, ``f``, and the application point of the force, ``r``. The torque part of the wrench will be computed as ``r \\times f``. The force and the application point should be expressed in the same frame. """ Wrench(application_point::Point3D, force::FreeVector3D) = Wrench(application_point × force, force)
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
14857
""" $(TYPEDEF) A geometric Jacobian (also known as basic, or spatial Jacobian) maps a vector of joint velocities to a twist. """ struct GeometricJacobian{A<:AbstractMatrix} body::CartesianFrame3D base::CartesianFrame3D frame::CartesianFrame3D angular::A linear::A @inline function GeometricJacobian{A}( body::CartesianFrame3D, base::CartesianFrame3D, frame::CartesianFrame3D, angular::AbstractMatrix, linear::AbstractMatrix) where A<:AbstractMatrix @boundscheck size(angular, 1) == 3 || throw(DimensionMismatch()) @boundscheck size(linear, 1) == 3 || throw(DimensionMismatch()) @boundscheck size(angular, 2) == size(linear, 2) || throw(DimensionMismatch()) new{A}(body, base, frame, angular, linear) end end # GeometricJacobian-specific functions @inline function GeometricJacobian( body::CartesianFrame3D, base::CartesianFrame3D, frame::CartesianFrame3D, angular::A, linear::A) where {A<:AbstractMatrix} GeometricJacobian{A}(body, base, frame, angular, linear) end @inline function GeometricJacobian( body::CartesianFrame3D, base::CartesianFrame3D, frame::CartesianFrame3D, angular::A1, linear::A2) where {A1<:AbstractMatrix, A2<:AbstractMatrix} GeometricJacobian(body, base, frame, promote(angular, linear)...) end @inline function GeometricJacobian{A}(jac::GeometricJacobian) where A GeometricJacobian(jac.body, jac.base, jac.frame, A(angular(jac)), A(linear(jac))) end change_base(jac::GeometricJacobian, base::CartesianFrame3D) = GeometricJacobian(jac.body, base, jac.frame, angular(jac), linear(jac)) Base.:-(jac::GeometricJacobian) = GeometricJacobian(jac.base, jac.body, jac.frame, -angular(jac), -linear(jac)) function Base.show(io::IO, jac::GeometricJacobian) print(io, "GeometricJacobian: body: \"$(string(jac.body))\", base: \"$(string(jac.base))\", expressed in \"$(string(jac.frame))\":\n$(Array(jac))") end """ $(SIGNATURES) Transform the `GeometricJacobian` to a different frame. """ @inline function transform(jac::GeometricJacobian, tf::Transform3D) @framecheck(jac.frame, tf.from) R = rotation(tf) ang = R * angular(jac) lin = R * linear(jac) + colwise(×, translation(tf), ang) GeometricJacobian(jac.body, jac.base, tf.to, ang, lin) end struct PointJacobian{M <: AbstractMatrix} frame::CartesianFrame3D J::M end Base.@deprecate PointJacobian{M}(J::M, frame::CartesianFrame3D) where {M<:AbstractMatrix} PointJacobian(frame, J) Base.@deprecate PointJacobian(J::AbstractMatrix, frame::CartesianFrame3D) PointJacobian(frame, J) # Construct/convert to Matrix (::Type{A})(jac::PointJacobian) where {A<:Array} = A(jac.J) Base.convert(::Type{A}, jac::PointJacobian) where {A<:Array} = A(jac) Base.eltype(::Type{PointJacobian{M}}) where {M} = eltype(M) Base.transpose(jac::PointJacobian) = Transpose(jac) function point_velocity(jac::PointJacobian, v::AbstractVector) FreeVector3D(jac.frame, jac.J * v) end function LinearAlgebra.mul!(τ::AbstractVector, jac_transpose::Transpose{<:Any, <:PointJacobian}, force::FreeVector3D) jac = parent(jac_transpose) @framecheck jac.frame force.frame mul!(τ, transpose(jac.J), force.v) end function Base.:*(jac_transpose::Transpose{<:Any, <:PointJacobian}, force::FreeVector3D) jac = parent(jac_transpose) @framecheck jac.frame force.frame transpose(jac.J) * force.v end """ $(TYPEDEF) A twist represents the relative angular and linear motion between two bodies. The twist of frame ``j`` with respect to frame ``i``, expressed in frame ``k`` is defined as ```math T_{j}^{k,i}=\\left(\\begin{array}{c} \\omega_{j}^{k,i}\\\\ v_{j}^{k,i} \\end{array}\\right)\\in\\mathbb{R}^{6} ``` such that ```math \\left[\\begin{array}{cc} \\hat{\\omega}_{j}^{k,i} & v_{j}^{k,i}\\\\ 0 & 0 \\end{array}\\right]=H_{i}^{k}\\dot{H}_{j}^{i}H_{k}^{j} ``` where ``H^{\\beta}_{\\alpha}`` is the homogeneous transform from frame ``\\alpha`` to frame ``\\beta``, and ``\\hat{x}`` is the ``3 \\times 3`` skew symmetric matrix that satisfies ``\\hat{x} y = x \\times y`` for all ``y \\in \\mathbb{R}^3``. Here, ``\\omega_{j}^{k,i}`` is the angular part and ``v_{j}^{k,i}`` is the linear part. Note that the linear part is not in general the same as the linear velocity of the origin of frame ``j``. """ struct Twist{T} body::CartesianFrame3D base::CartesianFrame3D frame::CartesianFrame3D angular::SVector{3, T} linear::SVector{3, T} @inline function Twist{T}(body::CartesianFrame3D, base::CartesianFrame3D, frame::CartesianFrame3D, angular::AbstractVector, linear::AbstractVector) where T new{T}(body, base, frame, angular, linear) end end """ $(TYPEDEF) A spatial acceleration is the time derivative of a twist. See [`Twist`](@ref). """ struct SpatialAcceleration{T} body::CartesianFrame3D base::CartesianFrame3D frame::CartesianFrame3D angular::SVector{3, T} linear::SVector{3, T} @inline function SpatialAcceleration{T}(body::CartesianFrame3D, base::CartesianFrame3D, frame::CartesianFrame3D, angular::AbstractVector, linear::AbstractVector) where T new{T}(body, base, frame, angular, linear) end end for MotionSpaceElement in (:Twist, :SpatialAcceleration) @eval begin # Construct with possibly eltype-heterogeneous inputs @inline function $MotionSpaceElement(body::CartesianFrame3D, base::CartesianFrame3D, frame::CartesianFrame3D, angular::AbstractVector, linear::AbstractVector) T = promote_eltype(angular, linear) $MotionSpaceElement{T}(body, base, frame, angular, linear) end # Construct given FreeVector3Ds function $MotionSpaceElement(body::CartesianFrame3D, base::CartesianFrame3D, angular::FreeVector3D, linear::FreeVector3D) @framecheck angular.frame linear.frame $MotionSpaceElement(body, base, angular.frame, angular.v, linear.v) end # Construct/convert given another $MotionSpaceElement function $MotionSpaceElement{T}(m::$MotionSpaceElement) where T $MotionSpaceElement(m.body, m.base, m.frame, SVector{3, T}(angular(m)), SVector{3, T}(linear(m))) end function Base.show(io::IO, m::$MotionSpaceElement) print(io, "$($(string(MotionSpaceElement))) of \"$(string(m.body))\" w.r.t \"$(string(m.base))\" in \"$(string(m.frame))\":\nangular: $(angular(m)), linear: $(linear(m))") end function Base.isapprox(x::$MotionSpaceElement, y::$MotionSpaceElement; atol = 1e-12) x.body == y.body && x.base == y.base && x.frame == y.frame && isapprox(angular(x), angular(y); atol = atol) && isapprox(linear(x), linear(y); atol = atol) end @inline function Base.:+(m1::$MotionSpaceElement, m2::$MotionSpaceElement) @framecheck(m1.frame, m2.frame) @boundscheck begin ((m1.body == m2.body && m1.base == m2.base) || m1.body == m2.base) || throw(ArgumentError("frame mismatch")) end $MotionSpaceElement(m2.body, m1.base, m1.frame, angular(m1) + angular(m2), linear(m1) + linear(m2)) end Base.:-(m::$MotionSpaceElement) = $MotionSpaceElement(m.base, m.body, m.frame, -angular(m), -linear(m)) change_base(m::$MotionSpaceElement, base::CartesianFrame3D) = $MotionSpaceElement(m.body, base, m.frame, angular(m), linear(m)) function Base.zero(::Type{$MotionSpaceElement{T}}, body::CartesianFrame3D, base::CartesianFrame3D, frame::CartesianFrame3D) where {T} $MotionSpaceElement(body, base, frame, zero(SVector{3, T}), zero(SVector{3, T})) end Base.zero(m::$MotionSpaceElement) = zero(typeof(m), m.body, m.base, m.frame) function Random.rand(::Type{$MotionSpaceElement{T}}, body::CartesianFrame3D, base::CartesianFrame3D, frame::CartesianFrame3D) where {T} $MotionSpaceElement(body, base, frame, rand(SVector{3, T}), rand(SVector{3, T})) end # GeometricJacobian * velocity vector --> Twist # GeometricJacobian * acceleration vector --> SpatialAcceleration function $MotionSpaceElement(jac::GeometricJacobian, x::AbstractVector) $MotionSpaceElement(jac.body, jac.base, jac.frame, convert(SVector{3}, angular(jac) * x), convert(SVector{3}, linear(jac) * x)) end end end """ $(SIGNATURES) Transform the `Twist` to a different frame. """ @inline function transform(twist::Twist, tf::Transform3D) @framecheck(twist.frame, tf.from) ang, lin = transform_spatial_motion(angular(twist), linear(twist), rotation(tf), translation(tf)) Twist(twist.body, twist.base, tf.to, ang, lin) end # log(::Transform3D) + some extra outputs that make log_with_time_derivative faster function _log(t::Transform3D) # Proposition 2.9 in Murray et al, "A mathematical introduction to robotic manipulation." rot = rotation(t) p = translation(t) # Rotational part of local coordinates is simply the rotation vector. aa = AngleAxis(rot) θ, axis = rotation_angle(aa), rotation_axis(aa) ϕrot = θ * axis # Translational part from Bullo and Murray, "Proportional derivative (PD) control on the Euclidean group.", # (2.4) and (2.5), which provide a closed form solution of the inverse of the A matrix in proposition 2.9 of Murray et al. θ_2 = θ / 2 sθ_2, cθ_2 = sincos(θ_2) θ_squared = θ^2 if abs(rem2pi(θ, RoundNearest)) < eps(typeof(θ)) α = one(θ_2) ϕtrans = p else α = θ_2 * cθ_2 / sθ_2 ϕtrans = p - ϕrot × p / 2 + (1 - α) / θ_squared * ϕrot × (ϕrot × p) # Bullo, Murray, (2.5) end ξ = Twist(t.from, t.to, t.to, ϕrot, ϕtrans) # twist in base frame; see section 4.3 ξ, θ, θ_squared, θ_2, sθ_2, cθ_2, α end """ $(SIGNATURES) Express a homogeneous transform in exponential coordinates centered around the identity. """ function Base.log(t::Transform3D) first(_log(t)) end """ $(SIGNATURES) Compute exponential coordinates as well as their time derivatives in one shot. This mainly exists because ForwardDiff won't work at the singularity of `log`. It is also ~50% faster than ForwardDiff in this case. """ function log_with_time_derivative(t::Transform3D, twist::Twist) # See Bullo and Murray, "Proportional derivative (PD) control on the Euclidean group.", Lemma 4. # This is truely magic. # Notation matches Bullo and Murray. @framecheck(twist.body, t.from) @framecheck(twist.base, t.to) @framecheck(twist.frame, twist.body) # required by Lemma 4. X, θ, θ_squared, θ_over_2, sθ_over_2, cθ_over_2, α = _log(t) ψ = angular(X) q = linear(X) ω = angular(twist) v = linear(twist) ψ̇ = ω q̇ = v if abs(rem2pi(θ, RoundNearest)) > eps(typeof(θ)) β = θ_over_2^2 / sθ_over_2^2 A = (2 * (1 - α) + (α - β) / 2) / θ_squared B = ((1 - α) + (α - β) / 2) / θ_squared^2 adψ̇, adq̇ = se3_commutator(ψ, q, ω, v) ad2ψ̇, ad2q̇ = se3_commutator(ψ, q, adψ̇, adq̇) ad3ψ̇, ad3q̇ = se3_commutator(ψ, q, ad2ψ̇, ad2q̇) ad4ψ̇, ad4q̇ = se3_commutator(ψ, q, ad3ψ̇, ad3q̇) ψ̇ += adψ̇ / 2 + A * ad2ψ̇ + B * ad4ψ̇ q̇ += adq̇ / 2 + A * ad2q̇ + B * ad4q̇ end Ẋ = SpatialAcceleration(X.body, X.base, X.frame, ψ̇, q̇) X, Ẋ end """ $(SIGNATURES) Convert exponential coordinates to a homogeneous transform. """ function Base.exp(twist::Twist) # See Murray et al, "A mathematical introduction to robotic manipulation." @framecheck(twist.frame, twist.base) # twist in base frame; see section 4.3 ϕrot = angular(twist) ϕtrans = linear(twist) θ = norm(ϕrot) if abs(rem2pi(θ, RoundNearest)) < eps(typeof(θ)) # (2.32) rot = one(RotMatrix3{typeof(θ)}) trans = ϕtrans else # (2.36) ω = ϕrot / θ rot = RotMatrix(AngleAxis(θ, ω[1], ω[2], ω[3], false)) v = ϕtrans / θ trans = ω × v trans -= rot * trans trans += ω * dot(ω, v) * θ end Transform3D(twist.body, twist.base, rot, trans) end @inline function LinearAlgebra.cross(twist1::Twist, twist2::Twist) @framecheck(twist1.frame, twist2.frame) ang, lin = se3_commutator(angular(twist1), linear(twist1), angular(twist2), linear(twist2)) SpatialAcceleration(twist2.body, twist2.base, twist2.frame, ang, lin) end """ $(SIGNATURES) Given the twist ``T_{j}^{k,i}`` of frame ``j`` with respect to frame ``i``, expressed in frame ``k``, and the location of a point fixed in frame ``j``, also expressed in frame ``k``, compute the velocity of the point relative to frame ``i``. """ function point_velocity(twist::Twist, point::Point3D) @framecheck twist.frame point.frame FreeVector3D(twist.frame, angular(twist) × point.v + linear(twist)) end """ $(SIGNATURES) Given the twist ``dot{T}_{j}^{k,i}`` of frame ``j`` with respect to frame ``i``, expressed in frame ``k`` and its time derivative (a spatial acceleration), as well as the location of a point fixed in frame ``j``, also expressed in frame ``k``, compute the acceleration of the point relative to frame ``i``. """ function point_acceleration(twist::Twist, accel::SpatialAcceleration, point::Point3D) @framecheck twist.base accel.base @framecheck twist.body accel.body @framecheck twist.frame accel.frame FreeVector3D(accel.frame, angular(accel) × point.v + linear(accel) + angular(twist) × point_velocity(twist, point).v) end # SpatialAcceleration-specific functions """ $(SIGNATURES) Transform the `SpatialAcceleration` to a different frame. The transformation rule is obtained by differentiating the transformation rule for twists. """ function transform(accel::SpatialAcceleration, old_to_new::Transform3D, twist_of_current_wrt_new::Twist, twist_of_body_wrt_base::Twist) # trivial case accel.frame == old_to_new.to && return accel # frame checks @framecheck(old_to_new.from, accel.frame) @framecheck(twist_of_current_wrt_new.frame, accel.frame) @framecheck(twist_of_current_wrt_new.body, accel.frame) @framecheck(twist_of_current_wrt_new.base, old_to_new.to) @framecheck(twist_of_body_wrt_base.frame, accel.frame) @framecheck(twist_of_body_wrt_base.body, accel.body) @framecheck(twist_of_body_wrt_base.base, accel.base) # 'cross term': ang, lin = se3_commutator( angular(twist_of_current_wrt_new), linear(twist_of_current_wrt_new), angular(twist_of_body_wrt_base), linear(twist_of_body_wrt_base)) # add current acceleration: ang += angular(accel) lin += linear(accel) # transform to new frame ang, lin = transform_spatial_motion(ang, lin, rotation(old_to_new), translation(old_to_new)) SpatialAcceleration(accel.body, accel.base, old_to_new.to, ang, lin) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
4355
# Point3D, FreeVector3D. The difference is that a FreeVector3D is only rotated when its frame is changed, # whereas a Point3D is also translated for VectorType in (:FreeVector3D, :Point3D) @eval begin # TODO: consider storing as a homogeneous vector struct $VectorType{V<:AbstractVector} v::V frame::CartesianFrame3D @inline function $VectorType(frame::CartesianFrame3D, v::V) where {V} @boundscheck length(v) == 3 || throw(DimensionMismatch()) new{V}(v, frame) end end $VectorType(::Type{T}, frame::CartesianFrame3D) where {T} = $VectorType(frame, zero(SVector{3, T})) $VectorType(frame::CartesianFrame3D, x::Number, y::Number, z::Number) = $VectorType(frame, SVector(x, y, z)) Base.convert(::Type{$VectorType{V}}, p::$VectorType{V}) where {V} = p Base.convert(::Type{$VectorType{V}}, p::$VectorType) where {V} = $VectorType(p.frame, convert(V, p.v)) Base.zero(p::$VectorType) = $VectorType(p.frame, zero(p.v)) Base.:/(p::$VectorType, s::Number) = $VectorType(p.frame, p.v / s) Base.:*(p::$VectorType, s::Number) = $VectorType(p.frame, p.v * s) Base.:*(s::Number, p::$VectorType) = $VectorType(p.frame, s * p.v) Base.:-(p::$VectorType) = $VectorType(p.frame, -p.v) Random.rand(::Type{$VectorType}, ::Type{T}, frame::CartesianFrame3D) where {T} = $VectorType(frame, rand(SVector{3, T})) Base.show(io::IO, p::$VectorType) = print(io, "$($(string(VectorType))) in \"$(string(p.frame))\": $(p.v)") Base.isapprox(x::$VectorType, y::$VectorType; atol::Real = 1e-12) = x.frame == y.frame && isapprox(x.v, y.v; atol = atol) """ $(SIGNATURES) Return `x` transformed to `CartesianFrame3D` `t.from`. """ transform(x::$VectorType, t::Transform3D) = t * x Base.eltype(::Type{$VectorType{V}}) where {V} = eltype(V) end end """ $(TYPEDEF) A `Point3D` represents a position in a given coordinate system. A `Point3D` is a [bound vector](https://en.wikipedia.org/wiki/Euclidean_vector#Overview). Applying a `Transform3D` to a `Point3D` both rotates and translates the `Point3D`. """ Point3D """ $(TYPEDEF) A `FreeVector3D` represents a [free vector](https://en.wikipedia.org/wiki/Euclidean_vector#Overview). Examples of free vectors include displacements and velocities of points. Applying a `Transform3D` to a `FreeVector3D` only rotates the `FreeVector3D`. """ FreeVector3D # Point3D-specific Base.:-(p1::Point3D, p2::Point3D) = begin @framecheck(p1.frame, p2.frame); FreeVector3D(p1.frame, p1.v - p2.v) end Base.:*(t::Transform3D, point::Point3D) = begin @framecheck(t.from, point.frame); Point3D(t.to, rotation(t) * point.v + translation(t)) end Base.:\(t::Transform3D, point::Point3D) = begin @framecheck point.frame t.to; Point3D(t.from, rotation(t) \ (point.v - translation(t))) end # FreeVector3D-specific FreeVector3D(p::Point3D) = FreeVector3D(p.frame, p.v) Base.:-(v1::FreeVector3D, v2::FreeVector3D) = begin @framecheck(v1.frame, v2.frame); FreeVector3D(v1.frame, v1.v - v2.v) end LinearAlgebra.cross(v1::FreeVector3D, v2::FreeVector3D) = begin @framecheck(v1.frame, v2.frame); FreeVector3D(v1.frame, v1.v × v2.v) end LinearAlgebra.dot(v1::FreeVector3D, v2::FreeVector3D) = begin @framecheck(v1.frame, v2.frame); v1.v ⋅ v2.v end Base.:*(t::Transform3D, vector::FreeVector3D) = begin @framecheck(t.from, vector.frame); FreeVector3D(t.to, rotation(t) * vector.v) end Base.:\(t::Transform3D, point::FreeVector3D) = begin @framecheck point.frame t.to; FreeVector3D(t.from, rotation(t) \ point.v) end LinearAlgebra.norm(v::FreeVector3D) = norm(v.v) LinearAlgebra.normalize(v::FreeVector3D, p::Real = 2) = FreeVector3D(v.frame, normalize(v.v, p)) # Mixed Point3D and FreeVector3D Base.:+(p1::FreeVector3D, p2::FreeVector3D) = begin @framecheck(p1.frame, p2.frame); FreeVector3D(p1.frame, p1.v + p2.v) end Base.:+(p::Point3D, v::FreeVector3D) = begin @framecheck(p.frame, v.frame); Point3D(p.frame, p.v + v.v) end Base.:+(v::FreeVector3D, p::Point3D) = p + v Base.:-(p::Point3D, v::FreeVector3D) = begin @framecheck(p.frame, v.frame); Point3D(p.frame, p.v - v.v) end LinearAlgebra.cross(p::Point3D, v::FreeVector3D) = begin @framecheck(p.frame, v.frame); FreeVector3D(p.frame, p.v × v.v) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
3760
""" $(TYPEDEF) A homogeneous transformation matrix representing the transformation from one three-dimensional Cartesian coordinate system to another. """ struct Transform3D{T} mat::SMatrix{4, 4, T, 16} from::CartesianFrame3D to::CartesianFrame3D @inline function Transform3D(from::CartesianFrame3D, to::CartesianFrame3D, mat::AbstractMatrix{T}) where T new{T}(mat, from, to) end end Base.eltype(::Type{Transform3D{T}}) where {T} = T @inline function Transform3D(from::CartesianFrame3D, to::CartesianFrame3D, rot::Rotation{3}, trans::SVector{3}) T = promote_eltype(rot, trans) R = convert(RotMatrix3{T}, rot) @inbounds mat = @SMatrix [R[1] R[4] R[7] trans[1]; R[2] R[5] R[8] trans[2]; R[3] R[6] R[9] trans[3]; zero(T) zero(T) zero(T) one(T)] Transform3D(from, to, mat) end @inline function Transform3D(from::CartesianFrame3D, to::CartesianFrame3D, rot::Rotation{3, T}) where {T} R = convert(RotMatrix3{T}, rot) @inbounds mat = @SMatrix [R[1] R[4] R[7] zero(T); R[2] R[5] R[8] zero(T); R[3] R[6] R[9] zero(T); zero(T) zero(T) zero(T) one(T)] Transform3D(from, to, mat) end @inline function Transform3D(from::CartesianFrame3D, to::CartesianFrame3D, trans::SVector{3, T}) where {T} @inbounds mat = @SMatrix [one(T) zero(T) zero(T) trans[1]; zero(T) one(T) zero(T) trans[2]; zero(T) zero(T) one(T) trans[3]; zero(T) zero(T) zero(T) one(T)] Transform3D(from, to, mat) end @inline Base.convert(::Type{Transform3D{T}}, t::Transform3D{T}) where {T} = t @inline Base.convert(::Type{Transform3D{T}}, t::Transform3D) where {T} = Transform3D(t.from, t.to, similar_type(t.mat, T)(t.mat)) @inline rotation(t::Transform3D) = @inbounds return RotMatrix(t.mat[1], t.mat[2], t.mat[3], t.mat[5], t.mat[6], t.mat[7], t.mat[9], t.mat[10], t.mat[11]) @inline translation(t::Transform3D) = @inbounds return SVector(t.mat[13], t.mat[14], t.mat[15]) function Base.show(io::IO, t::Transform3D) println(io, "Transform3D from \"$(string(t.from))\" to \"$(string(t.to))\":") angle_axis = AngleAxis(rotation(t)) angle = rotation_angle(angle_axis) axis = rotation_axis(angle_axis) print(io, "rotation: $(angle) rad about $(axis), translation: $(translation(t))") # TODO: use fixed Quaternions.jl version once it's updated end @inline function Base.:*(t1::Transform3D, t2::Transform3D) @framecheck(t1.from, t2.to) mat = t1.mat * t2.mat Transform3D(t2.from, t1.to, mat) end @inline function LinearAlgebra.inv(t::Transform3D) rotinv = inv(rotation(t)) Transform3D(t.to, t.from, rotinv, -(rotinv * translation(t))) end Base.one(::Type{Transform3D{T}}, from::CartesianFrame3D, to::CartesianFrame3D) where {T} = Transform3D(from, to, one(SMatrix{4, 4, T})) Base.one(::Type{Transform3D}, from::CartesianFrame3D, to::CartesianFrame3D) = one(Transform3D{Float64}, from, to) Base.one(::Type{T}, frame::CartesianFrame3D) where {T<:Transform3D} = one(T, frame, frame) function Random.rand(::Type{Transform3D{T}}, from::CartesianFrame3D, to::CartesianFrame3D) where T rot = rand(RotMatrix3{T}) trans = rand(SVector{3, T}) Transform3D(from, to, rot, trans) end Random.rand(::Type{Transform3D}, from::CartesianFrame3D, to::CartesianFrame3D) = rand(Transform3D{Float64}, from, to) function Base.isapprox(x::Transform3D, y::Transform3D; atol::Real = 1e-12) x.from == y.from && x.to == y.to && isapprox(rotation(x), rotation(y), atol = atol) && isapprox(translation(x), translation(y), atol = atol) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
5951
# Type aliases using ..RigidBodyDynamics: ModifiedRodriguesParam ## Colwise # TODO: replace with future mapslices specialization, see https://github.com/JuliaArrays/StaticArrays.jl/pull/99 """ $(SIGNATURES) Equivalent to one of ```julia mapslices(x -> f(a, x), B, dims=1) mapslices(x -> f(x, b), A, dims=1) ``` but optimized for statically-sized matrices. """ function colwise end colwise(f, a::AbstractVector, B::AbstractMatrix) = mapslices(x -> f(a, x), B, dims=1) colwise(f, A::AbstractMatrix, b::AbstractVector) = mapslices(x -> f(x, b), A, dims=1) @inline function colwise(f, a::StaticVector, B::StaticMatrix) Sa = Size(a) SB = Size(B) Sa[1] === SB[1] || throw(DimensionMismatch()) _colwise(f, Val(SB[2]), a, B) end @inline function _colwise(f, ::Val{0}, a::StaticVector, B::StaticMatrix) zero(similar_type(B, promote_eltype(a, B))) end @inline function _colwise(f, M::Val, a::StaticVector, B::StaticMatrix) cols = ntuple(i -> f(a, B[:, i]), M) hcat(cols...) end @inline function colwise(f, A::StaticMatrix, b::StaticVector) SA = Size(A) Sb = Size(b) SA[1] === Sb[1] || throw(DimensionMismatch()) _colwise(f, Val(SA[2]), A, b) end @inline function _colwise(f, ::Val{0}, A::StaticMatrix, b::StaticVector) zero(similar_type(A, promote_eltype(A, b))) end @inline function _colwise(f, M::Val, A::StaticMatrix, b::StaticVector) cols = ntuple(i -> f(A[:, i], b), M) hcat(cols...) end @inline function vector_to_skew_symmetric(v::SVector{3, T}) where {T} @SMatrix [zero(T) -v[3] v[2]; v[3] zero(T) -v[1]; -v[2] v[1] zero(T)] end const hat = vector_to_skew_symmetric @inline function vector_to_skew_symmetric_squared(a::SVector{3}) a1² = a[1] * a[1] a2² = a[2] * a[2] a3² = a[3] * a[3] b11 = -a2² - a3² b12 = a[1] * a[2] b13 = a[1] * a[3] b22 = -a1² - a3² b23 = a[2] * a[3] b33 = -a1² - a2² @SMatrix [b11 b12 b13; b12 b22 b23; b13 b23 b33] end const hat_squared = vector_to_skew_symmetric_squared # The 'Bortz equation'. # Bortz, John E. "A new mathematical formulation for strapdown inertial navigation." # IEEE transactions on aerospace and electronic systems 1 (1971): 61-66. # # Or, interpreted in a Lie setting: # d/dt(exp(ϕ(t))) = ̂(dexp(ϕ(t)) * ϕ̇(t)) * exp(ϕ(t)) (where dexp is the 'right trivialized' tangent of the exponential map) # ̂(dexp(ϕ(t)) * ϕ̇(t)) = d/dt(exp(ϕ(t))) * exp(ϕ(t))⁻¹ (hat form of angular velocity in world frame) # = ̂(exp(ϕ(t)) ω) (with ω angular velocity in body frame) # ϕ̇(t) = dexp⁻¹(ϕ(t)) * exp(ϕ(t)) * ω function rotation_vector_rate(rotation_vector::AbstractVector{T}, angular_velocity_in_body::AbstractVector{T}) where {T} ϕ = rotation_vector ω = angular_velocity_in_body @boundscheck length(ϕ) == 3 || error("ϕ has wrong length") @boundscheck length(ω) == 3 || error("ω has wrong length") ϕ̇ = ω + (ϕ × ω) / 2 θ = norm(ϕ) if θ > eps(typeof(θ)) s, c = sincos(θ) ϕ̇ += 1 / θ^2 * (1 - (θ * s) / (2 * (1 - c))) * ϕ × (ϕ × ω) end ϕ̇ end @inline function transform_spatial_motion(angular::SVector{3}, linear::SVector{3}, rot::R, trans::SVector{3}) where {R <: Rotation{3}} angular = rot * angular linear = rot * linear + trans × angular angular, linear end @inline function mul_inertia(J, c, m, ω, v) angular = J * ω + c × v linear = m * v - c × ω angular, linear end # also known as 'spatial motion cross product' @inline function se3_commutator(xω, xv, yω, yv) angular = xω × yω linear = xω × yv + xv × yω angular, linear end function quaternion_derivative end function spquat_derivative end function angular_velocity_in_body end @inline function velocity_jacobian(::typeof(quaternion_derivative), q::QuatRotation) w, x, y, z = Rotations.params(q) (@SMatrix [ -x -y -z; w -z y; z w -x; -y x w ]) / 2 end @inline function velocity_jacobian(::typeof(spquat_derivative), q::ModifiedRodriguesParam) quat = QuatRotation(q) dQuat_dW = velocity_jacobian(quaternion_derivative, quat) dSPQuat_dQuat = Rotations.jacobian(ModifiedRodriguesParam, quat) dSPQuat_dQuat * dQuat_dW end @inline function velocity_jacobian(::typeof(angular_velocity_in_body), q::QuatRotation) w, x, y, z = Rotations.params(q) 2 * @SMatrix [ -x w z -y; -y -z w x; -z y -x w ] end @inline function velocity_jacobian(::typeof(angular_velocity_in_body), q::ModifiedRodriguesParam) quat = QuatRotation(q) dW_dQuat = velocity_jacobian(angular_velocity_in_body, quat) dQuat_dSPQuat = Rotations.jacobian(QuatRotation, q) dW_dQuat * dQuat_dSPQuat end @inline function quaternion_derivative(q::QuatRotation, angular_velocity_in_body::AbstractVector) @boundscheck length(angular_velocity_in_body) == 3 || error("size mismatch") velocity_jacobian(quaternion_derivative, q) * angular_velocity_in_body end @inline function spquat_derivative(q::ModifiedRodriguesParam, angular_velocity_in_body::AbstractVector) @boundscheck length(angular_velocity_in_body) == 3 || error("size mismatch") velocity_jacobian(spquat_derivative, q) * angular_velocity_in_body end @inline function angular_velocity_in_body(q::QuatRotation, quat_derivative::AbstractVector) @boundscheck length(quat_derivative) == 4 || error("size mismatch") velocity_jacobian(angular_velocity_in_body, q) * quat_derivative end @inline function angular_velocity_in_body(q::ModifiedRodriguesParam, spq_derivative::AbstractVector) @boundscheck length(spq_derivative) == 3 || error("size mismatch") velocity_jacobian(angular_velocity_in_body, q) * spq_derivative end function linearized_rodrigues_vec(r::RotMatrix) # TODO: consider moving to Rotations x = (r[3, 2] - r[2, 3]) / 2 y = (r[1, 3] - r[3, 1]) / 2 z = (r[2, 1] - r[1, 2]) / 2 RotationVec(x, y, z) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
455
module URDF using RigidBodyDynamics using LightXML using StaticArrays using Rotations using DocStringExtensions using RigidBodyDynamics.Graphs using RigidBodyDynamics: Bounds, upper, lower using RigidBodyDynamics: has_loops, joint_to_predecessor using RigidBodyDynamics: DEFAULT_GRAVITATIONAL_ACCELERATION using LinearAlgebra: × export default_urdf_joint_types, parse_urdf, write_urdf include("parse.jl") include("write.jl") end # module
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
10605
""" $(SIGNATURES) Default mapping from URDF joint type name to `JointType` subtype used by [`parse_urdf`](@ref). """ function default_urdf_joint_types() Dict( "revolute" => Revolute, "continuous" => Revolute, "prismatic" => Prismatic, "floating" => QuaternionFloating, "fixed" => Fixed, "planar" => Planar ) end function parse_scalar(::Type{T}, e::XMLElement, name::String) where {T} parse(T, attribute(e, name)) end function parse_scalar(::Type{T}, e::XMLElement, name::String, default::String) where {T} parse(T, e == nothing ? default : attribute(e, name)) end function parse_vector(::Type{T}, e::Union{XMLElement, Nothing}, name::String, default::String) where {T} usedefault = e == nothing || attribute(e, name) == nothing # TODO: better handling of required attributes [parse(T, str) for str in split(usedefault ? default : attribute(e, name))] end function parse_inertia(::Type{T}, xml_inertia::XMLElement) where {T} ixx = parse_scalar(T, xml_inertia, "ixx", "0") ixy = parse_scalar(T, xml_inertia, "ixy", "0") ixz = parse_scalar(T, xml_inertia, "ixz", "0") iyy = parse_scalar(T, xml_inertia, "iyy", "0") iyz = parse_scalar(T, xml_inertia, "iyz", "0") izz = parse_scalar(T, xml_inertia, "izz", "0") @SMatrix [ixx ixy ixz; ixy iyy iyz; ixz iyz izz] end function parse_pose(::Type{T}, xml_pose::Nothing) where {T} rot = one(RotMatrix3{T}) trans = zero(SVector{3, T}) rot, trans end function parse_pose(::Type{T}, xml_pose::XMLElement) where {T} rpy = parse_vector(T, xml_pose, "rpy", "0 0 0") rot = RotMatrix(RotZYX(rpy[3], rpy[2], rpy[1])) trans = SVector{3}(parse_vector(T, xml_pose, "xyz", "0 0 0")) rot, trans end function parse_joint_type(::Type{T}, xml_joint::XMLElement, joint_types::AbstractDict{String}) where {T} urdf_joint_type = attribute(xml_joint, "type") joint_type = joint_types[urdf_joint_type] if urdf_joint_type == "revolute" || urdf_joint_type == "continuous" || urdf_joint_type == "prismatic" axis = SVector{3}(parse_vector(T, find_element(xml_joint, "axis"), "xyz", "1 0 0")) return joint_type(axis) elseif urdf_joint_type == "floating" || urdf_joint_type == "fixed" return joint_type{T}() elseif urdf_joint_type == "planar" urdf_axis = SVector{3}(parse_vector(T, find_element(xml_joint, "axis"), "xyz", "1 0 0")) # The URDF spec says that a planar joint allows motion in a # plane perpendicular to the axis. R = Rotations.rotation_between(SVector(0, 0, 1), urdf_axis) x_axis = R * SVector(1, 0, 0) y_axis = R * SVector(0, 1, 0) return joint_type(x_axis, y_axis) else error("joint type $(urdf_joint_type) not recognized") end end function parse_joint_bounds(jtype::JT, xml_joint::XMLElement) where {T, JT <: JointType{T}} position_bounds = fill(Bounds{T}(), num_positions(jtype)) velocity_bounds = fill(Bounds{T}(), num_velocities(jtype)) effort_bounds = fill(Bounds{T}(), num_velocities(jtype)) for element in get_elements_by_tagname(xml_joint, "limit") if has_attribute(element, "lower") position_bounds .= Bounds.(parse_scalar(T, element, "lower"), upper.(position_bounds)) end if has_attribute(element, "upper") position_bounds .= Bounds.(lower.(position_bounds), parse_scalar(T, element, "upper")) end if has_attribute(element, "velocity") v = parse_scalar(T, element, "velocity") velocity_bounds .= Bounds(-v, v) end if has_attribute(element, "effort") e = parse_scalar(T, element, "effort") effort_bounds .= Bounds(-e, e) end end position_bounds, velocity_bounds, effort_bounds end function parse_joint(::Type{T}, xml_joint::XMLElement, joint_types::AbstractDict{String}) where {T} name = attribute(xml_joint, "name") joint_type = parse_joint_type(T, xml_joint, joint_types) position_bounds, velocity_bounds, effort_bounds = parse_joint_bounds(joint_type, xml_joint) return Joint(name, joint_type; position_bounds=position_bounds, velocity_bounds=velocity_bounds, effort_bounds=effort_bounds) end function parse_inertia(::Type{T}, xml_inertial::XMLElement, frame::CartesianFrame3D) where {T} urdf_frame = CartesianFrame3D("inertia urdf helper") moment = parse_inertia(T, find_element(xml_inertial, "inertia")) com = zero(SVector{3, T}) mass = parse_scalar(T, find_element(xml_inertial, "mass"), "value", "0") inertia = SpatialInertia(urdf_frame, moment, com, mass) pose = parse_pose(T, find_element(xml_inertial, "origin")) transform(inertia, Transform3D(urdf_frame, frame, pose...)) end function parse_body(::Type{T}, xml_link::XMLElement, frame::CartesianFrame3D = CartesianFrame3D(attribute(xml_link, "name"))) where {T} xml_inertial = find_element(xml_link, "inertial") inertia = xml_inertial == nothing ? zero(SpatialInertia{T}, frame) : parse_inertia(T, xml_inertial, frame) linkname = attribute(xml_link, "name") # TODO: make sure link name is unique RigidBody(linkname, inertia) end function parse_root_link(mechanism::Mechanism{T}, xml_link::XMLElement, root_joint_type::JointType{T}=Fixed{T}()) where {T} parent = root_body(mechanism) body = parse_body(T, xml_link) joint = Joint("$(string(body))_to_world", root_joint_type) joint_to_parent = one(Transform3D{T}, frame_before(joint), default_frame(parent)) attach!(mechanism, parent, body, joint, joint_pose = joint_to_parent) end function parse_joint_and_link(mechanism::Mechanism{T}, xml_parent::XMLElement, xml_child::XMLElement, xml_joint::XMLElement, joint_types::AbstractDict{String}) where {T} parentname = attribute(xml_parent, "name") candidate_parents = collect(filter(b -> string(b) == parentname, non_root_bodies(mechanism))) # skip root (name not parsed from URDF) length(candidate_parents) == 1 || error("Duplicate name: $(parentname)") parent = first(candidate_parents) joint = parse_joint(T, xml_joint, joint_types) pose = parse_pose(T, find_element(xml_joint, "origin")) joint_to_parent = Transform3D(frame_before(joint), default_frame(parent), pose...) body = parse_body(T, xml_child, frame_after(joint)) attach!(mechanism, parent, body, joint, joint_pose = joint_to_parent) end """ $(SIGNATURES) Create a `Mechanism` by parsing a [URDF](https://wiki.ros.org/urdf/XML/model) file. Keyword arguments: * `scalar_type`: the scalar type used to store the `Mechanism`'s kinematic and inertial properties. Default: `Float64`. * `floating`: whether to use a floating joint as the root joint. Default: false. * `joint_types`: dictionary mapping URDF joint type names to `JointType` subtypes. Default: [`default_urdf_joint_types()`](@ref). * `root_joint_type`: the `JointType` instance used to connect the parsed `Mechanism` to the world. Default: an instance of the the joint type corresponding to the `floating` URDF joint type tag if `floating`, otherwise in an instance of the joint type for the `fixed` URDF joint type tag. * `remove_fixed_tree_joints`: whether to remove any fixed joints present in the kinematic tree using [`remove_fixed_tree_joints!`](@ref). Default: `true`. * `gravity`: gravitational acceleration as a 3-vector expressed in the `Mechanism`'s root frame Default: `$(DEFAULT_GRAVITATIONAL_ACCELERATION)`. """ function parse_urdf(filename::AbstractString; scalar_type::Type{T}=Float64, floating::Bool=false, joint_types::AbstractDict{String}=default_urdf_joint_types(), root_joint_type::JointType{T}=joint_types[floating ? "floating" : "fixed"]{scalar_type}(), remove_fixed_tree_joints=true, gravity::AbstractVector=DEFAULT_GRAVITATIONAL_ACCELERATION, revolute_joint_type=nothing, floating_joint_type=nothing) where T if revolute_joint_type !== nothing || floating_joint_type !== nothing """ The `revolute_joint_type` and `floating_joint_type` keyword arguments are no longer supported. Please use the `joint_types` keyword argument instead. """ |> error end if floating && !isfloating(root_joint_type) error("Ambiguous input arguments: `floating` specified, but `root_joint_type` is not a floating joint type.") end xdoc = parse_file(filename) xroot = LightXML.root(xdoc) @assert LightXML.name(xroot) == "robot" xml_links = get_elements_by_tagname(xroot, "link") xml_joints = get_elements_by_tagname(xroot, "joint") # create graph structure of XML elements graph = DirectedGraph{Vertex{XMLElement}, Edge{XMLElement}}() vertices = Vertex.(xml_links) for vertex in vertices add_vertex!(graph, vertex) end name_to_vertex = Dict(attribute(v.data, "name") => v for v in vertices) for xml_joint in xml_joints parent = name_to_vertex[attribute(find_element(xml_joint, "parent"), "link")] child = name_to_vertex[attribute(find_element(xml_joint, "child"), "link")] add_edge!(graph, parent, child, Edge(xml_joint)) end # create a spanning tree roots = collect(filter(v -> isempty(in_edges(v, graph)), vertices)) length(roots) != 1 && error("Can only handle a single root") tree = SpanningTree(graph, first(roots)) # create mechanism from spanning tree rootbody = RigidBody{T}("world") mechanism = Mechanism(rootbody, gravity=gravity) parse_root_link(mechanism, Graphs.root(tree).data, root_joint_type) for edge in edges(tree) parse_joint_and_link(mechanism, source(edge, tree).data, target(edge, tree).data, edge.data, joint_types) end if remove_fixed_tree_joints remove_fixed_tree_joints!(mechanism) end mechanism end @noinline function parse_urdf(scalar_type::Type, filename::AbstractString) # TODO: enable deprecation: # replacement = if scalar_type == Float64 # "parse_urdf(filename, remove_fixed_tree_joints=false)" # else # "parse_urdf(filename, scalar_type=$scalar_type, remove_fixed_tree_joints=false)" # end # msg = """ # `parse_urdf(scalar_type, filename)` is deprecated, use $replacement instead. # This is to reproduce the exact same behavior as before. # You may want to consider leaving `remove_fixed_tree_joints` to its default value (`true`). # """ # Base.depwarn(msg, :parse_urdf) parse_urdf(filename; scalar_type=scalar_type, remove_fixed_tree_joints=false) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
6943
function set_vector_attribute(element::XMLElement, attr::AbstractString, vec::AbstractVector) set_attribute(element, attr, join(vec, ' ')) end function to_urdf(body::RigidBody) xml_link = new_element("link") set_attribute(xml_link, "name", string(body)) isroot = !has_defined_inertia(body) if !isroot xml_inertial = new_child(xml_link, "inertial") xml_origin = new_child(xml_inertial, "origin") xml_mass = new_child(xml_inertial, "mass") xml_inertia = new_child(xml_inertial, "inertia") inertia = spatial_inertia(body) if inertia.mass > 0 origin = center_of_mass(inertia) centroidal = CartesianFrame3D() to_centroidal_frame = Transform3D(inertia.frame, centroidal, -origin.v) inertia = transform(inertia, to_centroidal_frame) @assert center_of_mass(inertia) ≈ Point3D(centroidal, zero(typeof(origin.v))) else origin = zero(center_of_mass(inertia)) end set_vector_attribute(xml_origin, "xyz", origin.v) set_vector_attribute(xml_origin, "rpy", zero(origin.v)) set_attribute(xml_mass, "value", inertia.mass) set_attribute(xml_inertia, "ixx", inertia.moment[1, 1]) set_attribute(xml_inertia, "ixy", inertia.moment[1, 2]) set_attribute(xml_inertia, "ixz", inertia.moment[1, 3]) set_attribute(xml_inertia, "iyy", inertia.moment[2, 2]) set_attribute(xml_inertia, "iyz", inertia.moment[2, 3]) set_attribute(xml_inertia, "izz", inertia.moment[3, 3]) end xml_link end function process_joint_type!(xml_joint::XMLElement, joint::Joint) if isfloating(joint) # handle this here instead of using dispatch to support user-defined # floating joint types out of the box set_attribute(xml_joint, "type", "floating") else throw(ArgumentError("Joint type $(typeof(joint_type(joint))) not handled.")) end xml_joint end function process_joint_type!(xml_joint::XMLElement, joint::Joint{<:Any, <:Fixed}) set_attribute(xml_joint, "type", "fixed") xml_joint end function process_joint_type!(xml_joint::XMLElement, joint::Joint{<:Any, <:Planar}) set_attribute(xml_joint, "type", "planar") jtype = joint_type(joint) xml_axis = new_child(xml_joint, "axis") set_vector_attribute(xml_axis, "xyz", jtype.x_axis × jtype.y_axis) xml_joint end function process_joint_type!(xml_joint::XMLElement, joint::Joint{T, JT}) where {T, JT<:Union{Revolute, Prismatic}} jtype = joint_type(joint) xml_axis = new_child(xml_joint, "axis") set_vector_attribute(xml_axis, "xyz", jtype.axis) qbounds, vbounds, τbounds = position_bounds(joint), velocity_bounds(joint), effort_bounds(joint) @assert length(qbounds) == length(vbounds) == length(τbounds) == 1 qbound, vbound, τbound = qbounds[1], vbounds[1], τbounds[1] @assert upper(vbound) == -lower(vbound) @assert upper(τbound) == -lower(τbound) realline = Bounds(-typemax(T), typemax(T)) xml_limit = new_child(xml_joint, "limit") set_position_limits = true if JT <: Revolute if qbound == realline set_attribute(xml_joint, "type", "continuous") set_position_limits = false # continuous joints don't allow `lower` and `upper` else set_attribute(xml_joint, "type", "revolute") end else # Prismatic set_attribute(xml_joint, "type", "prismatic") end if set_position_limits set_attribute(xml_limit, "lower", lower(qbound)) set_attribute(xml_limit, "upper", upper(qbound)) end set_attribute(xml_limit, "effort", upper(τbound)) set_attribute(xml_limit, "velocity", upper(vbound)) xml_joint end function to_urdf(joint::Joint, mechanism::Mechanism) parent = predecessor(joint, mechanism) child = successor(joint, mechanism) to_parent = joint_to_predecessor(joint) xyz = translation(to_parent) rpy = RotZYX(rotation(to_parent)) xml_joint = new_element("joint") set_attribute(xml_joint, "name", string(joint)) xml_parent = new_child(xml_joint, "parent") set_attribute(xml_parent, "link", string(parent)) xml_child = new_child(xml_joint, "child") set_attribute(xml_child, "link", string(child)) xml_origin = new_child(xml_joint, "origin") set_vector_attribute(xml_origin, "xyz", xyz) set_vector_attribute(xml_origin, "rpy", [rpy.theta3, rpy.theta2, rpy.theta1]) process_joint_type!(xml_joint, joint) xml_joint end function to_urdf(mechanism::Mechanism; robot_name::Union{Nothing, AbstractString}=nothing, include_root::Bool=true) @assert !has_loops(mechanism) xdoc = XMLDocument() xroot = create_root(xdoc, "robot") if robot_name !== nothing set_attribute(xroot, "name", robot_name) end bodies_to_include = include_root ? bodies(mechanism) : non_root_bodies(mechanism) for body in bodies(mechanism) !include_root && isroot(body, mechanism) && continue add_child(xroot, to_urdf(body)) end for joint in tree_joints(mechanism) !include_root && isroot(predecessor(joint, mechanism), mechanism) && continue add_child(xroot, to_urdf(joint, mechanism)) end xdoc end """ Serialize a `Mechanism` to the [URDF](https://wiki.ros.org/urdf/XML/model) file format. Limitations: * for `<link>` tags, only the `<inertial>` tag is written; there is no support for `<visual>` and `<collision>` tags. * for `<joint>` tags, only the `<origin>`, `<parent>`, `<child>`, and `<limit>` tags are written. There is no support for the `<calibration>` and `<safety_controller>` tags. These limitations are simply due to the fact that `Mechanism`s do not store the required information to write these tags. Keyword arguments: * `robot_name`: used to set the `name` attribute of the root `<robot>` tag in the URDF. Default: `nothing` (name attribute will not be set). * `include_root`: whether to include `root_body(mechanism)` in the URDF. If `false`, joints with `root_body(mechanism)` as their predecessor will also be omitted. Default: `true`. """ function write_urdf end const write_urdf_name_kwarg_doc = "Optionally, the `robot_name` keyword argument can be used to specify the robot's name." """ $(SIGNATURES) Write a URDF representation of `mechanism` to the stream `io` (a `Base.IO`). $write_urdf_name_kwarg_doc """ function write_urdf(io::IO, mechanism::Mechanism; robot_name=nothing, include_root=true) show(io, to_urdf(mechanism; robot_name=robot_name, include_root=include_root)) end """ $(SIGNATURES) Write a URDF representation of `mechanism` to a file. $write_urdf_name_kwarg_doc """ function write_urdf(filename::AbstractString, mechanism::Mechanism; robot_name=nothing, include_root=true) open(filename, "w") do io write_urdf(io, mechanism, robot_name=robot_name, include_root=include_root) end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
1133
using Test using LinearAlgebra using Random using RigidBodyDynamics using RigidBodyDynamics.Graphs using RigidBodyDynamics.Contact using RigidBodyDynamics.PDControl using Rotations using StaticArrays import Base.Iterators: filter import ForwardDiff import LightXML using RigidBodyDynamics: ModifiedRodriguesParam using BenchmarkTools: @ballocated include("test_exports.jl") include("test_graph.jl") include("test_custom_collections.jl") include("test_frames.jl") include("test_spatial.jl") include("test_contact.jl") include("test_urdf.jl") include("test_double_pendulum.jl") include("test_caches.jl") include("test_mechanism_algorithms.jl") include("test_simulate.jl") include("test_mechanism_modification.jl") include("test_pd_control.jl") if VERSION >= v"1.9" # The notebook tests rely on instantiating specific project manifests. # Attempting to do so on a version of Julia older than the one used to # create those manifests can cause errors in `Pkg.instantiate()`. include("test_notebooks.jl") @testset "benchmarks" begin @test begin include("../perf/runbenchmarks.jl"); true end end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
3165
module TestCaches using Test using RigidBodyDynamics using RigidBodyDynamics.Contact import Random function randmech() rand_tree_mechanism(Float64, QuaternionFloating{Float64}, [Revolute{Float64} for i = 1 : 5]..., [Fixed{Float64} for i = 1 : 5]..., [Prismatic{Float64} for i = 1 : 5]..., [Planar{Float64} for i = 1 : 5]..., [SPQuatFloating{Float64} for i = 1:2]..., [SinCosRevolute{Float64} for i = 1:2]... ) end function cachetest(cache, eltypefun) x64 = @inferred cache[Float64] @test eltypefun(x64) == Float64 @test cache[Float64] === x64 @test @allocated(cache[Float64]) == 0 x32 = @inferred cache[Float32] @test eltypefun(x32) == Float32 @test cache[Float32] === x32 @test @allocated(cache[Float32]) == 0 @test cache[Float64] === x64 @test @allocated(cache[Float64]) == 0 end @testset "caches (nthreads = $(Threads.nthreads()))" begin @testset "StateCache" begin Random.seed!(1) mechanism = randmech() cache = StateCache(mechanism) cachetest(cache, RigidBodyDynamics.state_vector_eltype) end @testset "DynamicsResultCache" begin @testset "Basic mechanism" begin Random.seed!(2) mechanism = randmech() cache = DynamicsResultCache(mechanism) cachetest(cache, result -> eltype(result.v̇)) end @testset "Mechanism with contact points (Issue #483)" begin Random.seed!(3) mechanism = randmech() contactmodel = SoftContactModel(hunt_crossley_hertz(k = 500e3), ViscoelasticCoulombModel(0.8, 20e3, 100.)) body = rand(bodies(mechanism)) add_contact_point!(body, ContactPoint(Point3D(default_frame(body), 0.0, 0.0, 0.0), contactmodel)) cache = DynamicsResultCache(mechanism) cachetest(cache, result -> eltype(result.v̇)) end end @testset "SegmentedVectorCache" begin Random.seed!(3) mechanism = randmech() state = MechanismState(mechanism) cache = SegmentedVectorCache(RigidBodyDynamics.ranges(velocity(state))) cachetest(cache, eltype) end @testset "StateCache multi-threaded (#548)" begin N = 2 mechanism = randmech() state_caches = [StateCache(mechanism) for _ = 1 : N] qs = let state = MechanismState(mechanism) [(rand_configuration!(state); copy(configuration(state))) for _ = 1 : N] end vs = [rand(num_velocities(mechanism)) for _ = 1 : N] Threads.@threads for i = 1 : N state = state_caches[i][Float64] set_configuration!(state, qs[i]) set_velocity!(state, vs[i]) end for i = 1 : N @test configuration(state_caches[i][Float64]) == qs[i] @test velocity(state_caches[i][Float64]) == vs[i] end Threads.@threads for i = 1 : N @test configuration(state_caches[i][Float64]) == qs[i] @test velocity(state_caches[i][Float64]) == vs[i] end end end end # module
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
662
@testset "contact" begin @testset "HalfSpace3D" begin Random.seed!(4) frame = CartesianFrame3D() point = Point3D(frame, rand(), rand(), rand()) normal = FreeVector3D(frame, 0., 0., 1.) halfspace = HalfSpace3D(point, normal) for i = 1 : 100 x = Point3D(frame, randn(), randn(), randn()) @test point_inside(halfspace, x) == (x.v[3] <= point.v[3]) ϕ, normal = detect_contact(halfspace, x) @test ϕ == separation(halfspace, x) @test isapprox(normal.v, ForwardDiff.gradient(xyz -> separation(halfspace, Point3D(frame, xyz)), x.v)) end end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
5762
using Test using RigidBodyDynamics import Random # A pathologically weird matrix which uses base -1 indexing # for its first dimension and base 2 indexing for its second struct NonOneBasedMatrix <: AbstractMatrix{Float64} m::Int n::Int end Base.size(m::NonOneBasedMatrix) = (m.m, m.n) Base.axes(m::NonOneBasedMatrix) = ((1:m.m) .- 2, (1:m.n) .+ 1) @testset "custom collections" begin @testset "nulldict" begin nd = RigidBodyDynamics.NullDict{Int, Int}() @test isempty(nd) @test length(nd) == 0 for element in nd @test false # should never be reached, since the nulldict is always empty end show(IOBuffer(), nd) end @testset "IndexDict" begin Int32Dict{V} = RigidBodyDynamics.IndexDict{Int32, Base.OneTo{Int32}, V} dict = Dict(Int32(2) => 4., Int32(1) => 3.) expected = Int32Dict{Float64}(Base.OneTo(Int32(2)), [3., 4.]) i32dict1 = @inferred Int32Dict(dict) @test i32dict1 == dict == expected @test keys(expected) === keys(i32dict1) @test values(expected) == values(i32dict1) i32dict2 = @inferred Int32Dict{Float64}(dict) @test i32dict2 == dict == expected @test keys(expected) === keys(i32dict2) @test values(expected) == values(i32dict2) end @testset "ConstDict" begin c = RigidBodyDynamics.ConstDict{Int}(2.0) @test c[1] == 2.0 @test c[-1] == 2.0 show(IOBuffer(), c) end @testset "SegmentedVector" begin x = [1., 2., 3., 4.] viewlength = i -> 2 xseg = SegmentedVector{Int}(x, 1 : 2, viewlength) @test segments(xseg)[1] == [1., 2.] @test segments(xseg)[2] == [3., 4.] @test length(segments(xseg)) == 2 yseg = similar(xseg, Int32) yseg .= 1 : 4 @test segments(yseg)[1] == [1, 2] @test segments(yseg)[2] == [3, 4] @test length(segments(yseg)) == 2 xseg2 = SegmentedVector(x, RigidBodyDynamics.IndexDict(Base.OneTo(2), [view(x, 1 : 3), view(x, 4 : 4)])) @test xseg2 isa SegmentedVector ranges2 = RigidBodyDynamics.CustomCollections.ranges(xseg2) @test ranges2[1] == 1 : 3 @test ranges2[2] == 4 : 4 @test xseg2 == xseg xseg3 = copy(xseg) @test xseg3 == xseg @test xseg3 isa SegmentedVector end @testset "SegmentedBlockDiagonalMatrix" begin Random.seed!(5) A = rand(10, 10) block_indices = [(1:1, 1:1), # square (2:4, 2:2), # non-square (5:4, 3:2), # empty (5:7, 3:6), # 2x2 (8:10, 7:10)] RigidBodyDynamics.CustomCollections.check_contiguous_block_ranges(A, block_indices) S = RigidBodyDynamics.SegmentedBlockDiagonalMatrix(A, block_indices) for (i, block) in enumerate(block_indices) @test S[block...] == RigidBodyDynamics.CustomCollections.blocks(S)[i] end A .= 0 for block in RigidBodyDynamics.CustomCollections.blocks(S) Random.rand!(block) end @testset "Malformed blocks" begin @testset "overlap" begin block_indices = [(1:1, 1:1), (2:4, 2:3), (5:4, 3:2), (5:7, 3:6), (8:10, 7:10)] @test_throws ArgumentError RigidBodyDynamics.CustomCollections.check_contiguous_block_ranges(A, block_indices) end @testset "out of bounds" begin block_indices = [(1:1, 0:1), (2:4, 2:2), (5:4, 3:2), (5:7, 3:6), (8:10, 7:10)] @test_throws ArgumentError RigidBodyDynamics.CustomCollections.check_contiguous_block_ranges(A, block_indices) block_indices = [(1:1, 1:1), (2:4, 2:2), (5:4, 3:2), (5:7, 3:6), (8:12, 7:10)] @test_throws ArgumentError RigidBodyDynamics.CustomCollections.check_contiguous_block_ranges(A, block_indices) end @testset "gap" begin block_indices = [(1:1, 1:1), (5:4, 3:2), (5:7, 3:6), (8:10, 7:10)] @test_throws ArgumentError RigidBodyDynamics.CustomCollections.check_contiguous_block_ranges(A, block_indices) end end @testset "Nonstandard indexing" begin M = NonOneBasedMatrix(5, 5) block_indices = [(-1:1, 2:3), (2:3, 4:6)] RigidBodyDynamics.CustomCollections.check_contiguous_block_ranges(M, block_indices) end @testset "mul! specialization" begin M = rand(20, size(S, 1)) C = M * S @test C ≈ M * parent(S) atol=1e-15 M = rand(size(S, 2), 20) C = S * M @test C ≈ parent(S) * M atol=1e-15 @test_throws DimensionMismatch rand(20, size(S, 1) + 1) * M @test_throws DimensionMismatch rand(size(A, 2) + 1, 20) * M end end @testset "UnorderedPair" begin UnorderedPair = RigidBodyDynamics.CustomCollections.UnorderedPair p1 = UnorderedPair(1, 2) p2 = UnorderedPair(2, 1) @test p1 == p2 @test hash(p1) == hash(p2) @test p1 != UnorderedPair(3, 1) dict = Dict(p1 => 3) @test dict[p2] == 3 end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
4175
@testset "double pendulum" begin Random.seed!(6) lc1 = -0.5 l1 = -1. m1 = 1. I1 = 0.333 # about joint instead of CoM in URDF lc2 = -1. l2 = -2. m2 = 1. I2 = 1.33 # about joint instead of CoM in URDF g = -9.81 axis = SVector(0., 1., 0.) double_pendulum = Mechanism(RigidBody{Float64}("world"); gravity = SVector(0, 0, g)) world = root_body(double_pendulum) # create first body and attach it to the world via a revolute joint inertia1 = SpatialInertia(CartesianFrame3D("upper_link"), moment=I1 * axis * axis', com=SVector(0, 0, lc1), mass=m1) body1 = RigidBody(inertia1) joint1 = Joint("shoulder", Revolute(axis)) joint1_to_world = one(Transform3D, joint1.frame_before, default_frame(world)) attach!(double_pendulum, world, body1, joint1, joint_pose = joint1_to_world) inertia2 = SpatialInertia(CartesianFrame3D("lower_link"), moment=I2 * axis * axis', com=SVector(0, 0, lc2), mass=m2) body2 = RigidBody(inertia2) joint2 = Joint("elbow", Revolute(axis)) joint2_to_body1 = Transform3D(joint2.frame_before, default_frame(body1), SVector(0, 0, l1)) attach!(double_pendulum, body1, body2, joint2, joint_pose = joint2_to_body1) @test findbody(double_pendulum, string(body1)) == body1 @test_throws ErrorException findbody(double_pendulum, "bla") @test findbody(double_pendulum, BodyID(body2)) == body2 @test findjoint(double_pendulum, string(joint2)) == joint2 @test_throws ErrorException findjoint(double_pendulum, "bla") @test findjoint(double_pendulum, JointID(joint2)) == joint2 x = MechanismState(double_pendulum) rand!(x) # from http://underactuated.csail.mit.edu/underactuated.html?chapter=3 q1 = configuration(x, joint1)[1] q2 = configuration(x, joint2)[1] v1 = velocity(x, joint1)[1] v2 = velocity(x, joint2)[1] c1 = cos(q1) c2 = cos(q2) s1 = sin(q1) s2 = sin(q2) s12 = sin(q1 + q2) T1 = 1/2 * I1 * v1^2 T2 = 1/2 * (m2 * l1^2 + I2 + 2 * m2 * l1 * lc2 * c2) * v1^2 + 1/2 * I2 * v2^2 + (I2 + m2 * l1 * lc2 * c2) * v1 * v2 M11 = I1 + I2 + m2 * l1^2 + 2 * m2 * l1 * lc2 * c2 M12 = I2 + m2 * l1 * lc2 * c2 M22 = I2 M = [M11 M12; M12 M22] C11 = -2 * m2 * l1 * lc2 * s2 * v2 C12 = -m2 * l1 * lc2 * s2 * v2 C21 = m2 * l1 * lc2 * s2 * v1 C22 = 0 C = [C11 C12; C21 C22] G = [m1 * g * lc1 * s1 + m2 * g * (l1 * s1 + lc2 * s12); m2 * g * lc2 * s12] v̇ = similar(velocity(x)) rand!(v̇) τ = inverse_dynamics(x, v̇) v = velocity(x) @test isapprox(T1, kinetic_energy(x, body1), atol = 1e-12) @test isapprox(T2, kinetic_energy(x, body2), atol = 1e-12) @test isapprox(M, mass_matrix(x), atol = 1e-12) @test isapprox(τ, M * v̇ + C * v + G, atol = 1e-12) # compare against URDF for revolute_joint_type in [Revolute, SinCosRevolute] double_pendulum_urdf = parse_urdf(joinpath(@__DIR__, "urdf", "Acrobot.urdf"), remove_fixed_tree_joints=false, joint_types=push!(default_urdf_joint_types(), "revolute" => revolute_joint_type)) x_urdf = MechanismState(double_pendulum_urdf) for (i, j) in enumerate(joints(double_pendulum)) urdf_joints = collect(joints(double_pendulum_urdf)) index = findfirst(joint -> string(joint) == string(j), urdf_joints) j_urdf = urdf_joints[index] set_configuration!(x_urdf, j_urdf, configuration(x, j)[1]) set_velocity!(x_urdf, j_urdf, velocity(x, j)) end v̇ = similar(velocity(x_urdf)) rand!(v̇) τ = inverse_dynamics(x_urdf, v̇) urdf_bodies = collect(bodies(double_pendulum_urdf)) urdf_upper_link = urdf_bodies[findfirst(b -> string(b) == string(body1), urdf_bodies)] urdf_lower_link = urdf_bodies[findfirst(b -> string(b) == string(body2), urdf_bodies)] @test isapprox(T1, kinetic_energy(x_urdf, urdf_upper_link), atol = 1e-12) @test isapprox(T2, kinetic_energy(x_urdf, urdf_lower_link), atol = 1e-12) @test isapprox(M, mass_matrix(x_urdf), atol = 1e-12) @test isapprox(τ, M * v̇ + C * v + G, atol = 1e-12) end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
185
@testset "exports" begin # Ensure that every exported name is actually defined for name in names(RigidBodyDynamics) @test isdefined(RigidBodyDynamics, name) end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
1497
@testset "frames" begin Random.seed!(7) f1name = "1" f1 = CartesianFrame3D(f1name) f2 = CartesianFrame3D() f3 = CartesianFrame3D() @test string(f1) == f1name string(f2) # just to make sure it doesn't crash @test f2 != f3 @boundscheck begin # only throws when bounds checks are enabled: @test_throws ArgumentError @framecheck(f1, f2) @test_throws ArgumentError @framecheck(f2, f3) @test_throws ArgumentError @framecheck(f2, (f1, f3)) end @framecheck(f1, f1) @framecheck(f2, (f2, f3)) t1 = rand(Transform3D, f2, f1) @test isapprox(t1 * inv(t1), one(Transform3D, f1)) @test isapprox(inv(t1) * t1, one(Transform3D, f2)) @test isapprox(t1 * Point3D(Float64, f2), Point3D(f1, translation(t1))) p = rand(Point3D, Float64, f2) v = FreeVector3D(f2, p.v) @test isapprox(inv(t1) * (t1 * p), p) @test isapprox(inv(t1) * (t1 * v), v) @test isapprox(t1 * p - t1 * v, Point3D(f1, translation(t1))) @test_throws DimensionMismatch Point3D(f2, rand(2)) @test_throws DimensionMismatch Point3D(f2, rand(4)) @test isapprox(transform(p, t1), t1 * p) @test isapprox(t1 \ (t1 * p), p) @test isapprox(transform(v, t1), t1 * v) @test isapprox(t1 \ (t1 * v), v) @test isapprox(p, Point3D(p.frame, p.v[1], p.v[2], p.v[3])) @test isapprox(-v, zero(v) - v) @test isapprox(norm(v), sqrt(dot(v, v))) show(devnull, t1) show(devnull, p) show(devnull, v) end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
15751
Graphs.flip_direction(edge::Edge{Int32}) = Edge(-edge.data) @testset "graphs" begin @testset "disconnected" begin Random.seed!(8) graph = DirectedGraph{Vertex{Int64}, Edge{Float64}}() verts = [Vertex(rand(Int64)) for i = 1 : 10] for v in verts add_vertex!(graph, v) end @test num_vertices(graph) == length(verts) @test num_edges(graph) == 0 for v in verts @test length(in_edges(v, graph)) == 0 @test length(out_edges(v, graph)) == 0 @test length(in_neighbors(v, graph)) == 0 @test length(out_neighbors(v, graph)) == 0 end @test isempty(setdiff(vertices(graph), verts)) @test isempty(edges(graph)) show(devnull, graph) end @testset "tree graph" begin Random.seed!(9) graph = DirectedGraph{Vertex{Int64}, Edge{Float64}}() root = Vertex(rand(Int64)) add_vertex!(graph, root) nedges = 15 for i = 1 : nedges parent = rand(vertices(graph)) child = Vertex(rand(Int64)) edge = Edge(rand()) add_edge!(graph, parent, child, edge) end @test num_vertices(graph) == nedges + 1 @test num_edges(graph) == nedges for v in vertices(graph) if v == root @test length(in_edges(v, graph)) == 0 @test length(out_edges(v, graph)) > 0 @test length(in_neighbors(v, graph)) == 0 @test length(out_neighbors(v, graph)) > 0 else @test length(in_edges(v, graph)) == 1 @test length(in_neighbors(v, graph)) == 1 end end show(devnull, graph) end @testset "remove_vertex!" begin Random.seed!(10) graph = DirectedGraph{Vertex{Int64}, Edge{Float64}}() edge = Edge(rand()) add_edge!(graph, Vertex(rand(Int64)), Vertex(rand(Int64)), edge) for v in vertices(graph) @test_throws ErrorException remove_vertex!(graph, v) end graph = DirectedGraph{Vertex{Int64}, Edge{Float64}}() for i = 1 : 100 add_vertex!(graph, Vertex(i)) end for i = 1 : num_vertices(graph) - 1 add_edge!(graph, rand(vertices(graph)), rand(vertices(graph)), Edge(Float64(i))) end original = deepcopy(graph) vertex = rand(collect(filter(v -> isempty(in_edges(v, graph)) && isempty(out_edges(v, graph)), vertices(graph)))) remove_vertex!(graph, vertex) @test vertex ∉ vertices(graph) for v in vertices(graph) v_orig = vertices(original)[findfirst(v_orig -> v.data == v_orig.data, vertices(original))] for (e, e_orig) in zip(in_edges(v, graph), in_edges(v_orig, original)) @test e.data == e_orig.data end for (e, e_orig) in zip(out_edges(v, graph), out_edges(v_orig, original)) @test e.data == e_orig.data end end end @testset "remove_edge!" begin Random.seed!(11) graph = DirectedGraph{Vertex{Int64}, Edge{Float64}}() for i = 1 : 100 add_vertex!(graph, Vertex(i)) end for i = 1 : num_vertices(graph) - 1 add_edge!(graph, rand(vertices(graph)), rand(vertices(graph)), Edge(Float64(i))) end original = deepcopy(graph) edge = rand(edges(graph)) remove_edge!(graph, edge) @test edge ∉ edges(graph) @test num_edges(graph) == num_edges(original) - 1 for v in vertices(graph) @test edge ∉ in_edges(v, graph) @test edge ∉ out_edges(v, graph) end for e in edges(graph) e_orig = edges(original)[findfirst(e_orig -> e.data == e_orig.data, edges(original))] @test source(e, graph).data == source(e_orig, original).data @test target(e, graph).data == target(e_orig, original).data end end @testset "rewire!" begin Random.seed!(12) graph = DirectedGraph{Vertex{Int64}, Edge{Float64}}() for i = 1 : 100 add_vertex!(graph, Vertex(i)) end for i = 1 : num_vertices(graph) - 1 add_edge!(graph, rand(vertices(graph)), rand(vertices(graph)), Edge(Float64(i))) end original = deepcopy(graph) edge = rand(edges(graph)) oldsource = source(edge, graph) oldtarget = target(edge, graph) non_source_vertices = delete!(Set(vertices(graph)), oldsource) non_target_vertices = delete!(Set(vertices(graph)), oldtarget) newsource = rand(collect(non_source_vertices)) newtarget = rand(collect(non_target_vertices)) rewire!(graph, edge, newsource, newtarget) @test source(edge, graph) == newsource @test target(edge, graph) == newtarget @test edge ∈ out_edges(newsource, graph) @test edge ∈ in_edges(newtarget, graph) @test edge ∉ out_edges(oldsource, graph) @test edge ∉ in_edges(oldtarget, graph) @test map(x -> x.data, vertices(original)) == map(x -> x.data, vertices(graph)) for e in filter(e -> e != edge, edges(graph)) e_orig = edges(original)[findfirst(e_orig -> e.data == e_orig.data, edges(original))] @test source(e, graph).data == source(e_orig, original).data @test target(e, graph).data == target(e_orig, original).data end end @testset "replace_edge!" begin Random.seed!(13) graph = DirectedGraph{Vertex{Int64}, Edge{Float64}}() for i = 1 : 100 add_vertex!(graph, Vertex(i)) end for i = 1 : num_vertices(graph) - 1 add_edge!(graph, rand(vertices(graph)), rand(vertices(graph)), Edge(Float64(i))) end original = deepcopy(graph) for i = 1 : 10 old_edge = rand(edges(graph)) src = source(old_edge, graph) dest = target(old_edge, graph) new_edge = Edge(NaN) replace_edge!(graph, old_edge, new_edge) @test Graphs.edge_index(old_edge) == -1 @test all(map(x -> x.data, vertices(graph)) .== map(x -> x.data, vertices(original))) @test new_edge ∈ in_edges(dest, graph) @test old_edge ∉ in_edges(dest, graph) @test new_edge ∈ out_edges(src, graph) @test old_edge ∉ out_edges(src, graph) @test source(new_edge, graph) == src @test target(new_edge, graph) == dest @test isnan(new_edge.data) end end @testset "SpanningTree" begin Random.seed!(14) rootdata = 0 # graph1: tree grown incrementally graph1 = DirectedGraph{Vertex{Int64}, Edge{Int32}}() root1 = Vertex(rootdata) add_vertex!(graph1, root1) tree1 = SpanningTree(graph1, root1) # graph2: tree constructed after graph is built graph2 = DirectedGraph{Vertex{Int64}, Edge{Int32}}() root2 = Vertex(rootdata) add_vertex!(graph2, root2) nedges = 15 for i = 1 : nedges parentind = rand(1 : num_vertices(graph1)) childdata = i edgedata = Int32(i + 3) add_edge!(tree1, vertices(tree1)[parentind], Vertex(childdata), Edge(edgedata)) add_edge!(graph2, vertices(graph2)[parentind], Vertex(childdata), Edge(edgedata)) end tree2 = SpanningTree(graph2, root2) @test all(map(x -> x.data, vertices(tree1)) == map(x -> x.data, vertices(tree2))) for (v1, v2) in zip(vertices(tree1), vertices(tree2)) if v1 == root(tree1) @test v2 == root(tree2) else @test edge_to_parent(v1, tree1).data == edge_to_parent(v2, tree2).data outedgedata1 = map(x -> x.data, collect(edges_to_children(v1, tree1))) outedgedata2 = map(x -> x.data, collect(edges_to_children(v2, tree2))) @test isempty(setdiff(outedgedata1, outedgedata2)) @test isempty(setdiff(out_edges(v1, graph1), edges_to_children(v1, tree1))) @test isempty(setdiff(out_edges(v2, graph2), edges_to_children(v2, tree2))) end end tree = tree1 show(devnull, tree) @test_throws AssertionError add_edge!(tree, rand(vertices(tree)), rand(vertices(tree)), Edge(rand(Int32))) for src in vertices(tree) for dest in vertices(tree) src_ancestors = ancestors(src, tree) dest_ancestors = ancestors(dest, tree) lca = lowest_common_ancestor(src, dest, tree) p = TreePath(src, dest, tree) show(devnull, p) @inferred collect(p) @test source(p) == src @test target(p) == dest source_to_lca = collect(edge for edge in p if direction(edge, p) == PathDirections.up) target_to_lca = reverse!(collect(edge for edge in p if direction(edge, p) == PathDirections.down)) for (v, v_ancestors, pathsegment) in [(src, src_ancestors, source_to_lca); (dest, dest_ancestors, target_to_lca)] if v == root(tree) @test tree_index(v, tree) == 1 @test lca == v @test length(v_ancestors) == 1 @test isempty(pathsegment) end for v_ancestor in v_ancestors @test tree_index(v_ancestor, tree) <= tree_index(v, tree) end @test lca ∈ v_ancestors if v != lca @test source(last(pathsegment), tree) == lca end end for v in intersect(src_ancestors, dest_ancestors) @test tree_index(v, tree) <= tree_index(lca, tree) if v != lca @test v ∉ (v -> source(v, tree)).(source_to_lca) @test v ∉ (v -> source(v, tree)).(target_to_lca) end end for v in setdiff(src_ancestors, dest_ancestors) @test tree_index(v, tree) > tree_index(lca, tree) end end end for i = 1 : 10 old_edge = rand(edges(tree)) src = source(old_edge, tree) dest = target(old_edge, tree) old_id = Graphs.edge_index(old_edge) # make sure that replacing edge with itself doesn't mess with anything replace_edge!(tree, old_edge, old_edge) @test source(old_edge, tree) == src @test target(old_edge, tree) == dest @test Graphs.edge_index(old_edge) == old_id # replace with a new edge d = Int32(-10 * i) new_edge = Edge(d) replace_edge!(tree, old_edge, new_edge) @test Graphs.edge_index(old_edge) == -1 @test new_edge ∈ in_edges(dest, tree) @test old_edge ∉ in_edges(dest, tree) @test new_edge ∈ out_edges(src, tree) @test old_edge ∉ out_edges(src, tree) @test source(new_edge, tree) == src @test target(new_edge, tree) == dest @test new_edge.data == d @test edge_to_parent(dest, tree) == new_edge @test new_edge ∈ edges_to_children(src, tree) end original = deepcopy(graph2) edgemap = Dict(zip(edges(original), edges(graph2))) newroot = rand(setdiff(vertices(graph2), [root2])) flipped_edge_map = Dict{Edge{Int32}, Edge{Int32}}() newtree = SpanningTree(graph2, newroot, flipped_edge_map) @test !isempty(flipped_edge_map) for (oldedge, newedge) in edgemap flipped = haskey(flipped_edge_map, newedge) if flipped newedge = flipped_edge_map[newedge] end old_source_ind = Graphs.vertex_index(source(oldedge, original)) old_target_ind = Graphs.vertex_index(target(oldedge, original)) new_source_ind = Graphs.vertex_index(source(newedge, graph2)) new_target_ind = Graphs.vertex_index(target(newedge, graph2)) if flipped @test oldedge.data == -newedge.data @test new_source_ind == old_target_ind @test new_target_ind == old_source_ind else @test oldedge.data == newedge.data @test new_source_ind == old_source_ind @test new_target_ind == old_target_ind end end end @testset "subtree_vertices" begin graph = DirectedGraph{Vertex{Int64}, Edge{Int32}}() root = Vertex(0) add_vertex!(graph, root) tree = SpanningTree(graph, root) for i = 1 : 30 parent = vertices(tree)[rand(1 : num_vertices(graph))] child = Vertex(i) edge = Edge(Int32(i + 3)) add_edge!(tree, parent, child, edge) end for subtree_root in vertices(tree) subtree = subtree_vertices(subtree_root, tree) for vertex in vertices(tree) @test (vertex ∈ subtree) == (subtree_root ∈ ancestors(vertex, tree)) end end end @testset "reindex!" begin Random.seed!(15) graph = DirectedGraph{Vertex{Int64}, Edge{Float64}}() for i = 1 : 100 add_vertex!(graph, Vertex(i)) end for i = 1 : num_vertices(graph) - 1 add_edge!(graph, rand(vertices(graph)), rand(vertices(graph)), Edge(Float64(i))) end newvertices = shuffle(vertices(graph)) newedges = shuffle(edges(graph)) reindex!(graph, newvertices, newedges) @test all(vertices(graph) .== newvertices) @test all(edges(graph) .== newedges) @test all(Graphs.vertex_index.(vertices(graph)) .== 1 : num_vertices(graph)) @test all(Graphs.edge_index.(edges(graph)) .== 1 : num_edges(graph)) end @testset "map-like constructor" begin Random.seed!(16) graph = DirectedGraph{Vertex{Int32}, Edge{Float32}}() for i = Int32(1) : Int32(100) add_vertex!(graph, Vertex(i)) end for i = 1 : num_vertices(graph) - 1 add_edge!(graph, rand(vertices(graph)), rand(vertices(graph)), Edge(Float32(i))) end mappedgraph = DirectedGraph(x -> Vertex(Int64(x.data), x.id), x -> Edge(Float64(x.data), x.id), graph) @test vertextype(mappedgraph) == Vertex{Int64} @test edgetype(mappedgraph) == Edge{Float64} @test all(v1.data == v2.data for (v1, v2) in zip(vertices(graph), vertices(mappedgraph))) @test all(e1.data == e2.data for (e1, e2) in zip(edges(graph), edges(mappedgraph))) @test all(source(e1, graph).data == source(e2, mappedgraph).data for (e1, e2) in zip(edges(graph), edges(mappedgraph))) @test all(target(e1, graph).data == target(e2, mappedgraph).data for (e1, e2) in zip(edges(graph), edges(mappedgraph))) inedgesmatch(v1, v2) = all(e1.data == e2.data for (e1, e2) in zip(in_edges(v1, graph), in_edges(v2, mappedgraph))) @test all(inedgesmatch(v1, v2) for (v1, v2) in zip(vertices(graph), vertices(mappedgraph))) outedgesmatch(v1, v2) = all(e1.data == e2.data for (e1, e2) in zip(out_edges(v1, graph), out_edges(v2, mappedgraph))) @test all(outedgesmatch(v1, v2) for (v1, v2) in zip(vertices(graph), vertices(mappedgraph))) end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
38475
function randmech() rand_tree_mechanism(Float64, QuaternionFloating{Float64}, [Revolute{Float64} for i = 1 : 5]..., [Fixed{Float64} for i = 1 : 5]..., [Prismatic{Float64} for i = 1 : 5]..., [Planar{Float64} for i = 1 : 5]..., [SPQuatFloating{Float64} for i = 1:2]..., [SinCosRevolute{Float64} for i = 1:2]... ) end @testset "mechanism algorithms" begin @testset "show" begin Random.seed!(17) mechanism = randmech() x = MechanismState(mechanism) rand!(x) mechanism_with_loops = deepcopy(mechanism) for i = 1 : 5 pred = rand(bodies(mechanism_with_loops)) succ = rand(bodies(mechanism_with_loops)) joint = Joint("non-tree-$i", Fixed{Float64}()) attach!(mechanism_with_loops, pred, succ, joint) end show(devnull, mechanism_with_loops) for joint in joints(mechanism_with_loops) show(devnull, joint) show(IOContext(devnull, :compact => true), joint) end for body in bodies(mechanism_with_loops) show(devnull, body) show(IOContext(devnull, :compact => true), body) end show(devnull, x) end @testset "supports" begin Random.seed!(25) mechanism = randmech() mc_mechanism = maximal_coordinates(mechanism) for m in [mechanism, mc_mechanism] state = MechanismState(m) for body in bodies(m) body_ancestors = RigidBodyDynamics.Graphs.ancestors(body, m.tree) for joint in tree_joints(m) @test RigidBodyDynamics.supports(joint, body, state) == (successor(joint, m) ∈ body_ancestors) end for joint in non_tree_joints(m) @test !RigidBodyDynamics.supports(joint, body, state) end end end end @testset "basic stuff" begin Random.seed!(18) mechanism = randmech() for joint in joints(mechanism) @test eltype(joint_type(joint)) == Float64 end x = MechanismState(mechanism) rand!(x) q = vcat([configuration(x, joint) for joint in tree_joints(mechanism)]...) v = vcat([velocity(x, joint) for joint in tree_joints(mechanism)]...) @test q == configuration(x) @test v == velocity(x) zero_configuration!(x) set_configuration!(x, q) @test q == configuration(x) zero_velocity!(x) set_velocity!(x, v) @test v == velocity(x) qcopy = copy(configuration(x)) zero_configuration!(x) for joint in joints(mechanism) set_configuration!(x, joint, qcopy[configuration_range(x, joint)]) end @test q == configuration(x) vcopy = copy(velocity(x)) zero_velocity!(x) for joint in joints(mechanism) set_velocity!(x, joint, vcopy[velocity_range(x, joint)]) end @test v == velocity(x) zero!(x) copyto!(x, [q; v]) @test q == configuration(x) @test v == velocity(x) q2 = rand(num_positions(mechanism)) v2 = rand(num_velocities(mechanism)) q2copy = deepcopy(q2) v2copy = deepcopy(v2) x2 = MechanismState(mechanism, q2, v2) @test parent(configuration(x2)) === q2 @test parent(velocity(x2)) === v2 @test all(configuration(x2) .== q2copy) @test all(velocity(x2) .== v2copy) @test @inferred(num_positions(mechanism)) == num_positions(x) @test @inferred(num_velocities(mechanism)) == num_velocities(x) for joint in tree_joints(mechanism) for i in configuration_range(x, joint) @test RigidBodyDynamics.configuration_index_to_joint_id(x, i) == JointID(joint) end for i in velocity_range(x, joint) @test RigidBodyDynamics.velocity_index_to_joint_id(x, i) == JointID(joint) end end rand!(x) q = configuration(x) @test q != qcopy for joint in tree_joints(mechanism) q[joint] .= qcopy[joint] end @test q == qcopy end @testset "copyto! / Vector" begin Random.seed!(19) mechanism = randmech() x1 = MechanismState(mechanism) rand!(x1) @test Vector(x1) == [configuration(x1); velocity(x1); additional_state(x1)] x2 = MechanismState(mechanism) rand!(x2) copyto!(x1, x2) @test Vector(x1) == Vector(x2) x3 = MechanismState(mechanism) copyto!(x3, Vector(x2)) @test Vector(x3) == Vector(x2) @test Vector{Float32}(x1) isa Vector{Float32} @test Vector{Float32}(x1) ≈ Vector(x1) atol=1e-6 @test Array(x1) == Array{Float64}(x1) == convert(Array, x1) == convert(Array{Float64}, x1) @test Vector(x1) == Vector{Float64}(x1) == convert(Vector, x1) == convert(Vector{Float64}, x1) end @testset "q̇ <-> v" begin Random.seed!(20) mechanism = randmech() x = MechanismState(mechanism) rand!(x) q = configuration(x) q̇ = configuration_derivative(x) v = velocity(x) for joint in joints(mechanism) qjoint = configuration(x, joint) q̇joint = q̇[configuration_range(x, joint)] vjoint = velocity(x, joint) vjoint_from_q̇ = similar(vjoint) configuration_derivative_to_velocity!(vjoint_from_q̇, joint, qjoint, q̇joint) @test isapprox(vjoint, vjoint_from_q̇; atol = 1e-12) end Jq̇_to_v = RigidBodyDynamics.configuration_derivative_to_velocity_jacobian(x) Jv_to_q̇ = RigidBodyDynamics.velocity_to_configuration_derivative_jacobian(x) for i in 1:10 rand!(x) q = configuration(x) q̇ = configuration_derivative(x) v = velocity(x) RigidBodyDynamics.configuration_derivative_to_velocity_jacobian!(Jq̇_to_v, x) RigidBodyDynamics.velocity_to_configuration_derivative_jacobian!(Jv_to_q̇, x) @test Jq̇_to_v * q̇ ≈ v @test Jv_to_q̇ * v ≈ q̇ @test @allocated(RigidBodyDynamics.configuration_derivative_to_velocity_jacobian!(Jq̇_to_v, x)) == 0 @test @allocated(RigidBodyDynamics.velocity_to_configuration_derivative_jacobian!(Jv_to_q̇, x)) == 0 for joint in joints(mechanism) qrange = configuration_range(x, joint) vrange = velocity_range(x, joint) qj = q[qrange] q̇j = q̇[qrange] vj = v[vrange] Jv_to_q̇_j = RigidBodyDynamics.velocity_to_configuration_derivative_jacobian(joint, qj) Jq̇_to_v_j = RigidBodyDynamics.configuration_derivative_to_velocity_jacobian(joint, qj) if num_velocities(joint) > 0 @test Jv_to_q̇_j * vj ≈ q̇j @test Jq̇_to_v_j * q̇j ≈ vj else @test size(Jv_to_q̇_j) == (0, 0) @test size(Jq̇_to_v_j) == (0, 0) end end end end @testset "set_configuration! / set_velocity!" begin Random.seed!(21) mechanism = randmech() x = MechanismState(mechanism) for joint in joints(mechanism) qjoint = rand(num_positions(joint)) set_configuration!(x, joint, qjoint) @test configuration(x, joint) == qjoint @test configuration(x, joint) !== qjoint vjoint = rand(num_velocities(joint)) set_velocity!(x, joint, vjoint) @test velocity(x, joint) == vjoint @test velocity(x, joint) !== vjoint if joint_type(joint) isa QuaternionFloating tf = rand(Transform3D{Float64}, frame_after(joint), frame_before(joint)) set_configuration!(x, joint, tf) @test RigidBodyDynamics.joint_transform(joint, configuration(x, joint)) ≈ tf atol = 1e-12 # TODO: the frame stuff is kind of awkward here. twist = RigidBodyDynamics.joint_twist(joint, configuration(x, joint), velocity(x, joint)) twist = rand(Twist{Float64}, frame_after(joint), frame_before(joint), frame_after(joint)) set_velocity!(x, joint, twist) twist_back = RigidBodyDynamics.joint_twist(joint, configuration(x, joint), velocity(x, joint)) @test twist_back.angular ≈ twist.angular atol = 1e-12 @test twist_back.linear ≈ twist.linear atol = 1e-12 end if joint_type(joint) isa Revolute || joint_type(joint) isa Prismatic qj = rand() set_configuration!(x, joint, qj) @test configuration(x, joint)[1] == qj vj = rand() set_velocity!(x, joint, vj) @test velocity(x, joint)[1] == vj end if joint_type(joint) isa QuaternionSpherical quat = rand(QuatRotation{Float64}) set_configuration!(x, joint, quat) tf = RigidBodyDynamics.joint_transform(joint, configuration(x, joint)) @test QuatRotation(rotation(tf)) ≈ quat atol = 1e-12 end if joint_type(joint) isa SinCosRevolute qj = rand() set_configuration!(x, joint, qj) @test SVector(sincos(qj)) == configuration(x, joint) vj = rand() set_velocity!(x, joint, vj) @test velocity(x, joint)[1] == vj end end end @testset "normalize_configuration!" begin Random.seed!(22) mechanism = randmech() let x = MechanismState(mechanism) # required to achieve zero allocations configuration(x) .= 1 for joint in joints(mechanism) qjoint = configuration(x, joint) requires_normalization = num_positions(joint) != num_velocities(joint) # TODO: not quite the right thing to check for @test requires_normalization != RigidBodyDynamics.is_configuration_normalized(joint, qjoint) end normalize_configuration!(x) for joint in joints(mechanism) @test RigidBodyDynamics.is_configuration_normalized(joint, configuration(x, joint)) end allocs = @allocated normalize_configuration!(x) @test allocs == 0 end end @testset "joint_torque! / motion_subspace" begin Random.seed!(23) mechanism = randmech() x = MechanismState(mechanism) rand!(x) for joint in tree_joints(mechanism) body = successor(joint, mechanism) qjoint = configuration(x, joint) wrench = rand(Wrench{Float64}, frame_after(joint)) τ = Vector{Float64}(undef, num_velocities(joint)) RigidBodyDynamics.joint_torque!(τ, joint, qjoint, wrench) S = motion_subspace(joint, configuration(x, joint)) @test isapprox(τ, torque(S, wrench)) end end @testset "isfloating" begin Random.seed!(24) mechanism = randmech() x = MechanismState(mechanism) rand!(x) for joint in joints(mechanism) num_positions(joint) == 0 && continue # https://github.com/JuliaLang/julia/issues/26578 S = motion_subspace(joint, configuration(x, joint)) @test isfloating(joint) == (rank(Array(S)) == 6) @test isfloating(joint) == (num_constraints(joint) == 0) end end @testset "geometric_jacobian / relative_twist" begin Random.seed!(25) mechanism = randmech() x = MechanismState(mechanism) rand!(x) frame = CartesianFrame3D() for i = 1 : 100 bs = Set(bodies(mechanism)) body = rand([bs...]) delete!(bs, body) base = rand([bs...]) p = path(mechanism, base, body) v = velocity(x) J = geometric_jacobian(x, p) T = relative_twist(x, body, base) @test isapprox(Twist(J, v), T; atol = 1e-12) J1 = GeometricJacobian(J.body, J.base, J.frame, similar(angular(J)), similar(linear(J))) geometric_jacobian!(J1, x, p) @test isapprox(Twist(J1, v), T; atol = 1e-12) H = rand(Transform3D, root_frame(mechanism), frame) J2 = GeometricJacobian(J.body, J.base, frame, similar(angular(J)), similar(linear(J))) if num_velocities(p) > 0 @test_throws ArgumentError geometric_jacobian!(J, x, p, H) end geometric_jacobian!(J2, x, p, H) @test isapprox(Twist(J2, v), transform(T, H); atol = 1e-12) J3 = GeometricJacobian(J.body, J.base, default_frame(body), similar(angular(J)), similar(linear(J))) geometric_jacobian!(J3, x, p) @test isapprox(Twist(J3, v), transform(x, T, default_frame(body)); atol = 1e-12) end end @testset "point jacobian" begin Random.seed!(26) mechanism = randmech() x = MechanismState(mechanism) rand!(x) @testset "point expressed in body frame" begin for i = 1 : 100 bs = Set(bodies(mechanism)) body = rand([bs...]) delete!(bs, body) base = rand([bs...]) p = path(mechanism, base, body) point = Point3D(default_frame(body), rand(SVector{3, Float64})) J_point = point_jacobian(x, p, point) # Check agreement with GeometricJacobian -> Twist -> point_velocity J = geometric_jacobian(x, p) T = Twist(J, velocity(x)) point_in_world = transform(x, point, root_frame(mechanism)) point_velocity_expected = point_velocity(T, point_in_world) @test point_velocity_expected ≈ transform(x, point_velocity(J_point, velocity(x)), root_frame(mechanism)) # Test that point_velocity give us what Jp * v does @test transform(x, point_velocity(J_point, velocity(x)), point.frame).v ≈ Array(J_point) * velocity(x) # Test that in-place updates work too rand!(x) if point.frame != default_frame(base) @test_throws ArgumentError point_jacobian!(J_point, x, p, transform(x, point, default_frame(base))) end point_jacobian!(J_point, x, p, point) @test(@ballocated(point_jacobian!($J_point, $x, $p, $point)) == 0) J = geometric_jacobian(x, p) T = Twist(J, velocity(x)) point_in_world = transform(x, point, root_frame(mechanism)) @test point_velocity(T, point_in_world) ≈ transform(x, point_velocity(J_point, velocity(x)), root_frame(mechanism)) # Test Jᵀ * f f = FreeVector3D(CartesianFrame3D(), rand(), rand(), rand()) τ = similar(velocity(x)) @test_throws ArgumentError mul!(τ, transpose(J_point), f) f = FreeVector3D(J_point.frame, rand(), rand(), rand()) mul!(τ, transpose(J_point), f) @test τ == transpose(J_point.J) * f.v @test τ == transpose(J_point) * f end end @testset "point expressed in world frame" begin Random.seed!(27) for i = 1 : 10 bs = Set(bodies(mechanism)) body = rand([bs...]) delete!(bs, body) base = rand([bs...]) p = path(mechanism, base, body) point = Point3D(root_frame(mechanism), rand(SVector{3, Float64})) J_point = point_jacobian(x, p, point) # Check agreement with GeometricJacobian -> Twist -> point_velocity J = geometric_jacobian(x, p) T = Twist(J, velocity(x)) @test point_velocity(T, point) ≈ point_velocity(J_point, velocity(x)) # Test that point_velocity give us what Jp * v does @test point_velocity(J_point, velocity(x)).v ≈ Array(J_point) * velocity(x) point_jacobian!(J_point, x, p, point) end end end @testset "motion_subspace / constraint_wrench_subspace" begin Random.seed!(28) mechanism = randmech() x = MechanismState(mechanism) rand!(x) for joint in tree_joints(mechanism) body = successor(joint, mechanism) qjoint = configuration(x, joint) S = motion_subspace(joint, configuration(x, joint)) tf = joint_transform(joint, qjoint) T = constraint_wrench_subspace(joint, tf) if 0 < num_constraints(joint) < 6 @test isapprox(angular(T)' * angular(S) + linear(T)' * linear(S), zeros(num_constraints(joint), num_velocities(joint)); atol = 1e-12) elseif num_constraints(joint) == 0 @test size(T) == (6, 0) else @test size(S) == (6, 0) end end end # TODO: good test, but currently don't want to support joints with variable wrench subspaces: # @testset "constraint_bias" begin # for joint in joints(mechanism) # qjoint = configuration(x, joint) # vjoint = velocity(x, joint) # q̇joint = similar(qjoint) # velocity_to_configuration_derivative!(joint, q̇joint, qjoint, vjoint) # qjoint_autodiff = ForwardDiff.Dual.(qjoint, q̇joint) # TAutodiff = constraint_wrench_subspace(joint, qjoint_autodiff)#::RigidBodyDynamics.WrenchSubspace{eltype(qjoint_autodiff)} # TODO # ang = map(x -> ForwardDiff.partials(x, 1), angular(TAutodiff)) # lin = map(x -> ForwardDiff.partials(x, 1), linear(TAutodiff)) # Ṫ = WrenchMatrix(frame_after(joint), ang, lin) # joint_twist = transform(x, relative_twist(x, frame_after(joint), frame_before(joint)), frame_after(joint)) # bias = fill(NaN, 6 - num_velocities(joint)) # constraint_bias!(joint, bias, joint_twist) # @test isapprox(angular(Ṫ)' * angular(joint_twist) + linear(Ṫ)' * linear(joint_twist), bias; atol = 1e-14) # end # end @testset "relative_acceleration" begin Random.seed!(29) mechanism = randmech() x = MechanismState(mechanism) rand!(x) result = DynamicsResult(mechanism) for body in bodies(mechanism) for base in bodies(mechanism) v̇ = similar(velocity(x)) rand!(v̇) spatial_accelerations!(result.accelerations, x, v̇) Ṫ = relative_acceleration(result, body, base) q = configuration(x) v = velocity(x) q̇ = configuration_derivative(x) q_autodiff = ForwardDiff.Dual.(q, q̇) v_autodiff = ForwardDiff.Dual.(v, v̇) x_autodiff = MechanismState{eltype(q_autodiff)}(mechanism) set_configuration!(x_autodiff, q_autodiff) set_velocity!(x_autodiff, v_autodiff) twist_autodiff = relative_twist(x_autodiff, body, base) accel_vec = [ForwardDiff.partials(x, 1)::Float64 for x in (SVector(twist_autodiff))] @test isapprox(SVector(Ṫ), accel_vec; atol = 1e-12) root = root_body(mechanism) f = default_frame(body) Ṫbody = transform(x, relative_acceleration(result, body, root), f) Ṫbase = transform(x, relative_acceleration(result, base, root), f) @test isapprox(transform(x, -Ṫbase + Ṫbody, Ṫ.frame), Ṫ; atol = 1e-12) end end end @testset "motion subspace / twist wrt world" begin Random.seed!(30) mechanism = randmech() x = MechanismState(mechanism) rand!(x) for joint in tree_joints(mechanism) body = successor(joint, mechanism) parent_body = predecessor(joint, mechanism) toroot = transform_to_root(x, body) S = transform(motion_subspace(joint, configuration(x, joint)), toroot) @test isapprox(relative_twist(x, body, parent_body), Twist(S, velocity(x, joint)); atol = 1e-12) end end @testset "composite rigid body inertias" begin Random.seed!(31) mechanism = randmech() x = MechanismState(mechanism) rand!(x) for joint in tree_joints(mechanism) body = successor(joint, mechanism) crb = crb_inertia(x, body) stack = [body] subtree = typeof(body)[] while !isempty(stack) b = pop!(stack) push!(subtree, b) for joint in out_joints(b, mechanism) push!(stack, successor(joint, mechanism)) end end @test isapprox(sum((b::RigidBody) -> spatial_inertia(x, b), subtree), crb; atol = 1e-12) end end @testset "momentum_matrix / summing momenta" begin Random.seed!(32) mechanism = randmech() x = MechanismState(mechanism) rand!(x) A = momentum_matrix(x) Amat = Array(A) for joint in tree_joints(mechanism) if num_velocities(joint) > 0 # TODO: Base.mapslices can't handle matrices with zero columns body = successor(joint, mechanism) Ajoint = Amat[:, velocity_range(x, joint)] S = transform(motion_subspace(joint, configuration(x, joint)), transform_to_root(x, body)) @test isapprox(Array(crb_inertia(x, body) * S), Ajoint; atol = 1e-12) end end v = velocity(x) hsum = sum(b -> spatial_inertia(x, b) * twist_wrt_world(x, b), non_root_bodies(mechanism)) @test isapprox(Momentum(A, v), hsum; atol = 1e-12) A1 = MomentumMatrix(A.frame, similar(angular(A)), similar(linear(A))) momentum_matrix!(A1, x) @test isapprox(Momentum(A1, v), hsum; atol = 1e-12) frame = CartesianFrame3D() A2 = MomentumMatrix(frame, similar(angular(A)), similar(linear(A))) H = rand(Transform3D, root_frame(mechanism), frame) @test_throws ArgumentError momentum_matrix!(A, x, H) momentum_matrix!(A2, x, H) @test isapprox(Momentum(A2, v), transform(hsum, H); atol = 1e-12) body = rand(collect(bodies(mechanism))) A3 = MomentumMatrix(default_frame(body), similar(angular(A)), similar(linear(A))) momentum_matrix!(A3, x) @test isapprox(Momentum(A3, v), transform(x, hsum, default_frame(body)); atol = 1e-12) end @testset "mass matrix / kinetic energy" begin Random.seed!(33) mechanism = randmech() x = MechanismState(mechanism) rand!(x) Ek = kinetic_energy(x) M = mass_matrix(x) v = velocity(x) @test isapprox(1/2 * dot(v, M * v), Ek; atol = 1e-12) q = configuration(x) cache = StateCache(mechanism) kinetic_energy_fun = function (v) local x = cache[eltype(v)] set_configuration!(x, q) set_velocity!(x, v) kinetic_energy(x) end # FIXME: excessive compilation time # M2 = similar(M.data) # NOTE: chunk size 1 necessary after updating to ForwardDiff 0.2 because creating a MechanismState with a max size Dual takes forever... # see https://github.com/JuliaDiff/ForwardDiff.jl/issues/266 # M2 = ForwardDiff.hessian!(M2, kinetic_energy_fun, v, ForwardDiff.HessianConfig(kinetic_energy_fun, v, ForwardDiff.Chunk{1}())) # @test isapprox(M2, M; atol = 1e-12) end @testset "spatial_inertia!" begin Random.seed!(34) mechanism = randmech() body = rand(collect(non_root_bodies(mechanism))) newinertia = rand(SpatialInertia{eltype(mechanism)}, spatial_inertia(body).frame) spatial_inertia!(body, newinertia) @assert spatial_inertia(body) == newinertia end @testset "inverse dynamics / acceleration term" begin Random.seed!(35) mechanism = randmech() x = MechanismState(mechanism) rand!(x) M = mass_matrix(x) function v̇_to_τ(v̇) inverse_dynamics(x, v̇) end M2 = similar(M.data) v̇ = similar(velocity(x)) v̇ .= 0 ForwardDiff.jacobian!(M2, v̇_to_τ, v̇) @test isapprox(M2, M; atol = 1e-12) end @testset "inverse dynamics / Coriolis term" begin Random.seed!(36) mechanism = rand_tree_mechanism(Float64, [[Revolute{Float64} for i = 1 : 10]; [Prismatic{Float64} for i = 1 : 10]]...) # skew symmetry property tested later on doesn't hold when q̇ ≠ v x = MechanismState{Float64}(mechanism) rand!(x) cache = StateCache(mechanism) function q_to_M(q) local x = cache[eltype(q)] set_configuration!(x, q) zero_velocity!(x) vec(mass_matrix(x)) end nv = num_velocities(mechanism) nq = num_positions(mechanism) dMdq = zeros(nv * nv, nq) ForwardDiff.jacobian!(dMdq, q_to_M, configuration(x)) q̇ = velocity(x) Ṁ = reshape(dMdq * q̇, num_velocities(mechanism), num_velocities(mechanism)) q = configuration(x) v̇ = similar(velocity(x)) v̇ .= 0 cache = StateCache(mechanism) function v_to_c(v) local x = cache[eltype(v)] set_configuration!(x, q) set_velocity!(x, v) inverse_dynamics(x, v̇) end C = similar(Ṁ) ForwardDiff.jacobian!(C, v_to_c, q̇) C *= 1/2 skew = Ṁ - 2 * C; @test isapprox(skew + skew', zeros(size(skew)); atol = 1e-12) end @testset "inverse dynamics / gravity term" begin Random.seed!(37) mechanism = rand_tree_mechanism(Float64, [[Revolute{Float64} for i = 1 : 10]; [Prismatic{Float64} for i = 1 : 10]]...) x = MechanismState(mechanism) rand!(x) v̇ = similar(velocity(x)) v̇ .= 0 zero_velocity!(x) g = inverse_dynamics(x, v̇) cache = StateCache(mechanism) function q_to_potential(q) local x = cache[eltype(q)] set_configuration!(x, q) zero_velocity!(x) return [gravitational_potential_energy(x)] end g2 = similar(g') ForwardDiff.jacobian!(g2, q_to_potential, configuration(x)) @test isapprox(g2, g'; atol = 1e-12) end @testset "momentum matrix" begin Random.seed!(38) mechanism = randmech() x = MechanismState(mechanism) rand!(x) q = configuration(x) q̇ = configuration_derivative(x) v = velocity(x) v̇ = similar(velocity(x)) rand!(v̇) # momentum computed two ways @test isapprox(Momentum(momentum_matrix(x), v), momentum(x)) # rate of change of momentum computed using autodiff: q_autodiff = ForwardDiff.Dual.(q, q̇) v_autodiff = ForwardDiff.Dual.(v, v̇) x_autodiff = MechanismState{eltype(q_autodiff)}(mechanism) set_configuration!(x_autodiff, q_autodiff) set_velocity!(x_autodiff, v_autodiff) A_autodiff = Array(momentum_matrix(x_autodiff)) A = [ForwardDiff.value(A_autodiff[i, j])::Float64 for i = 1 : size(A_autodiff, 1), j = 1 : size(A_autodiff, 2)] Ȧ = [ForwardDiff.partials(A_autodiff[i, j], 1)::Float64 for i = 1 : size(A_autodiff, 1), j = 1 : size(A_autodiff, 2)] ḣArray = A * v̇ + Ȧ * v # rate of change of momentum computed without autodiff: ḣ = Wrench(momentum_matrix(x), v̇) + momentum_rate_bias(x) @test isapprox(ḣArray, SVector(ḣ); atol = 1e-12) end @testset "inverse dynamics / external wrenches" begin # test requires a floating mechanism Random.seed!(39) mechanism = rand_floating_tree_mechanism(Float64, fill(Revolute{Float64}, 10)..., fill(Planar{Float64}, 10)..., fill(SinCosRevolute{Float64}, 5)...) x = MechanismState(mechanism) rand!(x) v̇ = similar(velocity(x)) rand!(v̇) externalwrenches = Dict(BodyID(body) => rand(Wrench{Float64}, root_frame(mechanism)) for body in bodies(mechanism)) τ = inverse_dynamics(x, v̇, externalwrenches) floatingjoint = first(out_joints(root_body(mechanism), mechanism)) τfloating = τ[velocity_range(x, floatingjoint)] floatingjointwrench = Wrench(frame_after(floatingjoint), SVector{3}(τfloating[1 : 3]), SVector{3}(τfloating[4 : 6])) floatingjointwrench = transform(x, floatingjointwrench, root_frame(mechanism)) ḣ = Wrench(momentum_matrix(x), v̇) + momentum_rate_bias(x) # momentum rate of change gravitational_force = mass(mechanism) * mechanism.gravitational_acceleration com = center_of_mass(x) gravitational_wrench = Wrench(gravitational_force.frame, (com × gravitational_force).v, gravitational_force.v) total_wrench = floatingjointwrench + gravitational_wrench + sum((b) -> transform(x, externalwrenches[BodyID(b)], root_frame(mechanism)), non_root_bodies(mechanism)) @test isapprox(total_wrench, ḣ; atol = 1e-10) end @testset "dynamics / inverse dynamics" begin Random.seed!(40) mechanism = randmech() x = MechanismState(mechanism) rand!(x) external_torques = rand(num_velocities(mechanism)) externalwrenches = Dict(BodyID(body) => rand(Wrench{Float64}, root_frame(mechanism)) for body in bodies(mechanism)) result = DynamicsResult(mechanism) dynamics!(result, x, external_torques, externalwrenches) τ = inverse_dynamics(x, result.v̇, externalwrenches) - external_torques @test isapprox(τ, zeros(num_velocities(mechanism)); atol = 1e-10) end @testset "dynamics_bias / inverse_dynamics" begin Random.seed!(41) mechanism = randmech() x = MechanismState(mechanism) rand!(x) externalwrenches = Dict(BodyID(body) => rand(Wrench{Float64}, root_frame(mechanism)) for body in bodies(mechanism)) v̇ = similar(velocity(x)) v̇ .= 0 τ1 = inverse_dynamics(x, v̇, externalwrenches) τ2 = dynamics_bias(x, externalwrenches) @test τ1 ≈ τ2 end @testset "dynamics ode method" begin Random.seed!(42) mechanism = randmech() x = MechanismState(mechanism) rand!(x) torques = rand(num_velocities(mechanism)) externalwrenches = Dict(BodyID(body) => rand(Wrench{Float64}, root_frame(mechanism)) for body in bodies(mechanism)) result1 = DynamicsResult(mechanism) ẋ = similar(Vector(x)) dynamics!(ẋ, result1, x, Vector(x), torques, externalwrenches) result2 = DynamicsResult(mechanism) dynamics!(result2, x, torques, externalwrenches) @test isapprox([configuration_derivative(x); result2.v̇], ẋ) end @testset "power flow" begin Random.seed!(43) mechanism = randmech() x = MechanismState(mechanism) rand!(x) externalwrenches = Dict(BodyID(body) => rand(Wrench{Float64}, root_frame(mechanism)) for body in bodies(mechanism)) τ = similar(velocity(x)) rand!(τ) result = DynamicsResult(mechanism) dynamics!(result, x, τ, externalwrenches) q = configuration(x) q̇ = configuration_derivative(x) v = velocity(x) v̇ = result.v̇ power = τ ⋅ v + sum(body -> externalwrenches[BodyID(body)] ⋅ twist_wrt_world(x, body), non_root_bodies(mechanism)) q_autodiff = ForwardDiff.Dual.(q, q̇) v_autodiff = ForwardDiff.Dual.(v, v̇) x_autodiff = MechanismState{eltype(q_autodiff)}(mechanism) set_configuration!(x_autodiff, q_autodiff) set_velocity!(x_autodiff, v_autodiff) energy_autodiff = gravitational_potential_energy(x_autodiff) + kinetic_energy(x_autodiff) energy_derivative = ForwardDiff.partials(energy_autodiff)[1] @test isapprox(power, energy_derivative, atol = 1e-10) end @testset "local / global coordinates" begin Random.seed!(44) mechanism = randmech() state = MechanismState(mechanism) rand!(state) for joint in joints(mechanism) # back and forth between local and global ϕ = Vector{Float64}(undef, num_velocities(joint)) ϕ̇ = Vector{Float64}(undef, num_velocities(joint)) q0 = Vector{Float64}(undef, num_positions(joint)) q = configuration(state, joint) v = velocity(state, joint) rand_configuration!(q0, joint) local_coordinates!(ϕ, ϕ̇, joint, q0, q, v) q_back = Vector{Float64}(undef, num_positions(joint)) global_coordinates!(q_back, joint, q0, ϕ) principal_value!(q_back, joint) let expected = copy(q) principal_value!(expected, joint) @test isapprox(q_back, expected) end # compare ϕ̇ to autodiff q̇ = Vector{Float64}(undef, num_positions(joint)) velocity_to_configuration_derivative!(q̇, joint, q, v) v̇ = rand(num_velocities(joint)) q_autodiff = ForwardDiff.Dual.(q, q̇) v_autodiff = ForwardDiff.Dual.(v, v̇) q0_autodiff = ForwardDiff.Dual.(q0, zeros(length(q0))) T = eltype(q_autodiff) ϕ_autodiff = Vector{T}(undef, length(ϕ)) ϕ̇_autodiff = Vector{T}(undef, length(ϕ̇)) local_coordinates!(ϕ_autodiff, ϕ̇_autodiff, joint, q0_autodiff, q_autodiff, v_autodiff) ϕ̇_from_autodiff = [ForwardDiff.partials(x)[1] for x in ϕ_autodiff] @test isapprox(ϕ̇, ϕ̇_from_autodiff) # local coordinates should be zero when q = q0 # Definition 2.9 in Duindam, "Port-Based Modeling and Control for Efficient Bipedal Walking Robots" copyto!(q, q0) local_coordinates!(ϕ, ϕ̇, joint, q0, q, v) @test isapprox(ϕ, zeros(num_velocities(joint)); atol = 1e-15) end end @testset "configuration_derivative_to_velocity_adjoint!" begin Random.seed!(45) mechanism = randmech() x = MechanismState(mechanism) configuration(x) .= rand(num_positions(x)) # needs to work for configuration vectors that do not satisfy the state constraints as well fv = similar(velocity(x)) rand!(fv) fq = similar(configuration(x)) rand!(fq) configuration_derivative_to_velocity_adjoint!(fq, x, fv) @test dot(fv, velocity(x)) ≈ dot(fq, configuration_derivative(x)) end @testset "joint bounds" begin @test @inferred(RigidBodyDynamics.Bounds{Float64}()).lower == -Inf @test @inferred(RigidBodyDynamics.Bounds{Float64}()).upper == Inf @test @inferred(RigidBodyDynamics.Bounds(-1, 2.0)).lower == -1 @test @inferred(RigidBodyDynamics.Bounds(-1, 2.0)).upper == 2 @test isa(RigidBodyDynamics.Bounds(-1, 1.0).lower, Float64) @test isa(RigidBodyDynamics.Bounds(-1, 1.0).upper, Float64) @test @inferred(clamp(1.5, RigidBodyDynamics.Bounds(-1, 1))) == RigidBodyDynamics.upper(RigidBodyDynamics.Bounds(-1, 1)) @test @inferred(clamp(-3, RigidBodyDynamics.Bounds(-2, 1))) == RigidBodyDynamics.lower(RigidBodyDynamics.Bounds(-2, 1)) @test @inferred(clamp(0, RigidBodyDynamics.Bounds(-1, 1))) == 0 @test @inferred(intersect(RigidBodyDynamics.Bounds(-1, 1), RigidBodyDynamics.Bounds(-0.5, 2.0))) == RigidBodyDynamics.Bounds(-0.5, 1.0) @test @inferred(convert(RigidBodyDynamics.Bounds{Float64}, RigidBodyDynamics.Bounds(1, 2))) == RigidBodyDynamics.Bounds{Float64}(1.0, 2.0) end @testset "issue #330" begin Random.seed!(46) mechanism = rand_tree_mechanism(Revolute{Float64}) f330(x::AbstractArray{T}) where {T} = begin result = DynamicsResult{T}(mechanism) 1. end @test ForwardDiff.hessian(f330, [1.]) == zeros(1, 1) end @testset "principal_value!" begin Random.seed!(47) state_orig = MechanismState(randmech()) Random.rand!(state_orig) for joint_k = tree_joints(state_orig.mechanism) joint_type_k = joint_type(joint_k) if isa(joint_type_k, SPQuatFloating) RigidBodyDynamics.set_rotation!(state_orig.q[joint_k], joint_type_k, ModifiedRodriguesParam(QuatRotation(-0.5, randn(), randn(), randn()))) end end setdirty!(state_orig) state_prin = deepcopy(state_orig) principal_value!(state_prin) for joint_k = tree_joints(state_orig.mechanism) joint_type_k = joint_type(joint_k) q_orig = state_orig.q[joint_k] q_prin = state_prin.q[joint_k] if joint_type_k isa SPQuatFloating rot_orig = rotation(joint_type_k, q_orig) rot_prin = rotation(joint_type_k, q_prin) @test isapprox(rot_orig, rot_prin) @test (rot_prin.x^2 + rot_prin.y^2 + rot_prin.z^2) < (1.0 + 1.0e-14) @test (1.0 + 1.0e-14) < (rot_orig.x^2 + rot_orig.y^2 + rot_orig.z^2) elseif joint_type_k isa QuaternionFloating || joint_type_k isa QuaternionSpherical rot_orig = rotation(joint_type_k, q_orig) rot_prin = rotation(joint_type_k, q_prin) w, x, y, z = Rotations.params(rot_prin) @test isapprox(rot_orig, rot_prin) @test w > 0 else @test q_orig == q_prin end if joint_type_k isa QuaternionFloating @test translation(joint_type_k, q_orig) === translation(joint_type_k, q_prin) end end end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
20442
@testset "mechanism modification" begin @testset "flip_direction" begin Bounds = RigidBodyDynamics.Bounds jointname = "joint1" axis = [1.0, 0.0, 0.0] for JT in [Revolute, Prismatic] jointtype = JT(axis) posbounds = [Bounds(1., 2.)] velbounds = [Bounds(3., 4.)] effbounds = [Bounds(5., 6.)] joint = Joint(jointname, jointtype, position_bounds = posbounds, velocity_bounds = velbounds, effort_bounds = effbounds) flipped = RigidBodyDynamics.Graphs.flip_direction(joint) @test flipped.name == joint.name @test joint_type(flipped) == JT(.-axis) @test flipped.position_bounds == [Bounds(-2., -1.)] @test flipped.velocity_bounds == [Bounds(-4., -3.)] @test flipped.effort_bounds == [Bounds(-6., -5.)] end end @testset "attach!" begin Random.seed!(47) body0 = RigidBody{Float64}("root") mechanism = Mechanism(body0) joint1 = Joint("joint1", rand(Revolute{Float64})) joint1_pose = rand(Transform3D{Float64}, frame_before(joint1), default_frame(body0)) body1 = RigidBody(rand(SpatialInertia{Float64}, frame_after(joint1))) joint2 = Joint("joint2", QuaternionFloating{Float64}()) joint2_pose = rand(Transform3D{Float64}, frame_before(joint2), default_frame(body1)) body2 = RigidBody(rand(SpatialInertia{Float64}, CartesianFrame3D("2"))) # can't attach if predecessor is not among bodies of mechanism @test_throws AssertionError attach!(mechanism, body1, body2, joint2, joint_pose = joint2_pose) # attach body1 attach!(mechanism, body0, body1, joint1, joint_pose = joint1_pose) @test length(bodies(mechanism)) == 2 @test body1 ∈ bodies(mechanism) @test length(joints(mechanism)) == 1 @test joint1 ∈ joints(mechanism) @test isapprox(fixed_transform(mechanism, frame_before(joint1), joint1_pose.to), joint1_pose) # can't use the same joint twice @test_throws AssertionError attach!(mechanism, body0, body1, joint1, joint_pose = joint1_pose) # attach body2 attach!(mechanism, body1, body2, joint2, joint_pose = joint2_pose) @test length(bodies(mechanism)) == 3 @test body2 ∈ bodies(mechanism) @test length(joints(mechanism)) == 2 @test joint2 ∈ joints(mechanism) @test isapprox(fixed_transform(mechanism, frame_before(joint2), joint2_pose.to), joint2_pose) end @testset "attach! mechanism" begin Random.seed!(48) mechanism = randmech() nq = num_positions(mechanism) nv = num_velocities(mechanism) mechanism2 = rand_tree_mechanism(Float64, [QuaternionFloating{Float64}; [Revolute{Float64} for i = 1 : 5]; QuaternionSpherical{Float64}; Planar{Float64}; [Prismatic{Float64} for i = 1 : 5]]...) additional_frames = Dict{CartesianFrame3D, RigidBody{Float64}}() for body in bodies(mechanism2) for i = 1 : 5 frame = CartesianFrame3D("frame_$i") tf = rand(Transform3D, frame, default_frame(body)) add_frame!(body, tf) additional_frames[frame] = body end end parent_body = rand(collect(bodies(mechanism))) attach!(mechanism, parent_body, mechanism2) @test num_positions(mechanism) == nq + num_positions(mechanism2) @test num_velocities(mechanism) == nv + num_velocities(mechanism2) # make sure all of the frame definitions got copied over for frame in keys(additional_frames) body = additional_frames[frame] if body == root_body(mechanism2) body = parent_body end @test RigidBodyDynamics.is_fixed_to_body(body, frame) end state = MechanismState(mechanism) # issue 63 rand!(state) M = mass_matrix(state) # independent acrobots in the same configuration # make sure mass matrix is block diagonal, and that blocks on diagonal are the same urdf = joinpath(@__DIR__, "urdf", "Acrobot.urdf") double_acrobot = parse_urdf(urdf) acrobot2 = parse_urdf(urdf) xsingle = MechanismState(acrobot2) rand!(xsingle) qsingle = configuration(xsingle) nq_single = length(qsingle) parent_body = root_body(double_acrobot) attach!(double_acrobot, parent_body, acrobot2) x = MechanismState(double_acrobot) set_configuration!(x, [qsingle; qsingle]) H = mass_matrix(x) H11 = H[1 : nq_single, 1 : nq_single] H12 = H[1 : nq_single, nq_single + 1 : end] H21 = H[nq_single + 1 : end, 1 : nq_single] H22 = H[nq_single + 1 : end, nq_single + 1 : end] @test isapprox(H11, H22) @test isapprox(H12, zero(H12)) @test isapprox(H21, zero(H21)) end @testset "remove fixed joints" begin Random.seed!(49) joint_types = [QuaternionFloating{Float64}; [Revolute{Float64} for i = 1 : 10]; QuaternionSpherical{Float64}; Planar{Float64}; [Fixed{Float64} for i = 1 : 10]; [SinCosRevolute{Float64} for i = 1 : 5]] shuffle!(joint_types) mechanism = rand_tree_mechanism(Float64, joint_types...) normal_model = RigidBodyDynamics.Contact.hunt_crossley_hertz() tangential_model = RigidBodyDynamics.Contact.ViscoelasticCoulombModel(0.8, 20e3, 100.) contact_model = RigidBodyDynamics.Contact.SoftContactModel(normal_model, tangential_model) num_contact_points = 0 for body in bodies(mechanism) for i in 1 : rand(1 : 3) contact_point = ContactPoint(Point3D(default_frame(body), rand(), rand(), rand()), contact_model) add_contact_point!(body, contact_point) num_contact_points += 1 end end state = MechanismState(mechanism) rand!(state) q = configuration(state) M = mass_matrix(state) nonfixedjoints = collect(filter(j -> !(joint_type(j) isa Fixed), tree_joints(mechanism))) remove_fixed_tree_joints!(mechanism) @test sum(body -> length(contact_points(body)), bodies(mechanism)) == num_contact_points @test tree_joints(mechanism) == nonfixedjoints state_no_fixed_joints = MechanismState(mechanism) set_configuration!(state_no_fixed_joints, q) M_no_fixed_joints = mass_matrix(state_no_fixed_joints) @test isapprox(M_no_fixed_joints, M, atol = 1e-12) end @testset "replace joint" begin Random.seed!(50) joint_types = [QuaternionFloating{Float64}; [Revolute{Float64} for i = 1 : 10]; QuaternionSpherical{Float64}; Planar{Float64}; [Fixed{Float64} for i = 1 : 10]; [SinCosRevolute{Float64} for i = 1 : 5]] shuffle!(joint_types) mechanism = rand_tree_mechanism(Float64, joint_types...) for m in [mechanism; maximal_coordinates(mechanism)] for i = 1 : 10 oldjoint = rand(joints(mechanism)) newjoint = Joint("new", frame_before(oldjoint), frame_after(oldjoint), Fixed{Float64}()) replace_joint!(mechanism, oldjoint, newjoint) @test newjoint ∈ joints(mechanism) @test oldjoint ∉ joints(mechanism) end end end @testset "submechanism" begin Random.seed!(51) for testnum = 1 : 100 # joint_types = [QuaternionFloating{Float64}; [Revolute{Float64} for i = 1 : 10]; QuaternionSpherical{Float64}; Planar{Float64}; [Fixed{Float64} for i = 1 : 10]] # FIXME: use this joint_types = [Revolute{Float64} for i = 1 : 4] shuffle!(joint_types) mechanism = rand_tree_mechanism(Float64, joint_types...) state = MechanismState(mechanism) rand!(state) M = mass_matrix(state) submechanism_root = rand(collect(bodies(mechanism))) bodymap = Dict{RigidBody{Float64}, RigidBody{Float64}}() jointmap = Dict{Joint{Float64}, Joint{Float64}}() mechanism_part = submechanism(mechanism, submechanism_root; bodymap=bodymap, jointmap=jointmap) @test root_body(mechanism_part) == bodymap[submechanism_root] @test mechanism.gravitational_acceleration.v == mechanism_part.gravitational_acceleration.v substate = MechanismState(mechanism_part) for (oldjoint, newjoint) in jointmap set_configuration!(substate, newjoint, configuration(state, oldjoint)) set_velocity!(substate, newjoint, velocity(state, oldjoint)) end Msub = mass_matrix(substate) if num_velocities(mechanism_part) > 0 indices = vcat([velocity_range(state, joint) for joint in tree_joints(mechanism) if joint ∈ keys(jointmap)]...) @test isapprox(M[indices, indices], Msub, atol = 1e-10) end end end @testset "reattach" begin Random.seed!(52) for testnum = 1 : 10 # create random floating mechanism with flippable joints joint_types = [[Prismatic{Float64} for i = 1 : 10]; [Revolute{Float64} for i = 1 : 10]; [Fixed{Float64} for i = 1 : 10]; [SinCosRevolute{Float64} for i = 1 : 5]] shuffle!(joint_types) mechanism1 = rand_floating_tree_mechanism(Float64, joint_types...) # random state x1 = MechanismState(mechanism1) rand!(x1) # copy and set up mapping from bodies and joints of mechanism1 to those of mechanism2 bodies1 = collect(bodies(mechanism1)) joints1 = collect(joints(mechanism1)) (bodies2, joints2, mechanism2) = deepcopy((bodies1, joints1, mechanism1)) bodymap = Dict(zip(bodies1, bodies2)) jointmap = Dict(zip(joints1, joints2)) # find world, floating joint, floating body of mechanism1, and determine a new floating body world = root_body(mechanism1) floatingjoint = first(out_joints(world, mechanism1)) floatingbody = successor(floatingjoint, mechanism1) newfloatingbody = rand(collect(non_root_bodies(mechanism1))) # reroot mechanism2 newfloatingjoint = Joint("new_floating", QuaternionFloating{Float64}()) joint_to_world = one(Transform3D, frame_before(newfloatingjoint), default_frame(world)) body_to_joint = one(Transform3D, default_frame(newfloatingbody), frame_after(newfloatingjoint)) attach!(mechanism2, bodymap[world], bodymap[newfloatingbody], newfloatingjoint, joint_pose = joint_to_world, successor_pose = body_to_joint) flipped_joint_map = Dict() remove_joint!(mechanism2, jointmap[floatingjoint]; flipped_joint_map = flipped_joint_map) # mimic the same state for the rerooted mechanism # copy non-floating joint configurations and velocities x2 = MechanismState(mechanism2) for (joint1, joint2) in jointmap if joint1 != floatingjoint joint2_rerooted = get(flipped_joint_map, joint2, joint2) set_configuration!(x2, joint2_rerooted, configuration(x1, joint1)) set_velocity!(x2, joint2_rerooted, velocity(x1, joint1)) end end # set configuration and velocity of new floating joint newfloatingjoint_transform = inv(joint_to_world) * relative_transform(x1, body_to_joint.from, joint_to_world.to) * inv(body_to_joint) set_configuration!(x2, newfloatingjoint, newfloatingjoint_transform) newfloatingjoint_twist = transform(x1, relative_twist(x1, newfloatingbody, world), body_to_joint.from) newfloatingjoint_twist = transform(newfloatingjoint_twist, body_to_joint) newfloatingjoint_twist = Twist(body_to_joint.to, joint_to_world.from, newfloatingjoint_twist.frame, angular(newfloatingjoint_twist), linear(newfloatingjoint_twist)) set_velocity!(velocity(x2, newfloatingjoint), newfloatingjoint, newfloatingjoint_twist) # do dynamics and compute spatial accelerations result1 = DynamicsResult(mechanism1) dynamics!(result1, x1) spatial_accelerations!(result1, x1) result2 = DynamicsResult(mechanism2) dynamics!(result2, x2) spatial_accelerations!(result2, x2) # make sure that joint accelerations for non-floating joints are the same for (joint1, joint2) in jointmap if joint1 != floatingjoint joint2_rerooted = get(flipped_joint_map, joint2, joint2) v̇1 = view(result1.v̇, velocity_range(x1, joint1)) v̇2 = view(result2.v̇, velocity_range(x2, joint2_rerooted)) @test isapprox(v̇1, v̇2) end end # make sure that body spatial accelerations are the same for (body1, body2) in bodymap accel1 = relative_acceleration(result1, body1, world) accel2 = relative_acceleration(result2, body2, bodymap[world]) @test isapprox(angular(accel1), angular(accel2)) @test isapprox(linear(accel1), linear(accel2)) end end # for end # reattach @testset "maximal coordinates" begin Random.seed!(53) # create random tree mechanism and equivalent mechanism in maximal coordinates joint_types = [QuaternionFloating{Float64}; [Revolute{Float64} for i = 1 : 10]; QuaternionSpherical{Float64}; Planar{Float64}; [Fixed{Float64} for i = 1 : 10]; [SinCosRevolute{Float64} for i = 1 : 5]] tree_mechanism = rand_tree_mechanism(Float64, joint_types...) bodymap = Dict{RigidBody{Float64}, RigidBody{Float64}}() jointmap = Dict{Joint{Float64}, Joint{Float64}}() mc_mechanism = maximal_coordinates(tree_mechanism; bodymap=bodymap, jointmap=jointmap) newfloatingjoints = filter(isfloating, tree_joints(mc_mechanism)) # randomize state of tree mechanism tree_state = MechanismState(tree_mechanism) rand!(tree_state) # put maximal coordinate system in state that is equivalent to tree mechanism state mc_state = MechanismState(mc_mechanism) for oldbody in non_root_bodies(tree_mechanism) newbody = bodymap[oldbody] joint = joint_to_parent(newbody, mc_mechanism) tf = relative_transform(tree_state, frame_after(joint), frame_before(joint)) set_configuration!(configuration(mc_state, joint), joint, tf) twist = transform(relative_twist(tree_state, frame_after(joint), frame_before(joint)), inv(tf)) set_velocity!(mc_state, joint, twist) end setdirty!(mc_state) # do dynamics and compute spatial accelerations tree_dynamics_result = DynamicsResult(tree_mechanism); dynamics!(tree_dynamics_result, tree_state) spatial_accelerations!(tree_dynamics_result, tree_state) mc_dynamics_result = DynamicsResult(mc_mechanism); dynamics!(mc_dynamics_result, mc_state) spatial_accelerations!(mc_dynamics_result, mc_state) # compare spatial accelerations of bodies for (treebody, mcbody) in bodymap tree_accel = relative_acceleration(tree_dynamics_result, treebody, root_body(tree_mechanism)) mc_accel = relative_acceleration(mc_dynamics_result, mcbody, root_body(mc_mechanism)) @test isapprox(tree_accel, mc_accel; atol = 1e-10) end end # maximal coordinates @testset "generic scalar dynamics" begin # TODO: move to a better place Random.seed!(54) joint_types = [QuaternionFloating{Float64}; [Revolute{Float64} for i = 1 : 10]; QuaternionSpherical{Float64}; Planar{Float64}; [Fixed{Float64} for i = 1 : 10]; [SinCosRevolute{Float64} for i = 1 : 5]] mechanism = rand_tree_mechanism(Float64, joint_types...); for m in [mechanism, maximal_coordinates(mechanism)] state_float64 = MechanismState(m) rand!(state_float64) NullDual = typeof(ForwardDiff.Dual(0., ())) state_dual = MechanismState{NullDual}(m) configuration(state_dual) .= configuration(state_float64) velocity(state_dual) .= velocity(state_float64) dynamics_result_float64 = DynamicsResult(m) dynamics!(dynamics_result_float64, state_float64) dynamics_result_dual = DynamicsResult{NullDual}(m) dynamics!(dynamics_result_dual, state_dual) @test isapprox(dynamics_result_float64.v̇, dynamics_result_dual.v̇; atol = 1e-3) @test isapprox(dynamics_result_float64.λ, dynamics_result_dual.λ; atol = 1e-3) end end @testset "modcount" begin Random.seed!(55) joint_types = [QuaternionFloating{Float64}; [Revolute{Float64} for i = 1 : 10]; QuaternionSpherical{Float64}; Planar{Float64}; [Fixed{Float64} for i = 1 : 10]; [SinCosRevolute{Float64} for i = 1 : 5]] mechanism = rand_tree_mechanism(Float64, joint_types...); state = MechanismState(mechanism) attach!(mechanism, root_body(mechanism), RigidBody(rand(SpatialInertia{Float64}, CartesianFrame3D())), Joint("bla", QuaternionFloating{Float64}())) @test_throws RigidBodyDynamics.ModificationCountMismatch mass_matrix(state) state2 = MechanismState(mechanism) mass_matrix(state2) # make sure this doesn't throw @test_throws RigidBodyDynamics.ModificationCountMismatch mass_matrix(state) # make sure this still throws try mass_matrix(state) catch e showerror(devnull, e) end end @testset "remove_subtree! - tree mechanism" begin mechanism = parse_urdf(joinpath(@__DIR__, "urdf", "atlas.urdf"), floating=true) @test_throws AssertionError remove_subtree!(mechanism, root_body(mechanism)) original_joints = copy(joints(mechanism)) # Behead. num_bodies = length(bodies(mechanism)) num_joints = length(joints(mechanism)) head = findbody(mechanism, "head") neck_joint = joint_to_parent(head, mechanism) remove_subtree!(mechanism, head) @test length(bodies(mechanism)) == num_bodies - 1 @test length(joints(mechanism)) == num_joints - 1 @test head ∉ bodies(mechanism) @test neck_joint ∉ joints(mechanism) # Lop off an arm. num_bodies = length(bodies(mechanism)) num_joints = length(joints(mechanism)) r_clav = findbody(mechanism, "r_clav") r_hand = findbody(mechanism, "r_hand") r_arm = path(mechanism, r_clav, r_hand) arm_joints = collect(r_arm) arm_bodies = [r_clav; map(joint -> successor(joint, mechanism), arm_joints)] remove_subtree!(mechanism, r_clav) @test length(joints(mechanism)) == num_joints - length(arm_joints) - 1 @test length(bodies(mechanism)) == num_bodies - length(arm_bodies) @test isempty(intersect(arm_joints, joints(mechanism))) @test isempty(intersect(arm_bodies, bodies(mechanism))) @test issorted(joints(mechanism), by=joint ->findfirst(isequal(joint), original_joints)) end @testset "remove_subtree! - maximal coordinates" begin original = parse_urdf(joinpath(@__DIR__, "urdf", "atlas.urdf"), floating=true) mechanism = maximal_coordinates(original) num_bodies = length(bodies(mechanism)) num_joints = length(joints(mechanism)) @test_throws AssertionError remove_subtree!(mechanism, findbody(original, "head")) # body not in tree head = findbody(mechanism, "head") head_joints = copy(in_joints(head, mechanism)) @test length(head_joints) == 2 # floating joint + neck loop joint remove_subtree!(mechanism, head) @test length(joints(mechanism)) == num_joints - length(head_joints) @test length(bodies(mechanism)) == num_bodies - 1 for joint in head_joints @test joint ∉ joints(mechanism) end @test head ∉ bodies(mechanism) end end # mechanism modification
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
1177
let num_notebooks_tested = 0 notebookdir = joinpath(@__DIR__, "..", "examples") excludedirs = [".ipynb_checkpoints"] excludefiles = String[] push!(excludefiles, "6. Symbolics.ipynb") # Disabled until https://github.com/JuliaGeometry/Quaternions.jl/issues/123 is solved. # push!(excludefiles, "7. Rigorous error bounds using IntervalArithmetic.ipynb") # Manifest used for 1.1 doesn't work for 1.0. for (root, dir, files) in walkdir(notebookdir) basename(root) in excludedirs && continue for file in files file in excludefiles && continue name, ext = splitext(file) lowercase(ext) == ".ipynb" || continue path = joinpath(root, file) @eval module $(gensym()) # Each notebook is run in its own module. using Test using NBInclude @testset "Notebook: $($name)" begin # Note: use #NBSKIP in a cell to skip it during tests. @nbinclude($path; regex = r"^((?!\#NBSKIP).)*$"s) end end # module num_notebooks_tested += 1 end end @test num_notebooks_tested > 0 end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
5130
@testset "pd" begin @testset "scalar" begin @test pd(PDGains(1, 2), 3, 4) == -11 end @testset "vector" begin gains = PDGains(1, 2) e = [3; 4; 5] ė = [6; 7; 8] @test pd(gains, e, ė) == ((e, ė) -> pd(gains, e, ė)).(e, ė) end @testset "specifying desireds" begin gains = PDGains(5, 6) x = SVector(1, 2) ẋ = SVector(5, 6) @test pd(gains, x, ẋ) == pd(gains, x, zero(x), ẋ, zero(ẋ)) end @testset "x-axis rotation" begin Random.seed!(56) gains = PDGains(2, 3) e = RotX(rand()) ė = rand() * SVector(1, 0, 0) @test pd(gains, e, ė)[1] ≈ pd(gains, e.theta, ė[1]) end @testset "orientation control" begin Random.seed!(57) mechanism = rand_floating_tree_mechanism(Float64) # single floating body joint = first(tree_joints(mechanism)) body = successor(joint, mechanism) base = root_body(mechanism) state = MechanismState(mechanism) rand!(state) Rdes = rand(RotMatrix{3}) ωdes = zero(SVector{3}) gains = PDGains(100, 20) v̇des = similar(velocity(state)) control_dynamics_result = DynamicsResult(mechanism) function control!(torques::SegmentedVector, t, state::MechanismState) H = transform_to_root(state, body) T = transform(twist_wrt_world(state, body), inv(H)) R = rotation(H) ω = T.angular ωddes = pd(gains, R, Rdes, ω, ωdes) v̇desjoint = v̇des[joint] v̇desjoint .= SVector([ωddes; zero(ωddes)]) wrenches = control_dynamics_result.jointwrenches accelerations = control_dynamics_result.accelerations inverse_dynamics!(torques, wrenches, accelerations, state, v̇des) end final_time = 3. simulate(state, final_time, control!; Δt = 1e-3) H = transform_to_root(state, body) T = transform(twist_wrt_world(state, body), inv(H)) R = rotation(H) ω = T.angular @test isapprox(R * Rdes', one(typeof(Rdes)); atol = 1e-8) @test isapprox(ω, zero(ω); atol = 1e-8) end @testset "pose control" begin Random.seed!(58) mechanism = rand_floating_tree_mechanism(Float64) # single floating body joint = first(tree_joints(mechanism)) body = successor(joint, mechanism) base = root_body(mechanism) baseframe = default_frame(base) desiredframe = CartesianFrame3D("desired") actualframe = frame_after(joint) state = MechanismState(mechanism) rand!(state) xdes = rand(Transform3D, desiredframe, baseframe) vdes = zero(Twist{Float64}, desiredframe, baseframe, actualframe) v̇des = similar(velocity(state)) gains = SE3PDGains(baseframe, PDGains(100 * one(SMatrix{3, 3}), 20), PDGains(100., 20.)) # world-fixed gains control_dynamics_result = DynamicsResult(mechanism) function control!(torques::SegmentedVector, t, state::MechanismState) x = transform_to_root(state, body) invx = inv(x) v = transform(twist_wrt_world(state, body), invx) v̇desjoint = v̇des[joint] v̇desjoint .= SVector(pd(transform(gains, invx), x, xdes, v, vdes)) wrenches = control_dynamics_result.jointwrenches accelerations = control_dynamics_result.accelerations inverse_dynamics!(torques, wrenches, accelerations, state, v̇des) end final_time = 3. simulate(state, final_time, control!; Δt = 1e-3) x = transform_to_root(state, body) v = transform(twist_wrt_world(state, body), inv(x)) @test isapprox(x, xdes * one(Transform3D, actualframe, desiredframe), atol = 1e-6) @test isapprox(v, vdes + zero(Twist{Float64}, actualframe, desiredframe, actualframe), atol = 1e-6) end @testset "linearized SE(3) control" begin Random.seed!(59) for i = 1 : 100 randpsd3() = (x = rand(SMatrix{3, 3}); x' * x) baseframe = CartesianFrame3D("base") bodyframe = CartesianFrame3D("body") gains = SE3PDGains(bodyframe, PDGains(randpsd3(), randpsd3()), PDGains(randpsd3(), randpsd3())) xdes = rand(Transform3D{Float64}, bodyframe, baseframe) Tdes = rand(Twist{Float64}, bodyframe, baseframe, bodyframe) ϵ = 1e-2 x = xdes * Transform3D(bodyframe, bodyframe, AngleAxis(ϵ, randn(), randn(), randn()), ϵ * randn(SVector{3})) T = rand(Twist{Float64}, bodyframe, baseframe, bodyframe) accel_nonlin = pd(gains, x, xdes, T, Tdes) accel_lin = pd(gains, x, xdes, T, Tdes, SE3PDMethod{:Linearized}()) @test isapprox(accel_nonlin, accel_lin; atol = 1e-6) T = Tdes accel_nonlin = pd(gains, x, xdes, T, Tdes) accel_lin = pd(gains, x, xdes, T, Tdes, SE3PDMethod{:Linearized}()) @test isapprox(accel_nonlin, accel_lin; atol = 1e-6) end end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
11910
@testset "simulation" begin @testset "simulate" begin Random.seed!(60) # use simulate function (Munthe-Kaas integrator) acrobot = parse_urdf(joinpath(@__DIR__, "urdf", "Acrobot.urdf"), remove_fixed_tree_joints=false) x = MechanismState(acrobot) rand!(x) total_energy_before = gravitational_potential_energy(x) + kinetic_energy(x) times, qs, vs = simulate(x, 0.1; Δt = 1e-2) set_configuration!(x, qs[end]) set_velocity!(x, vs[end]) total_energy_after = gravitational_potential_energy(x) + kinetic_energy(x) @test isapprox(total_energy_after, total_energy_before, atol = 1e-3) total_energy_before = gravitational_potential_energy(x) + kinetic_energy(x) result = DynamicsResult(acrobot) # use RingBufferStorage using RigidBodyDynamics.OdeIntegrators passive_dynamics! = (vd::AbstractArray, sd::AbstractArray, t, state) -> begin dynamics!(result, state) copyto!(vd, result.v̇) copyto!(sd, result.ṡ) nothing end storage = RingBufferStorage{Float64}(x, 3) integrator = MuntheKaasIntegrator(x, passive_dynamics!, runge_kutta_4(Float64), storage) integrate(integrator, 0.1, 1e-2, max_realtime_rate = 2.0) set_configuration!(x, storage.qs[storage.last_index]) set_velocity!(x, storage.vs[storage.last_index]) @test isapprox(gravitational_potential_energy(x) + kinetic_energy(x), total_energy_before, atol = 1e-3) end @testset "elastic ball drop" begin # Drop a single rigid body with a contact point at the center of mass # onto the floor with a conservative contact model. Check energy # balances and bounce heights. Random.seed!(61) world = RigidBody{Float64}("world") mechanism = Mechanism(world) bodyframe = CartesianFrame3D() body = RigidBody("body", rand(SpatialInertia{Float64}, bodyframe)) floatingjoint = Joint("floating", QuaternionFloating{Float64}()) attach!(mechanism, world, body, floatingjoint) com = center_of_mass(spatial_inertia(body)) model = SoftContactModel(hunt_crossley_hertz(; α = 0.), ViscoelasticCoulombModel(0.5, 1e3, 1e3)) contactpoint = ContactPoint(com, model) add_contact_point!(body, contactpoint) point = Point3D(root_frame(mechanism), zero(SVector{3})) normal = FreeVector3D(root_frame(mechanism), 0., 0., 1.) halfspace = HalfSpace3D(point, normal) add_environment_primitive!(mechanism, halfspace) state = MechanismState(mechanism) z0 = 0.05 zero!(state) tf = transform_to_root(state, body) tf = Transform3D(frame_after(floatingjoint), frame_before(floatingjoint), rotation(tf), SVector(1., 2., z0 - com.v[3])) set_configuration!(state, floatingjoint, tf) energy0 = gravitational_potential_energy(state) com_world = transform_to_root(state, body) * com ts, qs, vs = simulate(state, 0.5; Δt = 1e-3) currentsign = 0. switches = 0 for (t, q, v) in zip(ts, qs, vs) set_configuration!(state, q) set_velocity!(state, v) twist = twist_wrt_world(state, body) com_world = transform_to_root(state, body) * com velocity = point_velocity(twist, com_world) z = com_world.v[3] penetration = max(-z, zero(z)) n = model.normal.n elastic_potential_energy = model.normal.k * penetration^(n + 1) / (n + 1) energy = elastic_potential_energy + kinetic_energy(state) + gravitational_potential_energy(state) @test isapprox(energy0, energy; atol = 1e-2) newsign = sign(velocity.v[3]) (newsign != currentsign) && (switches += 1) currentsign = newsign end @test switches > 3 end @testset "inclined plane" begin θ = 0.5 # plane angle μcrit = tan(θ) # μ > μcrit should show sticking behavior, μ < μcrit should show sliding behavior # set up point mass + inclined plane world = RigidBody{Float64}("world") mechanism = Mechanism(world) floatingjoint = Joint("floating", QuaternionFloating{Float64}()) body = RigidBody("body", SpatialInertia(CartesianFrame3D("inertia"), SMatrix{3, 3}(1.0I), zero(SVector{3}), 2.)) attach!(mechanism, world, body, floatingjoint) worldframe = root_frame(mechanism) inclinedplane = HalfSpace3D(Point3D(worldframe, zero(SVector{3})), FreeVector3D(worldframe, sin(θ), 0., cos(θ))) add_environment_primitive!(mechanism, inclinedplane) irrelevantplane = HalfSpace3D(Point3D(worldframe, 0., 0., -100.), FreeVector3D(worldframe, 0., 0., 1.)) # #211 add_environment_primitive!(mechanism, irrelevantplane) # simulate inclined plane friction experiments normalmodel = hunt_crossley_hertz(k = 50e3; α = 1.) contactlocation = Point3D(default_frame(body), 0., 0., 0.) for μ in (μcrit + 1e-2, μcrit - 1e-2) frictionmodel = ViscoelasticCoulombModel(μ, 50e3, 1e4) m, b = deepcopy((mechanism, body)) add_contact_point!(b, ContactPoint(contactlocation, SoftContactModel(normalmodel, frictionmodel))) state = MechanismState(m) simulate(state, 1., Δt = 1e-3) # settle into steady state x1 = transform(state, contactlocation, worldframe) simulate(state, 0.5, Δt = 1e-3) x2 = transform(state, contactlocation, worldframe) if μ > μcrit # should stick @test isapprox(x1, x2, atol = 1e-4) else # should slip @test !isapprox(x1, x2, atol = 5e-2) end end end @testset "four-bar linkage" begin # gravitational acceleration g = -9.81 # link lengths l_0 = 1.10 l_1 = 0.5 l_2 = 1.20 l_3 = 0.75 # link masses m_1 = 0.5 m_2 = 1.0 m_3 = 0.75 # link center of mass offsets from the preceding joint axes c_1 = 0.25 c_2 = 0.60 c_3 = 0.375 # moments of inertia about the center of mass of each link I_1 = 0.333 I_2 = 0.537 I_3 = 0.4 # scalar type T = Float64 # Rotation axis: negative y-axis axis = SVector(zero(T), -one(T), zero(T)) world = RigidBody{T}("world") mechanism = Mechanism(world; gravity = SVector(0., 0., g)) rootframe = root_frame(mechanism) # link1 and joint1 joint1 = Joint("joint1", Revolute(axis)) inertia1 = SpatialInertia(CartesianFrame3D("inertia1_centroidal"), moment=I_1*axis*axis', com=zero(SVector{3, T}), mass=m_1) link1 = RigidBody(inertia1) before_joint1_to_world = one(Transform3D, frame_before(joint1), default_frame(world)) c1_to_joint = Transform3D(inertia1.frame, frame_after(joint1), SVector(c_1, 0, 0)) attach!(mechanism, world, link1, joint1, joint_pose = before_joint1_to_world, successor_pose = c1_to_joint) # link2 and joint2 joint2 = Joint("joint2", Revolute(axis)) inertia2 = SpatialInertia(CartesianFrame3D("inertia2_centroidal"), moment=I_2*axis*axis', com=zero(SVector{3, T}), mass=m_2) link2 = RigidBody(inertia2) before_joint2_to_after_joint1 = Transform3D(frame_before(joint2), frame_after(joint1), SVector(l_1, 0., 0.)) c2_to_joint = Transform3D(inertia2.frame, frame_after(joint2), SVector(c_2, 0, 0)) attach!(mechanism, link1, link2, joint2, joint_pose = before_joint2_to_after_joint1, successor_pose = c2_to_joint) # link3 and joint3 joint3 = Joint("joint3", Revolute(axis)) inertia3 = SpatialInertia(CartesianFrame3D("inertia3_centroidal"), moment=I_3*axis*axis', com=zero(SVector{3, T}), mass=m_3) link3 = RigidBody(inertia3) before_joint3_to_world = Transform3D(frame_before(joint3), default_frame(world), SVector(l_0, 0., 0.)) c3_to_joint = Transform3D(inertia3.frame, frame_after(joint3), SVector(c_3, 0, 0)) attach!(mechanism, world, link3, joint3, joint_pose = before_joint3_to_world, successor_pose = c3_to_joint) # loop joint between link2 and link3 joint4 = Joint("joint4", Revolute(axis)) before_joint4_to_joint2 = Transform3D(frame_before(joint4), frame_after(joint2), SVector(l_2, 0., 0.)) joint3_to_after_joint4 = Transform3D(frame_after(joint3), frame_after(joint4), SVector(-l_3, 0., 0.)) attach!(mechanism, link2, link3, joint4, joint_pose = before_joint4_to_joint2, successor_pose = joint3_to_after_joint4) # initial state set_initial_state! = function (state::MechanismState) # found through nonlinear optimization. Slightly inaccurate. set_configuration!(state, joint1, 1.6707963267948966) # θ set_configuration!(state, joint2, -1.4591054166649482) # γ set_configuration!(state, joint3, 1.5397303602625536) # ϕ set_velocity!(state, joint1, 0.5) set_velocity!(state, joint2, -0.47295) set_velocity!(state, joint3, 0.341) end # no stabilization state = MechanismState(mechanism) set_initial_state!(state) zero_velocity!(state) energy0 = gravitational_potential_energy(state) ts, qs, vs = simulate(state, 1., Δt = 1e-3, stabilization_gains=nothing) @test kinetic_energy(state) ≉ 0 atol=1e-2 energy1 = gravitational_potential_energy(state) + kinetic_energy(state) @test energy0 ≈ energy1 atol=1e-8 @test transform(state, Point3D(Float64, frame_before(joint4)), rootframe) ≈ transform(state, Point3D(Float64, frame_after(joint4)), rootframe) atol=1e-10 # no significant separation after a short simulation # with default stabilization: start with some separation set_initial_state!(state) set_configuration!(state, joint1, 1.7) @test transform(state, Point3D(Float64, frame_before(joint4)), rootframe) ≉ transform(state, Point3D(Float64, frame_after(joint4)), rootframe) atol=1e-2 # significant separation initially simulate(state, 15., Δt = 1e-3) @test transform(state, Point3D(Float64, frame_before(joint4)), rootframe) ≈ transform(state, Point3D(Float64, frame_after(joint4)), rootframe) atol=1e-5 # reduced separation after 15 seconds energy15 = gravitational_potential_energy(state) + kinetic_energy(state) simulate(state, 10, Δt = 1e-3) energy20 = gravitational_potential_energy(state) + kinetic_energy(state) @test energy20 ≈ energy15 atol=1e-5 # stabilization doesn't significantly affect energy after converging end @testset "Ball joint pendulum" begin # Issue #617 translation = [0.3, 0, 0] world = RigidBody{Float64}("world") pendulum = Mechanism(world; gravity=[0., 0., -9.81]) center_of_mass = [0, 0, 0.2] q0 = [cos(pi/8), sin(pi/8), 0.0, 0.0] joint1 = Joint("joint1", QuaternionSpherical{Float64}()) inertia1 = SpatialInertia(frame_after(joint1), com=center_of_mass, moment_about_com=diagm([1.,1.,1.]), mass=1.) link1 = RigidBody("link1", inertia1) before_joint1_to_world = Transform3D(frame_before(joint1), default_frame(world), one(RotMatrix{3}), SVector{3}(translation)) attach!(pendulum, world, link1, joint1, joint_pose=before_joint1_to_world) state = MechanismState(pendulum) set_configuration!(state, joint1, q0) ts, qs, vs = simulate(state, 1., Δt=0.001) @test all(all(!isnan, q) for q in qs) @test all(all(!isnan, v) for v in vs) end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
15793
function Ad(H::Transform3D) hat = RigidBodyDynamics.Spatial.hat p_hat = hat(translation(H)) [[rotation(H) zero(SMatrix{3, 3, eltype(H)})]; [p_hat * rotation(H) rotation(H)]] end @testset "spatial" begin f1 = CartesianFrame3D("1") f2 = CartesianFrame3D("2") f3 = CartesianFrame3D("3") f4 = CartesianFrame3D("4") @testset "rotation vector rate" begin Random.seed!(62) hat = RigidBodyDynamics.Spatial.hat rotation_vector_rate = RigidBodyDynamics.Spatial.rotation_vector_rate for ϕ in (rand(SVector{3}), zero(SVector{3})) # exponential coordinates (rotation vector) ω = rand(SVector{3}) # angular velocity in body frame R = RotMatrix(RotationVec(ϕ...)) Ṙ = R * hat(ω) ϕ̇ = rotation_vector_rate(ϕ, ω) Θ = norm(ϕ) if Θ > eps(Θ) ϕ_autodiff = ForwardDiff.Dual.(ϕ, ϕ̇) R_autodiff = RotMatrix(RotationVec(ϕ_autodiff...)) Ṙ_from_autodiff = map(x -> ForwardDiff.partials(x)[1], R_autodiff) @test isapprox(Ṙ_from_autodiff, Ṙ) else @test isapprox(ϕ̇, ω) # limit case; hard to test using autodiff because of division by zero end end end @testset "colwise" begin colwise = RigidBodyDynamics.Spatial.colwise v = @SVector [2, 4, 6] M = @SMatrix [1 2 3; 4 5 6; 7 8 9] T = eltype(v) vcross = @SMatrix [zero(T) -v[3] v[2]; v[3] zero(T) -v[1]; -v[2] v[1] zero(T)] @test vcross * M == colwise(×, v, M) @test colwise(×, M, v) == -colwise(×, v, M) @test colwise(+, M, v) == broadcast(+, M, v) v2 = @SVector [1, 2, 3, 4] @test_throws DimensionMismatch colwise(+, M, v2) end @testset "show" begin Random.seed!(63) show(devnull, rand(SpatialInertia{Float64}, f1)) show(devnull, rand(Twist{Float64}, f2, f1, f3)) show(devnull, rand(SpatialAcceleration{Float64}, f2, f1, f3)) show(devnull, rand(Wrench{Float64}, f2)) show(devnull, rand(Momentum{Float64}, f2)) n = 5 show(devnull, GeometricJacobian(f2, f1, f3, rand(SMatrix{3, n}), rand(SMatrix{3, n}))) show(devnull, MomentumMatrix(f2, rand(SMatrix{3, n}), rand(SMatrix{3, n}))) show(devnull, WrenchMatrix(f2, rand(SMatrix{3, n}), rand(SMatrix{3, n}))) end @testset "spatial inertia" begin Random.seed!(64) I2 = rand(SpatialInertia{Float64}, f2) H21 = rand(Transform3D, f2, f1) I1 = transform(I2, H21) I3 = rand(SpatialInertia{Float64}, f2) @test I2.mass == I1.mass @test isapprox(SMatrix(I1), Ad(inv(H21))' * SMatrix(I2) * Ad(inv(H21)); atol = 1e-12) @test isapprox(I2, transform(I1, inv(H21))) @test isapprox(SMatrix(I2) + SMatrix(I3), SMatrix(I2 + I3); atol = 1e-12) if VERSION >= v"1.8" # Inferred as `SpatialInertia{Any}` on Julia 1.6 and 1.7 @inferred transform(zero(SpatialInertia{Float32}, f1), one(Transform3D, f1)) end @test I2 + zero(I2) == I2 # Test that the constructor works with dynamic arrays (which are # converted to static arrays internally) I4 = @inferred(SpatialInertia(f2, Matrix(1.0I, 3, 3), zeros(3), 1.0)) # Ensure that the kwarg constructor matches the positional argument constructor. inertia = rand(SpatialInertia{Float64}, f1) centroidal = CartesianFrame3D("centroidal") to_centroidal = Transform3D(f1, centroidal, -center_of_mass(inertia).v) inertia_centroidal = transform(inertia, to_centroidal) @test inertia_centroidal.frame == centroidal @test center_of_mass(inertia_centroidal) ≈ Point3D(Float64, centroidal) atol=1e-12 inertia_back = SpatialInertia(inertia.frame, moment_about_com=inertia_centroidal.moment, com=center_of_mass(inertia).v, mass=inertia.mass) @test inertia ≈ inertia_back atol=1e-12 end @testset "twist" begin Random.seed!(65) T1 = rand(Twist{Float64}, f2, f1, f3) T2 = rand(Twist{Float64}, f3, f2, f3) T3 = T1 + T2 H31 = rand(Transform3D, f3, f1) @test T3.body == T2.body @test T3.base == T1.base @test T3.frame == f3 # @test isapprox(T2 + T1, T3) # used to be allowed, but makes code slower; just switch T1 and T2 around @test_throws ArgumentError T1 + rand(Twist{Float64}, f3, f2, f4) # wrong frame @test_throws ArgumentError T1 + rand(Twist{Float64}, f3, f4, f3) # wrong base @test isapprox(SVector(transform(T1, H31)), Ad(H31) * SVector(T1)) @test T3 + zero(T3) == T3 # 2.17 in Duindam: f0 = CartesianFrame3D("0") fi = CartesianFrame3D("i") Qi = Point3D(fi, rand(SVector{3})) H = rand(Transform3D, fi, f0) T0 = log(H) Q0 = H * Qi Q̇0 = point_velocity(T0, Q0) f = t -> Array((exp(Twist(T0.body, T0.base, T0.frame, t * angular(T0), t * linear(T0))) * Qi).v) Q̇0check = ForwardDiff.derivative(f, 1.) @test isapprox(Q̇0.v, Q̇0check) end @testset "wrench" begin Random.seed!(66) W = rand(Wrench{Float64}, f2) H21 = rand(Transform3D, f2, f1) @test isapprox(SVector(transform(W, H21)), Ad(inv(H21))' * SVector(W)) @test_throws ArgumentError transform(W, inv(H21)) # wrong frame @test W + zero(W) == W point2 = Point3D(f2, zero(SVector{3})) force2 = FreeVector3D(f2, rand(SVector{3})) W2 = Wrench(point2, force2) @test isapprox(angular(W2), zero(SVector{3})) @test isapprox(linear(W2), force2.v) @test W2.frame == force2.frame point1 = H21 * point2 force1 = H21 * force2 W1 = Wrench(point1, force1) @test W1.frame == f1 @test isapprox(W1, transform(W2, H21)) @test_throws ArgumentError Wrench(point1, force2) # wrong frame @testset "wrench constructed from plain Vectors" begin point1 = Point3D(f1, [1., 0., 0.]) force1 = FreeVector3D(f1, [0, 1, 0]) w = @inferred(Wrench(point1, force1)) @test isa(w, Wrench{Float64}) end end @testset "momentum" begin Random.seed!(67) T = rand(Twist{Float64}, f2, f1, f2) I = rand(SpatialInertia{Float64}, f2) T2 = rand(Twist{Float64}, f2, f1, f1) H21 = rand(Transform3D, f2, f1) h = I * T @test isapprox(SMatrix(I) * SVector(T), SVector(h); atol = 1e-12) @test_throws ArgumentError I * T2 # wrong frame @test isapprox(transform(I, H21) * transform(T, H21), transform(h, H21)) @test isapprox(SVector(transform(h, H21)), Ad(inv(H21))' * SVector(h)) @test_throws ArgumentError transform(h, inv(H21)) # wrong frame @test h + zero(h) == h end @testset "geometric jacobian, power" begin Random.seed!(68) n = 14 J = GeometricJacobian(f2, f1, f3, rand(SMatrix{3, n}), rand(SMatrix{3, n})) v = rand(size(J, 2)) W = rand(Wrench{Float64}, f3) T = Twist(J, v) H = rand(Transform3D, f3, f1) τ = torque(J, W) @test J.body == T.body @test J.base == T.base @test J.frame == T.frame @test isapprox(Twist(transform(J, H), v), transform(T, H)) @test isapprox(dot(Array(τ), v), dot(T, W); atol = 1e-12) # power equality @test_throws ArgumentError dot(transform(T, H), W) @test_throws ArgumentError torque(transform(J, H), W) Jmutable = GeometricJacobian(f2, f1, f3, rand(3, n), rand(3, n)) @test isapprox(Twist(transform(Jmutable, H), v), transform(Twist(Jmutable, v), H)) end @testset "mul! with transpose(mat)" begin Random.seed!(69) mat = WrenchMatrix(f1, rand(SMatrix{3, 4}), rand(SMatrix{3, 4})) vec = rand(SpatialAcceleration{Float64}, f2, f3, f1) k = fill(NaN, size(mat, 2)) mul!(k, transpose(mat), vec) @test isapprox(k, angular(mat)' * angular(vec) + linear(mat)' * linear(vec), atol = 1e-14) @test isapprox(k, transpose(mat) * vec, atol = 1e-14) end @testset "momentum matrix" begin Random.seed!(70) n = 13 A = MomentumMatrix(f3, rand(SMatrix{3, n}), rand(SMatrix{3, n})) v = rand(size(A, 2)) h = Momentum(A, v) H = rand(Transform3D, f3, f1) @test h.frame == A.frame @test isapprox(Momentum(transform(A, H), v), transform(h, H)) end @testset "spatial acceleration" begin Random.seed!(71) I = rand(SpatialInertia{Float64}, f2) Ṫ = rand(SpatialAcceleration{Float64}, f2, f1, f2) T = rand(Twist{Float64}, f2, f1, f2) W = newton_euler(I, Ṫ, T) H = rand(Transform3D, f2, f1) @test isapprox(transform(newton_euler(transform(I, H), transform(Ṫ, H, T, T), transform(T, H)), inv(H)), W) @test Ṫ + zero(Ṫ) == Ṫ end @testset "point_velocity, point_acceleration" begin body = CartesianFrame3D("body") base = CartesianFrame3D("base") frame = CartesianFrame3D("some other frame") # yes, the math does check out if this is different from the other two; ṗ will just be rotated to this frame T = rand(Twist{Float64}, body, base, frame) Ṫ = rand(SpatialAcceleration{Float64}, body, base, frame) p = Point3D(frame, rand(SVector{3})) ṗ = point_velocity(T, p) p̈ = point_acceleration(T, Ṫ, p) @test p̈.frame == frame p_dual = Point3D(p.frame, ForwardDiff.Dual.(p.v, ṗ.v)) T_dual = Twist(T.body, T.base, T.frame, ForwardDiff.Dual.(angular(T), angular(Ṫ)), ForwardDiff.Dual.(linear(T), linear(Ṫ))) ṗ_dual = point_velocity(T_dual, p_dual) p̈_check = FreeVector3D(ṗ_dual.frame, map(x -> ForwardDiff.partials(x, 1), ṗ_dual.v)) @test p̈ ≈ p̈_check atol=1e-12 end @testset "kinetic energy" begin Random.seed!(72) I = rand(SpatialInertia{Float64}, f2) T = rand(Twist{Float64}, f2, f1, f2) H = rand(Transform3D, f2, f1) Ek = kinetic_energy(I, T) @test isapprox((1//2 * SVector(T)' * SMatrix(I) * SVector(T))[1], Ek; atol = 1e-12) @test isapprox(kinetic_energy(transform(I, H), transform(T, H)), Ek; atol = 1e-12) end @testset "log / exp" begin Random.seed!(74) # TODO: https://github.com/JuliaRobotics/RigidBodyDynamics.jl/issues/135 hat = RigidBodyDynamics.Spatial.hat for θ in [LinRange(0., 10 * eps(), 100); LinRange(0., π - eps(), 100)] # have magnitude of parts of twist be bounded by θ to check for numerical issues ϕrot = normalize(rand(SVector{3})) * θ * 2 * (rand() - 0.5) ϕtrans = normalize(rand(SVector{3})) * θ * 2 * (rand() - 0.5) ξ = Twist{Float64}(f2, f1, f1, ϕrot, ϕtrans) H = exp(ξ) @test isapprox(ξ, log(H)) ξhat = [hat(ϕrot) ϕtrans] ξhat = [ξhat; zeros(1, 4)] H_mat = [rotation(H) translation(H)] H_mat = [H_mat; zeros(1, 3) 1.] @test isapprox(exp(ξhat), H_mat) end # test without rotation but with nonzero translation: ξ = Twist{Float64}(f2, f1, f1, zero(SVector{3}), rand(SVector{3})) H = exp(ξ) @test isapprox(ξ, log(H)) # test rotation for θ > π for θ in [LinRange(π - 10 * eps(), π + 10 * eps(), 100); LinRange(π, 6 * π, 100)] ω = normalize(rand(SVector{3})) ξ1 = Twist(f2, f1, f1, ω * θ, zero(SVector{3})) ξ2 = Twist(f2, f1, f1, ω * mod(θ, 2 * π), zero(SVector{3})) @test isapprox(exp(ξ1), exp(ξ2)) end # derivative for θ in LinRange(1e-3, π - 1e-3, 100) # autodiff doesn't work close to the identity rotation hat = RigidBodyDynamics.Spatial.hat ξ = Twist{Float64}(f2, f1, f1, θ * normalize(rand(SVector{3})), θ * normalize(rand(SVector{3}))) H = exp(ξ) T = Twist{Float64}(f2, f1, f2, rand(SVector{3}), rand(SVector{3})) ξ2, ξ̇ = RigidBodyDynamics.log_with_time_derivative(H, T) @test isapprox(ξ, ξ2) # autodiff log. Need time derivative of transform in ForwardDiff form, so need to basically v_to_qdot for quaternion floating joint rotdot = rotation(H) * hat(angular(T)) transdot = rotation(H) * linear(T) trans_autodiff = @SVector [ForwardDiff.Dual(translation(H)[i], transdot[i]) for i in 1 : 3] rot_autodiff = RotMatrix(@SMatrix [ForwardDiff.Dual(rotation(H)[i, j], rotdot[i, j]) for i in 1 : 3, j in 1 : 3]) H_autodiff = Transform3D(H.from, H.to, rot_autodiff, trans_autodiff) ξ_autodiff = log(H_autodiff) ξ̇rot_from_autodiff = @SVector [ForwardDiff.partials(angular(ξ_autodiff)[i])[1] for i in 1 : 3] ξ̇trans_from_autodiff = @SVector [ForwardDiff.partials(linear(ξ_autodiff)[i])[1] for i in 1 : 3] ξ̇_from_autodiff = SpatialAcceleration(ξ.body, ξ.base, ξ.frame, ξ̇rot_from_autodiff, ξ̇trans_from_autodiff) @test isapprox(ξ̇, ξ̇_from_autodiff) end end @testset "RotationVec linearization" begin Random.seed!(75) ϵ = 1e-3 for i = 1 : 100 e = RotMatrix(AngleAxis(ϵ, randn(), randn(), randn())) rv = RotationVec(e) rv_lin = linearized_rodrigues_vec(e) lin_error = AngleAxis(rv \ rv_lin) @test rotation_angle(lin_error) ≈ 0 atol = 1e-8 end end @testset "Conversions to vector/matrix" begin f = CartesianFrame3D() angular = [1, 2, 3] linear = [4, 5, 6] twist = Twist(f, f, f, angular, linear) svec = SVector(angular..., linear...) twist64 = Twist(f, f, f, Float64.(angular), Float64.(linear)) svec64 = SVector{6, Float64}(svec) @test twist isa Twist{Int} @test Twist{Float64}(twist) === twist64 @test convert(Twist{Float64}, twist) === twist64 @test SVector{6, Float64}(twist) === svec64 @test convert(SVector{6, Float64}, twist) === svec64 @test SVector{6}(twist) === svec @test convert(SVector{6}, twist) === svec @test SArray(twist) === svec @test convert(SArray, twist) === svec moment = [1 2 3; 2 4 5; 3 5 6] crosspart = [7, 8, 9] mass = 10 inertia = SpatialInertia(f, moment, crosspart, mass) inertia64 = SpatialInertia(f, Float64.(moment), Float64.(crosspart), Float64(mass)) mat = SMatrix(inertia) # already tested above mat64 = SMatrix{6, 6, Float64}(mat) @test inertia isa SpatialInertia{Int} @test SpatialInertia{Float64}(inertia) === inertia64 @test convert(SpatialInertia{Float64}, inertia) === inertia64 @test SMatrix{6, 6}(inertia) === mat @test convert(SMatrix{6, 6}, inertia) === mat @test SMatrix{6, 6, Float64}(inertia) === mat64 @test convert(SMatrix{6, 6, Float64}, inertia) === mat64 @test SMatrix(inertia64) === mat64 @test convert(SMatrix, inertia64) === mat64 J = GeometricJacobian(f, f, f, rand(1:10, 3, 4), rand(1:10, 3, 4)) @test convert(Array, J) == Array(J) == Matrix(J) == [J.angular; J.linear] @test convert(Array{Float64}, J) == Array{Float64}(J) == Matrix{Float64}(J) == Float64[J.angular; J.linear] @test Matrix(J) == [J.angular; J.linear] @test Matrix(J) == [J.angular; J.linear] end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
9866
@testset "URDF parse" begin @testset "joint bounds" begin acrobot = parse_urdf(joinpath(@__DIR__, "urdf", "Acrobot.urdf"), remove_fixed_tree_joints=false) @test position_bounds(findjoint(acrobot, "shoulder")) == [RigidBodyDynamics.Bounds(-Inf, Inf)] @test velocity_bounds(findjoint(acrobot, "shoulder")) == [RigidBodyDynamics.Bounds(-Inf, Inf)] @test effort_bounds(findjoint(acrobot, "shoulder")) == [RigidBodyDynamics.Bounds(-Inf, Inf)] @test position_bounds(findjoint(acrobot, "elbow")) == [RigidBodyDynamics.Bounds(-Inf, Inf)] @test velocity_bounds(findjoint(acrobot, "elbow")) == [RigidBodyDynamics.Bounds(-Inf, Inf)] @test effort_bounds(findjoint(acrobot, "elbow")) == [RigidBodyDynamics.Bounds(-Inf, Inf)] acrobot_with_limits = parse_urdf(joinpath(@__DIR__, "urdf", "Acrobot_with_limits.urdf"), remove_fixed_tree_joints=false) @test position_bounds(findjoint(acrobot_with_limits, "shoulder")) == [RigidBodyDynamics.Bounds(-6.28, 6.28)] @test velocity_bounds(findjoint(acrobot_with_limits, "shoulder")) == [RigidBodyDynamics.Bounds(-10, 10)] @test effort_bounds(findjoint(acrobot_with_limits, "shoulder")) == [RigidBodyDynamics.Bounds(0, 0)] @test position_bounds(findjoint(acrobot_with_limits, "elbow")) == [RigidBodyDynamics.Bounds(-6.28, 6.28)] @test velocity_bounds(findjoint(acrobot_with_limits, "elbow")) == [RigidBodyDynamics.Bounds(-10, 10)] @test effort_bounds(findjoint(acrobot_with_limits, "elbow")) == [RigidBodyDynamics.Bounds(-5, 5)] end @testset "planar joints" begin robot = parse_urdf(joinpath(@__DIR__, "urdf", "planar_slider.urdf"), remove_fixed_tree_joints=false) # the first joint is the fixed joint between the world and the base link jt = joint_type(joints(robot)[1]) @test jt isa Fixed # the 2nd joint is planar with <axis xyz="1 0 0"/> jt = joint_type(joints(robot)[2]) @test jt isa Planar @test jt.x_axis ≈ SVector(0, 0, -1) @test jt.y_axis ≈ SVector(0, 1, 0) # the 3rd joint is planar with <axis xyz="0 1 0"/> jt = joint_type(joints(robot)[3]) @test jt isa Planar @test jt.x_axis ≈ SVector(1, 0, 0) @test jt.y_axis ≈ SVector(0, 0, -1) # the 4th joint is planar with <axis xyz="0 0 1"/> jt = joint_type(joints(robot)[4]) @test jt isa Planar @test jt.x_axis ≈ SVector(1, 0, 0) @test jt.y_axis ≈ SVector(0, 1, 0) end @testset "rotation handling" begin # https://github.com/JuliaRobotics/RigidBodyDynamics.jl/issues/429 xml = """ <origin rpy="0 0 0"/> """ xpose = LightXML.root(LightXML.parse_string(xml)) rot, trans = RigidBodyDynamics.parse_pose(Float64, xpose) @test rot ≈ SDiagonal(1, 1, 1) @test trans ≈ SVector(0, 0, 0) xml = """ <origin rpy="0.3 0 0"/> """ xpose = LightXML.root(LightXML.parse_string(xml)) rot, trans = RigidBodyDynamics.parse_pose(Float64, xpose) @test rot ≈ RotMatrix(RotX(0.3)) @test trans ≈ SVector(0, 0, 0) xml = """ <origin rpy="0 0.2 0"/> """ xpose = LightXML.root(LightXML.parse_string(xml)) rot, trans = RigidBodyDynamics.parse_pose(Float64, xpose) @test rot ≈ RotMatrix(RotY(0.2)) @test trans ≈ SVector(0, 0, 0) xml = """ <origin rpy="0 0 0.1"/> """ xpose = LightXML.root(LightXML.parse_string(xml)) rot, trans = RigidBodyDynamics.parse_pose(Float64, xpose) @test rot ≈ RotMatrix(RotZ(0.1)) @test trans ≈ SVector(0, 0, 0) # Comparison against ROS's tf.transformations.quaternion_from_euler xml = """ <origin rpy="1 2 3"/> """ xpose = LightXML.root(LightXML.parse_string(xml)) rot, trans = RigidBodyDynamics.parse_pose(Float64, xpose) @test rot ≈ [0.41198225 -0.83373765 -0.36763046; -0.05872664 -0.42691762 0.90238159; -0.90929743 -0.35017549 -0.2248451] atol=1e-7 @test rot ≈ RotZ(3) * RotY(2) * RotX(1) @test trans ≈ SVector(0, 0, 0) # Comparison against ROS's tf.transformations.quaternion_from_euler xml = """ <origin rpy="0.5 0.1 0.2"/> """ xpose = LightXML.root(LightXML.parse_string(xml)) rot, trans = RigidBodyDynamics.parse_pose(Float64, xpose) @test rot ≈ [0.97517033 -0.12744012 0.18111281; 0.19767681 0.86959819 -0.45246312; -0.09983342 0.47703041 0.8731983] atol=1e-7 @test rot ≈ RotZ(0.2) * RotY(0.1) * RotX(0.5) @test trans ≈ SVector(0, 0, 0) end end function test_inverse_dynamics_match(mechanism1::Mechanism, mechanism2::Mechanism; atol::Real=0, rtol::Real=atol>0 ? 0 : √eps) state1 = MechanismState(mechanism1) v̇_vec = rand(num_velocities(mechanism1)) rand!(state1) v̇1 = copyto!(similar(velocity(state1)), v̇_vec) τ1 = inverse_dynamics(state1, v̇1) state2 = MechanismState(mechanism2) copyto!(state2, Vector(state1)) v̇2 = copyto!(similar(velocity(state2)), v̇_vec) τ2 = inverse_dynamics(state2, v̇2) @test τ1 ≈ τ2 rtol=rtol atol=atol end function test_kinematic_graph_layout_match(mechanism1::Mechanism, mechanism2::Mechanism) for (j1, j2) in zip(joints(mechanism1), joints(mechanism2)) @test string(j1) == string(j2) @test string(predecessor(j1, mechanism1)) == string(predecessor(j2, mechanism2)) @test string(successor(j1, mechanism1)) == string(successor(j2, mechanism2)) @test joint_type(j1) == joint_type(j2) end end function test_urdf_serialize_deserialize(mechanism1::Mechanism; remove_fixed_tree_joints::Bool) state1 = MechanismState(mechanism1) mktempdir() do dir urdf2 = joinpath(dir, "test.urdf") write_urdf(urdf2, mechanism1, robot_name="test") mechanism2 = parse_urdf(urdf2, remove_fixed_tree_joints=remove_fixed_tree_joints) test_inverse_dynamics_match(mechanism1, mechanism2, atol=1e-10) for joint1 in tree_joints(mechanism1) if remove_fixed_tree_joints && joint_type(joint1) isa Fixed continue else joint2 = findjoint(mechanism2, string(joint1)) @test position_bounds(joint1) == position_bounds(joint2) @test velocity_bounds(joint1) == velocity_bounds(joint2) @test effort_bounds(joint1) == effort_bounds(joint2) end end end end @testset "URDF write" begin @testset "Basics" begin Random.seed!(124) urdfdir = joinpath(@__DIR__, "urdf") for basename in readdir(urdfdir) last(splitext(basename)) == ".urdf" || continue urdf = joinpath(urdfdir, basename) for floating in (true, false) for remove_fixed_joints_before in (true, false) mechanism = parse_urdf(urdf, remove_fixed_tree_joints=remove_fixed_joints_before, floating=floating) for remove_fixed_joints_after in (true, false) test_urdf_serialize_deserialize(mechanism, remove_fixed_tree_joints=remove_fixed_joints_after) end end end end end @testset "include_root" begin Random.seed!(1245) urdfdir = joinpath(@__DIR__, "urdf") for basename in readdir(urdfdir) last(splitext(basename)) == ".urdf" || continue urdf = joinpath(urdfdir, basename) unmodified_mechanism = parse_urdf(urdf, remove_fixed_tree_joints=false) floating_mechanism = parse_urdf(urdf, remove_fixed_tree_joints=false, floating=true) # Write unmodified mechanism to URDF using `include_root=false`, then parse # using the default `Fixed` joint type as the root joint type. Ensure we get # the same kinematic tree. mktempdir() do dir urdf2 = joinpath(dir, "test.urdf") write_urdf(urdf2, unmodified_mechanism, include_root=false) unmodified_mechanism_back = parse_urdf(urdf2, remove_fixed_tree_joints=false) test_kinematic_graph_layout_match(unmodified_mechanism, unmodified_mechanism_back) test_inverse_dynamics_match(unmodified_mechanism, unmodified_mechanism_back, atol=1e-10) end # Write floating-base mechanism to URDF using `include_root=true` (default), then parse # using the default `Fixed` joint type as the root joint type: mktempdir() do dir urdf2 = joinpath(dir, "test.urdf") write_urdf(urdf2, floating_mechanism) floating_mechanism_back = parse_urdf(urdf2) # Note: floating_mechanism_back has an extra fixed joint at the root, compared to floating_mechanism, # but is dynamically equivalent. test_inverse_dynamics_match(floating_mechanism, floating_mechanism_back, atol=1e-10) end # Write floating-base mechanism to URDF using `include_root=false`, then parse and compare # to unmodified mechanism: mktempdir() do dir urdf2 = joinpath(dir, "test.urdf") write_urdf(urdf2, floating_mechanism, include_root=false) unmodified_mechanism_back = parse_urdf(urdf2, remove_fixed_tree_joints=false) test_kinematic_graph_layout_match(unmodified_mechanism, unmodified_mechanism_back) test_inverse_dynamics_match(unmodified_mechanism, unmodified_mechanism_back, atol=1e-10) end end end end
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
4375
# RigidBodyDynamics.jl [![Build Status](https://github.com/JuliaRobotics/RigidBodyDynamics.jl/workflows/CI/badge.svg)](https://github.com/JuliaRobotics/RigidBodyDynamics.jl/actions?query=workflow%3ACI) [![codecov.io](https://codecov.io/github/JuliaRobotics/RigidBodyDynamics.jl/coverage.svg?branch=master)](https://codecov.io/github/JuliaRobotics/RigidBodyDynamics.jl?branch=master) [![](https://img.shields.io/badge/docs-latest-blue.svg)](https://JuliaRobotics.github.io/RigidBodyDynamics.jl/dev) [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaRobotics.github.io/RigidBodyDynamics.jl/stable) RigidBodyDynamics.jl is a rigid body dynamics library in pure Julia. It aims to be **user friendly** and [**performant**](https://github.com/JuliaRobotics/RigidBodyDynamics.jl/blob/master/docs/src/benchmarks.md), but also **generic** in the sense that the algorithms can be called with inputs of any (suitable) scalar types. This means that if fast numeric dynamics evaluations are required, a user can supply `Float64` or `Float32` inputs. However, if symbolic quantities are desired for analysis purposes, they can be obtained by calling the algorithms with e.g. [`SymPy.Sym`](https://github.com/JuliaPy/SymPy.jl) inputs. If gradients are required, e.g. the [`ForwardDiff.Dual`](https://github.com/JuliaDiff/ForwardDiff.jl) type, which implements forward-mode [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation), can be used. See the [latest stable documentation](https://JuliaRobotics.github.io/RigidBodyDynamics.jl/stable) for a list of features, installation instructions, and a quick-start guide. Installation should only take a couple of minutes, including installing Julia itself. The documentation includes various usage examples, starting with a [quickstart guide](http://www.juliarobotics.org/RigidBodyDynamics.jl/dev/generated/1.%20Quickstart%20-%20double%20pendulum/1.%20Quickstart%20-%20double%20pendulum/). These examples are also runnable locally as Jupyter notebooks; see [the readme in the examples directory](https://github.com/JuliaRobotics/RigidBodyDynamics.jl/blob/master/examples/README.md) for instructions. ## Related packages RigidBodyDynamics.jl is part of the [JuliaRobotics GitHub organization](http://www.juliarobotics.org/). Packages built on top of RigidBodyDynamics.jl include: * [RigidBodySim.jl](https://github.com/JuliaRobotics/RigidBodySim.jl) - simulator built on top of RigidBodyDynamics.jl. * [MeshCatMechanisms.jl](https://github.com/JuliaRobotics/MeshCatMechanisms.jl) - 3D visualization of articulated mechanisms using MeshCat.jl (built on top of [three.js](https://threejs.org/)) and RigidBodyDynamics.jl. * [RigidBodyTreeInspector.jl](https://github.com/rdeits/RigidBodyTreeInspector.jl) - 3D visualization of RigidBodyDynamics.jl `Mechanism`s using [Director](https://github.com/RobotLocomotion/director). * [MotionCaptureJointCalibration.jl](https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl) - kinematic calibration for robots using motion capture data, built on top of RigidBodyDynamics.jl * [QPControl.jl](https://github.com/tkoolen/QPControl.jl) - quadratic-programming-based robot controllers implemented using RigidBodyDynamics.jl. * [StrandbeestRobot.jl](https://github.com/rdeits/StrandbeestRobot.jl) - simulations of a 12-legged parallel walking mechanism inspired by Theo Jansens's [Strandbeest](https://www.strandbeest.com/) using RigidBodyDynamics.jl. ## Talks / publications * May 20, 2019: paper at ICRA 2019: [Julia for robotics: simulation and real-time control in a high-level programming language](https://www.researchgate.net/publication/331983442_Julia_for_robotics_simulation_and_real-time_control_in_a_high-level_programming_language). * August 10, 2018: Robin Deits gave [a talk](https://www.youtube.com/watch?v=dmWQtI3DFFo) at JuliaCon 2018 demonstrating RigidBodyDynamics.jl and related packages. * August 23, 2017: a video of a JuliaCon 2017 talk given by Robin Deits and Twan Koolen on using Julia for robotics [has been uploaded](https://www.youtube.com/watch?v=gPYc77M90Qg). It includes a brief demo of RigidBodyDynamics.jl and RigidBodyTreeInspector.jl. Note that RigidBodyDynamics.jl performance has significantly improved since this talk. The margins of the slides have unfortunately been cut off somewhat in the video.
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
675
Release checklist: * [ ] check REQUIRE files * [ ] Run tests from previous released version against master. Ensure that there are reasonable deprecation messages, etc. * Run tests for registered dependencies: * [ ] MechanismGeometries * [ ] MeshCatMechanisms * [ ] RigidBodyTreeInspector * [ ] MotionCaptureJointCalibration (Interact problem though) * [ ] RigidBodySim * [ ] ValkyrieRobot * [ ] AtlasRobot * Run tests for unregistered dependencies: * [ ] LCPSim * [ ] HumanoidLCMSim * [ ] Ensure that docs are up to date and that they build properly * [ ] Update benchmark results, if relevant * [ ] Write release notes * [ ] Use Attobot to set up release
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
276
# Algorithms ## Index ```@index Pages = ["algorithms.md"] Order = [:type, :function] ``` ## The `DynamicsResult` type ```@docs DynamicsResult ``` ## Functions ```@autodocs Modules = [RigidBodyDynamics] Order = [:function] Pages = ["mechanism_algorithms.jl"] ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
2637
# Benchmarks To attain maximal performance, it is recommended to pass `-O3`, `--check-bounds=no` as command line flags to `julia`. As of Julia 1.1, maximizing performance for the `dynamics!` algorithm requires either setting the number of BLAS threads to 1 (`using LinearAlgebra; BLAS.set_num_threads(1)`) if using OpenBLAS (the default), or compiling Julia with MKL. See [this issue](https://github.com/JuliaRobotics/RigidBodyDynamics.jl/issues/500) for more information. Run `perf/runbenchmarks.jl` to see benchmark results for the Atlas robot (v5). Results below are for the following scenarios: 1. Compute the joint-space mass matrix. 2. Compute both the mass matrix and a geometric Jacobian from the left hand to the right foot. 3. Do inverse dynamics. 4. Do forward dynamics. Note that results on CI builds are **not at all** representative because of code coverage. Results on a reasonably fast laptop at commit [870bea6](https://github.com/JuliaRobotics/RigidBodyDynamics.jl/commit/870bea668d5b11ce0555fa0552592d2c3cb15c54): Output of `versioninfo()`: ``` Julia Version 1.5.3 Commit 788b2c77c1 (2020-11-09 13:37 UTC) Platform Info: OS: macOS (x86_64-apple-darwin18.7.0) CPU: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz WORD_SIZE: 64 LIBM: libopenlibm LLVM: libLLVM-9.0.1 (ORCJIT, skylake) ``` Note that this is a different machine than the one that was used for earlier benchmarks. Mass matrix: ``` memory estimate: 0 bytes allocs estimate: 0 -------------- minimum time: 4.415 μs (0.00% GC) median time: 4.579 μs (0.00% GC) mean time: 4.916 μs (0.00% GC) maximum time: 19.794 μs (0.00% GC) ``` Mass matrix and Jacobian from left hand to right foot: ``` memory estimate: 0 bytes allocs estimate: 0 -------------- minimum time: 4.860 μs (0.00% GC) median time: 4.982 μs (0.00% GC) mean time: 5.399 μs (0.00% GC) maximum time: 24.712 μs (0.00% GC) ``` Note the low additional cost of computing a Jacobian when the mass matrix is already computed. This is because RigidBodyDynamics.jl caches intermediate computation results. Inverse dynamics: ``` memory estimate: 0 bytes allocs estimate: 0 -------------- minimum time: 4.256 μs (0.00% GC) median time: 4.541 μs (0.00% GC) mean time: 4.831 μs (0.00% GC) maximum time: 21.625 μs (0.00% GC) ``` Forward dynamics: ``` memory estimate: 0 bytes allocs estimate: 0 -------------- minimum time: 13.600 μs (0.00% GC) median time: 14.419 μs (0.00% GC) mean time: 16.071 μs (0.00% GC) maximum time: 55.328 μs (0.00% GC) ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
81
# `StateCache` ```@docs StateCache DynamicsResultCache SegmentedVectorCache ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
256
# Custom collection types ## Index ```@index Pages = ["customcollections.md"] Order = [:type, :function] ``` ## Types ```@autodocs Modules = [RigidBodyDynamics.CustomCollections] Order = [:type, :function] Pages = ["custom_collections.jl"] ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
4006
# RigidBodyDynamics RigidBodyDynamics implements various rigid body dynamics and kinematics algorithms. ## Design features Some of the key design features of this package are: * pure Julia implementation, enabling seamless support for e.g. automatic differentiation using [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl) and symbolic dynamics using [SymPy.jl](https://github.com/JuliaPy/SymPy.jl). * easy creation and modification of general rigid body mechanisms. * basic parsing of and writing to the [URDF](http://wiki.ros.org/urdf) file format. * extensive checks that verify that coordinate systems match before computation, with the goal of making reference frame mistakes impossible * flexible caching of intermediate results to prevent doing double work * fairly small codebase and few dependencies * singularity-free rotation parameterizations ## Functionality Current functionality of RigidBodyDynamics.jl includes: * kinematics/transforming points and free vectors from one coordinate system to another * transforming wrenches, momenta (spatial force vectors) and twists and their derivatives (spatial motion vectors) from one coordinate system to another * relative twists/spatial accelerations between bodies * kinetic/potential energy * center of mass * geometric/basic/spatial Jacobians * momentum * momentum matrix * momentum rate bias (= momentum matrix time derivative multiplied by joint velocity vector) * mass matrix (composite rigid body algorithm) * inverse dynamics (recursive Newton-Euler) * dynamics * simulation, either using an off-the-shelf ODE integrator or using an included custom Munthe-Kaas integrator that properly handles second-order ODEs defined on a manifold. Closed-loop systems (parallel mechanisms) are supported, with optional Baumgarte stabilization of the loop joint constraints. Support for contact is very limited (possibly subject to major changes in the future), implemented using penalty methods. ## Installation ### Installing Julia Download links and more detailed instructions are available on the [Julia website](http://julialang.org/). The latest version of RigidBodyDynamics.jl requires Julia 0.7, but we recommend downloading 1.0 (the latest stable Julia release at the time of writing). Version 0.7 of RigidBodyDynamics.jl is the last to support Julia 0.6. !!! warning Do **not** use `apt-get` or `brew` to install Julia, as the versions provided by these package managers tend to be out of date. ### Installing RigidBodyDynamics To install the latest tagged release of RigidBodyDynamics, start Julia and enter `Pkg` mode by pressing `]`. Then simply run ```julia add RigidBodyDynamics ``` To use the latest master version and work on the bleeding edge (generally, not recommended), instead run ```julia add RigidBodyDynamics#master ``` A third option is to clone the repository (to the directory printed by `julia -e 'import Pkg; println(Pkg.devdir())'`): ```julia dev RigidBodyDynamics ``` ## About This library was inspired by [IHMCRoboticsToolkit](https://bitbucket.org/ihmcrobotics/ihmc-open-robotics-software) and by [Drake](http://drake.mit.edu). Most of the nomenclature used and algorithms implemented by this package stem from the following resources: * Murray, Richard M., et al. *A mathematical introduction to robotic manipulation*. CRC press, 1994. * Featherstone, Roy. *Rigid body dynamics algorithms*. Springer, 2008. * Duindam, Vincent. *Port-based modeling and control for efficient bipedal walking robots*. Diss. University of Twente, 2006. ## Contents ```@contents Pages = [ "spatial.md", "joints.md", "rigidbody.md", "mechanism.md", "mechanismstate.md", "algorithms.md", "caches.md", "simulation.md", "urdf.md", "benchmarks.md"] Depth = 2 ``` ## Citing this library ```bibtex @misc{rigidbodydynamicsjl, author = "Twan Koolen and contributors", title = "RigidBodyDynamics.jl", year = 2016, url = "https://github.com/JuliaRobotics/RigidBodyDynamics.jl" } ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
750
# Joints ## Index ```@index Pages = ["joints.md"] Order = [:type, :function] ``` ## The `Joint` type ```@docs Joint ``` ## Functions ```@autodocs Modules = [RigidBodyDynamics] Order = [:function] Pages = ["joint.jl"] ``` ## `JointType`s ```@docs JointType ``` ### Fixed ```@docs Fixed ``` ### Revolute ```@docs Revolute Revolute(axis) ``` ### Prismatic ```@docs Prismatic Prismatic(axis) ``` ### Planar ```@docs Planar Planar{T}(x_axis::AbstractVector, y_axis::AbstractVector) where {T} ``` ### QuaternionSpherical ```@docs QuaternionSpherical ``` ### QuaternionFloating ```@docs QuaternionFloating ``` ### SPQuatFloating ```@docs SPQuatFloating ``` ### SinCosRevolute ```@docs SinCosRevolute SinCosRevolute(axis) ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
555
# Mechanisms ## Index ```@index Pages = ["mechanism.md"] Order = [:type, :function] ``` ## The `Mechanism` type ```@docs Mechanism ``` ## [Creating and modifying `Mechanism`s](@id mechanism_create) See also [URDF parsing and writing](@ref) for URDF file format support. ```@docs Mechanism(root_body; gravity) ``` ```@autodocs Modules = [RigidBodyDynamics] Order = [:function] Pages = ["mechanism_modification.jl"] ``` ## Basic functionality ```@autodocs Modules = [RigidBodyDynamics] Order = [:function] Pages = ["mechanism.jl"] ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
279
# MechanismState ## Index ```@index Pages = ["mechanismstate.md"] Order = [:type, :function] ``` ## The `MechanismState` type ```@docs MechanismState ``` ## Functions ```@autodocs Modules = [RigidBodyDynamics] Order = [:function] Pages = ["mechanism_state.jl"] ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
257
# Rigid bodies ## Index ```@index Pages = ["rigidbody.md"] Order = [:type, :function] ``` ## The `RigidBody` type ```@docs RigidBody ``` ## Functions ```@autodocs Modules = [RigidBodyDynamics] Order = [:function] Pages = ["rigid_body.jl"] ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
528
# Simulation ## Index ```@index Pages = ["simulation.md"] Order = [:type, :function] ``` ## Basic simulation ```@docs simulate ``` ## Lower level ODE integration interface ```@docs MuntheKaasIntegrator MuntheKaasIntegrator(state::X, dynamics!::F, tableau::ButcherTableau{N, T, L}, sink::S) where {N, T, F, S<:OdeResultsSink, X, L} ButcherTableau OdeResultsSink RingBufferStorage ExpandingStorage ``` ```@autodocs Modules = [RigidBodyDynamics.OdeIntegrators] Order = [:function] Pages = ["ode_integrators.jl"] ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
751
# Spatial vector algebra ## Index ```@index Pages = ["spatial.md"] Order = [:type, :function, :macro] ``` ## Types ### Coordinate frames ```@docs CartesianFrame3D CartesianFrame3D(::String) CartesianFrame3D() ``` ### Transforms ```@docs Transform3D ``` ### Points, free vectors ```@docs Point3D FreeVector3D ``` ### Inertias ```@docs SpatialInertia ``` ### Twists, spatial accelerations ```@docs Twist SpatialAcceleration ``` ### Momenta, wrenches ```@docs Momentum Wrench ``` ### Geometric Jacobians ```@docs GeometricJacobian ``` ### Momentum matrices ```@docs MomentumMatrix ``` ## The `@framecheck` macro ```@docs @framecheck ``` ## Functions ```@autodocs Modules = [RigidBodyDynamics.Spatial] Order = [:function] ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
88
# URDF parsing and writing ```@docs default_urdf_joint_types parse_urdf write_urdf ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
docs
862
# RigidBodyDynamics.jl examples This directory contains various RigidBodyDynamics.jl usage examples. The `.jl` files in each subdirectory are meant to be processed using [Literate.jl](https://github.com/fredrikekre/Literate.jl). During the documentation build process, the `.jl` files are converted to markdown files that end up in the package documentation. You can also generate Jupyter notebooks and run them locally by performing the following steps: 1. [install RigidBodyDynamics.jl](http://www.juliarobotics.org/RigidBodyDynamics.jl/stable/#Installation-1) 2. [install IJulia](https://github.com/JuliaLang/IJulia.jl) (`add` it to the default project) 3. in the Julia REPL, run ``` using Pkg Pkg.build("RigidBodyDynamics") using IJulia, RigidBodyDynamics notebook(dir=joinpath(dirname(pathof(RigidBodyDynamics)), "..", "examples")) ```
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git
[ "MIT" ]
0.4.7
1e03704320016415ef5dcc2c54edc3f20ee37bca
code
551
# ----------------------------------------------------------------- # Licensed under the MIT License. See LICENSE in the project root. # ----------------------------------------------------------------- module DataScienceTraitsCategoricalArraysExt using DataScienceTraits using CategoricalArrays DataScienceTraits.scitype(::Type{<:CategoricalValue}) = DataScienceTraits.Categorical DataScienceTraits.elscitype(::Type{<:CategoricalArray}) = DataScienceTraits.Categorical DataScienceTraits.isordered(array::CategoricalArray) = isordered(array) end
DataScienceTraits
https://github.com/JuliaML/DataScienceTraits.jl.git
[ "MIT" ]
0.4.7
1e03704320016415ef5dcc2c54edc3f20ee37bca
code
361
# ----------------------------------------------------------------- # Licensed under the MIT License. See LICENSE in the project root. # ----------------------------------------------------------------- module DataScienceTraitsCoDaExt using DataScienceTraits using CoDa DataScienceTraits.scitype(::Type{<:Composition}) = DataScienceTraits.Compositional end
DataScienceTraits
https://github.com/JuliaML/DataScienceTraits.jl.git
[ "MIT" ]
0.4.7
1e03704320016415ef5dcc2c54edc3f20ee37bca
code
365
# ----------------------------------------------------------------- # Licensed under the MIT License. See LICENSE in the project root. # ----------------------------------------------------------------- module DataScienceTraitsColorTypesExt using DataScienceTraits using ColorTypes DataScienceTraits.scitype(::Type{<:Colorant}) = DataScienceTraits.Colorful end
DataScienceTraits
https://github.com/JuliaML/DataScienceTraits.jl.git
[ "MIT" ]
0.4.7
1e03704320016415ef5dcc2c54edc3f20ee37bca
code
395
# ----------------------------------------------------------------- # Licensed under the MIT License. See LICENSE in the project root. # ----------------------------------------------------------------- module DataScienceTraitsDistributionsExt using DataScienceTraits using Distributions: Distribution DataScienceTraits.scitype(::Type{<:Distribution}) = DataScienceTraits.Distributional end
DataScienceTraits
https://github.com/JuliaML/DataScienceTraits.jl.git
[ "MIT" ]
0.4.7
1e03704320016415ef5dcc2c54edc3f20ee37bca
code
753
# ----------------------------------------------------------------- # Licensed under the MIT License. See LICENSE in the project root. # ----------------------------------------------------------------- module DataScienceTraitsDynamicQuantitiesExt using DataScienceTraits using DynamicQuantities: AbstractQuantity, Quantity DataScienceTraits.scitype(::Type{<:AbstractQuantity{T}}) where {T} = scitype(T) DataScienceTraits.sciconvert(::Type{DataScienceTraits.Continuous}, x::AbstractQuantity{<:Integer}) = float(x) DataScienceTraits.sciconvert(::Type{DataScienceTraits.Categorical}, x::AbstractQuantity{<:Number}) = convert(Quantity{Int}, x) DataScienceTraits.sciconvert(::Type{DataScienceTraits.Categorical}, x::AbstractQuantity{<:Integer}) = x end
DataScienceTraits
https://github.com/JuliaML/DataScienceTraits.jl.git
[ "MIT" ]
0.4.7
1e03704320016415ef5dcc2c54edc3f20ee37bca
code
369
# ----------------------------------------------------------------- # Licensed under the MIT License. See LICENSE in the project root. # ----------------------------------------------------------------- module DataScienceTraitsMeshesExt using DataScienceTraits using Meshes: Geometry DataScienceTraits.scitype(::Type{<:Geometry}) = DataScienceTraits.Geometrical end
DataScienceTraits
https://github.com/JuliaML/DataScienceTraits.jl.git
[ "MIT" ]
0.4.7
1e03704320016415ef5dcc2c54edc3f20ee37bca
code
733
# ----------------------------------------------------------------- # Licensed under the MIT License. See LICENSE in the project root. # ----------------------------------------------------------------- module DataScienceTraitsUnitfulExt using DataScienceTraits using Unitful: AbstractQuantity, Quantity DataScienceTraits.scitype(::Type{<:AbstractQuantity{T}}) where {T} = scitype(T) DataScienceTraits.sciconvert(::Type{DataScienceTraits.Continuous}, x::AbstractQuantity{<:Integer}) = float(x) DataScienceTraits.sciconvert(::Type{DataScienceTraits.Categorical}, x::AbstractQuantity{<:Number}) = convert(Quantity{Int}, x) DataScienceTraits.sciconvert(::Type{DataScienceTraits.Categorical}, x::AbstractQuantity{<:Integer}) = x end
DataScienceTraits
https://github.com/JuliaML/DataScienceTraits.jl.git
[ "MIT" ]
0.4.7
1e03704320016415ef5dcc2c54edc3f20ee37bca
code
3684
# ----------------------------------------------------------------- # Licensed under the MIT License. See LICENSE in the project root. # ----------------------------------------------------------------- module DataScienceTraits using Dates: TimeType """ SciType Parent type of all scientific types. """ abstract type SciType end """ Continuous Scientific type of continuous variables. """ abstract type Continuous <: SciType end """ Categorical Scientific type of categorical (a.k.a. discrete) variables. """ abstract type Categorical <: SciType end """ Colorful Scientific type of colorful data (see Colors.jl). """ abstract type Colorful <: SciType end """ Compositional Scientific type of compositional data (see CoDa.jl). """ abstract type Compositional <: SciType end """ Distributional Scientific type of distributional data (see Distributions.jl) """ abstract type Distributional <: SciType end """ Geometrical Scientific type of geometrical data (see Meshes.jl) """ abstract type Geometrical <: SciType end """ Tensorial Scientific type of tensorial data (e.g. Vector, Matrix) """ abstract type Tensorial <: SciType end """ Temporal Scientific type of temporal data (e.g. Date, Time, DateTime). """ abstract type Temporal <: SciType end """ Unknown Scientific type used as a fallback in the `scitype` trait function. """ abstract type Unknown <: SciType end """ scitype(x) -> SciType scitype(T::Type) -> SciType Return the scientific type of object `x` of type `T`. """ function scitype end """ elscitype(itr) -> SciType elscitype(I::Type) -> SciType Return the scientific type of the elements of iterator `itr` of type `I`. """ function elscitype end """ sciconvert(S::Type{<:SciType}, x) Convert the scientific type of object `x` to `S`. """ function sciconvert end #----------- # FALLBACKS #----------- scitype(x) = scitype(typeof(x)) elscitype(itr) = elscitype(typeof(itr)) elscitype(::Type{T}) where {T} = scitype(eltype(T)) function sciconvert(::Type{S}, x::T) where {S<:SciType,T} if !(scitype(T) <: S) context = :compact => true throw(ArgumentError("cannot convert $(repr(x; context)) to $(repr(S; context))")) end x end #----------------- # IMPLEMENTATIONS #----------------- scitype(::Type) = Unknown scitype(::Type{Union{}}) = Unknown scitype(::Type{Missing}) = Unknown scitype(::Type{<:Number}) = Continuous scitype(::Type{<:Integer}) = Categorical scitype(::Type{<:AbstractChar}) = Categorical scitype(::Type{<:AbstractString}) = Categorical scitype(::Type{<:AbstractArray}) = Tensorial scitype(::Type{<:TimeType}) = Temporal scitype(::Type{Union{T,Missing}}) where {T} = scitype(T) sciconvert(::Type{Continuous}, x::Integer) = float(x) sciconvert(::Type{Categorical}, x::Symbol) = string(x) sciconvert(::Type{Categorical}, x::Number) = convert(Int, x) sciconvert(::Type{Categorical}, x::Integer) = x #----------- # UTILITIES #----------- """ coerce(S::Type{<:SciType}, itr) Convert the scientific type of elements of the iterable `itr` to `S`, ignoring missing values. """ coerce(::Type{S}, itr) where {S<:SciType} = map(x -> ismissing(x) ? missing : sciconvert(S, x), itr) """ isordered(itr) Checks whether the categorical variables of the iterable `itr` are ordered. """ function isordered(itr) if !(elscitype(itr) <: Categorical) throw(ArgumentError("iterable elements are not categorical")) end false end #--------- # EXPORTS #--------- export # functions scitype, elscitype, # types Continuous, Categorical, Colorful, Compositional, Distributional, Geometrical, Tensorial, Temporal, Unknown end
DataScienceTraits
https://github.com/JuliaML/DataScienceTraits.jl.git