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"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 211 | append!(empty!(LOAD_PATH), Base.DEFAULT_LOAD_PATH)
using Pkg
exampledir = joinpath(@__DIR__, "..", "examples")
Pkg.activate(exampledir)
Pkg.add("Literate")
include(joinpath(exampledir, "generate_notebooks.jl"))
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | 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
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 3334 | # PREAMBLE
# PKG_SETUP
# ## Setup
using LinearAlgebra
using Plots
using DirectTrajectoryOptimization
# ## horizon
T = 101
# ## acrobot
num_state = 4
num_action = 1
num_parameter = 0
function acrobot(x, u, w)
mass1 = 1.0
inertia1 = 0.33
length1 = 1.0
lengthcom1 = 0.5
mass2 = 1.0
inertia2 = 0.33
length2 = 1.0
lengthcom2 = 0.5
gravity = 9.81
friction1 = 0.1
friction2 = 0.1
function M(x, w)
a = (inertia1 + inertia2 + mass2 * length1 * length1
+ 2.0 * mass2 * length1 * lengthcom2 * cos(x[2]))
b = inertia2 + mass2 * length1 * lengthcom2 * cos(x[2])
c = inertia2
return [a b; b c]
end
function Minv(x, w)
a = (inertia1 + inertia2 + mass2 * length1 * length1
+ 2.0 * mass2 * length1 * lengthcom2 * cos(x[2]))
b = inertia2 + mass2 * length1 * lengthcom2 * cos(x[2])
c = inertia2
return 1.0 / (a * c - b * b) * [c -b; -b a]
end
function τ(x, w)
a = (-1.0 * mass1 * gravity * lengthcom1 * sin(x[1])
- mass2 * gravity * (length1 * sin(x[1])
+ lengthcom2 * sin(x[1] + x[2])))
b = -1.0 * mass2 * gravity * lengthcom2 * sin(x[1] + x[2])
return [a; b]
end
function C(x, w)
a = -2.0 * mass2 * length1 * lengthcom2 * sin(x[2]) * x[4]
b = -1.0 * mass2 * length1 * lengthcom2 * sin(x[2]) * x[4]
c = mass2 * length1 * lengthcom2 * sin(x[2]) * x[3]
d = 0.0
return [a b; c d]
end
function B(x, w)
[0.0; 1.0]
end
q = view(x, 1:2)
v = view(x, 3:4)
qdd = Minv(q, w) * (-1.0 * C(x, w) * v
+ τ(q, w) + B(q, w) * u[1] - [friction1; friction2] .* v)
return [x[3]; x[4]; qdd[1]; qdd[2]]
end
function midpoint_implicit(y, x, u, w)
h = 0.05 # timestep
y - (x + h * acrobot(0.5 * (x + y), u, w))
end
# ## model
dt = Dynamics(midpoint_implicit, num_state, num_state, num_action, num_parameter=num_parameter, evaluate_hessian=true)
dynamics = [dt for t = 1:T-1]
# ## initialization
x1 = [0.0; 0.0; 0.0; 0.0]
xT = [π; 0.0; 0.0; 0.0]
# ## objective
ot = (x, u, w) -> 0.1 * dot(x[3:4], x[3:4]) + 0.1 * dot(u, u)
oT = (x, u, w) -> 0.1 * dot(x[3:4], x[3:4])
ct = Cost(ot, num_state, num_action, num_parameter=num_parameter)
cT = Cost(oT, num_state, 0, num_parameter=num_parameter)
objective = [[ct for t = 1:T-1]..., cT]
# ## constraints
bnd1 = Bound(num_state, num_action)
bndt = Bound(num_state, num_action)
bndT = Bound(num_state, 0)
bounds = [bnd1, [bndt for t = 2:T-1]..., bndT]
constraints = [
Constraint((x, u, w) -> x - x1, num_state, num_action),
[Constraint() for t = 2:T-1]...,
Constraint((x, u, w) -> x - xT, num_state, 0)
]
# ## problem
solver = Solver(dynamics, objective, constraints, bounds,
options=Options{Float64}())
# ## initialize
x_interpolation = linear_interpolation(x1, xT, T)
u_guess = [1.0 * randn(num_action) for t = 1:T-1]
initialize_states!(solver, x_interpolation)
initialize_controls!(solver, u_guess)
# ## solve
@time solve!(solver)
# ## solution
x_sol, u_sol = get_trajectory(solver)
@show x_sol[1]
@show x_sol[T]
# ## state
plot(hcat(x_sol...)')
# ## control
plot(hcat(u_sol[1:end-1]..., u_sol[end-1])', linetype = :steppost)
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 2386 | # PREAMBLE
# PKG_SETUP
# ## Setup
using DirectTrajectoryOptimization
using LinearAlgebra
using Plots
# ## horizon
T = 51
# ## car
num_state = 3
num_action = 2
num_parameter = 0
function car(x, u, w)
[u[1] * cos(x[3]); u[1] * sin(x[3]); u[2]]
end
function midpoint_implicit(y, x, u, w)
h = 0.1 # timestep
y - (x + h * car(0.5 * (x + y), u, w))
end
# ## model
dt = Dynamics(midpoint_implicit, num_state, num_state, num_action, num_parameter=num_parameter)
dynamics = [dt for t = 1:T-1]
# ## initialization
x1 = [0.0; 0.0; 0.0]
xT = [1.0; 1.0; 0.0]
# ## objective
ot = (x, u, w) -> 0.0 * dot(x - xT, x - xT) + 1.0 * dot(u, u)
oT = (x, u, w) -> 0.0 * dot(x - xT, x - xT)
ct = Cost(ot, num_state, num_action, num_parameter=num_parameter)
cT = Cost(oT, num_state, 0, num_parameter=num_parameter)
objective = [[ct for t = 1:T-1]..., cT]
# ## constraints
action_lower = -0.5 * ones(num_action)
action_upper = 0.5 * ones(num_action)
bnd1 = Bound(num_state, num_action, state_lower=x1, state_upper=x1, action_lower=action_lower, action_upper=action_upper)
bndt = Bound(num_state, num_action, action_lower=action_lower, action_upper=action_upper)
bndT = Bound(num_state, 0, state_lower=xT, state_upper=xT)
bounds = [bnd1, [bndt for t = 2:T-1]..., bndT]
p_obs = [0.5; 0.5]
r_obs = 0.1
function obs(x, u, w)
e = x[1:2] - p_obs
return [r_obs^2.0 - dot(e, e)]
end
cont = Constraint(obs, num_state, num_action, num_parameter=num_parameter, indices_inequality=collect(1:1))
conT = Constraint(obs, num_state, 0, num_parameter=num_parameter, indices_inequality=collect(1:1))
constraints = [[cont for t = 1:T-1]..., conT]
# ## problem
solver = Solver(dynamics, objective, constraints, bounds)
# ## initialize
x_interpolation = linear_interpolation(x1, xT, T)
u_guess = [0.001 * randn(num_action) for t = 1:T-1]
initialize_states!(solver, x_interpolation)
initialize_controls!(solver, u_guess)
# ## solve
solve!(solver)
# ## solution
x_sol, u_sol = get_trajectory(solver)
@show x_sol[1]
@show x_sol[T]
# ## state
plot(hcat(x_sol...)[1, :], hcat(x_sol...)[2, :], label = "", color = :orange, width=2.0)
pts = Plots.partialcircle(0.0, 2.0 * π, 100, r_obs)
cx, cy = Plots.unzip(pts)
plot!(Shape(cx .+ p_obs[1], cy .+ p_obs[2]), color = :black, label = "", linecolor = :black)
# ## control
plot(hcat(u_sol[1:end-1]..., u_sol[end-1])', linetype = :steppost) | DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 2532 | # PREAMBLE
# PKG_SETUP
# ## Setup
using LinearAlgebra
using Plots
using DirectTrajectoryOptimization
# ## horizon
T = 101
# ## cartpole
num_state = 4
num_action = 1
num_parameter = 0
function cartpole(x, u, w)
mc = 1.0
mp = 0.2
l = 0.5
g = 9.81
q = x[1:2]
qd = x[3:4]
s = sin(q[2])
c = cos(q[2])
H = [mc+mp mp*l*c; mp*l*c mp*l^2]
Hinv = 1.0 / (H[1, 1] * H[2, 2] - H[1, 2] * H[2, 1]) * [H[2, 2] -H[1, 2]; -H[2, 1] H[1, 1]]
C = [0 -mp*qd[2]*l*s; 0 0]
G = [0, mp*g*l*s]
B = [1, 0]
qdd = -Hinv * (C*qd + G - B*u[1])
return [qd; qdd]
end
function rk3_explicit(x, u, w)
h = 0.05 # timestep
k1 = h * cartpole(x, u, w)
k2 = h * cartpole(x + 0.5 * k1, u, w)
k3 = h * cartpole(x - k1 + 2.0 * k2, u, w)
return x + (k1 + 4.0 * k2 + k3) / 6.0
end
function rk3_implicit(y, x, u, w)
return y - rk3_explicit(x, u, w)
end
# ## model
dt = Dynamics(rk3_implicit, num_state, num_state, num_action,
num_parameter=num_parameter)
dyn = [dt for t = 1:T-1]
# ## initialization
x1 = [0.0; 0.0; 0.0; 0.0]
xT = [0.0; π; 0.0; 0.0]
# ## objective
Q = 1.0e-2
R = 1.0e-1
Qf = 1.0e2
ot = (x, u, w) -> 0.5 * Q * dot(x - xT, x - xT) + 0.5 * R * dot(u, u)
oT = (x, u, w) -> 0.5 * Qf * dot(x - xT, x - xT)
ct = Cost(ot, num_state, num_action,
num_parameter=num_parameter)
cT = Cost(oT, num_state, 0,
num_parameter=num_parameter)
obj = [[ct for t = 1:T-1]..., cT]
# ## constraints
u_bnd = 3.0
bnd1 = Bound(num_state, num_action,
action_lower=[-u_bnd],
action_upper=[u_bnd])
bndt = Bound(num_state, num_action,
action_lower=[-u_bnd],
action_upper=[u_bnd])
bndT = Bound(num_state, 0)
bounds = [bnd1, [bndt for t = 2:T-1]..., bndT]
cons = [
Constraint((x, u, w) -> x - x1, num_state, num_action),
[Constraint() for t = 2:T-1]...,
Constraint((x, u, w) -> x - xT, num_state, 0)
]
# ## problem
solver = Solver(dyn, obj, cons, bounds,
options=Options{Float64}())
# ## initialize
u_guess = [0.01 * ones(num_action) for t = 1:T-1]
x_rollout = [x1]
for t = 1:T-1
push!(x_rollout, rk3_explicit(x_rollout[end], u_guess[t], zeros(num_parameter)))
end
initialize_states!(solver, x_rollout)
initialize_controls!(solver, u_guess)
# ## solve
@time solve!(solver)
# ## solution
x_sol, u_sol = get_trajectory(solver)
@show x_sol[1]
@show x_sol[T]
# ## state
plot(hcat(x_sol...)')
# ## control
plot(hcat(u_sol[1:end-1]..., u_sol[end-1])', linetype = :steppost) | DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 4037 | # PREAMBLE
# PKG_SETUP
# ## Setup
using LinearAlgebra
using Plots
using DirectTrajectoryOptimization
# ##
eval_hess_lag = true
# ## horizon
T = 11
# ## acrobot
num_state = 2
num_action = 1
num_parameter = 0
function pendulum(x, u, w)
mass = 1.0
length_com = 0.5
gravity = 9.81
damping = 0.1
[
x[2],
(u[1] / ((mass * length_com * length_com))
- gravity * sin(x[1]) / length_com
- damping * x[2] / (mass * length_com * length_com))
]
end
function midpoint_implicit(y, x, u, w)
h = 0.05 # timestep
y - (x + h * pendulum(0.5 * (x + y), u, w))
end
# ## model
dt = Dynamics(
midpoint_implicit,
num_state,
num_state,
num_action,
num_parameter=num_parameter,
evaluate_hessian=eval_hess_lag)
dynamics = [dt for t = 1:T-1]
# ## initialization
x1 = [0.0; 0.0]
xT = [π; 0.0]
# ## objective
ot = (x, u, w) -> 0.1 * dot(x[1:2], x[1:2]) + 0.1 * dot(u, u)
oT = (x, u, w) -> 0.1 * dot(x[1:2], x[1:2])
ct = Cost(ot, num_state, num_action,
num_parameter=num_parameter,
evaluate_hessian=eval_hess_lag)
cT = Cost(oT, num_state, 0,
num_parameter=num_parameter,
evaluate_hessian=eval_hess_lag)
objective = [[ct for t = 1:T-1]..., cT]
# ## constraints
bnd1 = Bound(num_state, num_action)
bndt = Bound(num_state, num_action)
bndT = Bound(num_state, 0)
bounds = [bnd1, [bndt for t = 2:T-1]..., bndT]
# ## initial
con1 = Constraint((x, u, w) -> x - x1, num_state, num_action,
evaluate_hessian=eval_hess_lag)
conT = Constraint((x, u, w) -> x - xT, num_state, num_action,
evaluate_hessian=eval_hess_lag)
constraints = [con1, [Constraint() for t = 2:T-1]..., conT]
# ## problem
solver = Solver(dynamics, objective, constraints, bounds,
evaluate_hessian=eval_hess_lag,
options=Options{Float64}())
# ## initialize
x_interpolation = linear_interpolation(x1, xT, T)
u_guess = [1.0 * randn(num_action) for t = 1:T-1]
initialize_states!(solver, x_interpolation)
initialize_controls!(solver, u_guess)
# ## solve
@time solve!(solver)
# ## solution
x_sol, u_sol = get_trajectory(solver)
@show x_sol[1]
@show x_sol[T]
# ## state
plot(hcat(x_sol...)')
# ## control
plot(hcat(u_sol[1:end-1]..., u_sol[end-1])',
linetype=:steppost)
# DirectTrajectoryOptimization.jl environment
# ## tested w/ pendulum example
# ## assemble full system
# dimensions
nz = solver.nlp.num_variables
ny = solver.nlp.num_constraint
nj = solver.nlp.num_jacobian
nh = solver.nlp.num_hessian_lagrangian
# variables
z = rand(nz)
y = rand(ny)
# data
obj_grad = zeros(nz)
con = zeros(ny)
con_jac = zeros(nj)
hess_lag = zeros(nh)
# objective
MOI.eval_objective(solver.nlp, z)
MOI.eval_objective_gradient(solver.nlp, obj_grad, z)
# constraints
MOI.eval_constraint(solver.nlp, con, z)
MOI.eval_constraint_jacobian(solver.nlp, con_jac, z)
solver.nlp.hessian_lagrangian && MOI.eval_hessian_lagrangian(solver.nlp, hess_lag, z, 1.0, y)
"""
KKT system
H = [
∇²L C'
C 0
]
h = [
∇L
c
]
"""
H = spzeros(nz + ny, nz + ny)
h = zeros(nz + ny)
# ∇L
for i = 1:nz
# objective gradient
h[i] += obj_grad[i]
# C' y
cy = 0.0
for j = 1:ny
# cy += C[j, i] * y[j]
if (j, i) in solver.nlp.jacobian_sparsity
cy += C[j, i] * y[j]
end
end
h[i] += cy
end
# c
for j = 1:ny
h[nz + j] += con[j]
end
#TODO: only fill in half?
# ∇²L
for (i, idx) in enumerate(solver.nlp.hessian_lagrangian_sparsity)
H[idx...] = hess_lag[i]
end
for (i, idx) in enumerate(solver.nlp.jacobian_sparsity)
# C
H[nz + idx[1], idx[2]] = con_jac[i]
# C'
H[idx[2], nz + idx[1]] = con_jac[i]
end
# regularization
primal_reg = 1.0e-5
for i = 1:nz
H[i, i] += primal_reg
end
dual_reg = 1.0e-5
for j = 1:ny
H[nz + j, nz + j] -= dual_reg
end
H_dense = Array(H)
eigen(H_dense)
cond(H_dense)
rank(H_dense)
using QDLDL
H
F = qdldl(H)
sol = zeros(nz + ny)
sol = copy(h)
QDLDL.solve!(F, sol)
norm(sol - (H \ h), Inf)
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 693 | module DirectTrajectoryOptimization
using LinearAlgebra
using SparseArrays
using Symbolics, IfElse
using Parameters
using Ipopt
using MathOptInterface
const MOI = MathOptInterface
include("costs.jl")
include("constraints.jl")
include("bounds.jl")
include("general_constraint.jl")
include("dynamics.jl")
include("options.jl")
include("data.jl")
include("solver.jl")
include("moi.jl")
include("utils.jl")
# objective
export Cost
# constraints
export Bound, Bounds, Constraint, Constraints, GeneralConstraint
# dynamics
export Dynamics
# solver
export Solver, Options, initialize_states!, initialize_controls!, solve!, get_trajectory
# utils
export linear_interpolation
end # module
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 462 | struct Bound{T}
state_lower::Vector{T}
state_upper::Vector{T}
action_lower::Vector{T}
action_upper::Vector{T}
end
function Bound(num_state::Int=0, num_action::Int=0;
state_lower=-Inf * ones(num_state),
state_upper=Inf * ones(num_state),
action_lower=-Inf * ones(num_action),
action_upper=Inf * ones(num_action))
return Bound(state_lower, state_upper, action_lower, action_upper)
end
const Bounds{T} = Vector{Bound{T}}
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 6133 | struct Constraint{T}
evaluate::Any
jacobian::Any
hessian::Any
num_state::Int
num_action::Int
num_parameter::Int
num_constraint::Int
num_jacobian::Int
num_hessian::Int
jacobian_sparsity::Vector{Vector{Int}}
hessian_sparsity::Vector{Vector{Int}}
evaluate_cache::Vector{T}
jacobian_cache::Vector{T}
hessian_cache::Vector{T}
indices_inequality::Vector{Int}
end
Constraints{T} = Vector{Constraint{T}} where T
function Constraint(f::Function, num_state::Int, num_action::Int;
num_parameter::Int=0,
indices_inequality=collect(1:0),
evaluate_hessian=false)
#TODO: option to load/save methods
@variables x[1:num_state], u[1:num_action], w[1:num_parameter]
evaluate = f(x, u, w)
jac = Symbolics.sparsejacobian(evaluate, [x; u])
evaluate_func = eval(Symbolics.build_function(evaluate, x, u, w)[2])
jac_func = eval(Symbolics.build_function(jac.nzval, x, u, w)[2])
num_constraint = length(evaluate)
num_jacobian = length(jac.nzval)
jacobian_sparsity = [findnz(jac)[1:2]...]
if evaluate_hessian
@variables λ[1:num_constraint]
lag_con = dot(λ, evaluate)
hessian = Symbolics.sparsehessian(lag_con, [x; u])
hess_func = eval(Symbolics.build_function(hessian.nzval, x, u, w, λ)[2])
hessian_sparsity = [findnz(hessian)[1:2]...]
num_hessian = length(hessian.nzval)
else
hess_func = Expr(:null)
hessian_sparsity = [Int[]]
num_hessian = 0
end
return Constraint(
evaluate_func,
jac_func,
hess_func,
num_state,
num_action,
num_parameter,
num_constraint,
num_jacobian,
num_hessian,
jacobian_sparsity,
hessian_sparsity,
zeros(num_constraint),
zeros(num_jacobian),
zeros(num_hessian),
indices_inequality)
end
function Constraint()
return Constraint(
(constraint, state, action, parameter) -> nothing,
(jacobian, state, action, parameter) -> nothing,
(hessian, state, action, parameter) -> nothing,
0, 0, 0, 0, 0, 0,
[Int[], Int[]],
[Int[], Int[]],
Float64[],
Float64[],
Float64[],
collect(1:0))
end
function constraints!(violations, indices, constraints::Constraints{T}, states, actions, parameters) where T
for (t, con) in enumerate(constraints)
con.evaluate(con.evaluate_cache, states[t], actions[t], parameters[t])
@views violations[indices[t]] .= con.evaluate_cache
fill!(con.evaluate_cache, 0.0) # TODO: confirm this is necessary
end
end
function jacobian!(jacobians, indices, constraints::Constraints{T}, states, actions, parameters) where T
for (t, con) in enumerate(constraints)
con.jacobian(con.jacobian_cache, states[t], actions[t], parameters[t])
@views jacobians[indices[t]] .= con.jacobian_cache
fill!(con.jacobian_cache, 0.0) # TODO: confirm this is necessary
end
end
function hessian_lagrangian!(hessians, indices, constraints::Constraints{T}, states, actions, parameters, duals) where T
for (t, con) in enumerate(constraints)
if !isempty(con.hessian_cache)
con.hessian(con.hessian_cache, states[t], actions[t], parameters[t], duals[t])
@views hessians[indices[t]] .+= con.hessian_cache
fill!(con.hessian_cache, 0.0) # TODO: confirm this is necessary
end
end
end
function sparsity_jacobian(constraints::Constraints{T}, num_state::Vector{Int}, num_action::Vector{Int};
row_shift=0) where T
row = Int[]
col = Int[]
for (t, con) in enumerate(constraints)
col_shift = (t > 1 ? (sum(num_state[1:t-1]) + sum(num_action[1:t-1])) : 0)
push!(row, (con.jacobian_sparsity[1] .+ row_shift)...)
push!(col, (con.jacobian_sparsity[2] .+ col_shift)...)
row_shift += con.num_constraint
end
return collect(zip(row, col))
end
function sparsity_hessian(constraints::Constraints{T}, num_state::Vector{Int}, num_action::Vector{Int}) where T
row = Int[]
col = Int[]
for (t, con) in enumerate(constraints)
if !isempty(con.hessian_sparsity[1])
shift = (t > 1 ? (sum(num_state[1:t-1]) + sum(num_action[1:t-1])) : 0)
push!(row, (con.hessian_sparsity[1] .+ shift)...)
push!(col, (con.hessian_sparsity[2] .+ shift)...)
end
end
return collect(zip(row, col))
end
num_constraint(constraints::Constraints{T}) where T = sum([con.num_constraint for con in constraints])
num_jacobian(constraints::Constraints{T}) where T = sum([con.num_jacobian for con in constraints])
# num_hessian(constraints::Constraints{T}) where T = sum([con.num_hessian for con in constraints])
function constraint_indices(constraints::Constraints{T};
shift=0) where T
indices = Vector{Int}[]
for (t, con) in enumerate(constraints)
indices = [indices..., collect(shift .+ (1:con.num_constraint)),]
shift += con.num_constraint
end
return indices
end
function jacobian_indices(constraints::Constraints{T};
shift=0) where T
indices = Vector{Int}[]
for (t, con) in enumerate(constraints)
push!(indices, collect(shift .+ (1:con.num_jacobian)))
shift += con.num_jacobian
end
return indices
end
function hessian_indices(constraints::Constraints{T}, key::Vector{Tuple{Int,Int}}, num_state::Vector{Int}, num_action::Vector{Int}) where T
indices = Vector{Int}[]
for (t, con) in enumerate(constraints)
if !isempty(con.hessian_sparsity[1])
row = Int[]
col = Int[]
shift = (t > 1 ? (sum(num_state[1:t-1]) + sum(num_action[1:t-1])) : 0)
push!(row, (con.hessian_sparsity[1] .+ shift)...)
push!(col, (con.hessian_sparsity[2] .+ shift)...)
rc = collect(zip(row, col))
push!(indices, [findfirst(x -> x == i, key) for i in rc])
else
push!(indices, Int[])
end
end
return indices
end
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 3723 | struct Cost{T}
evaluate::Any
gradient::Any
hessian::Any
num_gradient::Int
num_hessian::Int
sparsity::Vector{Vector{Int}}
evaluate_cache::Vector{T}
gradient_cache::Vector{T}
hessian_cache::Vector{T}
end
function Cost(f::Function, num_state::Int, num_action::Int;
num_parameter::Int=0,
evaluate_hessian=false)
#TODO: option to load/save methods
@variables x[1:num_state], u[1:num_action], w[1:num_parameter]
evaluate = f(x, u, w)
gradient = Symbolics.gradient(evaluate, [x; u])
num_gradient = num_state + num_action
evaluate_func = eval(Symbolics.build_function([evaluate], x, u, w)[2])
gradient_func = eval(Symbolics.build_function(gradient, x, u, w)[2])
if evaluate_hessian
hessian = Symbolics.sparsehessian(evaluate, [x; u])
hessian_func = eval(Symbolics.build_function(hessian.nzval, x, u, w)[2])
sparsity = [findnz(hessian)[1:2]...]
num_hessian = length(hessian.nzval)
else
hessian_func = Expr(:null)
sparsity = [Int[]]
num_hessian = 0
end
return Cost(
evaluate_func,
gradient_func,
hessian_func,
num_gradient,
num_hessian,
sparsity,
zeros(1),
zeros(num_gradient),
zeros(num_hessian))
end
Objective{T} = Vector{Cost{T}} where T
function cost(objective::Objective, states, actions, parameters)
J = 0.0
for (t, cost) in enumerate(objective)
cost.evaluate(cost.evaluate_cache, states[t], actions[t], parameters[t])
J += cost.evaluate_cache[1]
end
return J
end
function gradient!(gradient, indices, objective::Objective, states, actions, parameters)
for (t, cost) in enumerate(objective)
cost.gradient(cost.gradient_cache, states[t], actions[t], parameters[t])
@views gradient[indices[t]] .+= cost.gradient_cache
# fill!(cost.gradient_cache, 0.0) # TODO: confirm this is necessary
end
end
function hessian!(hessian, indices, objective::Objective, states, actions, parameters, scaling)
for (t, cost) in enumerate(objective)
cost.hessian(cost.hessian_cache, states[t], actions[t], parameters[t])
cost.hessian_cache .*= scaling
@views hessian[indices[t]] .+= cost.hessian_cache
# fill!(cost.hessian_cache, 0.0) # TODO: confirm this is necessary
end
end
function sparsity_hessian(objective::Objective, num_state::Vector{Int}, num_action::Vector{Int})
row = Int[]
col = Int[]
for (t, cost) in enumerate(objective)
if !isempty(cost.sparsity[1])
shift = (t > 1 ? (sum(num_state[1:t-1]) + sum(num_action[1:t-1])) : 0)
push!(row, (cost.sparsity[1] .+ shift)...)
push!(col, (cost.sparsity[2] .+ shift)...)
end
end
return collect(zip(row, col))
end
function hessian_indices(objective::Objective, key::Vector{Tuple{Int,Int}}, num_state::Vector{Int}, num_action::Vector{Int})
indices = Vector{Int}[]
for (t, cost) in enumerate(objective)
if !isempty(cost.sparsity[1])
row = Int[]
col = Int[]
shift = (t > 1 ? (sum(num_state[1:t-1]) + sum(num_action[1:t-1])) : 0)
push!(row, (cost.sparsity[1] .+ shift)...)
push!(col, (cost.sparsity[2] .+ shift)...)
rc = collect(zip(row, col))
push!(indices, [findfirst(x -> x == i, key) for i in rc])
else
push!(indices, Int[])
end
end
return indices
end
# num_gradient(objective::Objective{T}) where T = sum([obj.num_gradient for obj in objective])
# num_hessian(objective::Objective{T}) where T = sum([obj.num_hessian for obj in objective])
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 10994 | struct TrajectoryOptimizationData{T}
states::Vector{Vector{T}}
actions::Vector{Vector{T}}
parameters::Vector{Vector{T}}
objective::Objective{T}
dynamics::Vector{Dynamics{T}}
constraints::Constraints{T}
bounds::Bounds{T}
duals_dynamics::Vector{Vector{T}}
duals_constraints::Vector{Vector{T}}
state_dimensions::Vector{Int}
action_dimensions::Vector{Int}
parameter_dimensions::Vector{Int}
end
function TrajectoryOptimizationData(objective::Objective{T}, dynamics::Vector{Dynamics{T}}, constraints::Constraints{T}, bounds::Bounds{T};
parameters=[zeros(num_parameter) for num_parameter in dimensions(dynamics)[3]]) where T
state_dimensions, action_dimensions, parameter_dimensions = dimensions(dynamics)
states = [zeros(num_state) for num_state in state_dimensions]
actions = [zeros(nu) for nu in action_dimensions]
duals_dynamics = [zeros(num_state) for num_state in state_dimensions[2:end]]
duals_constraints = [zeros(con.num_constraint) for con in constraints]
TrajectoryOptimizationData(
states,
actions,
parameters,
objective,
dynamics,
constraints,
bounds,
duals_dynamics,
duals_constraints,
state_dimensions,
action_dimensions,
parameter_dimensions)
end
TrajectoryOptimizationData(objective::Objective, dynamics::Vector{Dynamics}) = TrajectoryOptimizationData(objective, dynamics, [Constraint() for t = 1:length(dynamics)], [Bound() for t = 1:length(dynamics)])
struct TrajectoryOptimizationIndices
objective_hessians::Vector{Vector{Int}}
dynamics_constraints::Vector{Vector{Int}}
dynamics_jacobians::Vector{Vector{Int}}
dynamics_hessians::Vector{Vector{Int}}
stage_constraints::Vector{Vector{Int}}
stage_jacobians::Vector{Vector{Int}}
stage_hessians::Vector{Vector{Int}}
general_constraint::Vector{Int}
general_jacobian::Vector{Int}
general_hessian::Vector{Int}
states::Vector{Vector{Int}}
actions::Vector{Vector{Int}}
state_action::Vector{Vector{Int}}
state_action_next_state::Vector{Vector{Int}}
end
function indices(objective::Objective{T}, dynamics::Vector{Dynamics{T}}, constraints::Constraints{T}, general::GeneralConstraint{T},
key::Vector{Tuple{Int,Int}}, num_state::Vector{Int}, num_action::Vector{Int}, num_trajectory::Int) where T
# Jacobians
dynamics_constraints = constraint_indices(dynamics,
shift=0)
dynamics_jacobians = jacobian_indices(dynamics,
shift=0)
stage_constraints = constraint_indices(constraints,
shift=num_constraint(dynamics))
stage_jacobians = jacobian_indices(constraints,
shift=num_jacobian(dynamics))
general_constraint = constraint_indices(general,
shift=(num_constraint(dynamics) + num_constraint(constraints)))
general_jacobian = jacobian_indices(general,
shift=(num_jacobian(dynamics) + num_jacobian(constraints)))
# Hessian of Lagrangian
objective_hessians = hessian_indices(objective, key, num_state, num_action)
dynamics_hessians = hessian_indices(dynamics, key, num_state, num_action)
stage_hessians = hessian_indices(constraints, key, num_state, num_action)
general_hessian = hessian_indices(general, key, num_trajectory)
# indices
x_idx = state_indices(dynamics)
u_idx = action_indices(dynamics)
xu_idx = state_action_indices(dynamics)
xuy_idx = state_action_next_state_indices(dynamics)
return TrajectoryOptimizationIndices(
objective_hessians,
dynamics_constraints,
dynamics_jacobians,
dynamics_hessians,
stage_constraints,
stage_jacobians,
stage_hessians,
general_constraint,
general_jacobian,
general_hessian,
x_idx,
u_idx,
xu_idx,
xuy_idx)
end
struct NLPData{T} <: MOI.AbstractNLPEvaluator
trajopt::TrajectoryOptimizationData{T}
num_variables::Int
num_constraint::Int
num_jacobian::Int
num_hessian_lagrangian::Int
variable_bounds::Vector{Vector{T}}
constraint_bounds::Vector{Vector{T}}
indices::TrajectoryOptimizationIndices
jacobian_sparsity
hessian_lagrangian_sparsity
hessian_lagrangian::Bool
general_constraint::GeneralConstraint{T}
parameters::Vector{T}
duals_general::Vector{T}
end
function primal_bounds(bounds::Bounds{T}, num_variables::Int, state_indices::Vector{Vector{Int}}, action_indices::Vector{Vector{Int}}) where T
lower, upper = -Inf * ones(num_variables), Inf * ones(num_variables)
for (t, bnd) in enumerate(bounds)
length(bnd.state_lower) > 0 && (lower[state_indices[t]] = bnd.state_lower)
length(bnd.state_upper) > 0 && (upper[state_indices[t]] = bnd.state_upper)
length(bnd.action_lower) > 0 && (lower[action_indices[t]] = bnd.action_lower)
length(bnd.action_upper) > 0 && (upper[action_indices[t]] = bnd.action_upper)
end
return lower, upper
end
function constraint_bounds(constraints::Constraints{T}, general::GeneralConstraint{T},
num_dynamics::Int, num_stage::Int, indices::TrajectoryOptimizationIndices) where T
# total constraints
total_constraint = num_dynamics + num_stage + general.num_constraint
# bounds
lower, upper = zeros(total_constraint), zeros(total_constraint)
# stage
for (t, con) in enumerate(constraints)
lower[indices.stage_constraints[t][con.indices_inequality]] .= -Inf
end
# general
lower[collect(num_dynamics + num_stage .+ general.indices_inequality)] .= -Inf
return lower, upper
end
function NLPData(trajopt::TrajectoryOptimizationData;
evaluate_hessian=false,
general_constraint=GeneralConstraint())
# number of variables
total_variables = sum(trajopt.state_dimensions) + sum(trajopt.action_dimensions)
# number of constraints
num_dynamics = num_constraint(trajopt.dynamics)
num_stage = num_constraint(trajopt.constraints)
num_general = num_constraint(general_constraint)
total_constraints = num_dynamics + num_stage + num_general
# number of nonzeros in constraint Jacobian
num_dynamics_jacobian = num_jacobian(trajopt.dynamics)
num_constraint_jacobian = num_jacobian(trajopt.constraints)
num_general_jacobian = num_jacobian(general_constraint)
total_jacobians = num_dynamics_jacobian + num_constraint_jacobian + num_general_jacobian
# constraint Jacobian sparsity
sparsity_dynamics = sparsity_jacobian(trajopt.dynamics, trajopt.state_dimensions, trajopt.action_dimensions,
row_shift=0)
sparsity_constraint = sparsity_jacobian(trajopt.constraints, trajopt.state_dimensions, trajopt.action_dimensions,
row_shift=num_dynamics)
sparsity_general = sparsity_jacobian(general_constraint, total_variables, row_shift=(num_dynamics + num_stage))
jacobian_sparsity = collect([sparsity_dynamics..., sparsity_constraint..., sparsity_general...])
# Hessian of Lagrangian sparsity
sparsity_objective_hessians = sparsity_hessian(trajopt.objective, trajopt.state_dimensions, trajopt.action_dimensions)
sparsity_dynamics_hessians = sparsity_hessian(trajopt.dynamics, trajopt.state_dimensions, trajopt.action_dimensions)
sparsity_constraint_hessian = sparsity_hessian(trajopt.constraints, trajopt.state_dimensions, trajopt.action_dimensions)
sparsity_general_hessian = sparsity_hessian(general_constraint, total_variables)
hessian_lagrangian_sparsity = [sparsity_objective_hessians..., sparsity_dynamics_hessians..., sparsity_constraint_hessian..., sparsity_general_hessian...]
hessian_lagrangian_sparsity = !isempty(hessian_lagrangian_sparsity) ? hessian_lagrangian_sparsity : Tuple{Int,Int}[]
hessian_sparsity_key = sort(unique(hessian_lagrangian_sparsity))
# number of nonzeros in Hessian of Lagrangian
num_hessian_lagrangian = length(hessian_lagrangian_sparsity)
# indices
idx = indices(
trajopt.objective,
trajopt.dynamics,
trajopt.constraints,
general_constraint,
hessian_sparsity_key,
trajopt.state_dimensions,
trajopt.action_dimensions,
total_variables)
# primal variable bounds
primal_lower, primal_upper = primal_bounds(trajopt.bounds, total_variables, idx.states, idx.actions)
# nonlinear constraint bounds
constraint_lower, constraint_upper = constraint_bounds(trajopt.constraints, general_constraint, num_dynamics, num_stage, idx)
NLPData(trajopt,
total_variables,
total_constraints,
total_jacobians,
num_hessian_lagrangian,
[primal_lower, primal_upper],
[constraint_lower, constraint_upper],
idx,
jacobian_sparsity,
hessian_sparsity_key,
evaluate_hessian,
general_constraint,
vcat(trajopt.parameters...),
zeros(general_constraint.num_constraint))
end
struct SolverData
nlp_bounds::Vector{MOI.NLPBoundsPair}
block_data::MOI.NLPBlockData
optimizer::Ipopt.Optimizer
variables::Vector{MOI.VariableIndex}
end
function SolverData(nlp::NLPData;
options=Options())
# solver
nlp_bounds = MOI.NLPBoundsPair.(nlp.constraint_bounds...)
block_data = MOI.NLPBlockData(nlp_bounds, nlp, true)
# instantiate NLP solver
optimizer = Ipopt.Optimizer()
# set NLP optimizer options
for name in fieldnames(typeof(options))
optimizer.options[String(name)] = getfield(options, name)
end
z = MOI.add_variables(optimizer, nlp.num_variables)
for i = 1:nlp.num_variables
MOI.add_constraint(optimizer, z[i], MOI.LessThan(nlp.variable_bounds[2][i]))
MOI.add_constraint(optimizer, z[i], MOI.GreaterThan(nlp.variable_bounds[1][i]))
end
MOI.set(optimizer, MOI.NLPBlock(), block_data)
MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MIN_SENSE)
return SolverData(nlp_bounds, block_data, optimizer, z)
end
function trajectory!(states::Vector{Vector{T}}, actions::Vector{Vector{T}},
trajectory::Vector{T},
state_indices::Vector{Vector{Int}}, action_indices::Vector{Vector{Int}}) where T
for (t, idx) in enumerate(state_indices)
states[t] .= @views trajectory[idx]
end
for (t, idx) in enumerate(action_indices)
actions[t] .= @views trajectory[idx]
end
end
function duals!(duals_dynamics::Vector{Vector{T}}, duals_constraints::Vector{Vector{T}}, duals_general::Vector{T}, duals,
dynamics_indices::Vector{Vector{Int}}, constraint_indices::Vector{Vector{Int}}, general_indices::Vector{Int}) where T
for (t, idx) in enumerate(dynamics_indices)
duals_dynamics[t] .= @views duals[idx]
end
for (t, idx) in enumerate(constraint_indices)
duals_constraints[t] .= @views duals[idx]
end
duals_general .= duals[general_indices]
end
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 8579 | struct Dynamics{T}
evaluate::Any
jacobian::Any
hessian::Any
num_next_state::Int
num_state::Int
num_action::Int
num_parameter::Int
num_jacobian::Int
num_hessian::Int
jacobian_sparsity::Vector{Vector{Int}}
hessian_sparsity::Vector{Vector{Int}}
evaluate_cache::Vector{T}
jacobian_cache::Vector{T}
hessian_cache::Vector{T}
end
function Dynamics(f::Function, num_next_state::Int, num_state::Int, num_action::Int;
num_parameter::Int=0,
evaluate_hessian=false)
#TODO: option to load/save methods
@variables y[1:num_next_state], x[1:num_state], u[1:num_action], w[1:num_parameter]
evaluate = f(y, x, u, w)
jac = Symbolics.sparsejacobian(evaluate, [x; u; y]);
evaluate_func = eval(Symbolics.build_function(evaluate, y, x, u, w)[2]);
jacobian_func = eval(Symbolics.build_function(jac.nzval, y, x, u, w)[2]);
num_jacobian = length(jac.nzval)
jacobian_sparsity = [findnz(jac)[1:2]...]
if evaluate_hessian
@variables λ[1:num_next_state]
lag_con = dot(λ, evaluate)
hessian = Symbolics.sparsehessian(lag_con, [x; u; y])
hessian_func = eval(Symbolics.build_function(hessian.nzval, y, x, u, w, λ)[2])
hessian_sparsity = [findnz(hessian)[1:2]...]
num_hessian = length(hessian.nzval)
else
hessian_func = Expr(:null)
hessian_sparsity = [Int[]]
num_hessian = 0
end
return Dynamics(evaluate_func,
jacobian_func,
hessian_func,
num_next_state,
num_state,
num_action,
num_parameter,
num_jacobian,
num_hessian,
jacobian_sparsity,
hessian_sparsity,
zeros(num_next_state),
zeros(num_jacobian),
zeros(num_hessian))
end
function Dynamics(constraint::Function, constraint_jacobian::Function, num_next_state::Int, num_state::Int, num_action::Int;
num_parameter::Int=0)
# jacobian function
num_variables = num_state + num_action + num_next_state
jacobian_func = (J, y, x, u, w) -> constraint_jacobian(reshape(view(J, :), num_next_state, num_variables), y, x, u, w)
# number of Jacobian elements
num_jacobian = num_next_state * num_variables
# Jacobian sparsity
row = Int[]
col = Int[]
for j = 1:num_variables
for i = 1:num_next_state
push!(row, i)
push!(col, j)
end
end
jacobian_sparsity = [row, col]
# Hessian
hessian_func = Expr(:null)
hessian_sparsity = [Int[]]
num_hessian = 0
return Dynamics(
constraint,
jacobian_func,
hessian_func,
num_next_state,
num_state,
num_action,
num_parameter,
num_jacobian,
num_hessian,
jacobian_sparsity,
hessian_sparsity,
zeros(num_next_state),
zeros(num_jacobian),
zeros(num_hessian))
end
function constraints!(violations, indices, constraints::Vector{Dynamics{T}}, states, actions, parameters) where T
for (t, con) in enumerate(constraints)
con.evaluate(con.evaluate_cache, states[t+1], states[t], actions[t], parameters[t])
@views violations[indices[t]] .= con.evaluate_cache
fill!(con.evaluate_cache, 0.0) # TODO: confirm this is necessary
end
end
function jacobian!(jacobians, indices, constraints::Vector{Dynamics{T}}, states, actions, parameters) where T
for (t, con) in enumerate(constraints)
con.jacobian(con.jacobian_cache, states[t+1], states[t], actions[t], parameters[t])
@views jacobians[indices[t]] .= con.jacobian_cache
fill!(con.jacobian_cache, 0.0) # TODO: confirm this is necessary
end
end
function hessian_lagrangian!(hessians, indices, constraints::Vector{Dynamics{T}}, states, actions, parameters, duals) where T
for (t, con) in enumerate(constraints)
if !isempty(con.hessian_cache)
con.hessian(con.hessian_cache, states[t+1], states[t], actions[t], parameters[t], duals[t])
@views hessians[indices[t]] .+= con.hessian_cache
fill!(con.hessian_cache, 0.0) # TODO: confirm this is necessary
end
end
end
function sparsity_jacobian(constraints::Vector{Dynamics{T}}, num_state::Vector{Int}, num_actions::Vector{Int};
row_shift=0) where T
row = Int[]
col = Int[]
for (t, con) in enumerate(constraints)
col_shift = (t > 1 ? (sum(num_state[1:t-1]) + sum(num_actions[1:t-1])) : 0)
push!(row, (con.jacobian_sparsity[1] .+ row_shift)...)
push!(col, (con.jacobian_sparsity[2] .+ col_shift)...)
row_shift += con.num_next_state
end
return collect(zip(row, col))
end
function sparsity_hessian(constraints::Vector{Dynamics{T}}, num_state::Vector{Int}, num_actions::Vector{Int}) where T
row = Int[]
col = Int[]
for (t, con) in enumerate(constraints)
if !isempty(con.hessian_sparsity[1])
shift = (t > 1 ? (sum(num_state[1:t-1]) + sum(num_actions[1:t-1])) : 0)
push!(row, (con.hessian_sparsity[1] .+ shift)...)
push!(col, (con.hessian_sparsity[2] .+ shift)...)
end
end
return collect(zip(row, col))
end
num_state_action_next_state(constraints::Vector{Dynamics{T}}) where T = sum([con.num_state + con.num_action for con in constraints]) + constraints[end].num_next_state
num_constraint(constraints::Vector{Dynamics{T}}) where T = sum([con.num_next_state for con in constraints])
num_jacobian(constraints::Vector{Dynamics{T}}) where T = sum([con.num_jacobian for con in constraints])
# num_hessian(constraints::Vector{Dynamics{T}}) where T = sum([con.num_hessian for con in constraints])
function constraint_indices(constraints::Vector{Dynamics{T}};
shift=0) where T
[collect(shift + (t > 1 ? sum([constraints[s].num_next_state for s = 1:(t-1)]) : 0) .+ (1:constraints[t].num_next_state)) for t = 1:length(constraints)]
end
function jacobian_indices(constraints::Vector{Dynamics{T}};
shift=0) where T
[collect(shift + (t > 1 ? sum([constraints[s].num_jacobian for s = 1:(t-1)]) : 0) .+ (1:constraints[t].num_jacobian)) for t = 1:length(constraints)]
end
function hessian_indices(constraints::Vector{Dynamics{T}}, key::Vector{Tuple{Int,Int}}, num_state::Vector{Int}, num_action::Vector{Int}) where T
indices = Vector{Int}[]
for (t, con) in enumerate(constraints)
if !isempty(con.hessian_sparsity[1])
shift = (t > 1 ? (sum(num_state[1:t-1]) + sum(num_action[1:t-1])) : 0)
row = collect(con.hessian_sparsity[1] .+ shift)
col = collect(con.hessian_sparsity[2] .+ shift)
rc = collect(zip(row, col))
push!(indices, [findfirst(x -> x == i, key) for i in rc])
else
push!(indices, Int[])
end
end
return indices
end
function state_indices(constraints::Vector{Dynamics{T}}) where T
[[collect((t > 1 ? sum([constraints[s].num_state + constraints[s].num_action for s = 1:(t-1)]) : 0) .+ (1:constraints[t].num_state)) for t = 1:length(constraints)]...,
collect(sum([constraints[s].num_state + constraints[s].num_action for s = 1:length(constraints)]) .+ (1:constraints[end].num_next_state))]
end
function action_indices(constraints::Vector{Dynamics{T}}) where T
[collect((t > 1 ? sum([constraints[s].num_state + constraints[s].num_action for s = 1:(t-1)]) : 0) + constraints[t].num_state .+ (1:constraints[t].num_action)) for t = 1:length(constraints)]
end
function state_action_indices(constraints::Vector{Dynamics{T}}) where T
[[collect((t > 1 ? sum([constraints[s].num_state + constraints[s].num_action for s = 1:(t-1)]) : 0) .+ (1:(+ constraints[t].num_state + constraints[t].num_action))) for t = 1:length(constraints)]...,
collect(sum([constraints[s].num_state + constraints[s].num_action for s = 1:length(constraints)]) .+ (1:constraints[end].num_next_state))]
end
function state_action_next_state_indices(constraints::Vector{Dynamics{T}}) where T
[collect((t > 1 ? sum([constraints[s].num_state + constraints[s].num_action for s = 1:(t-1)]) : 0) .+ (1:(+ constraints[t].num_state + constraints[t].num_action + constraints[t].num_next_state))) for t = 1:length(constraints)]
end
function dimensions(dynamics::Vector{Dynamics{T}};
parameters=[0 for t = 1:(length(dynamics) + 1)]) where T
states = [[d.num_state for d in dynamics]..., dynamics[end].num_next_state]
actions = [[d.num_action for d in dynamics]..., 0]
return states, actions, parameters
end | DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 4826 | struct GeneralConstraint{T}
evaluate::Any
jacobian::Any
hessian::Any
num_variables::Int
num_parameter::Int
num_constraint::Int
num_jacobian::Int
num_hessian::Int
jacobian_sparsity::Vector{Vector{Int}}
hessian_sparsity::Vector{Vector{Int}}
evaluate_cache::Vector{T}
jacobian_cache::Vector{T}
hessian_cache::Vector{T}
indices_inequality::Vector{Int}
end
function GeneralConstraint(f::Function, num_variables::Int, num_parameter::Int;
indices_inequality=collect(1:0),
evaluate_hessian=false)
#TODO: option to load/save methods
@variables z[1:num_variables], w[1:num_parameter]
evaluate = f(z, w)
jacobian = Symbolics.sparsejacobian(evaluate, z)
evaluate_func = eval(Symbolics.build_function(evaluate, z, w)[2])
jacobian_func = eval(Symbolics.build_function(jacobian.nzval, z, w)[2])
num_constraint = length(evaluate)
num_jacobian = length(jacobian.nzval)
jacobian_sparsity = [findnz(jacobian)[1:2]...]
if evaluate_hessian
@variables λ[1:num_constraint]
lag_con = dot(λ, evaluate)
hessian = Symbolics.sparsehessian(lag_con, z)
hessian_func = eval(Symbolics.build_function(hessian.nzval, z, w, λ)[2])
hessian_sparsity = [findnz(hessian)[1:2]...]
num_hessian = length(hessian.nzval)
else
hessian_func = Expr(:null)
hessian_sparsity = [Int[]]
num_hessian = 0
end
return GeneralConstraint(
evaluate_func,
jacobian_func,
hessian_func,
num_variables,
num_parameter,
num_constraint,
num_jacobian,
num_hessian,
jacobian_sparsity,
hessian_sparsity,
zeros(num_constraint),
zeros(num_jacobian),
zeros(num_hessian),
indices_inequality)
end
function GeneralConstraint()
return GeneralConstraint(
(constraint, variables, parameters) -> nothing,
(jacobian, variables, parameters) -> nothing,
(hessian, variables, parameters) -> nothing,
0, 0, 0, 0, 0,
[Int[], Int[]],
[Int[], Int[]],
Float64[], Float64[], Float64[],
collect(1:0))
end
function constraints!(violations, indices, general::GeneralConstraint{T}, variables, parameters) where T
general.evaluate(general.evaluate_cache, variables, parameters)
@views violations[indices] .= general.evaluate_cache
fill!(general.evaluate_cache, 0.0) # TODO: confirm this is necessary
end
function jacobian!(jacobians, indices, general::GeneralConstraint{T}, variables, parameters) where T
general.jacobian(general.jacobian_cache, variables, parameters)
@views jacobians[indices] .= general.jacobian_cache
fill!(general.jacobian_cache, 0.0) # TODO: confirm this is necessary
end
function hessian_lagrangian!(hessian, indices, general::GeneralConstraint{T}, variables, parameters, duals) where T
if !isempty(general.hessian_cache)
general.hessian(general.hessian_cache, variables, duals)
@views hessian[indices] .+= general.hessian_cache
fill!(general.hessian_cache, 0.0) # TODO: confirm this is necessary
end
end
function sparsity_jacobian(general::GeneralConstraint{T}, num_variables::Int;
row_shift=0) where T
row = Int[]
col = Int[]
push!(row, (general.jacobian_sparsity[1] .+ row_shift)...)
push!(col, general.jacobian_sparsity[2]...)
return collect(zip(row, col))
end
function sparsity_hessian(general::GeneralConstraint{T}, num_variables::Int) where T
row = Int[]
col = Int[]
if !isempty(general.hessian_sparsity[1])
shift = 0
push!(row, (general.hessian_sparsity[1] .+ shift)...)
push!(col, (general.hessian_sparsity[2] .+ shift)...)
end
return collect(zip(row, col))
end
num_constraint(general::GeneralConstraint{T}) where T = general.num_constraint
num_jacobian(general::GeneralConstraint{T}) where T = general.num_jacobian
# num_hessian(general::GeneralConstraint{T}) where T = general.num_hessian
constraint_indices(general::GeneralConstraint{T}; shift=0) where T = collect(shift .+ (1:general.num_constraint))
jacobian_indices(general::GeneralConstraint{T}; shift=0) where T = collect(shift .+ (1:general.num_jacobian))
function hessian_indices(general::GeneralConstraint{T}, key::Vector{Tuple{Int,Int}}, num_variables::Int) where T
if !isempty(general.hessian_sparsity[1])
row = Int[]
col = Int[]
shift = 0
push!(row, (general.hessian_sparsity[1] .+ shift)...)
push!(col, (general.hessian_sparsity[2] .+ shift)...)
rc = collect(zip(row, col))
indices = [findfirst(x -> x == i, key) for i in rc]
else
indices = Vector{Int}[]
end
return indices
end
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 4275 | function MOI.eval_objective(nlp::NLPData{T}, variables::Vector{T}) where T
trajectory!(
nlp.trajopt.states,
nlp.trajopt.actions,
variables,
nlp.indices.states,
nlp.indices.actions)
cost(
nlp.trajopt.objective,
nlp.trajopt.states,
nlp.trajopt.actions,
nlp.trajopt.parameters)
end
function MOI.eval_objective_gradient(nlp::NLPData{T}, gradient, variables) where T
fill!(gradient, 0.0)
trajectory!(
nlp.trajopt.states,
nlp.trajopt.actions,
variables,
nlp.indices.states,
nlp.indices.actions)
gradient!(gradient,
nlp.indices.state_action,
nlp.trajopt.objective,
nlp.trajopt.states,
nlp.trajopt.actions,
nlp.trajopt.parameters)
return
end
function MOI.eval_constraint(nlp::NLPData{T}, violations, variables) where T
fill!(violations, 0.0)
trajectory!(
nlp.trajopt.states,
nlp.trajopt.actions,
variables,
nlp.indices.states,
nlp.indices.actions)
constraints!(
violations,
nlp.indices.dynamics_constraints,
nlp.trajopt.dynamics,
nlp.trajopt.states,
nlp.trajopt.actions,
nlp.trajopt.parameters)
!isempty(nlp.indices.stage_constraints) && constraints!(violations, nlp.indices.stage_constraints, nlp.trajopt.constraints, nlp.trajopt.states, nlp.trajopt.actions, nlp.trajopt.parameters)
nlp.general_constraint.num_constraint != 0 && constraints!(violations, nlp.indices.general_constraint, nlp.general_constraint, variables, nlp.parameters)
return
end
function MOI.eval_constraint_jacobian(nlp::NLPData{T}, jacobian, variables) where T
fill!(jacobian, 0.0)
trajectory!(
nlp.trajopt.states,
nlp.trajopt.actions,
variables,
nlp.indices.states,
nlp.indices.actions)
jacobian!(
jacobian,
nlp.indices.dynamics_jacobians,
nlp.trajopt.dynamics,
nlp.trajopt.states,
nlp.trajopt.actions,
nlp.trajopt.parameters)
!isempty(nlp.indices.stage_jacobians) && jacobian!(jacobian, nlp.indices.stage_jacobians, nlp.trajopt.constraints, nlp.trajopt.states, nlp.trajopt.actions, nlp.trajopt.parameters)
nlp.general_constraint.num_constraint != 0 && jacobian!(jacobian, nlp.indices.general_jacobian, nlp.general_constraint, variables, nlp.parameters)
return
end
function MOI.eval_hessian_lagrangian(nlp::MOI.AbstractNLPEvaluator, hessian, variables, scaling, duals)
fill!(hessian, 0.0)
trajectory!(
nlp.trajopt.states,
nlp.trajopt.actions,
variables,
nlp.indices.states,
nlp.indices.actions)
duals!(
nlp.trajopt.duals_dynamics,
nlp.trajopt.duals_constraints,
nlp.duals_general,
duals,
nlp.indices.dynamics_constraints,
nlp.indices.stage_constraints,
nlp.indices.general_constraint)
hessian!(
hessian,
nlp.indices.objective_hessians,
nlp.trajopt.objective,
nlp.trajopt.states,
nlp.trajopt.actions,
nlp.trajopt.parameters,
scaling)
hessian_lagrangian!(
hessian,
nlp.indices.dynamics_hessians,
nlp.trajopt.dynamics,
nlp.trajopt.states,
nlp.trajopt.actions,
nlp.trajopt.parameters,
nlp.trajopt.duals_dynamics)
hessian_lagrangian!(
hessian,
nlp.indices.stage_hessians,
nlp.trajopt.constraints,
nlp.trajopt.states,
nlp.trajopt.actions,
nlp.trajopt.parameters,
nlp.trajopt.duals_constraints)
hessian_lagrangian!(
hessian,
nlp.indices.general_hessian,
nlp.general_constraint,
variables,
nlp.parameters,
nlp.duals_general)
return
end
MOI.features_available(nlp::MOI.AbstractNLPEvaluator) = nlp.hessian_lagrangian ? [:Grad, :Jac, :Hess] : [:Grad, :Jac]
MOI.initialize(nlp::MOI.AbstractNLPEvaluator, features) = nothing
MOI.jacobian_structure(nlp::MOI.AbstractNLPEvaluator) = nlp.jacobian_sparsity
MOI.hessian_lagrangian_structure(nlp::MOI.AbstractNLPEvaluator) = nlp.hessian_lagrangian_sparsity
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 1089 | """
Solver options for Ipopt
https://coin-or.github.io/Ipopt/OPTIONS.html#OPT_print_options_documentation
"""
Base.@kwdef mutable struct Options{T}
tol::T = 1e-6
s_max::T = 100.0
max_iter::Int = 1000
# max_wall_time = 300.0
max_cpu_time = 300.0
dual_inf_tol::T = 1.0
constr_viol_tol::T = 1.0e-3
compl_inf_tol::T = 1.0e-3
acceptable_tol::T = 1.0e-6
acceptable_iter::Int = 15
acceptable_dual_inf_tol::T = 1.0e10
acceptable_constr_viol_tol::T = 1.0e-2
acceptable_compl_inf_tol::T = 1.0e-2
acceptable_obj_change_tol::T = 1.0e-5
diverging_iterates_tol::T = 1.0e8
mu_target::T = 1.0e-4
print_level::Int = 5
output_file = "output.txt"
print_user_options = "no"
# print_options_documentation = "no"
# print_timing_statistics = "no"
# print_options_mode = "text"
# print_advanced_options = "no"
print_info_string = "no"
inf_pr_output = "original"
print_frequency_iter = 1
print_frequency_time = 0.0
skip_finalize_solution_call = "no"
# timing_statistics = :no
end
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 1521 | struct Solver{T} <: MOI.AbstractNLPEvaluator
nlp::NLPData{T}
data::SolverData
end
function Solver(dynamics::Vector{Dynamics{T}}, objective::Objective{T}, constraints::Constraints{T}, bounds::Bounds{T};
evaluate_hessian=false,
general_constraint=GeneralConstraint(),
options=Options(),
parameters=[[zeros(num_parameter) for num_parameter in dimensions(dynamics)[3]]..., zeros(0)]) where T
trajopt = TrajectoryOptimizationData(objective, dynamics, constraints, bounds,
parameters=parameters)
nlp = NLPData(trajopt,
general_constraint=general_constraint,
evaluate_hessian=evaluate_hessian)
data = SolverData(nlp,
options=options)
Solver(nlp, data)
end
function initialize_states!(solver::Solver, states)
for (t, xt) in enumerate(states)
n = length(xt)
for i = 1:n
MOI.set(solver.data.optimizer, MOI.VariablePrimalStart(), solver.data.variables[solver.nlp.indices.states[t][i]], xt[i])
end
end
end
function initialize_controls!(solver::Solver, actions)
for (t, ut) in enumerate(actions)
m = length(ut)
for j = 1:m
MOI.set(solver.data.optimizer, MOI.VariablePrimalStart(), solver.data.variables[solver.nlp.indices.actions[t][j]], ut[j])
end
end
end
function get_trajectory(solver::Solver)
return solver.nlp.trajopt.states, solver.nlp.trajopt.actions[1:end-1]
end
function solve!(solver::Solver)
MOI.optimize!(solver.data.optimizer)
end | DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 334 | function linear_interpolation(initial_state, final_state, horizon)
n = length(initial_state)
X = [copy(Array(initial_state)) for t = 1:horizon]
for t = 1:horizon
for i = 1:n
X[t][i] = (final_state[i] - initial_state[i]) / (horizon - 1) * (t - 1) + initial_state[i]
end
end
return X
end
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 1723 | @testset "Constraints" begin
T = 5
num_state = 2
num_action = 1
num_parameter = 0
dim_x = [num_state for t = 1:T]
dim_u = [num_action for t = 1:T-1]
dim_w = [num_parameter for t = 1:T]
x = [rand(dim_x[t]) for t = 1:T]
u = [[rand(dim_u[t]) for t = 1:T-1]..., zeros(0)]
w = [rand(dim_w[t]) for t = 1:T]
ct = (x, u, w) -> [-ones(num_state) - x; x - ones(num_state)]
cT = (x, u, w) -> x
cont = Constraint(ct, num_state, num_action, num_parameter=num_parameter, indices_inequality=collect(1:2num_state))
conT = Constraint(cT, num_state, 0, num_parameter=0)
constraints = [[cont for t = 1:T-1]..., conT]
nc = DTO.num_constraint(constraints)
nj = DTO.num_jacobian(constraints)
idx_c = DTO.constraint_indices(constraints)
idx_j = DTO.jacobian_indices(constraints)
c = zeros(nc)
j = zeros(nj)
cont.evaluate(c[idx_c[1]], x[1], u[1], w[1])
conT.evaluate(c[idx_c[T]], x[T], u[T], w[T])
DTO.constraints!(c, idx_c, constraints, x, u, w)
# info = @benchmark DTO.constraints!($c, $idx_c, $constraints, $x, $u, $w)
@test norm(c - vcat([ct(x[t], u[t], w[t]) for t = 1:T-1]..., cT(x[T], u[T], w[T]))) < 1.0e-8
DTO.jacobian!(j, idx_j, constraints, x, u, w)
# info = @benchmark DTO.jacobian!($j, $idx_j, $constraints, $x, $u, $w)
dct = [-I zeros(num_state, num_action); I zeros(num_state, num_action)]
dcT = Diagonal(ones(num_state))
dc = cat([dct for t = 1:T-1]..., dcT, dims=(1,2))
sp = DTO.sparsity_jacobian(constraints, dim_x, dim_u)
j_dense = zeros(nc, sum(dim_x) + sum(dim_u))
for (i, v) in enumerate(sp)
j_dense[v[1], v[2]] = j[i]
end
@test norm(j_dense - dc) < 1.0e-8
end | DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 3239 | @testset "Dynamics" begin
T = 3
num_state = 2
num_action = 1
num_parameter = 0
parameter_dimensions = [num_parameter for t = 1:T]
function pendulum(z, u, w)
mass = 1.0
lc = 1.0
gravity = 9.81
damping = 0.1
[z[2], (u[1] / ((mass * lc * lc)) - gravity * sin(z[1]) / lc - damping * z[2] / (mass * lc * lc))]
end
function euler_implicit(y, x, u, w)
h = 0.1
y - (x + h * pendulum(y, u, w))
end
dt = Dynamics(euler_implicit, num_state, num_state, num_action,
num_parameter=num_parameter);
dynamics = [dt for t = 1:T-1]
x1 = ones(num_state)
u1 = ones(num_action)
w1 = zeros(num_parameter)
X = [x1 for t = 1:T]
U = [u1 for t = 1:T]
W = [w1 for t = 1:T]
idx_dyn = DTO.constraint_indices(dynamics)
idx_jac = DTO.jacobian_indices(dynamics)
d = zeros(DTO.num_constraint(dynamics))
j = zeros(DTO.num_jacobian(dynamics))
dt.evaluate(dt.evaluate_cache, x1, x1, u1, w1)
# @benchmark $dt.evaluate($dt.evaluate_cache, $x1, $x1, $u1, $w1)
@test norm(dt.evaluate_cache - euler_implicit(x1, x1, u1, w1)) < 1.0e-8
dt.jacobian(dt.jacobian_cache, x1, x1, u1, w1)
jac_dense = zeros(dt.num_next_state, dt.num_state + dt.num_action + dt.num_next_state)
for (i, ji) in enumerate(dt.jacobian_cache)
jac_dense[dt.jacobian_sparsity[1][i], dt.jacobian_sparsity[2][i]] = ji
end
jac_fd = ForwardDiff.jacobian(a -> euler_implicit(a[num_state + num_action .+ (1:num_state)], a[1:num_state], a[num_state .+ (1:num_action)], w1), [x1; u1; x1])
@test norm(jac_dense - jac_fd) < 1.0e-8
DTO.constraints!(d, idx_dyn, dynamics, X, U, W)
@test norm(vcat(d...) - vcat([euler_implicit(X[t+1], X[t], U[t], W[t]) for t = 1:T-1]...)) < 1.0e-8
# info = @benchmark DTO.constraints!($d, $idx_dyn, $dynamics, $X, $U, $W)
DTO.jacobian!(j, idx_jac, dynamics, X, U, W)
s = DTO.sparsity_jacobian(dynamics, DTO.dimensions(dynamics)[1:2]...)
jac_dense = zeros(DTO.num_constraint(dynamics), DTO.num_state_action_next_state(dynamics))
for (i, ji) in enumerate(j)
jac_dense[s[i][1], s[i][2]] = ji
end
@test norm(jac_dense - [jac_fd zeros(dynamics[2].num_state, dynamics[2].num_action + dynamics[2].num_next_state); zeros(dynamics[2].num_next_state, dynamics[1].num_state + dynamics[1].num_action) jac_fd]) < 1.0e-8
# info = @benchmark DTO.jacobian!($j, $idx_jac, $dynamics, $X, $U, $W)
x_idx = DTO.state_indices(dynamics)
u_idx = DTO.action_indices(dynamics)
xu_idx = DTO.state_action_indices(dynamics)
xuy_idx = DTO.state_action_next_state_indices(dynamics)
nz = sum([t < T ? dynamics[t].num_state : dynamics[t-1].num_next_state for t = 1:T]) + sum([dynamics[t].num_action for t = 1:T-1])
z = rand(nz)
x = [zero(z[x_idx[t]]) for t = 1:T]
u = [[zero(z[u_idx[t]]) for t = 1:T-1]..., zeros(0)]
DTO.trajectory!(x, u, z, x_idx, u_idx)
z̄ = zero(z)
for (t, idx) in enumerate(x_idx)
z̄[idx] .= x[t]
end
for (t, idx) in enumerate(u_idx)
z̄[idx] .= u[t]
end
@test norm(z - z̄) < 1.0e-8
# info = @benchmark DTO.trajectory!($x, $u, $z, $x_idx, $u_idx)
end
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 9006 | @testset "Hessian of Lagrangian" begin
MOI = DTO.MOI
# horizon
T = 3
# acrobot
num_state = 4
num_action = 1
num_parameter = 0
parameter_dimensions = [num_parameter for t = 1:T]
function acrobot(x, u, w)
# dimensions
n = 4
m = 1
d = 0
# link 1
mass1 = 1.0
inertia1 = 0.33
length1 = 1.0
lengthcom1 = 0.5
# link 2
mass2 = 1.0
inertia2 = 0.33
length2 = 1.0
lengthcom2 = 0.5
gravity = 9.81
friction1 = 0.1
friction2 = 0.1
# mass matrix
function M(x, w)
a = (inertia1 + inertia2 + mass2 * length1 * length1
+ 2.0 * mass2 * length1 * lengthcom2 * cos(x[2]))
b = inertia2 + mass2 * length1 * lengthcom2 * cos(x[2])
c = inertia2
return [a b; b c]
end
function Minv(x, w)
a = (inertia1 + inertia2 + mass2 * length1 * length1
+ 2.0 * mass2 * length1 * lengthcom2 * cos(x[2]))
b = inertia2 + mass2 * length1 * lengthcom2 * cos(x[2])
c = inertia2
return 1.0 / (a * c - b * b) * [c -b; -b a]
end
# dynamics bias
function τ(x, w)
a = (-1.0 * mass1 * gravity * lengthcom1 * sin(x[1])
- mass2 * gravity * (length1 * sin(x[1])
+ lengthcom2 * sin(x[1] + x[2])))
b = -1.0 * mass2 * gravity * lengthcom2 * sin(x[1] + x[2])
return [a; b]
end
function C(x, w)
a = -2.0 * mass2 * length1 * lengthcom2 * sin(x[2]) * x[4]
b = -1.0 * mass2 * length1 * lengthcom2 * sin(x[2]) * x[4]
c = mass2 * length1 * lengthcom2 * sin(x[2]) * x[3]
d = 0.0
return [a b; c d]
end
# input Jacobian
function B(x, w)
[0.0; 1.0]
end
# dynamics
q = view(x, 1:2)
v = view(x, 3:4)
qdd = Minv(q, w) * (-1.0 * C(x, w) * v
+ τ(q, w) + B(q, w) * u[1] - [friction1; friction2] .* v)
return [x[3]; x[4]; qdd[1]; qdd[2]]
end
function midpoint_implicit(y, x, u, w)
h = 0.05 # timestep
y - (x + h * acrobot(0.5 * (x + y), u, w))
end
dt = Dynamics(midpoint_implicit, num_state, num_state, num_action, num_parameter=num_parameter, evaluate_hessian=true)
dynamics = [dt for t = 1:T-1]
# initial state
x1 = [0.0; 0.0; 0.0; 0.0]
# goal state
xT = [0.0; π; 0.0; 0.0]
# objective
ot = (x, u, w) -> 0.1 * dot(x[3:4], x[3:4]) + 0.1 * dot(u, u)
oT = (x, u, w) -> 0.1 * dot(x[3:4], x[3:4])
objt = Cost(ot, num_state, num_action, num_parameter=num_parameter, evaluate_hessian=true)
objT = Cost(oT, num_state, 0, num_parameter=num_parameter, evaluate_hessian=true)
objective = [[objt for t = 1:T-1]..., objT]
# constraints
bnd1 = Bound(num_state, num_action, state_lower=x1, state_upper=x1)
bndt = Bound(num_state, num_action)
bndT = Bound(num_state, 0, state_lower=xT, state_upper=xT)
bounds = [bnd1, [bndt for t = 2:T-1]..., bndT]
ct = (x, u, w) -> [-5.0 * ones(num_action) - cos.(u) .* sum(x.^2); cos.(x) .* tan.(u) - 5.0 * ones(num_state)]
cT = (x, u, w) -> sin.(x.^3.0)
cont = Constraint(ct, num_state, num_action, num_parameter=num_parameter, indices_inequality=collect(1:(num_action + num_state)), evaluate_hessian=true)
conT = Constraint(cT, num_state, 0, num_parameter=num_parameter, evaluate_hessian=true)
constraints = [[cont for t = 1:T-1]..., conT]
# data
# trajopt = DTO.TrajectoryOptimizationData(objective, dynamics, constraints, bounds)
# nlp = DTO.NLPData(trajopt, evaluate_hessian=true)
solver = Solver(dynamics, objective, constraints, bounds, evaluate_hessian=true)
# Lagrangian
function lagrangian(z)
x1 = z[1:num_state]
u1 = z[num_state .+ (1:num_action)]
x2 = z[num_state + num_action .+ (1:num_state)]
u2 = z[num_state + num_action + num_state .+ (1:num_action)]
x3 = z[num_state + num_action + num_state + num_action .+ (1:num_state)]
λ1_dyn = z[num_state + num_action + num_state + num_action + num_state .+ (1:num_state)]
λ2_dyn = z[num_state + num_action + num_state + num_action + num_state + num_state .+ (1:num_state)]
λ1_stage = z[num_state + num_action + num_state + num_action + num_state + num_state + num_state .+ (1:(num_action + num_state))]
λ2_stage = z[num_state + num_action + num_state + num_action + num_state + num_state + num_state + num_action + num_state .+ (1:(num_action + num_state))]
λ3_stage = z[num_state + num_action + num_state + num_action + num_state + num_state + num_state + num_action + num_state + num_action + num_state .+ (1:num_state)]
L = 0.0
L += ot(x1, u1, zeros(num_parameter))
L += ot(x2, u2, zeros(num_parameter))
L += oT(x3, zeros(0), zeros(num_parameter))
L += dot(λ1_dyn, midpoint_implicit(x2, x1, u1, zeros(num_parameter)))
L += dot(λ2_dyn, midpoint_implicit(x3, x2, u2, zeros(num_parameter)))
L += dot(λ1_stage, ct(x1, u1, zeros(num_parameter)))
L += dot(λ2_stage, ct(x2, u2, zeros(num_parameter)))
L += dot(λ3_stage, cT(x3, zeros(0), zeros(num_parameter)))
return L
end
nz = num_state + num_action + num_state + num_action + num_state + num_state + num_state + num_action + num_state + num_action + num_state + num_state
np = num_state + num_action + num_state + num_action + num_state
nd = num_state + num_state + num_action + num_state + num_action + num_state + num_state
@variables z[1:nz]
L = lagrangian(z)
Lxx = Symbolics.hessian(L, z[1:np])
Lxx_sp = Symbolics.sparsehessian(L, z[1:np])
spar = [findnz(Lxx_sp)[1:2]...]
Lxx_func = eval(Symbolics.build_function(Lxx, z)[1])
Lxx_sp_func = eval(Symbolics.build_function(Lxx_sp.nzval, z)[1])
z0 = rand(nz)
nh = length(solver.nlp.hessian_lagrangian_sparsity)
h0 = zeros(nh)
σ = 1.0
fill!(h0, 0.0)
DTO.trajectory!(solver.nlp.trajopt.states, solver.nlp.trajopt.actions, z0[1:np],
solver.nlp.indices.states, solver.nlp.indices.actions)
DTO.duals!(solver.nlp.trajopt.duals_dynamics, solver.nlp.trajopt.duals_constraints, solver.nlp.duals_general, z0[np .+ (1:nd)], solver.nlp.indices.dynamics_constraints, solver.nlp.indices.stage_constraints, solver.nlp.indices.general_constraint)
DTO.hessian!(h0, solver.nlp.indices.objective_hessians, solver.nlp.trajopt.objective, solver.nlp.trajopt.states, solver.nlp.trajopt.actions, solver.nlp.trajopt.parameters, σ)
DTO.hessian_lagrangian!(h0, solver.nlp.indices.dynamics_hessians, solver.nlp.trajopt.dynamics, solver.nlp.trajopt.states, solver.nlp.trajopt.actions, solver.nlp.trajopt.parameters, solver.nlp.trajopt.duals_dynamics)
DTO.hessian_lagrangian!(h0, solver.nlp.indices.stage_hessians, solver.nlp.trajopt.constraints, solver.nlp.trajopt.states, solver.nlp.trajopt.actions, solver.nlp.trajopt.parameters, solver.nlp.trajopt.duals_constraints)
sparsity_objective_hessians = DTO.sparsity_hessian(objective, solver.nlp.trajopt.state_dimensions, solver.nlp.trajopt.action_dimensions)
sparsity_dynamics_hessians = DTO.sparsity_hessian(dynamics, solver.nlp.trajopt.state_dimensions, solver.nlp.trajopt.action_dimensions)
sparsity_constraint_hessian = DTO.sparsity_hessian(constraints, solver.nlp.trajopt.state_dimensions, solver.nlp.trajopt.action_dimensions)
hessian_sparsity = collect([sparsity_objective_hessians..., sparsity_dynamics_hessians..., sparsity_constraint_hessian...])
sp_key = sort(unique(hessian_sparsity))
idx_objective_hessians = DTO.hessian_indices(objective, sp_key, solver.nlp.trajopt.state_dimensions, solver.nlp.trajopt.action_dimensions)
idx_dynamics_hessians = DTO.hessian_indices(dynamics, sp_key, solver.nlp.trajopt.state_dimensions, solver.nlp.trajopt.action_dimensions)
idx_con_hess = DTO.hessian_indices(constraints, sp_key, solver.nlp.trajopt.state_dimensions, solver.nlp.trajopt.action_dimensions)
# indices
@test sp_key[vcat(idx_objective_hessians...)] == sparsity_objective_hessians
@test sp_key[vcat(idx_dynamics_hessians...)] == sparsity_dynamics_hessians
@test sp_key[vcat(idx_con_hess...)] == sparsity_constraint_hessian
# Hessian
h0_full = zeros(np, np)
for (i, h) in enumerate(h0)
h0_full[sp_key[i][1], sp_key[i][2]] = h
end
@test norm(h0_full - Lxx_func(z0)) < 1.0e-8
@test norm(norm(h0 - Lxx_sp_func(z0))) < 1.0e-8
h0 = zeros(nh)
MOI.eval_hessian_lagrangian(solver.nlp, h0, z0[1:np], σ, z0[np .+ (1:nd)])
@test norm(norm(h0 - Lxx_sp_func(z0))) < 1.0e-8
# a = z0[1:np]
# b = z0[np .+ (1:nd)]
# info = @benchmark MOI.evaluate_hessianian_lagrangian($solver, $h0, $a, $σ, $b)
end
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 1554 | @testset "Objective" begin
T = 3
num_state = 2
num_action = 1
num_parameter = 0
ot = (x, u, w) -> dot(x, x) + 0.1 * dot(u, u)
oT = (x, u, w) -> 10.0 * dot(x, x)
ct = Cost(ot, num_state, num_action, num_parameter=num_parameter)
cT = Cost(oT, num_state, 0, num_parameter=num_parameter)
objective = [[ct for t = 1:T-1]..., cT]
J = [0.0]
gradient = zeros((T - 1) * (num_state + num_action) + num_state)
idx_xu = [collect((t - 1) * (num_state + num_action) .+ (1:(num_state + (t == T ? 0 : num_action)))) for t = 1:T]
x1 = ones(num_state)
u1 = ones(num_action)
w1 = zeros(num_parameter)
X = [x1 for t = 1:T]
U = [t < T ? u1 : zeros(0) for t = 1:T]
W = [w1 for t = 1:T]
ct.evaluate(ct.evaluate_cache, x1, u1, w1)
ct.gradient(ct.gradient_cache, x1, u1, w1)
@test ct.evaluate_cache[1] ≈ ot(x1, u1, w1)
@test norm(ct.gradient_cache - [2.0 * x1; 0.2 * u1]) < 1.0e-8
cT.evaluate(cT.evaluate_cache, x1, u1, w1)
cT.gradient(cT.gradient_cache, x1, u1, w1)
@test cT.evaluate_cache[1] ≈ oT(x1, u1, w1)
@test norm(cT.gradient_cache - 20.0 * x1) < 1.0e-8
@test DTO.cost(objective, X, U, X) - sum([ot(X[t], U[t], W[t]) for t = 1:T-1]) - oT(X[T], U[T], W[T]) ≈ 0.0
DTO.gradient!(gradient, idx_xu, objective, X, U, W)
@test norm(gradient - vcat([[2.0 * x1; 0.2 * u1] for t = 1:T-1]..., 20.0 * x1)) < 1.0e-8
# info = @benchmark DTO.cost($objective, $X, $U, $W)
# info = @benchmark DTO.gradient!($gradient, $idx_xu, $objective, $X, $U, $W)
end
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 286 | using Test
using Symbolics
using ForwardDiff
using LinearAlgebra
using SparseArrays
using DirectTrajectoryOptimization
const DTO = DirectTrajectoryOptimization
include("objective.jl")
include("dynamics.jl")
include("constraints.jl")
include("hessian_lagrangian.jl")
include("solve.jl") | DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | code | 7968 | @testset "Solve: acrobot" begin
# horizon
T = 101
# acrobot
num_state = 4
num_action = 1
num_parameter = 0
parameter_dimensions = [num_parameter for t = 1:T]
function acrobot(x, u, w)
# dimensions
n = 4
m = 1
d = 0
# link 1
mass1 = 1.0
inertia1 = 0.33
length1 = 1.0
lengthcom1 = 0.5
# link 2
mass2 = 1.0
inertia2 = 0.33
length2 = 1.0
lengthcom2 = 0.5
gravity = 9.81
friction1 = 0.1
friction2 = 0.1
# mass matrix
function M(x, w)
a = (inertia1 + inertia2 + mass2 * length1 * length1
+ 2.0 * mass2 * length1 * lengthcom2 * cos(x[2]))
b = inertia2 + mass2 * length1 * lengthcom2 * cos(x[2])
c = inertia2
return [a b; b c]
end
function Minv(x, w)
a = (inertia1 + inertia2 + mass2 * length1 * length1
+ 2.0 * mass2 * length1 * lengthcom2 * cos(x[2]))
b = inertia2 + mass2 * length1 * lengthcom2 * cos(x[2])
c = inertia2
return 1.0 / (a * c - b * b) * [c -b; -b a]
end
# dynamics bias
function τ(x, w)
a = (-1.0 * mass1 * gravity * lengthcom1 * sin(x[1])
- mass2 * gravity * (length1 * sin(x[1])
+ lengthcom2 * sin(x[1] + x[2])))
b = -1.0 * mass2 * gravity * lengthcom2 * sin(x[1] + x[2])
return [a; b]
end
function C(x, w)
a = -2.0 * mass2 * length1 * lengthcom2 * sin(x[2]) * x[4]
b = -1.0 * mass2 * length1 * lengthcom2 * sin(x[2]) * x[4]
c = mass2 * length1 * lengthcom2 * sin(x[2]) * x[3]
d = 0.0
return [a b; c d]
end
# input Jacobian
function B(x, w)
[0.0; 1.0]
end
# dynamics
q = view(x, 1:2)
v = view(x, 3:4)
qdd = Minv(q, w) * (-1.0 * C(x, w) * v
+ τ(q, w) + B(q, w) * u[1] - [friction1; friction2] .* v)
return [x[3]; x[4]; qdd[1]; qdd[2]]
end
function midpoint_implicit(y, x, u, w)
h = 0.05 # timestep
y - (x + h * acrobot(0.5 * (x + y), u, w))
end
dt = Dynamics(midpoint_implicit, num_state, num_state, num_action, num_parameter=num_parameter)
dynamics = [dt for t = 1:T-1]
# initial state
x1 = [0.0; 0.0; 0.0; 0.0]
# goal state
xT = [0.0; π; 0.0; 0.0]
# interpolation
x_interpolation = linear_interpolation(x1, xT, T)
# objective
ot = (x, u, w) -> 0.1 * dot(x[3:4], x[3:4]) + 0.1 * dot(u, u)
oT = (x, u, w) -> 0.1 * dot(x[3:4], x[3:4])
ct = Cost(ot, num_state, num_action, num_parameter=num_parameter)
cT = Cost(oT, num_state, 0, num_parameter=num_parameter)
objective = [[ct for t = 1:T-1]..., cT]
# constraints
bnd1 = Bound(num_state, num_action, state_lower=x1, state_upper=x1)
bndt = Bound(num_state, num_action)
bndT = Bound(num_state, 0, state_lower=xT, state_upper=xT)
bounds = [bnd1, [bndt for t = 2:T-1]..., bndT]
constraints = [Constraint() for t = 1:T]
# problem
solver = Solver(dynamics, objective, constraints, bounds)
# initialize
initialize_states!(solver, x_interpolation)
initialize_controls!(solver, [randn(num_action) for t = 1:T-1])
# solve
solve!(solver)
# solution
x_sol, u_sol = get_trajectory(solver)
@test norm(x_sol[1] - x1) < 1.0e-3
@test norm(x_sol[T] - xT) < 1.0e-3
end
@testset "Solve: user-provided dynamics gradients" begin
# ## horizon
T = 11
# ## double integrator
num_state = 2
num_action = 1
num_parameter = 0
function double_integrator(d, y, x, u, w)
A = [1.0 1.0; 0.0 1.0]
B = [0.0; 1.0]
d .= y - (A * x + B * u[1])
end
function double_integrator_grad(dz, y, x, u, w)
A = [1.0 1.0; 0.0 1.0]
B = [0.0; 1.0]
dz .= [-A -B I]
end
# ## fast methods
function double_integrator(y, x, u, w)
A = [1.0 1.0; 0.0 1.0]
B = [0.0; 1.0]
y - (A * x + B * u[1])
end
function double_integrator_grad(y, x, u, w)
A = [1.0 1.0; 0.0 1.0]
B = [0.0; 1.0]
[-A -B I]
end
@variables y[1:num_state] x[1:num_state] u[1:num_action] w[1:num_parameter]
di = double_integrator(y, x, u, w)
diz = double_integrator_grad(y, x, u, w)
di_func = eval(Symbolics.build_function(di, y, x, u, w)[2])
diz_func = eval(Symbolics.build_function(diz, y, x, u, w)[2])
# ## model
dt = Dynamics(di_func, diz_func, num_state, num_state, num_action)
dynamics = [dt for t = 1:T-1]
# ## initialization
x1 = [0.0; 0.0]
xT = [1.0; 0.0]
# ## objective
ot = (x, u, w) -> 0.1 * dot(x, x) + 0.1 * dot(u, u)
oT = (x, u, w) -> 0.1 * dot(x, x)
ct = Cost(ot, num_state, num_action, num_parameter=num_parameter)
cT = Cost(oT, num_state, 0, num_parameter=num_parameter)
objective = [[ct for t = 1:T-1]..., cT]
# ## constraints
bnd1 = Bound(num_state, num_action,
state_lower=x1,
state_upper=x1)
bndt = Bound(num_state, num_action)
bndT = Bound(num_state, 0,
state_lower=xT,
state_upper=xT)
bounds = [bnd1, [bndt for t = 2:T-1]..., bndT]
constraints = [Constraint() for t = 1:T]
# ## problem
solver = Solver(dynamics, objective, constraints, bounds)
# ## initialize
x_interpolation = linear_interpolation(x1, xT, T)
u_guess = [1.0 * randn(num_action) for t = 1:T-1]
initialize_states!(solver, x_interpolation)
initialize_controls!(solver, u_guess)
# ## solve
solve!(solver)
# ## solution
x_sol, u_sol = get_trajectory(solver)
@test norm(x_sol[1] - x1) < 1.0e-3
@test norm(x_sol[T] - xT) < 1.0e-3
end
@testset "Solve: general constraint" begin
# ##
evaluate_hessian = true
# ## horizon
T = 11
# ## double integrator
num_state = 2
num_action = 1
num_parameter = 0
function double_integrator(y, x, u, w)
A = [1.0 1.0; 0.0 1.0]
B = [0.0; 1.0]
y - (A * x + B * u[1])
end
# ## model
dt = Dynamics(double_integrator, num_state, num_state, num_action, evaluate_hessian=evaluate_hessian)
dynamics = [dt for t = 1:T-1]
dynamics[1].hessian_cache
# ## initialization
x1 = [0.0; 0.0]
xT = [1.0; 0.0]
# ## objective
ot = (x, u, w) -> 0.1 * dot(x, x) + 0.1 * dot(u, u)
oT = (x, u, w) -> 0.1 * dot(x, x)
ct = Cost(ot, num_state, num_action, num_parameter=num_parameter,
evaluate_hessian=evaluate_hessian)
cT = Cost(oT, num_state, 0, num_parameter=num_parameter,
evaluate_hessian=evaluate_hessian)
objective = [[ct for t = 1:T-1]..., cT]
# ## constraints
bnd1 = Bound(num_state, num_action,
state_lower=x1,
state_upper=x1)
bndt = Bound(num_state, num_action)
bndT = Bound(num_state, 0)#, state_lower=xT, state_upper=xT)
bounds = [bnd1, [bndt for t = 2:T-1]..., bndT]
constraints = [Constraint() for t = 1:T]
gc = GeneralConstraint((z, w) -> z[(end-1):end] - xT, num_state * T + num_action * (T-1), 0,
evaluate_hessian=true)
# ## problem
solver = Solver(dynamics, objective, constraints, bounds,
general_constraint=gc,
evaluate_hessian=true,
options=Options())
# ## initialize
x_interpolation = linear_interpolation(x1, xT, T)
u_guess = [1.0 * randn(num_action) for t = 1:T-1]
initialize_states!(solver, x_interpolation)
initialize_controls!(solver, u_guess)
# ## solve
solve!(solver)
# ## solution
x_sol, u_sol = get_trajectory(solver)
@test norm(x_sol[1] - x1) < 1.0e-3
@test norm(x_sol[T] - xT) < 1.0e-3
end | DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | docs | 1365 | # DirectTrajectoryOptimization.jl
[](https://github.com/thowell/DirectTrajectoryOptimization.jl/actions/workflows/CI.yml)
[](https://codecov.io/gh/thowell/DirectTrajectoryOptimization.jl)
A Julia package for solving constrained trajectory optimization problems:
```
minimize cost_T(state_T; parameter_T) + sum(cost_t(state_t, action_t; parameter_t))
states, actions
subject to dynamics_t(state_t, action_t, state_t+1; parameter_t), t = 1,...,T-1
constraint_t(state_t, action_t; parameter_t) {<,=} 0, t = 1,...,T
state_lower_t < state_t < state_upper_t, t = 1,...,T
action_lower_t < action_t < action_upper_t, t = 1,...,T-1.
```
with direct trajectory optimization.
Fast and allocation-free gradients and sparse Jacobians are automatically generated using [Symbolics.jl](https://github.com/JuliaSymbolics/Symbolics.jl) for user-provided costs, constraints, and dynamics. The problem is solved with [Ipopt](https://coin-or.github.io/Ipopt/).
## Installation
```
Pkg.add("DirectTrajectoryOptimization")
```
## Quick Start
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.2.0 | b14763be7e90836eb56370fda4ff2fab25f5892a | docs | 910 | # DirectTrajectoryOptimization.jl examples
This directory contains various DirectTrajectoryOptimization.jl 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 DirectTrajectoryOptimization.jl](https://github.com/thowell/DirectTrajectoryOptimization.jl)
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("DirectTrajectoryOptimization")
using IJulia, DirectTrajectoryOptimization
notebook(dir=joinpath(dirname(pathof(DirectTrajectoryOptimization)), "..", "examples"))
```
| DirectTrajectoryOptimization | https://github.com/thowell/DirectTrajectoryOptimization.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 88 | function module_dir()
@__DIR__
end
using Pkg
Pkg.activate(module_dir())
using Dojo
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 571 | module DojoEnvironments
using LinearAlgebra
using Random
using Dojo
import Dojo: string_to_symbol, add_limits, RotX, RotY, RotZ, rotation_vector, SVector
using PrecompileTools
include("mechanisms.jl")
include("environments.jl")
include("utilities.jl")
include("mechanisms/include.jl")
include("environments/include.jl")
# Precompilation
include("precompile.jl")
# Mechanism
export
get_mechanism,
set_springs!,
set_dampers!,
set_limits
# Environment
export
Environment,
get_environment,
step!,
get_state,
visualize
end # module
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 3499 | """
Environment{T,N}
abstract type for an environment consisting of a mechanism and a storage
"""
abstract type Environment{T,N} end
function Base.show(io::IO, mime::MIME{Symbol("text/plain")}, environment::Environment)
summary(io, environment)
end
"""
get_environment(model; kwargs...)
construct existing environment
model: name of of environment
kwargs: environment specific parameters
"""
function get_environment(model; kwargs...)
return eval(string_to_symbol(model))(; string_to_symbol(kwargs)...)
end
"""
state_map(environment, state)
maps the provided state to the environments internal state
environment: environment
state: provided state
"""
function state_map(::Environment, state)
return state
end
"""
input_map(environment, input)
maps the provided input to the environment's internal input
environment: environment
input: provided input
"""
function input_map(::Environment, input)
return input
end
function input_map(environment::Environment, ::Nothing)
return zeros(input_dimension(environment.mechanism))
end
"""
set_input!(environment, input)
sets the provided input to the environment's mechanism
environment: environment
input: provided input
"""
function Dojo.set_input!(environment::Environment, input)
set_input!(environment.mechanism, input_map(environment, input))
return
end
"""
step(environment, x, u; k, record, opts)
simulates environment one time step
environment: Environment
x: state
u: input
k: current timestep
record: record step in storage
opts: SolverOptions
"""
function Dojo.step!(environment::Environment, state, input=nothing; k=1, record=false, opts=SolverOptions())
state = state_map(environment, state)
input = input_map(environment, input)
Dojo.step_minimal_coordinates!(environment.mechanism, state, input; opts)
record && Dojo.save_to_storage!(environment.mechanism, environment.storage, k)
return
end
"""
simulate!(environment, controller! = (mechanism, k) -> nothing; kwargs...)
simulates the mechanism of the environment
environment: Environment
controller!: Control function
kwargs: same as for Dojo.simulate
"""
function Dojo.simulate!(environment::Environment{T,N}, controller! = (environment, k) -> nothing; kwargs...) where {T,N}
controller_wrapper!(mechanism, k) = controller!(environment, k)
simulate!(environment.mechanism, 1:N, environment.storage, controller_wrapper!; kwargs...)
end
"""
get_state(environment)
returns the state of the environment
environment: Environment
"""
function get_state(environment::Environment)
return get_minimal_state(environment.mechanism)
end
"""
initialize!(environment; kwargs...)
initializes the environment's mechanism
environment: Environment
kwargs: same as for DojoEnvironments' mechanisms
"""
function Dojo.initialize!(environment::Environment, model; kwargs...)
eval(Symbol(:initialize, :_, string_to_symbol(model), :!))(environment.mechanism; kwargs...)
end
"""
visualize(environment; kwargs...)
visualizes the environment with its internal storage
environment: Environment
kwargs: same as for Dojo.visualize
"""
function Dojo.visualize(environment::Environment; kwargs...)
visualize(environment.mechanism, environment.storage; kwargs...)
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 702 | """
get_mechanism(model; kwargs...)
constructs mechanism
model: name of mechanism
kwargs: mechanism specific parameters
"""
function get_mechanism(model; kwargs...)
# convert potential strings to symbols
mechanism = eval(Symbol(:get, :_, string_to_symbol(model)))(; string_to_symbol(kwargs)...)
return mechanism
end
"""
initialize!(mechanism, model; kwargs)
state initialization for mechanism
mechanism: Mechanism
model: name of mechanism
kwargs: mechanism specific parameters
"""
function Dojo.initialize!(mechanism::Mechanism, model; kwargs...)
eval(Symbol(:initialize, :_, string_to_symbol(model), :!))(mechanism; kwargs...)
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1328 | @setup_workload begin
mechanisms = [
:ant,
:atlas,
:block,
:block2d,
:cartpole,
:dzhanibekov,
:exoskeleton,
:fourbar,
:halfcheetah,
:hopper,
:humanoid,
:npendulum,
:nslider,
:panda,
:pendulum,
:quadrotor,
:quadruped,
:raiberthopper,
:slider,
:snake,
:sphere,
:tippetop,
:twister,
:uuv,
:walker,
:youbot,
]
environments = [
:ant_ars,
:cartpole_dqn,
:pendulum,
:quadruped_waypoint,
:quadruped_sampling,
:quadrotor_waypoint,
:uuv_waypoint,
:youbot_waypoint,
]
@compile_workload begin
# Simulate all mechanisms
for name in mechanisms
mech = get_mechanism(name)
initialize!(mech, name)
simulate!(mech, mech.timestep * 2)
end
# Simulate all environments
for name in environments
env = get_environment(name; horizon=2)
x = get_state(env)
u = DojoEnvironments.input_map(env, nothing)
set_input!(env, nothing)
step!(env, x)
step!(env, x, u)
simulate!(env)
end
end
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2105 | function set_springs!(joints, value::Real)
for joint in joints
(value==0) && break
typeof(joint) <: JointConstraint{T,0} where T && continue # floating base
joint.spring = true
joint.translational.spring=value
joint.rotational.spring=value
end
end
function set_springs!(joints, springs::AbstractArray)
for (i,value) in enumerate(springs)
(value==0) && continue
typeof(joints[i]) <: JointConstraint{T,0} where T && continue # floating base
joints[i].spring = true
joints[i].translational.spring=value
joints[i].rotational.spring=value
end
end
function set_dampers!(joints, value::Real)
for joint in joints
(value==0) && break
typeof(joint) <: JointConstraint{T,0} where T && continue # floating base
joint.damper = true
joint.translational.damper=value
joint.rotational.damper=value
end
end
function set_dampers!(joints, dampers::AbstractArray)
for (i,value) in enumerate(dampers)
(value==0) && continue
typeof(joints[i]) <: JointConstraint{T,0} where T && continue # floating base
joints[i].damper = true
joints[i].translational.damper=value
joints[i].rotational.damper=value
end
end
function set_limits(mechanism::Mechanism{T}, joint_limits) where T
joints = JointConstraint{T}[deepcopy(mechanism.joints)...]
for (joint_symbol,limits) in joint_limits
joint = get_joint(mechanism, joint_symbol)
if input_dimension(joint.translational) == 0 && input_dimension(joint.rotational) == 1
joints[joint.id] = add_limits(mechanism, joint,
rot_limits=[SVector{1}(limits[1]), SVector{1}(limits[2])])
elseif input_dimension(joint.translational) == 1 && input_dimension(joint.rotational) == 0
joints[joint.id] = add_limits(mechanism, joint,
tra_limits=[SVector{1}(limits[1]), SVector{1}(limits[2])])
else
@warn "joint limits can only be set for one-dimensional joints"
end
end
return joints
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2137 | mutable struct AntARS{T,N} <: Environment{T,N}
mechanism::Mechanism{T}
storage::Storage{T,N}
end
function ant_ars(;
horizon=100,
timestep=0.05,
input_scaling=timestep,
gravity=-9.81,
urdf=:ant,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict([
(:hip_1, [-30,30] * π / 180),
(:ankle_1, [30,70] * π / 180),
(:hip_2, [-30,30] * π / 180),
(:ankle_2, [-70,-30] * π / 180),
(:hip_3, [-30,30] * π / 180),
(:ankle_3, [-70,-30] * π / 180),
(:hip_4, [-30,30] * π / 180),
(:ankle_4, [30,70] * π / 180)]),
keep_fixed_joints=true,
friction_coefficient=0.5,
contact_feet=true,
contact_body=true,
T=Float64)
mechanism = get_ant(;
timestep,
input_scaling,
gravity,
urdf,
springs,
dampers,
parse_springs,
parse_dampers,
joint_limits,
keep_fixed_joints,
friction_coefficient,
contact_feet,
contact_body,
T
)
storage = Storage(horizon, length(mechanism.bodies))
return AntARS{T,horizon}(mechanism, storage)
end
function DojoEnvironments.state_map(::AntARS, state)
state = state[1:28]
return state
end
function DojoEnvironments.input_map(::AntARS, input::AbstractVector)
input = [zeros(6);input] # floating base not actuated
return input
end
function Dojo.step!(environment::AntARS, state, input=nothing; k=1, record=false, opts=SolverOptions())
state = state_map(environment, state)
input = input_map(environment, input)
Dojo.step_minimal_coordinates!(environment.mechanism, state, input; opts)
record && Dojo.save_to_storage!(environment.mechanism, environment.storage, k)
return
end
function DojoEnvironments.get_state(environment::AntARS{T}) where T
contact_force = T[]
for contact in environment.mechanism.contacts
push!(contact_force, max(-1, min(1, contact.impulses[2][1])))
end
state = [get_minimal_state(environment.mechanism); contact_force]
return state
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1562 | mutable struct CartpoleDQN{T,N} <: Environment{T,N}
mechanism::Mechanism{T}
storage::Storage{T,N}
end
function cartpole_dqn(;
horizon=100,
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
slider_mass=1,
pendulum_mass=1,
link_length=1,
radius=0.075,
color=RGBA(0.7, 0.7, 0.7, 1),
springs=0,
dampers=0,
joint_limits=Dict(),
keep_fixed_joints=true,
T=Float64)
mechanism = get_cartpole(;
timestep,
input_scaling,
gravity,
slider_mass,
pendulum_mass,
link_length,
radius,
color,
springs,
dampers,
joint_limits,
keep_fixed_joints,
T
)
storage = Storage(horizon, length(mechanism.bodies))
return CartpoleDQN{T,horizon}(mechanism, storage)
end
function DojoEnvironments.state_map(::CartpoleDQN, state)
return state
end
function DojoEnvironments.input_map(::CartpoleDQN, input::Real)
input = [input;0] # only the cart is actuated
return input
end
function Dojo.step!(environment::CartpoleDQN, state, input=nothing; k=1, record=false, opts=SolverOptions())
state = state_map(environment, state)
input = input_map(environment, input)
Dojo.step_minimal_coordinates!(environment.mechanism, state, input; opts)
record && Dojo.save_to_storage!(environment.mechanism, environment.storage, k)
return
end
function DojoEnvironments.get_state(environment::CartpoleDQN)
state = get_minimal_state(environment.mechanism)
return state
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 227 | include("ant_ars.jl")
include("cartpole_dqn.jl")
include("pendulum.jl")
include("quadruped_waypoint.jl")
include("quadruped_sampling.jl")
include("quadrotor_waypoint.jl")
include("uuv_waypoint.jl")
include("youbot_waypoint.jl") | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1456 | mutable struct Pendulum{T,N} <: Environment{T,N}
mechanism::Mechanism{T}
storage::Storage{T,N}
end
function pendulum(;
horizon=100,
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
mass=1,
link_length=1,
color=RGBA(1, 0, 0),
springs=0,
dampers=0,
joint_limits=Dict(),
spring_offset=szeros(1),
orientation_offset=one(Quaternion),
T=Float64)
mechanism = get_pendulum(;
timestep,
input_scaling,
gravity,
mass,
link_length,
color,
springs,
dampers,
joint_limits,
spring_offset,
orientation_offset,
T
)
storage = Storage(horizon, length(mechanism.bodies))
return Pendulum{T,horizon}(mechanism, storage)
end
function DojoEnvironments.state_map(::Pendulum, state)
return state
end
function DojoEnvironments.input_map(::Pendulum, input::AbstractVector)
return input
end
function Dojo.step!(environment::Pendulum, state, input=nothing; k=1, record=false, opts=SolverOptions())
state = state_map(environment, state)
input = input_map(environment, input)
Dojo.step_minimal_coordinates!(environment.mechanism, state, input; opts)
record && Dojo.save_to_storage!(environment.mechanism, environment.storage, k)
return
end
function DojoEnvironments.get_state(environment::Pendulum)
state = get_minimal_state(environment.mechanism)
return state
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 4971 | mutable struct QuadrotorWaypoint{T,N} <: Environment{T,N}
mechanism::Mechanism{T}
storage::Storage{T,N}
rpms::AbstractVector
end
function quadrotor_waypoint(;
horizon=100,
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:pelican,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict(),
keep_fixed_joints=false,
friction_coefficient=0.5,
contact_rotors=true,
contact_body=true,
T=Float64)
mechanism = get_quadrotor(;
timestep,
input_scaling,
gravity,
urdf,
springs,
dampers,
parse_springs,
parse_dampers,
joint_limits,
keep_fixed_joints,
friction_coefficient,
contact_rotors,
contact_body,
T
)
storage = Storage(horizon, length(mechanism.bodies))
return QuadrotorWaypoint{T,horizon}(mechanism, storage, zeros(4))
end
function DojoEnvironments.state_map(::QuadrotorWaypoint, state)
state = [state;zeros(8)]
return state
end
function DojoEnvironments.input_map(environment::QuadrotorWaypoint, input::AbstractVector)
# Input is rotor rpm directly
# Rotors are only visualized, dynamics are mapped here
environment.rpms = input
body = get_body(environment.mechanism, :base_link)
q = body.state.q2
force_torque = rpm_to_force_torque(environment, input, q)
input = [force_torque;zeros(4)]
return input
end
function Dojo.step!(environment::QuadrotorWaypoint, state, input=nothing; k=1, record=false, opts=SolverOptions())
state = state_map(environment, state)
input = input_map(environment, input)
Dojo.step_minimal_coordinates!(environment.mechanism, state, input; opts)
record && Dojo.save_to_storage!(environment.mechanism, environment.storage, k)
return
end
function Dojo.simulate!(environment::QuadrotorWaypoint{T,N}, controller! = (environment, k) -> nothing; kwargs...) where {T,N}
mechanism = environment.mechanism
joint_rotor_0 = get_joint(mechanism, :rotor_0_joint)
joint_rotor_1 = get_joint(mechanism, :rotor_1_joint)
joint_rotor_2 = get_joint(mechanism, :rotor_2_joint)
joint_rotor_3 = get_joint(mechanism, :rotor_3_joint)
function controller_wrapper!(mechanism, k)
rpms = environment.rpms
set_minimal_velocities!(mechanism, joint_rotor_0, [rpms[1]])
set_minimal_velocities!(mechanism, joint_rotor_1, [-rpms[2]])
set_minimal_velocities!(mechanism, joint_rotor_2, [rpms[3]])
set_minimal_velocities!(mechanism, joint_rotor_3, [-rpms[4]])
controller!(environment, k)
end
simulate!(environment.mechanism, 1:N, environment.storage, controller_wrapper!; kwargs...)
end
function DojoEnvironments.get_state(environment::QuadrotorWaypoint)
state = get_minimal_state(environment.mechanism)[1:12]
return state
end
function Dojo.visualize(environment::QuadrotorWaypoint;
waypoints=[
[1;1;0.3],
[2;0;0.3],
[1;-1;0.3],
[0;0;0.3],
],
return_animation=false,
kwargs...)
vis, animation = visualize(environment.mechanism, environment.storage; return_animation=true, kwargs...)
for (i,waypoint) in enumerate(waypoints)
waypoint_shape = Sphere(0.2;color=RGBA(0,0.25*i,0,0.3))
visshape = Dojo.convert_shape(waypoint_shape)
subvisshape = vis["waypoints"]["waypoint$i"]
Dojo.setobject!(subvisshape, visshape, waypoint_shape)
Dojo.atframe(animation, 1) do
Dojo.set_node!(waypoint, one(Quaternion), waypoint_shape, subvisshape, true)
end
end
Dojo.setanimation!(vis,animation)
return_animation ? (return vis, animation) : (return vis)
end
# ## physics functions
function rpm_to_force_torque(::QuadrotorWaypoint, rpm::Real, rotor_sign::Int64)
force_factor = 0.001
torque_factor = 0.0001
force = sign(rpm)*force_factor*rpm^2
torque = sign(rpm)*rotor_sign*torque_factor*rpm^2
return [force;0;0], [torque;0;0]
end
function rpm_to_force_torque(environment::QuadrotorWaypoint, rpms::AbstractVector, q::Quaternion)
qympi2 = Dojo.RotY(-pi/2)
orientations = [qympi2;qympi2;qympi2;qympi2]
directions = [1;-1;1;-1]
force_vertices = [
[0.21; 0; 0.05],
[0; 0.21; 0.05],
[-0.21; 0; 0.05],
[0; -0.21; 0.05],
]
forces_torques = [rpm_to_force_torque(environment, rpms[i], directions[i]) for i=1:4]
forces = getindex.(forces_torques,1)
torques = getindex.(forces_torques,2)
forces = Dojo.vector_rotate.(forces, orientations) # in local frame
torques = Dojo.vector_rotate.(torques, orientations) # in local frame
torques_from_forces = Dojo.cross.(force_vertices, forces)
force = Dojo.vector_rotate(sum(forces), q) # in minimal frame
torque = Dojo.vector_rotate(sum(torques .+ torques_from_forces), q) # in minimal frame
return [force; torque]
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1957 | mutable struct QuadrupedSampling{T,N} <: Environment{T,N}
mechanism::Mechanism{T}
storage::Storage{T,N}
end
function quadruped_sampling(;
horizon=100,
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:gazebo_a1,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
spring_offset=true,
joint_limits=Dict(vcat([[
(Symbol(group,:_hip_joint), [-0.5,0.5]),
(Symbol(group,:_thigh_joint), [-0.5,1.5]),
(Symbol(group,:_calf_joint), [-2.5,-1])]
for group in [:FR, :FL, :RR, :RL]]...)),
keep_fixed_joints=false,
friction_coefficient=0.8,
contact_feet=true,
contact_body=true,
T=Float64)
mechanism = get_quadruped(;
timestep,
input_scaling,
gravity,
urdf,
springs,
dampers,
parse_springs,
parse_dampers,
spring_offset,
joint_limits,
keep_fixed_joints,
friction_coefficient,
contact_feet,
contact_body,
T
)
storage = Storage(horizon, length(mechanism.bodies))
return QuadrupedSampling{T,horizon}(mechanism, storage)
end
function DojoEnvironments.state_map(::QuadrupedSampling, state)
return state
end
function DojoEnvironments.input_map(::QuadrupedSampling, input::AbstractVector)
input = [zeros(6);input] # trunk not actuated
return input
end
function Dojo.step!(environment::QuadrupedSampling, state, input=nothing; k=1, record=false, opts=SolverOptions())
state = state_map(environment, state)
input = input_map(environment, input)
Dojo.step_minimal_coordinates!(environment.mechanism, state, input; opts)
record && Dojo.save_to_storage!(environment.mechanism, environment.storage, k)
return
end
function DojoEnvironments.get_state(environment::QuadrupedSampling)
state = get_minimal_state(environment.mechanism)
# x: floating base, FR (hip, thigh, calf), FL, RR, RL
return state
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2814 | mutable struct QuadrupedWaypoint{T,N} <: Environment{T,N}
mechanism::Mechanism{T}
storage::Storage{T,N}
end
function quadruped_waypoint(;
horizon=100,
timestep=0.001,
input_scaling=timestep,
gravity=-9.81,
urdf=:gazebo_a1,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
spring_offset=true,
joint_limits=Dict(vcat([[
(Symbol(group,:_hip_joint), [-0.5,0.5]),
(Symbol(group,:_thigh_joint), [-0.5,1.5]),
(Symbol(group,:_calf_joint), [-2.5,-1])]
for group in [:FR, :FL, :RR, :RL]]...)),
keep_fixed_joints=false,
friction_coefficient=0.8,
contact_feet=true,
contact_body=false,
T=Float64)
mechanism = get_quadruped(;
timestep,
input_scaling,
gravity,
urdf,
springs,
dampers,
parse_springs,
parse_dampers,
spring_offset,
joint_limits,
keep_fixed_joints,
friction_coefficient,
contact_feet,
contact_body,
T
)
storage = Storage(horizon, length(mechanism.bodies))
return QuadrupedWaypoint{T,horizon}(mechanism, storage)
end
function DojoEnvironments.state_map(::QuadrupedWaypoint, state)
return state
end
function DojoEnvironments.input_map(::QuadrupedWaypoint, input::AbstractVector)
input = [zeros(6);input] # trunk not actuated
return input
end
function Dojo.step!(environment::QuadrupedWaypoint, state, input=nothing; k=1, record=false, opts=SolverOptions())
state = state_map(environment, state)
input = input_map(environment, input)
Dojo.step_minimal_coordinates!(environment.mechanism, state, input; opts)
record && Dojo.save_to_storage!(environment.mechanism, environment.storage, k)
return
end
function DojoEnvironments.get_state(environment::QuadrupedWaypoint)
state = get_minimal_state(environment.mechanism)
# x: floating base, FR (hip, thigh, calf), FL, RR, RL
return state
end
function Dojo.visualize(environment::QuadrupedWaypoint;
waypoints=[
[0.5;0.5;0.3],
[1;0;0.3],
[0.5;-0.5;0.3],
[0;0;0.3],
],
return_animation=false,
kwargs...)
vis, animation = visualize(environment.mechanism, environment.storage; return_animation=true, kwargs...)
for (i,waypoint) in enumerate(waypoints)
waypoint_shape = Sphere(0.2;color=RGBA(0,0.25*i,0,0.3))
visshape = Dojo.convert_shape(waypoint_shape)
subvisshape = vis["waypoints"]["waypoint$i"]
Dojo.setobject!(subvisshape, visshape, waypoint_shape)
Dojo.atframe(animation, 1) do
Dojo.set_node!(waypoint, one(Quaternion), waypoint_shape, subvisshape, true)
end
end
Dojo.setanimation!(vis,animation)
return_animation ? (return vis, animation) : (return vis)
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 5589 | mutable struct UUVWaypoint{T,N} <: Environment{T,N}
mechanism::Mechanism{T}
storage::Storage{T,N}
rpms::AbstractVector
end
function uuv_waypoint(;
horizon=100,
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:mini_tortuga,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict(),
keep_fixed_joints=false,
friction_coefficient=0.5,
contact_body=true,
T=Float64)
mechanism = get_uuv(;
timestep,
input_scaling,
gravity,
urdf,
springs,
dampers,
parse_springs,
parse_dampers,
joint_limits,
keep_fixed_joints,
friction_coefficient,
contact_body,
T
)
storage = Storage(horizon, length(mechanism.bodies))
return UUVWaypoint{T,horizon}(mechanism, storage, zeros(6))
end
function DojoEnvironments.state_map(::UUVWaypoint, state)
state = [state;zeros(12)]
return state
end
function DojoEnvironments.input_map(environment::UUVWaypoint, input::AbstractVector)
# Input is rotor rpm directly
# Rotors are only visualized, dynamics are mapped here
environment.rpms = input
body = get_body(environment.mechanism, :base_link)
q = body.state.q2
force_torque = rpm_to_force_torque(environment, input, q)
input = [force_torque;zeros(6)]
return input
end
function Dojo.step!(environment::UUVWaypoint, state, input=nothing; k=1, record=false, opts=SolverOptions())
state = state_map(environment, state)
input = input_map(environment, input)
Dojo.step_minimal_coordinates!(environment.mechanism, state, input; opts)
record && Dojo.save_to_storage!(environment.mechanism, environment.storage, k)
return
end
function Dojo.simulate!(environment::UUVWaypoint{T,N}, controller! = (environment, k) -> nothing; kwargs...) where {T,N}
mechanism = environment.mechanism
rotor_1_joint = get_joint(mechanism, :rotor_1_joint)
rotor_2_joint = get_joint(mechanism, :rotor_2_joint)
rotor_3_joint = get_joint(mechanism, :rotor_3_joint)
rotor_4_joint = get_joint(mechanism, :rotor_4_joint)
rotor_5_joint = get_joint(mechanism, :rotor_5_joint)
rotor_6_joint = get_joint(mechanism, :rotor_6_joint)
function controller_wrapper!(mechanism, k)
rpms = environment.rpms
set_minimal_velocities!(mechanism, rotor_1_joint, [rpms[1]])
set_minimal_velocities!(mechanism, rotor_2_joint, [rpms[2]])
set_minimal_velocities!(mechanism, rotor_3_joint, [-rpms[3]])
set_minimal_velocities!(mechanism, rotor_4_joint, [-rpms[4]])
set_minimal_velocities!(mechanism, rotor_5_joint, [rpms[5]])
set_minimal_velocities!(mechanism, rotor_6_joint, [-rpms[6]])
buoyancy!(environment, mechanism)
controller!(environment, k)
end
simulate!(environment.mechanism, 1:N, environment.storage, controller_wrapper!; kwargs...)
end
function DojoEnvironments.get_state(environment::UUVWaypoint)
state = get_minimal_state(environment.mechanism)[1:12]
return state
end
function Dojo.visualize(environment::UUVWaypoint;
waypoints=[
[1;1;0.3],
[2;0;0.3],
[1;-1;0.3],
[0;0;0.3],
],
return_animation=false,
kwargs...)
vis, animation = visualize(environment.mechanism, environment.storage; return_animation=true, kwargs...)
for (i,waypoint) in enumerate(waypoints)
waypoint_shape = Sphere(0.2;color=RGBA(0,0.25*i,0,0.3))
visshape = Dojo.convert_shape(waypoint_shape)
subvisshape = vis["waypoints"]["waypoint$i"]
Dojo.setobject!(subvisshape, visshape, waypoint_shape)
Dojo.atframe(animation, 1) do
Dojo.set_node!(waypoint, one(Quaternion), waypoint_shape, subvisshape, true)
end
end
Dojo.setanimation!(vis,animation)
return_animation ? (return vis, animation) : (return vis)
end
# ## physics functions
function rpm_to_force_torque(::UUVWaypoint, rpm::Real, rotor_sign::Int64)
force_factor = 0.01
torque_factor = 0.001
force = sign(rpm)*force_factor*rpm^2
torque = sign(rpm)*rotor_sign*torque_factor*rpm^2
return [force;0;0], [torque;0;0]
end
function rpm_to_force_torque(environment::UUVWaypoint, rpms::AbstractVector, q::Quaternion)
qzpi4 = Dojo.RotZ(pi/4)
qzmpi4 = Dojo.RotZ(-pi/4)
qympi2 = Dojo.RotY(-pi/2)
orientations = [qzpi4;qzmpi4;qzmpi4;qzpi4;qympi2;qympi2]
directions = [1;1;-1;-1;1;-1]
force_vertices = [
[0.14; -0.09; 0.059],
[0.14; 0.09; 0.059],
[-0.14; -0.09; 0.059],
[-0.14; 0.09; 0.059],
[0; -0.0855; 0.165],
[0; 0.0855; 0.165],
]
forces_torques = [rpm_to_force_torque(environment, rpms[i], directions[i]) for i=1:6]
forces = getindex.(forces_torques,1)
torques = getindex.(forces_torques,2)
forces = Dojo.vector_rotate.(forces, orientations) # in local frame
torques = Dojo.vector_rotate.(torques, orientations) # in local frame
torques_from_forces = Dojo.cross.(force_vertices, forces)
force = Dojo.vector_rotate(sum(forces), q) # in minimal frame
torque = Dojo.vector_rotate(sum(torques .+ torques_from_forces), q) # in minimal frame
return [force; torque]
end
function buoyancy!(::UUVWaypoint, mechanism)
body = get_body(mechanism, :base_link)
q = body.state.q2
force = Dojo.vector_rotate([0;0;19.5*9.81], inv(q)) # slightly positive
torque = Dojo.cross([0;0;0.2], force)
add_external_force!(body; force, torque)
return
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 5082 | mutable struct YoubotWaypoint{T,N} <: Environment{T,N}
mechanism::Mechanism{T}
storage::Storage{T,N}
end
function youbot_waypoint(;
horizon=100,
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:youbot,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict([
(:arm_joint_1, [-2.95,2.95]),
(:arm_joint_2, [-1.57,1.13]),
(:arm_joint_3, [-2.55,2.55]),
(:arm_joint_4, [-1.78,1.78]),
(:arm_joint_5, [-2.92,2.92]),
# (:gripper_finger_joint_l, [0,0.03]),
# (:gripper_finger_joint_r, [-0.03,0]),
]),
keep_fixed_joints=false,
T=Float64)
mechanism = get_youbot(;
timestep,
input_scaling,
gravity,
urdf,
springs,
dampers,
parse_springs,
parse_dampers,
joint_limits,
keep_fixed_joints,
T
)
storage = Storage(horizon, length(mechanism.bodies))
return YoubotWaypoint{T,horizon}(mechanism, storage)
end
function DojoEnvironments.state_map(::YoubotWaypoint, state)
xy = state[1:2] # minimal coordinates are rotated for youbot
vxy = state[4:5] # minimal coordinates are rotated for youbot
xy_minimal = Dojo.vector_rotate([xy;0],Dojo.RotZ(-pi/2))[1:2]
vxy_minimal = Dojo.vector_rotate([vxy;0],Dojo.RotZ(-pi/2))[1:2]
state[1:2] = xy_minimal
state[4:5] = vxy_minimal
state = [state[1:6]; zeros(8); state[7:end]]
return state
end
function DojoEnvironments.input_map(environment::YoubotWaypoint, input::AbstractVector)
# Wheels are only for visualization and not actuated
# so the wheel input must be mapped to the base
l = 0.456
w = 0.316
H = [
1 -1 -l-w
1 1 l+w
1 1 -l-w
1 -1 l+w
]
θz = get_state(environment)[3]
wheel_input = input[1:4] # fl, fr, bl, br
base_input = H\wheel_input/10 # incorrect but roughly ok mapping
xy = base_input[1:2]
xy_minimal = Dojo.vector_rotate([xy;0],Dojo.RotZ(θz-pi/2))[1:2]
base_input[1:2] = xy_minimal
wheel_input = zeros(4)
arm_input = input[5:end] # joint1 to joint5 to fingerl to fingerr
input = [base_input;wheel_input;arm_input]
return input
end
function Dojo.step!(environment::YoubotWaypoint, state, input=nothing; k=1, record=false, opts=SolverOptions())
state = state_map(environment, state)
input = input_map(environment, input)
Dojo.step_minimal_coordinates!(environment.mechanism, state, input; opts)
record && Dojo.save_to_storage!(environment.mechanism, environment.storage, k)
return
end
function Dojo.simulate!(environment::YoubotWaypoint{T,N}, controller! = (environment, k) -> nothing; kwargs...) where {T,N}
mechanism = environment.mechanism
joint_fl = get_joint(mechanism, :wheel_joint_fl)
joint_fr = get_joint(mechanism, :wheel_joint_fr)
joint_bl = get_joint(mechanism, :wheel_joint_bl)
joint_br = get_joint(mechanism, :wheel_joint_br)
function controller_wrapper!(mechanism, k)
l = 0.456; w = 0.316; r = 0.0475
H = [
1 -1 -l-w
1 1 l+w
1 1 -l-w
1 -1 l+w
]
v = get_state(environment)[4:6]
wheel_speeds = H*v/r
set_minimal_velocities!(mechanism, joint_fl, [wheel_speeds[1]])
set_minimal_velocities!(mechanism, joint_fr, [wheel_speeds[2]])
set_minimal_velocities!(mechanism, joint_bl, [wheel_speeds[3]])
set_minimal_velocities!(mechanism, joint_br, [wheel_speeds[4]])
controller!(environment, k)
end
simulate!(environment.mechanism, 1:N, environment.storage, controller_wrapper!; kwargs...)
end
function DojoEnvironments.get_state(environment::YoubotWaypoint)
state = get_minimal_state(environment.mechanism)
xy_minimal = state[1:2] # minimal coordinates are rotated for youbot
vxy_minimal = state[4:5] # minimal coordinates are rotated for youbot
xy = Dojo.vector_rotate([xy_minimal;0],Dojo.RotZ(pi/2))[1:2]
vxy = Dojo.vector_rotate([vxy_minimal;0],Dojo.RotZ(pi/2))[1:2]
state[1:2] = xy
state[4:5] = vxy
state = [state[1:6]; state[15:end]]
return state
end
function Dojo.visualize(environment::YoubotWaypoint;
waypoints=[
[1;1;0.3],
[2;0;0.3],
[1;-1;0.3],
[0;0;0.3],
],
return_animation=false,
kwargs...)
vis, animation = visualize(environment.mechanism, environment.storage; return_animation=true, kwargs...)
for (i,waypoint) in enumerate(waypoints)
waypoint_shape = Sphere(0.2;color=RGBA(0,0.25*i,0,0.3))
visshape = Dojo.convert_shape(waypoint_shape)
subvisshape = vis["waypoints"]["waypoint$i"]
Dojo.setobject!(subvisshape, visshape, waypoint_shape)
Dojo.atframe(animation, 1) do
Dojo.set_node!(waypoint, one(Quaternion), waypoint_shape, subvisshape, true)
end
end
Dojo.setanimation!(vis,animation)
return_animation ? (return vis, animation) : (return vis)
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 838 | include("ant/mechanism.jl")
include("atlas/mechanism.jl")
include("block/mechanism.jl")
include("block2d/mechanism.jl")
include("cartpole/mechanism.jl")
include("dzhanibekov/mechanism.jl")
include("exoskeleton/mechanism.jl")
include("fourbar/mechanism.jl")
include("halfcheetah/mechanism.jl")
include("hopper/mechanism.jl")
include("humanoid/mechanism.jl")
include("npendulum/mechanism.jl")
include("nslider/mechanism.jl")
include("panda/mechanism.jl")
include("pendulum/mechanism.jl")
include("quadrotor/mechanism.jl")
include("quadruped/mechanism.jl")
include("raiberthopper/mechanism.jl")
include("slider/mechanism.jl")
include("snake/mechanism.jl")
include("sphere/mechanism.jl")
include("tippetop/mechanism.jl")
include("twister/mechanism.jl")
include("uuv/mechanism.jl")
include("walker/mechanism.jl")
include("youbot/mechanism.jl") | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 3912 | function get_ant(;
timestep=0.05,
input_scaling=timestep,
gravity=-9.81,
urdf=:ant,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict([
(:hip_1, [-30,30] * π / 180),
(:ankle_1, [30,70] * π / 180),
(:hip_2, [-30,30] * π / 180),
(:ankle_2, [-70,-30] * π / 180),
(:hip_3, [-30,30] * π / 180),
(:ankle_3, [-70,-30] * π / 180),
(:hip_4, [-30,30] * π / 180),
(:ankle_4, [30,70] * π / 180)]),
keep_fixed_joints=true,
friction_coefficient=0.5,
contact_feet=true,
contact_body=true,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(string(urdf)).urdf")
mechanism = Mechanism(path; floating=true, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact_feet
# feet contacts
body_names = [:front_left_foot, :front_right_foot, :left_back_foot, :right_back_foot]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[0.2; 0.2; 0],
[-0.2; 0.2; 0],
[-0.2; -0.2; 0],
[0.2; -0.2; 0]
]
contact_radii = [body.shape.shapes[1].rh[1] for body in contact_bodies]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii)]
end
if contact_body
# torso contact
torso = get_body(mechanism, :torso)
contact_radius = torso.shape.r
contacts = [contacts;contact_constraint(torso, Z_AXIS; friction_coefficient, contact_radius)]
# elbow contact
body_names = [:aux_1, :aux_2, :aux_3, :aux_4]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
-[0.1; 0.1; 0],
-[-0.1; 0.1; 0],
-[-0.1;-0.1; 0],
-[0.1; -0.1; 0]
]
contact_radii = [body.shape.shapes[1].rh[1] for body in contact_bodies]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_ant!(mechanism)
# construction finished
return mechanism
end
function initialize_ant!(mechanism::Mechanism;
body_position=0.5*Z_AXIS, body_orientation=one(Quaternion), ankle_angle=0.25)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, get_joint(mechanism, :floating_base), [body_position; Dojo.rotation_vector(body_orientation)])
for i in [1, 4]
set_minimal_coordinates!(mechanism, get_joint(mechanism, Symbol("hip_$i")), [0])
set_minimal_coordinates!(mechanism, get_joint(mechanism, Symbol("ankle_$i")), [ankle_angle * π])
end
for i in [2, 3]
set_minimal_coordinates!(mechanism, get_joint(mechanism, Symbol("hip_$i")), [0])
set_minimal_coordinates!(mechanism, get_joint(mechanism, Symbol("ankle_$i")), [-ankle_angle * π])
end
return
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 4130 | function get_atlas(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:atlas_simple,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict(),
keep_fixed_joints=false,
friction_coefficient=0.8,
contact_feet=true,
contact_body=true,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(string(urdf)).urdf")
mechanism = Mechanism(path; floating=!(urdf==:armless), T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact_feet
# feet contacts
left_names=[Symbol("l_" .* name) for name in ["RR", "FR", "RL", "RR"]]
right_names=[Symbol("r_" .* name) for name in ["RR", "FR", "RL", "RR"]]
n = length(left_names)
left_foot = get_body(mechanism, :l_foot)
right_foot = get_body(mechanism, :r_foot)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[-0.08; -0.04; 0.015],
[+0.12; -0.02; 0.015],
[-0.08; +0.04; 0.015],
[+0.12; +0.02; 0.015],
]
contact_radii = fill(0.025,n)
contacts = [
contacts
contact_constraint(left_foot, normals; friction_coefficients, contact_origins, contact_radii, names=left_names)
contact_constraint(right_foot, normals; friction_coefficients, contact_origins, contact_radii, names=right_names)
]
end
if contact_body
body_names = [:l_hand, :r_hand, :l_lleg, :r_lleg, :l_clav, :r_clav, :pelvis, :l_uarm, :r_uarm, :head, :utorso, :utorso]
names = [:l_hand, :r_hand, :l_knee, :r_knee, :l_clavis, :r_clavis, :pelvis, :l_elbow, :r_elbow, :head, :backpack_bottom, :backpack_top]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
zeros(3), # l_hand
zeros(3), # r_hand
[0.025; 0; 0.175], # l_lleg
[0.025; 0; 0.175], # r_lleg
[0; -0.05; -0.075], # l_clav
[0; -0.05; -0.075], # r_clav
[0; 0; 0.05], # pelvis
[0; -0.185; 0], # l_uarm
[0; -0.185; 0], # r_uarm
zeros(3), # head
[-0.095; 0; 0.25], # backpack_bottom
[-0.095; 0; -0.2], # backpack_top
]
contact_radii = [
0.06, # l_hand
0.06, # r_hand
0.075, # l_lleg
0.075, # r_lleg
0.11, # l_clav
0.11, # r_clav
0.19, # pelvis
0.085, # l_uarm
0.085, # r_uarm
0.175, # head
0.15, # backpack_bottom
0.15, # backpack_top
]
contacts = [
contacts
contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii, names)
]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_atlas!(mechanism)
# construction finished
return mechanism
end
function initialize_atlas!(mechanism::Mechanism;
body_position=[0, 0, 0.9385], body_orientation=one(Quaternion))
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, get_joint(mechanism, :floating_base), [body_position; Dojo.rotation_vector(body_orientation)])
return
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2907 | function get_block(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
mass=1,
edge_length=0.5,
color=RGBA(0.9, 0.9, 0.9, 1),
springs=0,
dampers=0,
joint_limits=Dict(),
keep_fixed_joints=true,
friction_coefficient=0.8,
contact=true,
contact_radius=0,
contact_type=:nonlinear,
T=Float64)
# mechanism
origin = Origin{T}()
block = Box(edge_length, edge_length, edge_length, mass; color, name=:block)
bodies = [block]
joint = JointConstraint(Floating(origin, block))
joints = [joint]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact
names = [Symbol(:contact, i) for i=1:8]
n = length(names)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[ edge_length / 2; edge_length / 2; -edge_length / 2],
[ edge_length / 2; -edge_length / 2; -edge_length / 2],
[-edge_length / 2; edge_length / 2; -edge_length / 2],
[-edge_length / 2; -edge_length / 2; -edge_length / 2],
[ edge_length / 2; edge_length / 2; edge_length / 2],
[ edge_length / 2; -edge_length / 2; edge_length / 2],
[-edge_length / 2; edge_length / 2; edge_length / 2],
[-edge_length / 2; -edge_length / 2; edge_length / 2],
]
contact_radii = fill(contact_radius,n)
contacts = [contacts;contact_constraint(block, normals; friction_coefficients, contact_origins, contact_radii, contact_type, names)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_block!(mechanism)
# construction finished
return mechanism
end
function initialize_block!(mechanism::Mechanism;
position = [0;0;1], orientation=one(Quaternion), velocity=zeros(3), angular_velocity=randn(3))
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
body = mechanism.bodies[1]
edge_length = body.shape.xyz[3]/2
if length(mechanism.contacts) > 0
model = mechanism.contacts[1].model
offset = model.collision.contact_radius
else
offset = 0.0
end
height = edge_length + offset
set_maximal_configurations!(body,
x=position + Z_AXIS*height, q=orientation)
set_maximal_velocities!(body,
v=velocity, ω=angular_velocity)
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2606 | function get_block2d(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
mass=1,
edge_length=0.5,
color=RGBA(1, 1, 0.),
springs=0,
dampers=0,
joint_limits=Dict(),
keep_fixed_joints=true,
friction_coefficient=0.8,
contact=true,
contact_radius=0,
contact_type=:nonlinear,
T=Float64)
# mechanism
origin = Origin{T}()
block = Box(edge_length, edge_length, edge_length, mass; color, name=:block)
bodies = [block]
joint = JointConstraint(PlanarAxis(origin, block, X_AXIS); name=:joint)
joints = [joint]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact
names = [Symbol(:contact, i) for i=1:4]
n = length(names)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[0, edge_length / 2, edge_length / 2],
[0, edge_length / 2, -edge_length / 2],
[0, -edge_length / 2, edge_length / 2],
[0, -edge_length / 2, -edge_length / 2],
]
contact_radii = fill(contact_radius,n)
contacts = [contacts;contact_constraint(block, normals; friction_coefficients, contact_origins, contact_radii, contact_type, names)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_block2d!(mechanism)
# construction finished
return mechanism
end
function initialize_block2d!(mechanism::Mechanism;
position = [0;1], orientation=0, velocity=zeros(2), angular_velocity=randn())
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
body = mechanism.bodies[1]
edge_length = body.shape.xyz[3]/2
if length(mechanism.contacts) > 0
model = mechanism.contacts[1].model
offset = model.collision.contact_radius
else
offset = 0.0
end
height = edge_length + offset
set_maximal_configurations!(body,
x=[0;position] + Z_AXIS*height, q=Dojo.RotX(orientation))
set_maximal_velocities!(body,
v=[0;velocity], ω=[angular_velocity;0;0])
return
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1716 | function get_cartpole(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
slider_mass=1,
pendulum_mass=1,
link_length=1,
radius=0.075,
color=RGBA(0.7, 0.7, 0.7, 1),
springs=0,
dampers=0,
joint_limits=Dict(),
keep_fixed_joints=true,
T=Float64)
# mechanism
origin = Origin{Float64}()
slider = Capsule(1.5 * radius, 1, slider_mass;
orientation_offset=Dojo.RotX(0.5 * π), color, name=:cart)
pendulum = Capsule(radius, link_length, pendulum_mass; color, name=:pole)
bodies = [slider, pendulum]
joint_origin_slider = JointConstraint(Prismatic(origin, slider, Y_AXIS); name=:cart_joint)
joint_slider_pendulum = JointConstraint(Revolute(slider, pendulum, X_AXIS;
child_vertex=-0.5*link_length*Z_AXIS); name=:pole_joint)
joints = [joint_origin_slider, joint_slider_pendulum]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# zero configuration
initialize_cartpole!(mechanism)
# construction finished
return mechanism
end
function initialize_cartpole!(mechanism::Mechanism;
position=0, orientation=pi/4)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, mechanism.joints[1], [position])
set_minimal_coordinates!(mechanism, mechanism.joints[2], [orientation])
return
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1714 | function get_dzhanibekov(;
timestep=0.01,
input_scaling=timestep,
gravity=0,
springs=0,
dampers=0,
color=RGBA(0.9,0.9,0.9,1),
joint_limits=Dict(),
keep_fixed_joints=true,
T=Float64)
# mechanism
origin = Origin{Float64}()
main_body = Capsule(0.1, 1, 1; color, name=:main)
main_body.inertia = Diagonal([3e-2, 1e-3, 1e-1])
side_body = Capsule(0.5 * 0.1, 0.35 * 1, 0.5 * 1;
orientation_offset=Dojo.RotY(0.5 * π),
color=color, name=:side)
bodies = [main_body, side_body]
joint_float = JointConstraint(Floating(origin, bodies[1]); name=:floating)
joint_fixed = JointConstraint(Fixed(bodies[1], bodies[2];
parent_vertex=szeros(3), child_vertex=[-0.25 * 1; 0; 0]), name=:fixed)
joints = [joint_float, joint_fixed]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# zero configuration
initialize_dzhanibekov!(mechanism)
# construction finished
return mechanism
end
function initialize_dzhanibekov!(mechanism::Mechanism;
linear_velocity=zeros(3), angular_velocity=[10.0; 0.01; 0.0])
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
joint = mechanism.joints[1]
set_minimal_coordinates!(mechanism, joint, [Z_AXIS; zeros(3)])
set_minimal_velocities!(mechanism, joint, [linear_velocity; angular_velocity])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1592 | function get_exoskeleton(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:model,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict([
(:sAA, [0, 90]*π/180),
(:sFE, [0, 90]*π/180),
(:sIE, [-80, 25]*π/180),
(:eFE, [-125,0]*π/180),]),
keep_fixed_joints=false,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(string(urdf)).urdf")
mechanism = Mechanism(path; floating=false, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# zero configuration
initialize_exoskeleton!(mechanism)
# construction finished
return mechanism
end
function initialize_exoskeleton!(mechanism::Mechanism;
joint_angles=[pi/2;pi/2-0.1;0;-0.1])
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, get_joint(mechanism, :sAA), [joint_angles[1]])
set_minimal_coordinates!(mechanism, get_joint(mechanism, :sFE), [joint_angles[2]])
set_minimal_coordinates!(mechanism, get_joint(mechanism, :sIE), [joint_angles[3]])
set_minimal_coordinates!(mechanism, get_joint(mechanism, :eFE), [joint_angles[4]])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1662 | function get_fourbar(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:fourbar,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict(),
keep_fixed_joints=false,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(String(urdf)).urdf")
mechanism = Mechanism(path; floating=false, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# zero configuration
initialize_fourbar!(mechanism)
# construction finished
return mechanism
end
function initialize_fourbar!(mechanism::Mechanism;
base_angle=pi/4, inner_angle=pi/4)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
loop_joint_id = get_joint(mechanism, :joint24).id
set_minimal_coordinates!(mechanism, get_joint(mechanism, :jointb1), [base_angle+inner_angle]; exclude_ids = [loop_joint_id])
set_minimal_coordinates!(mechanism, get_joint(mechanism, :jointb3), [base_angle-inner_angle]; exclude_ids = [loop_joint_id])
set_minimal_coordinates!(mechanism, get_joint(mechanism, :joint12), [-2*inner_angle]; exclude_ids = [loop_joint_id])
set_minimal_coordinates!(mechanism, get_joint(mechanism, :joint34), [2*inner_angle]; exclude_ids = [loop_joint_id])
return
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 3718 | function get_halfcheetah(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:halfcheetah,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict([
(:bthigh, [-0.52,1.05]),
(:bshin, [-0.785,0.785]),
(:bfoot, [-0.400,0.785]),
(:fthigh, [-1,0.7]),
(:fshin, [-1.20,0.87]),
(:ffoot, [-0.5,0.5])]),
keep_fixed_joints=false,
friction_coefficient=0.4,
contact_feet=true,
contact_body=true,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(String(urdf)).urdf")
mechanism = Mechanism(path; floating=false, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact_feet
body_names = [:ffoot, :bfoot]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[0;0; -0.5 * contact_bodies[1].shape.shapes[1].rh[2]],
[0;0; -0.5 * contact_bodies[2].shape.shapes[1].rh[2]],
]
contact_radii = [
contact_bodies[1].shape.shapes[1].rh[1]
contact_bodies[2].shape.shapes[1].rh[1]
]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii)]
end
if contact_body
body_names = getfield.(mechanism.bodies, :name)
body_names = deleteat!(body_names, findall(x->(x==:ffoot||x==:bfoot||x==:torso),body_names))
body_names = [:torso; :torso; :torso; body_names]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[[+0.5 * contact_bodies[1].shape.shapes[1].shapes[1].rh[2]; 0; 0]]
[[-0.5 * contact_bodies[2].shape.shapes[1].shapes[1].rh[2]; 0; 0]]
[[+0.5 * contact_bodies[3].shape.shapes[1].shapes[1].rh[2] + 0.214; 0; 0.1935]]
[[0;0; -0.5 * contact_bodies[i].shape.shapes[1].rh[2]] for i = 4:n]
]
contact_radii = [
contact_bodies[1].shape.shapes[1].shapes[1].rh[1]
contact_bodies[2].shape.shapes[1].shapes[1].rh[1]
contact_bodies[3].shape.shapes[1].shapes[1].rh[1]
[contact_bodies[i].shape.shapes[1].rh[1] for i = 4:n]
]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_halfcheetah!(mechanism)
# construction finished
return mechanism
end
function initialize_halfcheetah!(mechanism::Mechanism;
body_position=[0, 0], body_orientation=0)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, get_joint(mechanism, :floating_joint),
[body_position[1] + 0.576509, body_position[2], body_orientation + 0.02792])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 3025 | function get_hopper(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:hopper,
springs=10,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict([
(:thigh, [0,150] * π / 180),
(:leg, [0,150] * π / 180),
(:foot, [-45,45] * π / 180)]),
keep_fixed_joints=false,
friction_coefficient=2,
contact_foot=true,
contact_body=true,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(string(urdf)).urdf")
mechanism = Mechanism(path; floating=false, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact_foot
body_names = [:foot; :foot]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[0, 0, +0.5 * contact_bodies[1].shape.shapes[1].rh[2]],
[0, 0, -0.5 * contact_bodies[2].shape.shapes[1].rh[2]],
]
contact_radii = [
contact_bodies[1].shape.shapes[1].rh[1]
contact_bodies[2].shape.shapes[1].rh[1]
]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii)]
end
if contact_body
body_names = getfield.(mechanism.bodies, :name)
body_names = deleteat!(body_names, findall(x->(x==:foot),body_names))
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [[0;0; 0.5 * contact_bodies[i].shape.shapes[1].rh[2]] for i = 1:n]
contact_radii = [contact_bodies[i].shape.shapes[1].rh[1] for i = 1:n]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_hopper!(mechanism)
# construction finished
return mechanism
end
function initialize_hopper!(mechanism::Mechanism;
body_position=[0, 0], body_orientation=0)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, get_joint(mechanism, :floating_joint),
[body_position[1] + 1.25 , body_position[2], body_orientation])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2626 | function get_humanoid(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:humanoid,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict(),
keep_fixed_joints=false,
friction_coefficient=0.8,
contact_feet=true,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(string(urdf)).urdf")
mechanism = Mechanism(path; floating=true, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact_feet
# feet contacts
body_names = [:left_foot; :left_foot; :right_foot; :right_foot]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[0.5 * contact_bodies[1].shape.shapes[1].shapes[1].rh[2]; 0; 0],
[-0.5 * contact_bodies[2].shape.shapes[1].shapes[1].rh[2]; 0; 0],
[0.5 * contact_bodies[3].shape.shapes[1].shapes[1].rh[2]; 0; 0],
[-0.5 * contact_bodies[4].shape.shapes[1].shapes[1].rh[2]; 0; 0],
]
contact_radii = [
contact_bodies[1].shape.shapes[1].shapes[1].rh[1]
contact_bodies[2].shape.shapes[1].shapes[1].rh[1]
contact_bodies[3].shape.shapes[1].shapes[1].rh[1]
contact_bodies[4].shape.shapes[1].shapes[1].rh[1]
]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_humanoid!(mechanism)
# construction finished
return mechanism
end
function initialize_humanoid!(mechanism::Mechanism;
body_position=[0, 0, 1.33], body_orientation=one(Quaternion))
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, get_joint(mechanism, :floating_base),
[body_position; Dojo.rotation_vector(body_orientation)])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1659 | function get_npendulum(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
num_bodies=5,
mass=1,
link_length=1,
color=RGBA(1, 0, 0),
springs=0,
dampers=0,
joint_limits=Dict(),
keep_fixed_joints=true,
base_joint_type=:Revolute,
rest_joint_type=:Revolute,
T=Float64)
# mechanism
origin = Origin{T}()
bodies = [Box(0.05, 0.05, link_length, mass; color) for i = 1:num_bodies]
jointb1 = JointConstraint(Dojo.Prototype(base_joint_type, origin, bodies[1], X_AXIS;
parent_vertex=(link_length+0.1)*Z_AXIS*num_bodies, child_vertex=Z_AXIS*link_length/2))
joints = JointConstraint{T}[
jointb1;
[
JointConstraint(Dojo.Prototype(rest_joint_type, bodies[i - 1], bodies[i], X_AXIS;
parent_vertex=-Z_AXIS*link_length/2, child_vertex=Z_AXIS*link_length/2)) for i = 2:num_bodies
]
]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# zero configuration
initialize_npendulum!(mechanism)
# construction finished
return mechanism
end
function initialize_npendulum!(mechanism::Mechanism;
base_angle=π/4)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, mechanism.joints[1], [base_angle])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1485 | function get_nslider(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
num_bodies=5,
color=RGBA(1, 0, 0),
springs=0,
dampers=0,
joint_limits=Dict(),
keep_fixed_joints=true,
T=Float64)
# mechanism
origin = Origin{T}()
bodies = [Cylinder(0.05, 1, 1; color) for i = 1:num_bodies]
jointb1 = JointConstraint(Prismatic(origin, bodies[1], Z_AXIS))
joints = JointConstraint{T}[
jointb1;
[JointConstraint(Prismatic(bodies[i - 1], bodies[i], Z_AXIS;
parent_vertex=-Y_AXIS*0.05, child_vertex=Y_AXIS*0.05)) for i = 2:num_bodies
]
]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# zero coordinates
initialize_nslider!(mechanism)
# construction finished
return mechanism
end
function initialize_nslider!(mechanism::Mechanism;
position=mechanism.bodies[1].shape.rh[2], velocity=0)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, mechanism.joints[1], [position])
set_minimal_velocities!(mechanism, mechanism.joints[1], [velocity])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1683 | function get_panda(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:panda_end_effector,
springs=0,
dampers=5,
parse_springs=true,
parse_dampers=false,
joint_limits=Dict([
(:joint1, [-2.8973, 2.8973]),
(:joint2, [-1.7628, 1.7628]),
(:joint3, [-2.8973, 2.8973]),
(:joint4, [-3.0718,-0.0698]),
(:joint5, [-2.8973, 2.8973]),
(:joint6, [-0.0175, 3.7525]),
(:joint7, [-2.8973, 2.8973]),
(:jointf1, [-0.00, 0.04]),
(:jointf2, [-0.00, 0.04])]),
keep_fixed_joints=false,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(string(urdf)).urdf")
mechanism = Mechanism(path; floating=false, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# zero configuration
initialize_panda!(mechanism)
# construction finished
return mechanism
end
function initialize_panda!(mechanism::Mechanism;
joint_angles=[0;0.5;0;-0.5;0;0.5;0; zeros(input_dimension(mechanism)-7)],
joint_velocities=zeros(input_dimension(mechanism)))
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
nu = input_dimension(mechanism)
x = vcat([[joint_angles[i], joint_velocities[i]] for i=1:nu]...)
set_minimal_state!(mechanism, x)
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1505 | function get_pendulum(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
mass=1,
link_length=1,
color=RGBA(1, 0, 0),
springs=0,
dampers=0,
joint_limits=Dict(),
spring_offset=szeros(1),
orientation_offset=one(Quaternion),
T=Float64)
# mechanism
origin = Origin{T}()
body = Box(0.1, 0.1, link_length, mass; color, name=:pendulum)
bodies = [body]
joint = JointConstraint(Revolute(origin, body, X_AXIS;
parent_vertex=(link_length+0.1)*Z_AXIS, child_vertex=0.5*link_length*Z_AXIS,
rot_spring_offset=spring_offset, orientation_offset),
name=:joint)
joints = [joint]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# zero configuration
initialize_pendulum!(mechanism)
# construction finished
return mechanism
end
function initialize_pendulum!(mechanism::Mechanism;
angle=pi/4, angular_velocity=0)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, mechanism.joints[1], [angle])
set_minimal_velocities!(mechanism, mechanism.joints[1], [angular_velocity])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2682 | function get_quadrotor(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:pelican_fixed_rotors,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict(),
keep_fixed_joints=false,
friction_coefficient=0.5,
contact_rotors=true,
contact_body=true,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(string(urdf)).urdf")
mechanism = Mechanism(path; floating=true, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact_rotors
# rotor contacts
body_in_contact = get_body(mechanism, :base_link)
n = 4
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_radii = fill(0.07,n) # smaller than rotor size to allow for pitching close to ground
contact_origins = [
[0.21; 0; 0.045],
[-0.21; 0; 0.045],
[0; 0.21; 0.045],
[0; -0.21; 0.045]
]
contacts = [contacts;contact_constraint(body_in_contact, normals; friction_coefficients, contact_radii, contact_origins)]
end
if contact_body
# base contact
body_in_contact = get_body(mechanism, :base_link)
n = 4
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[0.11; 0; -0.085],
[-0.11; 0; -0.085],
[0; 0.11; -0.085],
[0; -0.11; -0.085]
]
contacts = [contacts;contact_constraint(body_in_contact, normals; friction_coefficients, contact_origins)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_quadrotor!(mechanism)
# construction finished
return mechanism
end
function initialize_quadrotor!(mechanism::Mechanism;
body_position=0.085*Z_AXIS, body_orientation=one(Quaternion))
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, get_joint(mechanism, :floating_base), [body_position; Dojo.rotation_vector(body_orientation)])
return
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 5322 | function get_quadruped(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:gazebo_a1,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
spring_offset=true,
joint_limits=Dict(vcat([[
(Symbol(group,:_hip_joint), [-0.5,0.5]),
(Symbol(group,:_thigh_joint), [-0.5,1.5]),
(Symbol(group,:_calf_joint), [-2.5,-1])]
for group in [:FR, :FL, :RR, :RL]]...)),
keep_fixed_joints=false,
friction_coefficient=0.8,
contact_feet=true,
contact_body=true,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(string(urdf)).urdf")
mechanism = Mechanism(path; floating=true, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
if spring_offset
θ_thigh = 0.9
θ_calf = -1.425
get_node(mechanism, :FR_hip_joint).rotational.spring_offset=0.0*sones(1)
get_node(mechanism, :FL_hip_joint).rotational.spring_offset=0.0*sones(1)
get_node(mechanism, :RR_hip_joint).rotational.spring_offset=0.0*sones(1)
get_node(mechanism, :RL_hip_joint).rotational.spring_offset=0.0*sones(1)
get_node(mechanism, :FR_thigh_joint).rotational.spring_offset=θ_thigh*sones(1)
get_node(mechanism, :FL_thigh_joint).rotational.spring_offset=θ_thigh*sones(1)
get_node(mechanism, :RR_thigh_joint).rotational.spring_offset=θ_thigh*sones(1)
get_node(mechanism, :RL_thigh_joint).rotational.spring_offset=θ_thigh*sones(1)
get_node(mechanism, :FR_calf_joint).rotational.spring_offset=θ_calf*sones(1)
get_node(mechanism, :FL_calf_joint).rotational.spring_offset=θ_calf*sones(1)
get_node(mechanism, :RR_calf_joint).rotational.spring_offset=θ_calf*sones(1)
get_node(mechanism, :RL_calf_joint).rotational.spring_offset=θ_calf*sones(1)
end
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact_feet
# feet contacts
body_names = [:FR_calf, :FL_calf, :RR_calf, :RL_calf]
names = [:FR_calf_contact, :FL_calf_contact, :RR_calf_contact, :RL_calf_contact]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = fill([-0.006; 0; -0.092],n)
contact_radii = fill(0.021,n)
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii, names)]
end
if contact_body
# thigh contacts
body_names = [:FR_thigh, :FL_thigh, :RR_thigh, :RL_thigh]
names = [:FR_thigh_contact, :FL_thigh_contact, :RR_thigh_contact, :RL_thigh_contact]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[-0.005; -0.023; -0.16],
[-0.005; 0.023; -0.16],
[-0.005; -0.023; -0.16],
[-0.005; 0.023; -0.16],
]
contact_radii = fill(0.023,n)
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii, names)]
# hip contacts
body_names = [:FR_hip, :FL_hip, :RR_hip, :RL_hip]
names = [:FR_hip_contact, :FL_hip_contact, :RR_hip_contact, :RL_hip_contact]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = fill([0; 0.05; 0],n)
contact_radii = fill(0.05,n)
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii, names)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_quadruped!(mechanism)
# construction finished
return mechanism
end
function initialize_quadruped!(mechanism::Mechanism;
body_position=[0, 0, 0], body_orientation=one(Quaternion),
hip_angle=0, thigh_angle=pi/4, calf_angle=-pi/2)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
body_position += [0, 0, 0.43]
set_minimal_coordinates!(mechanism, get_joint(mechanism, :floating_base), [body_position; Dojo.rotation_vector(body_orientation)])
for group in [:FR, :FL, :RR, :RL]
set_minimal_coordinates!(mechanism, get_joint(mechanism, Symbol(group, :_hip_joint)), [hip_angle])
set_minimal_coordinates!(mechanism, get_joint(mechanism, Symbol(group, :_thigh_joint)), [thigh_angle])
set_minimal_coordinates!(mechanism, get_joint(mechanism, Symbol(group, :_calf_joint)), [calf_angle])
end
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2333 | function get_raiberthopper(;
timestep=0.05,
input_scaling=timestep,
gravity=-9.81,
body_mass=4.18,
foot_mass=0.52,
body_radius=0.1,
foot_radius=0.05,
color=RGBA(0.9, 0.9, 0.9),
springs=[0;0],
dampers=[0;0.1],
joint_limits=Dict(),
keep_fixed_joints=true,
friction_coefficient=0.5,
contact_foot=true,
contact_body=true,
T=Float64)
# mechanism
origin = Origin{Float64}()
body = Sphere(body_radius, body_mass; color)
foot = Sphere(foot_radius, foot_mass; color)
bodies = [body, foot]
joint_origin_body = JointConstraint(Floating(origin, body))
joint_body_foot = JointConstraint(Prismatic(body, foot, Z_AXIS;
parent_vertex=szeros(Float64, 3), child_vertex=szeros(Float64, 3)))
joints = [joint_origin_body, joint_body_foot]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact_foot
# foot contact
contact_radius = foot_radius
contacts = [contacts;contact_constraint(foot, Z_AXIS; friction_coefficient, contact_radius)]
end
if contact_body
# body contact
contact_radius = body_radius
contacts = [contacts;contact_constraint(body, Z_AXIS; friction_coefficient, contact_radius)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_raiberthopper!(mechanism)
# construction finished
return mechanism
end
function initialize_raiberthopper!(mechanism::Mechanism;
body_position=zeros(3), leg_length=0.5)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
body_position += [0;0;leg_length+mechanism.bodies[2].shape.r]
set_minimal_coordinates!(mechanism, mechanism.joints[1], [body_position; 0; 0; 0])
set_minimal_coordinates!(mechanism, mechanism.joints[2], [-leg_length])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1415 | function get_slider(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
color=RGBA(1, 0, 0),
springs=0,
dampers=0,
joint_limits=Dict(),
keep_fixed_joints=true,
T=Float64)
# mechanism
origin = Origin{T}()
pbody = Box(0.1, 0.1, 1, 1; color)
bodies = [pbody]
joint_between_origin_and_pbody = JointConstraint(Prismatic(origin, pbody, Z_AXIS;
child_vertex=Z_AXIS/2))
joints = [joint_between_origin_and_pbody]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# zero coordinates
initialize_slider!(mechanism)
# construction finished
return mechanism
end
function initialize_slider!(mechanism::Mechanism;
position=0, velocity=0)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
child_vertex = mechanism.joints[1].translational.vertices[2]
set_maximal_configurations!(mechanism.origin, mechanism.bodies[1];
child_vertex=child_vertex - Z_AXIS*position)
set_minimal_velocities!(mechanism, mechanism.joints[1], [velocity])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2559 | function get_snake(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
num_bodies=2,
link_length=1,
radius=0.05,
color=RGBA(0.9, 0.9, 0.9),
springs=0,
dampers=0,
joint_limits=Dict(),
joint_type=:Spherical,
keep_fixed_joints=true,
friction_coefficient=0.8,
contact=true,
contact_type=:nonlinear,
T=Float64)
# mechanism
origin = Origin{T}()
bodies = [Box(link_length, 3 * radius, 2 * radius, link_length; color) for i = 1:num_bodies]
jointb1 = JointConstraint(Floating(origin, bodies[1]))
joints = JointConstraint{T}[
jointb1;
[
JointConstraint(Dojo.Prototype(joint_type, bodies[i - 1], bodies[i], X_AXIS;
parent_vertex=-X_AXIS*link_length/2, child_vertex=X_AXIS*link_length/2)) for i = 2:num_bodies
]
]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact
contact_bodies = [bodies;bodies] # we need to duplicate contacts for prismatic joint for instance
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
fill(X_AXIS*link_length/2, Int64(n/2))
fill(-X_AXIS*link_length/2, Int64(n/2))
]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_type)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_snake!(mechanism)
# construction finished
return mechanism
end
function initialize_snake!(mechanism::Mechanism;
base_position=zeros(3), base_orientation=one(Quaternion),
base_linear_velocity=zeros(3), base_angular_velocity=zeros(3))
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, mechanism.joints[1], [base_position; Dojo.rotation_vector(base_orientation)])
set_minimal_velocities!(mechanism, mechanism.joints[1], [base_linear_velocity; base_angular_velocity])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1891 | function get_sphere(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
mass=1,
radius=0.5,
color=RGBA(0.9, 0.9, 0.9),
springs=0,
dampers=0,
joint_limits=Dict(),
keep_fixed_joints=true,
friction_coefficient=0.8,
contact=true,
contact_type=:nonlinear,
T=Float64)
# mechanism
origin = Origin{T}(name=:origin)
sphere = Sphere(radius, mass; color, name=:sphere)
bodies = [sphere]
joints = [JointConstraint(Floating(origin, bodies[1]); name=:floating_joint)]
mechanism = Mechanism(origin, bodies, joints;
timestep, gravity, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact
contact_radius = radius
contacts = [contacts;contact_constraint(sphere, Z_AXIS; friction_coefficient, contact_radius, contact_type)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_sphere!(mechanism)
# construction finished
return mechanism
end
function initialize_sphere!(mechanism::Mechanism;
position=Z_AXIS/2, orientation=one(Quaternion),
velocity=[1;0;0], angular_velocity=zeros(3))
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
position += Z_AXIS*mechanism.bodies[1].shape.r
set_minimal_coordinates!(mechanism, mechanism.joints[1], [position; Dojo.rotation_vector(orientation)])
set_minimal_velocities!(mechanism, mechanism.joints[1], [velocity; angular_velocity])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2369 | function get_tippetop(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
mass=1,
radius=0.5,
scale=0.2,
color=RGBA(0.9, 0.9, 0.9, 1.0),
springs=0,
dampers=0,
joint_limits=Dict(),
keep_fixed_joints=true,
friction_coefficient=0.4,
contact=true,
contact_type=:nonlinear,
T=Float64)
# mechanism
origin = Origin{T}(name=:origin)
bodies = [
Sphere(radius, mass; name=:sphere1, color),
Sphere(radius*scale, mass*scale^3; name=:sphere2, color)
]
bodies[1].inertia = Diagonal([1.9, 2.1, 2])
joints = [
JointConstraint(Floating(origin, bodies[1]); name=:floating_joint),
JointConstraint(Fixed(bodies[1], bodies[2];
parent_vertex=[0,0,radius]), name = :fixed_joint)
]
mechanism = Mechanism(origin, bodies, joints;
timestep, gravity, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact
n = length(bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_radii = [radius;radius*scale]
contacts = [contacts;contact_constraint(bodies, normals; friction_coefficients, contact_radii, contact_type)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_tippetop!(mechanism)
# construction finished
return mechanism
end
function initialize_tippetop!(mechanism::Mechanism{T};
body_position=2*Z_AXIS*mechanism.bodies[1].shape.r, body_orientation=one(Quaternion),
body_linear_velocity=zeros(3), body_angular_velocity=[0.0, 0.1, 50.0]) where T
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
floating_joint = mechanism.joints[1]
set_minimal_coordinates!(mechanism, floating_joint, [body_position; Dojo.rotation_vector(body_orientation)])
set_minimal_velocities!(mechanism, floating_joint, [body_linear_velocity; body_angular_velocity])
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2488 | function get_twister(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
num_bodies=5,
height=1,
radius=0.05,
color=RGBA(1, 0, 0),
springs=0,
dampers=0,
joint_limits=Dict(),
joint_type=:Prismatic,
keep_fixed_joints=true,
friction_coefficient=0.8,
contact=true,
contact_type=:nonlinear,
T=Float64)
# mechanism
origin = Origin{T}()
bodies = [Box(height, 3 * radius, 2 * radius, height; color) for i = 1:num_bodies]
jointb1 = JointConstraint(Floating(origin, bodies[1]))
axes = [X_AXIS, Y_AXIS, Z_AXIS]
joints = JointConstraint{T}[
jointb1;
[
JointConstraint(Dojo.Prototype(joint_type, bodies[i - 1], bodies[i], axes[i%3+1];
parent_vertex=-X_AXIS*height/2, child_vertex=X_AXIS*height/2)) for i = 2:num_bodies
]
]
mechanism = Mechanism(origin, bodies, joints;
gravity, timestep, input_scaling)
# springs and dampers
set_springs!(mechanism.joints, springs)
set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact
contact_bodies = [bodies[1];bodies]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[X_AXIS*height/2]
fill(-X_AXIS*height/2,n-1)
]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_type)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_twister!(mechanism)
# construction finished
return mechanism
end
function initialize_twister!(mechanism::Mechanism;
base_position=zeros(3), base_orientation=one(Quaternion),
base_linear_velocity=zeros(3), base_angular_velocity=zeros(3))
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, mechanism.joints[1], [base_position; Dojo.rotation_vector(base_orientation)])
set_minimal_velocities!(mechanism, mechanism.joints[1], [base_linear_velocity; base_angular_velocity])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2004 | function get_uuv(;
timestep=0.01,
input_scaling=timestep,
gravity=0,
urdf=:mini_tortuga_fixed_rotors,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict(),
keep_fixed_joints=false,
friction_coefficient=0.5,
contact_body=true,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(string(urdf)).urdf")
mechanism = Mechanism(path; floating=false, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact_body
# base contact
body_in_contact = get_body(mechanism, :base_link)
n = 2
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_radii = fill(0.21,n)
contact_origins = [
[0.12; 0; 0.07],
[-0.12; 0; 0.07],
]
contacts = [contacts;contact_constraint(body_in_contact, normals; friction_coefficients, contact_radii, contact_origins)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_uuv!(mechanism)
# construction finished
return mechanism
end
function initialize_uuv!(mechanism::Mechanism;
body_position=Z_AXIS, body_orientation=one(Quaternion))
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, get_joint(mechanism, :floating_base), [body_position; Dojo.rotation_vector(body_orientation)])
return
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 3433 | function get_walker(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:walker,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict([
(:thigh, [0,150] * π / 180),
(:leg, [0,150] * π / 180),
(:foot, [-45,45] * π / 180),
(:thigh_left, [0,150] * π / 180),
(:leg_left, [0,150] * π / 180),
(:foot_left, [-45,45] * π / 180)]),
keep_fixed_joints=false,
friction_coefficient=0.5,
contact_feet=true,
contact_body=true,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(string(urdf)).urdf")
mechanism = Mechanism(path; floating=false, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# contacts
contacts = ContactConstraint{T}[]
if contact_feet
body_names = [:foot; :foot; :foot_left; :foot_left]
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [
[0, 0, +0.5 * contact_bodies[1].shape.shapes[1].rh[2]],
[0, 0, -0.5 * contact_bodies[2].shape.shapes[1].rh[2]],
[0, 0, +0.5 * contact_bodies[3].shape.shapes[1].rh[2]],
[0, 0, -0.5 * contact_bodies[4].shape.shapes[1].rh[2]],
]
contact_radii = [
contact_bodies[1].shape.shapes[1].rh[1]
contact_bodies[2].shape.shapes[1].rh[1]
contact_bodies[3].shape.shapes[1].rh[1]
contact_bodies[4].shape.shapes[1].rh[1]
]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii)]
end
if contact_body
body_names = getfield.(mechanism.bodies, :name)
body_names = deleteat!(body_names, findall(x->(x==:foot||x==:foot_left),body_names))
contact_bodies = [get_body(mechanism, name) for name in body_names]
n = length(contact_bodies)
normals = fill(Z_AXIS,n)
friction_coefficients = fill(friction_coefficient,n)
contact_origins = [[0;0; 0.5 * contact_bodies[i].shape.shapes[1].rh[2]] for i = 1:n]
contact_radii = [contact_bodies[i].shape.shapes[1].rh[1] for i = 1:n]
contacts = [contacts;contact_constraint(contact_bodies, normals; friction_coefficients, contact_origins, contact_radii)]
end
mechanism = Mechanism(mechanism.origin, mechanism.bodies, mechanism.joints, contacts;
gravity, timestep, input_scaling)
# zero configuration
initialize_walker!(mechanism)
# construction finished
return mechanism
end
function initialize_walker!(mechanism::Mechanism;
body_position=[0, 0], body_orientation=0)
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
set_minimal_coordinates!(mechanism, get_joint(mechanism, :floating_joint),
[body_position[1] + 1.25 , body_position[2], body_orientation])
return
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2456 | function get_youbot(;
timestep=0.01,
input_scaling=timestep,
gravity=-9.81,
urdf=:youbot,
springs=0,
dampers=0,
parse_springs=true,
parse_dampers=true,
joint_limits=Dict([
(:arm_joint_1, [-2.95,2.95]),
(:arm_joint_2, [-1.57,1.13]),
(:arm_joint_3, [-2.55,2.55]),
(:arm_joint_4, [-1.78,1.78]),
(:arm_joint_5, [-2.92,2.92]),
# (:gripper_finger_joint_l, [0,0.03]),
# (:gripper_finger_joint_r, [-0.03,0]),
]),
keep_fixed_joints=false,
T=Float64)
# mechanism
path = joinpath(@__DIR__, "dependencies/$(String(urdf)).urdf")
mechanism = Mechanism(path; floating=false, T,
gravity, timestep, input_scaling,
parse_dampers, keep_fixed_joints)
# springs and dampers
!parse_springs && set_springs!(mechanism.joints, springs)
!parse_dampers && set_dampers!(mechanism.joints, dampers)
# joint limits
joints = set_limits(mechanism, joint_limits)
mechanism = Mechanism(mechanism.origin, mechanism.bodies, joints;
gravity, timestep, input_scaling)
# zero configuration
initialize_youbot!(mechanism)
# construction finished
return mechanism
end
function initialize_youbot!(mechanism;
body_position=zeros(2), body_orientation=0, arm_angles=zeros(5))
zero_velocities!(mechanism)
zero_coordinates!(mechanism)
base_joint = get_joint(mechanism, :base_footprint_joint)
arm_joint_1 = get_joint(mechanism, :arm_joint_1)
arm_joint_2 = get_joint(mechanism, :arm_joint_2)
arm_joint_3 = get_joint(mechanism, :arm_joint_3)
arm_joint_4 = get_joint(mechanism, :arm_joint_4)
arm_joint_5 = get_joint(mechanism, :arm_joint_5)
base_joint !== nothing && set_minimal_coordinates!(mechanism, base_joint, [body_position;body_orientation])
arm_joint_1 !== nothing && set_minimal_coordinates!(mechanism, get_joint(mechanism, :arm_joint_1), [arm_angles[1]])
arm_joint_2 !== nothing && set_minimal_coordinates!(mechanism, get_joint(mechanism, :arm_joint_2), [arm_angles[2]])
arm_joint_3 !== nothing && set_minimal_coordinates!(mechanism, get_joint(mechanism, :arm_joint_3), [arm_angles[3]])
arm_joint_4 !== nothing && set_minimal_coordinates!(mechanism, get_joint(mechanism, :arm_joint_4), [arm_angles[4]])
arm_joint_5 !== nothing && set_minimal_coordinates!(mechanism, get_joint(mechanism, :arm_joint_5), [arm_angles[5]])
return
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 463 | environments = [
:ant_ars,
:cartpole_dqn,
:pendulum,
:quadruped_waypoint,
:quadruped_sampling,
:quadrotor_waypoint,
:uuv_waypoint,
:youbot_waypoint,
]
for name in environments
env = get_environment(name; horizon=2)
x = get_state(env)
u = DojoEnvironments.input_map(env, nothing)
set_input!(env, nothing)
step!(env, x)
step!(env, x, u)
simulate!(env; record=true)
visualize(env)
@test true
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 535 | mechanisms = [
:ant,
:atlas,
:block,
:block2d,
:cartpole,
:dzhanibekov,
:exoskeleton,
:fourbar,
:halfcheetah,
:hopper,
:humanoid,
:npendulum,
:nslider,
:panda,
:pendulum,
:quadrotor,
:quadruped,
:raiberthopper,
:slider,
:snake,
:sphere,
:tippetop,
:twister,
:uuv,
:walker,
:youbot,
]
for name in mechanisms
mech = get_mechanism(name)
initialize!(mech, name)
simulate!(mech, 0.5; record=true)
@test true
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 234 | using Test
using DojoEnvironments
using Dojo
@testset "DojoEnvironments" begin
@testset "mechanisms" begin
include("mechanisms.jl")
end
@testset "environments" begin
include("environments.jl")
end
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 132 | using Pkg
Pkg.develop(path="./DojoEnvironments")
using BenchmarkTools
SUITE = BenchmarkGroup()
include("mechanisms_benchmark.jl") | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 605 | using Dojo
using DojoEnvironments
mechanisms = [
:ant,
:atlas,
:block,
:block2d,
:exoskeleton,
:cartpole,
:dzhanibekov,
:fourbar,
:halfcheetah,
:hopper,
:humanoid,
:npendulum,
:nslider,
:panda,
:pendulum,
:quadrotor,
:quadruped,
:raiberthopper,
:slider,
:snake,
:sphere,
:tippetop,
:twister,
:uuv,
:walker,
:youbot,
]
for name in mechanisms
mech = get_mechanism(name)
SUITE[string(name)] = @benchmarkable simulate!($mech, 1, opts=SolverOptions(rtol=1.0e-6, btol=1.0e-6)) samples=2
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 392 | append!(empty!(LOAD_PATH), Base.DEFAULT_LOAD_PATH)
using Pkg
################################################################################
# Generate notebooks
################################################################################
exampledir = joinpath(@__DIR__, "..", "examples")
Pkg.activate(exampledir)
Pkg.instantiate()
include(joinpath(exampledir, "generate_notebooks.jl")) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2090 | push!(LOAD_PATH, "../src/")
using Documenter, Dojo
makedocs(
modules = [Dojo],
format = Documenter.HTML(prettyurls=false),
sitename = "Dojo",
pages = [
##############################################
## MAKE SURE TO SYNC WITH docs/src/index.md ##
##############################################
"index.md",
"Examples" => [
"examples/simulation.md",
"examples/reinforcement_learning.md",
"examples/system_identification.md",
"examples/trajectory_optimization.md",
],
"Creating a Mechanism" => [
"creating_mechanism/overview.md",
"creating_mechanism/mechanism_directly.md",
"creating_mechanism/mechanism_existing.md",
"creating_mechanism/environment_existing.md",
"creating_mechanism/tippetop.md",
"creating_mechanism/quadruped.md",
],
"Creating a Simulation" => [
"creating_simulation/define_simulation.md",
"creating_simulation/define_controller.md",
"creating_simulation/simulation_with_gradients.md",
],
"Environments" => [
"environments/overview.md",
],
"Background: Contact Models" => [
"background_contact/contact_models.md",
"background_contact/impact.md",
"background_contact/nonlinear_friction.md",
"background_contact/linearized_friction.md",
"background_contact/collisions.md",
],
"Background: Representations" => [
"background_representations/maximal_representation.md",
"background_representations/minimal_representation.md",
"background_representations/gradients.md",
],
"Background: Solver" => [
"background_solver/interior_point.md",
"background_solver/solver_options.md",
],
"api.md",
"contributing.md",
"citing.md"
]
)
deploydocs(
repo = "github.com/dojo-sim/Dojo.jl.git",
)
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 846 | using Literate
function preprocess(str)
str = replace(str, "# PKG_SETUP_2" =>
"""
using Pkg
Pkg.activate(joinpath(@__DIR__, "../.."))
Pkg.instantiate()
""")
str = replace(str, "# PKG_SETUP" =>
"""
using Pkg
Pkg.activate(joinpath(@__DIR__, ".."))
Pkg.instantiate()
""")
return str
end
exampledir = @__DIR__
for subdir in ["control", "learning", "simulation", "simulation/mechanics", "system_identification"]
root = joinpath(exampledir, subdir)
isdir(root) || continue
@show subdir
for file in readdir(root)
name, ext = splitext(file)
name == "utilities" && continue
lowercase(ext) == ".jl" || continue
absfile = joinpath(root, file)
@show absfile
Literate.notebook(absfile, root, execute=false, preprocess=preprocess)
end
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1105 | # ### Setup
# PKG_SETUP
using Dojo
using DojoEnvironments
using ControlSystemsBase
using LinearAlgebra
# ### Mechanism
mechanism = get_mechanism(:cartpole)
# ### Controller
x0 = zeros(4)
u0 = zeros(2)
A, B = get_minimal_gradients!(mechanism, x0, u0)
Q = I(4)
R = I(1)
K = lqr(Discrete,A,B[:,1],Q,R)
function controller!(mechanism, k)
## Target state
x_goal = [0;0; 0.0;0]
## Current state
x = get_minimal_state(mechanism)
## Control inputs
u = -K * (x - x_goal)
## 3 ways to set input:
## 1: get joint and set input
cart_joint = get_joint(mechanism, :cart_joint)
set_input!(cart_joint, u)
## 2: set input for all joints at once
## set_input!(mechanism, [u;0]) # need to know joint order
## 3: direct external force on body
## cart = get_body(mechanism, :cart)
## set_external_force!(cart; force=[0;u;0])
end
# ### Simulate
initialize!(mechanism, :cartpole; position=0, orientation=pi/4)
storage = simulate!(mechanism, 10.0, controller!, record=true)
# ### Visualize
vis = visualize(mechanism, storage)
render(vis)
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 759 | # ### Setup
# PKG_SETUP
using Dojo
using DojoEnvironments
# ### Mechanism
mechanism = get_mechanism(:pendulum)
# ### Controller
summed_error = 0 # for integral part
function controller!(mechanism, k)
## Target state
x_goal = [π/2; 0.0]
## Current state
x = get_minimal_state(mechanism)
error = (x_goal-x)
global summed_error += error[1]*mechanism.timestep
## Gains
Kp = 25
Ki = 50
Kd = 5
## Control inputs
u = Kp*error[1] + Ki*summed_error + Kd*error[2]
set_input!(mechanism, [u])
end
# ### Simulate
initialize!(mechanism, :pendulum,
angle=0.0, angular_velocity=0.0)
storage = simulate!(mechanism, 5.0, controller!, record=true)
# ### Visualize
vis = visualize(mechanism, storage)
render(vis)
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 839 | # ### Setup
# PKG_SETUP
using Dojo
using DojoEnvironments
using LinearAlgebra
# ### Environment
quadrotor_env = get_environment(:quadrotor_waypoint; horizon=200)
# ### Controllers
trans_z_mode = normalize([1;1;1;1])
function velocity_controller!(environment, v_des)
v_is = get_state(environment)[9]
error_z = v_des - v_is
thrust = (10*error_z - 1*v_is + 5.1)*trans_z_mode # P, D, feedforward
rpm = thrust*20
set_input!(environment, rpm)
end
function position_controller!(environment, z_des)
z_is = get_state(environment)[3]
v_des = z_des - z_is
velocity_controller!(environment, v_des)
end
function controller!(environment, k)
position_controller!(environment, 0.3)
end
# ### Simulate
simulate!(quadrotor_env, controller!; record=true)
# ### Visualize
vis = visualize(quadrotor_env)
render(vis)
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 6011 | # ### Setup
# PKG_SETUP
using Dojo
using DojoEnvironments
using Random
using LinearAlgebra
using Statistics
import LinearAlgebra.normalize
# ### Parameters and structs
rng = MersenneTwister(1)
Base.@kwdef struct HyperParameters{T}
main_loop_size::Int = 100
horizon::Int = 200
step_size::T = 0.05
n_directions::Int = 16
b::Int = 16
noise::T = 0.1
end
mutable struct Policy{T}
hp::HyperParameters{T}
θ::Matrix{T}
function Policy(input_size::Int, output_size::Int, hp::HyperParameters{T}; scale=0.2) where T
new{T}(hp, scale * randn(output_size, input_size))
end
end
mutable struct Normalizer{T}
n::Vector{T}
mean::Vector{T}
mean_diff::Vector{T}
var::Vector{T}
function Normalizer(num_inputs::Int)
n = zeros(num_inputs)
mean = zeros(num_inputs)
mean_diff = zeros(num_inputs)
var = zeros(num_inputs)
new{eltype(n)}(n, mean, mean_diff, var)
end
end
# ### Oberservation functions
function normalize(normalizer, inputs)
obs_std = sqrt.(normalizer.var)
return (inputs .- normalizer.mean) ./ obs_std
end
function observe!(normalizer, inputs)
normalizer.n .+= 1
last_mean = deepcopy(normalizer.mean)
normalizer.mean .+= (inputs .- normalizer.mean) ./ normalizer.n
normalizer.mean_diff .+= (inputs .- last_mean) .* (inputs .- normalizer.mean)
normalizer.var .= max.(1e-2, normalizer.mean_diff ./ normalizer.n)
end
# ### Environment
env = get_environment(:ant_ars;
horizon=100,
gravity=-9.81,
timestep=0.05,
dampers=50.0,
springs=25.0,
friction_coefficient=0.5,
contact_feet=true,
contact_body=true);
# ### Reset and rollout functions
function reset_state!(env)
initialize!(env, :ant)
return
end
function rollout_policy(θ::Matrix, env, normalizer::Normalizer, parameters::HyperParameters; record=false)
reset_state!(env)
rewards = 0.0
for k=1:parameters.horizon
## get state
state = DojoEnvironments.get_state(env)
x = state[1:28] # minimal state without contacts
observe!(normalizer, state)
state = normalize(normalizer, state)
action = θ * state
## single step
step!(env, x, action; record, k)
## get reward
state_after = DojoEnvironments.get_state(env)
x_pos_before = x[1]
x_pos_after = state_after[1]
forward_reward = 100 * (x_pos_after - x_pos_before) / env.mechanism.timestep
control_cost = (0.05/10 * action' * action)[1]
contact_cost = 0.0
for contact in env.mechanism.contacts
contact_cost += 0.5 * 1.0e-3 * max(-1, min(1, contact.impulses[2][1]))^2.0
end
survive_reward = 0.05
reward = forward_reward - control_cost - contact_cost + survive_reward
rewards += reward
## check for failure
if !(all(isfinite.(state_after)) && (state_after[3] >= 0.2) && (state_after[3] <= 1))
println(" failed")
break
end
end
return rewards
end
# ### Training functions
function sample_policy(policy::Policy{T}) where T
δ = [randn(size(policy.θ)) for i = 1:policy.hp.n_directions]
θp = [policy.θ + policy.hp.noise .* δ[i] for i = 1:policy.hp.n_directions]
θn = [policy.θ - policy.hp.noise .* δ[i] for i = 1:policy.hp.n_directions]
return [θp..., θn...], δ
end
function update!(policy::Policy, rollouts, σ_r)
stp = zeros(size(policy.θ))
for (r_pos, r_neg, d) in rollouts
stp += (r_pos - r_neg) * d
end
policy.θ += policy.hp.step_size * stp ./ (σ_r * policy.hp.b)
return
end
function train(env, policy::Policy{T}, normalizer::Normalizer{T}, hp::HyperParameters{T}) where T
println("Training linear policy with Augmented Random Search (ARS)\n ")
## pre-allocate for rewards
rewards = zeros(2 * hp.n_directions)
for episode = 1:hp.main_loop_size
## initialize deltas and rewards
θs, δs = sample_policy(policy)
## evaluate policies
roll_time = @elapsed begin
for k = 1:(2 * hp.n_directions)
rewards[k] = rollout_policy(θs[k], env, normalizer, hp)
end
end
## reward evaluation
r_max = [max(rewards[k], rewards[hp.n_directions + k]) for k = 1:hp.n_directions]
σ_r = std(rewards)
order = sortperm(r_max, rev = true)[1:hp.b]
rollouts = [(rewards[k], rewards[hp.n_directions + k], δs[k]) for k = order]
## policy update
update!(policy, rollouts, σ_r)
## finish, print:
println("episode $episode reward_evaluation $(mean(rewards)). Took $(roll_time) seconds")
end
return nothing
end
# ### Training
train_times = Float64[]
rewards = Float64[]
policies = Matrix{Float64}[]
N = 2
for i = 1:N
## Random policy
hp = HyperParameters(
main_loop_size=20,
horizon=100,
n_directions=6,
b=6,
step_size=0.05)
input_size = 37
output_size = 8
normalizer = Normalizer(input_size)
policy = Policy(input_size, output_size, hp)
## Train policy
train_time = @elapsed train(env, policy, normalizer, hp)
## Evaluate policy
reward = rollout_policy(policy.θ, env, normalizer, hp)
## Cache
push!(train_times, train_time)
push!(rewards, reward)
push!(policies, policy.θ)
end
# ### Training results
max_idx = sortperm(rewards, lt=Base.isgreater)
train_time_best = (train_times[max_idx])[1]
rewards_best = (rewards[max_idx])[1]
policies_best = (policies[max_idx])[1];
# ### Controller with best policy
θ = policies_best
input_size = 37
normalizer = Normalizer(input_size)
function controller!(environment, k)
state = get_state(env)
observe!(normalizer, state)
state = normalize(normalizer, state)
action = θ * state
set_input!(environment, action)
end
# ### Visualize policy
reset_state!(env)
simulate!(env, controller!; record=true)
vis = visualize(env)
render(vis) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 6957 | # Running from within Dojo repo does not work somehow; create temp environment
# Copied from https://github.com/JuliaReinforcementLearning/ReinforcementLearning.jl/blob/main/src/ReinforcementLearningEnvironments/src/environments/examples/CartPoleEnv.jl
# ### Setup
# PKG_SETUP
using ReinforcementLearning # v0.10.2
using Random
using ClosedIntervals
using StableRNGs: StableRNG
using Flux
using Flux: params, ignore
using Flux.Losses: huber_loss
using Dojo
using DojoEnvironments
# ### BEGIN Redefinition because of breaking changes in ReinforcementLearning.jl repo
function RLBase.update!(learner::BasicDQNLearner, batch::NamedTuple{SARTS})
Q = learner.approximator
γ = learner.γ
loss_func = learner.loss_func
s, a, r, t, s′ = send_to_device(device(Q), batch)
a = CartesianIndex.(a, 1:length(a))
gs = gradient(params(Q)) do
q = Q(s)[a]
q′ = vec(maximum(Q(s′); dims = 1))
G = @. r + γ * (1 - t) * q′
loss = loss_func(G, q)
ignore() do
learner.loss = loss
end
loss
end
update!(Q, gs)
end
RLBase.update!(app::NeuralNetworkApproximator, gs) =
Flux.Optimise.update!(app.optimizer, params(app), gs)
# ### END Redefinition because of breaking changes in ReinforcementLearning.jl repo
struct CartPoleEnvParams{T}
gravity::T
masscart::T
masspole::T
totalmass::T
halflength::T
polemasslength::T
forcemag::T
dt::T
thetathreshold::T
xthreshold::T
max_steps::Int
end
Base.show(io::IO, params::CartPoleEnvParams) = print(
io,
join(["$p=$(getfield(params, p))" for p in fieldnames(CartPoleEnvParams)], ","),
)
function CartPoleEnvParams{T}(;
gravity=9.8,
masscart=1.0,
masspole=0.1,
halflength=0.5,
forcemag=10.0,
max_steps=200,
dt=0.02,
thetathreshold=12.0,
xthreshold=2.4
) where {T}
CartPoleEnvParams{T}(
gravity,
masscart,
masspole,
masscart + masspole,
halflength,
masspole * halflength,
forcemag,
dt,
thetathreshold * π / 180,
xthreshold,
max_steps,
)
end
mutable struct CartPoleEnv{T,ACT} <: AbstractEnv
dojo_env::DojoEnvironments.CartpoleDQN # Dojo Environment
record::Bool # Select if trajectory should be recorded in Dojo Storage
params::CartPoleEnvParams{T}
state::Vector{T}
action::ACT
done::Bool
t::Int
rng::AbstractRNG
end
function CartPoleEnv(; T=Float64, record=false, continuous=false, rng=Random.GLOBAL_RNG, kwargs...)
params = CartPoleEnvParams{T}(; kwargs...)
## create Dojo Environment
dojo_env = get_environment(:cartpole_dqn;
horizon=params.max_steps+1,
timestep = params.dt,
gravity = -params.gravity,
slider_mass = params.masscart,
pendulum_mass = params.masspole,
link_length = params.halflength*2
)
env = CartPoleEnv(dojo_env, record, params, zeros(T, 4), continuous ? zero(T) : zero(Int), false, 0, rng)
reset!(env)
env
end
CartPoleEnv{T}(; kwargs...) where {T} = CartPoleEnv(T=T, kwargs...)
Random.seed!(env::CartPoleEnv, seed) = Random.seed!(env.rng, seed)
RLBase.reward(env::CartPoleEnv{T}) where {T} = env.done ? zero(T) : one(T)
RLBase.is_terminated(env::CartPoleEnv) = env.done
RLBase.state(env::CartPoleEnv) = env.state
function RLBase.state_space(env::CartPoleEnv{T}) where {T}
((-2 * env.params.xthreshold) .. (2 * env.params.xthreshold)) ×
(typemin(T) .. typemax(T)) ×
((-2 * env.params.thetathreshold) .. (2 * env.params.thetathreshold)) ×
(typemin(T) .. typemax(T))
end
RLBase.action_space(env::CartPoleEnv{<:AbstractFloat,Int}, player) = Base.OneTo(2)
RLBase.action_space(env::CartPoleEnv{<:AbstractFloat,<:AbstractFloat}, player) = -1.0 .. 1.0
function RLBase.reset!(env::CartPoleEnv{T}) where {T}
env.state[:] = T(0.1) * rand(env.rng, T, 4) .- T(0.05)
env.t = 0
env.action = rand(env.rng, action_space(env))
env.done = false
nothing
end
function (env::CartPoleEnv)(a::AbstractFloat)
@assert a in action_space(env)
env.action = a
_step!(env, a)
end
function (env::CartPoleEnv)(a::Int)
@assert a in action_space(env)
env.action = a
_step!(env, a == 2 ? 1 : -1)
end
function _step!(env::CartPoleEnv, a)
env.t += 1
force = a * env.params.forcemag
#=
Remove ReinforcementLearningEnvironments dynamics
x, xdot, theta, thetadot = env.state
costheta = cos(theta)
sintheta = sin(theta)
tmp = (force + env.params.polemasslength * thetadot^2 * sintheta) / env.params.totalmass
thetaacc =
(env.params.gravity * sintheta - costheta * tmp) / (
env.params.halflength *
(4 / 3 - env.params.masspole * costheta^2 / env.params.totalmass)
)
xacc = tmp - env.params.polemasslength * thetaacc * costheta / env.params.totalmass
env.state[1] += env.params.dt * xdot
env.state[2] += env.params.dt * xacc
env.state[3] += env.params.dt * thetadot
env.state[4] += env.params.dt * thetaacc
=#
## Use Dojo dynamics
DojoEnvironments.step!(env.dojo_env, env.state, force; k=env.t, env.record)
env.state = DojoEnvironments.get_state(env.dojo_env)
env.done =
abs(env.state[1]) > env.params.xthreshold ||
abs(env.state[3]) > env.params.thetathreshold ||
env.t > env.params.max_steps
nothing
end
# Copied from https://juliareinforcementlearning.org/docs/experiments/experiments/DQN/JuliaRL_BasicDQN_CartPole/#JuliaRL\\_BasicDQN\\_CartPole
env = CartPoleEnv(; record=true, rng = MersenneTwister(123))
seed = 123
rng = StableRNG(seed)
ns, na = length(state(env)), length(action_space(env))
policy = Agent(
policy = QBasedPolicy(
learner = BasicDQNLearner(
approximator = NeuralNetworkApproximator(
model = Chain(
Dense(ns, 128, relu; init = glorot_uniform(rng)),
Dense(128, 128, relu; init = glorot_uniform(rng)),
Dense(128, na; init = glorot_uniform(rng)),
) |> gpu,
optimizer = ADAM(),
),
batch_size = 32,
min_replay_history = 100,
loss_func = huber_loss,
rng = rng,
),
explorer = EpsilonGreedyExplorer(
kind = :exp,
ϵ_stable = 0.01,
decay_steps = 500,
rng = rng,
),
),
trajectory = CircularArraySARTTrajectory(
capacity = 1000,
state = Vector{Float32} => (ns,),
),
);
# ## Train policy
run(
policy,
CartPoleEnv(),
StopAfterEpisode(1000),
TotalRewardPerEpisode()
)
# ## Rollout policy once and record (record=true in env)
run(
policy,
env,
StopAfterEpisode(1),
TotalRewardPerEpisode()
)
# ### Visualize trained cartpole
vis = visualize(env.dojo_env)
render(vis) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 4045 | # ### Setup
# PKG_SETUP
using Dojo
using DojoEnvironments
using Random
using LinearAlgebra
# ### Parameters
rng = MersenneTwister(1)
N = 2000
M = 20
paramcontainer = [[0.1; 0; 1; 0; -1.5]] # result: [[0.3604389380437305, 0.15854285262309512, 0.9575825661369068, -0.325769852046206, -1.4824537456751052]]
paramstorage = [[0.1; 0; 1; 0; -1.5]]
bias = zeros(5)
distance = 0.0
explore_factor = 0.1
distancestorage = zeros(M);
# ### Environment
env = get_environment(:quadruped_sampling; horizon=N, timestep=0.001, joint_limits=Dict(), gravity=-9.81, contact_body=false)
# ### Controller
legmovement(k,a,b,c,offset) = a*cos(k*b*0.01*2*pi+offset)+c
Kp = [100;80;60]
Kd = [5;4;3]
function controller!(x, k)
angle21 = legmovement(k,paramcontainer[1][2],paramcontainer[1][1],paramcontainer[1][3],0)
angle22 = legmovement(k,paramcontainer[1][2],paramcontainer[1][1],paramcontainer[1][3],pi)
angle31 = legmovement(k,paramcontainer[1][4],paramcontainer[1][1],paramcontainer[1][5],-pi/2)
angle32 = legmovement(k,paramcontainer[1][4],paramcontainer[1][1],paramcontainer[1][5],pi/2)
u = zeros(12)
for i=1:4
θ1 = x[12+(i-1)*6+1]
dθ1 = x[12+(i-1)*6+2]
θ2 = x[12+(i-1)*6+3]
dθ2 = x[12+(i-1)*6+4]
θ3 = x[12+(i-1)*6+5]
dθ3 = x[12+(i-1)*6+6]
if i == 1 || i == 4
u[(i-1)*3+1] = Kp[1]*(0-θ1) + Kd[1]*(0-dθ1)
u[(i-1)*3+2] = Kp[2]*(angle21-θ2) + Kd[2]*(0-dθ2)
u[(i-1)*3+3] = Kp[3]*(angle31-θ3) + Kd[3]*(0-dθ3)
else
u[(i-1)*3+1] = Kp[1]*(0-θ1) + Kd[1]*(0-dθ1)
u[(i-1)*3+2] = Kp[2]*(angle22-θ2) + Kd[2]*(0-dθ2)
u[(i-1)*3+3] = Kp[3]*(angle32-θ3) + Kd[3]*(0-dθ3)
end
end
return u
end
# ### Reset and rollout functions
function reset_state!(env)
initialize!(env, :quadruped; body_position=[0;0;-0.43], hip_angle=0, thigh_angle=paramcontainer[1][3], calf_angle=paramcontainer[1][5])
calf_state = get_body(env.mechanism, :FR_calf).state
position = get_sdf(get_contact(env.mechanism, :FR_calf_contact), Dojo.current_position(calf_state), Dojo.current_orientation(calf_state))
initialize!(env, :quadruped; body_position=[0;0;-position-0.43], hip_angle=0, thigh_angle=paramcontainer[1][3], calf_angle=paramcontainer[1][5])
end
function rollout(env; record=false)
for k=1:N
x = get_state(env)
if x[3] < 0 || !all(isfinite.(x)) || abs(x[1]) > 1000 # upsidedown || failed || "exploding"
println(" failed")
return 1
end
u = controller!(x, k)
step!(env, x, u; k, record)
end
return 0
end
# ### Learning routine
for i=1:M
println("run: $i")
if bias == zeros(5)
paramcontainer[1] += randn!(rng, zeros(5))*explore_factor
else
paramcontainer[1] += randn!(rng, zeros(5))*0.002 + normalize(bias)*0.01
end
reset_state!(env)
x0 = DojoEnvironments.get_state(env)[1]
res = 0
try
res = rollout(env)
catch
res = 1
end
if res == 1
println(" errored")
end
new_state = DojoEnvironments.get_state(env)
distancenew = new_state[1] - x0
if res == 1 || distancenew <= distance
println(" unsuccessful")
!all(isfinite.(new_state)) && println(" nans")
paramcontainer[1] = paramstorage[end]
bias = zeros(5)
explore_factor *= 0.9
else
println(" successful")
distance = distancenew
push!(paramstorage,paramcontainer[1])
bias = paramstorage[end]-paramstorage[end-1]
explore_factor = 0.1
end
println(" distance: $distancenew")
distancestorage[i] = distance
end
# ### Controller for best parameter set
paramcontainer[1] = paramstorage[end]
function environment_controller!(environment, k)
x = get_state(environment)
u = controller!(x, k)
set_input!(environment, u)
end
# ### Visualize learned behavior
reset_state!(env)
simulate!(env, environment_controller!; record=true)
vis = visualize(env)
render(vis) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 886 | # ### Setup
# PKG_SETUP
using Dojo
using DojoEnvironments
# ### List of all convenience mechanisms
mechanisms = [
:ant,
:atlas,
:block,
:block2d,
:cartpole,
:dzhanibekov,
:exoskeleton,
:fourbar,
:halfcheetah,
:hopper,
:humanoid,
:npendulum,
:nslider,
:panda,
:pendulum,
:quadrotor,
:quadruped,
:raiberthopper,
:slider,
:snake,
:sphere,
:tippetop,
:twister,
:uuv,
:walker,
:youbot,
]
# ### Select mechanism
name = :ant
# ### Get mechanism (check DojoEnvironments/src/mechanisms files for kwargs)
mech = get_mechanism(name)
# ### Initialize mechanism (check DojoEnvironments/src/mechanisms files for kwargs)
initialize!(mech, name)
# ### Simulate mechanism
storage = simulate!(mech, 5, record=true)
# ### Visualize mechanism
vis = visualize(mech, storage)
render(vis)
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 669 | # ### Setup
# PKG_SETUP
using Dojo
# ### Parameters
radius = 0.1
link_length = 1
mass = 1
rotation_axis = [1;0;0]
connection = [0;0;link_length/2]
# ### Mechanism components
origin = Origin()
body = Cylinder(radius, link_length, mass)
joint = JointConstraint(Revolute(origin, body, rotation_axis; child_vertex=connection))
# ### Construct Mechanism
mechanism = Mechanism(origin, [body], [joint])
# ### Set state
set_minimal_coordinates!(mechanism, joint, [pi/4])
set_minimal_velocities!(mechanism, joint, [0.2])
# ### Simulate
storage = simulate!(mechanism, 5.0, record=true)
# ### Visualize
vis = visualize(mechanism, storage; visualize_floor=false)
render(vis) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 480 | # ### Setup
# PKG_SETUP
using Dojo
using DojoEnvironments
# ### Get environment (check DojoEnvironment/environments files for kwargs)
environment = get_environment(:pendulum; timestep=0.01, horizon=200)
# ### Initialize mechanism (check DojoEnvironment/mechanisms files for kwargs)
initialize!(environment.mechanism, :pendulum; angle=-0.3)
# ### Simulate environment
simulate!(environment, record=true)
# ### Visualize environment
vis = visualize(environment)
render(vis) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 479 | # ### Setup
# PKG_SETUP
using Dojo
using DojoEnvironments
# ### Get mechanism (check DojoEnvironment/mechanisms files for kwargs)
mechanism = get_mechanism(:pendulum; timestep=0.02, link_length=0.75)
# ### Initialize mechanism (check DojoEnvironment/mechanisms files for kwargs)
initialize!(mechanism, :pendulum; angle=-0.3)
# ### Simulate mechanism
storage = simulate!(mechanism, 5, record=true)
# ### Visualize mechanism
vis = visualize(mechanism, storage)
render(vis) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2241 | # ### Setup
# PKG_SETUP_2
using Dojo
using DojoEnvironments
using Plots
using LinearAlgebra
# ### Define gradient functions
function get_gradients(mechanism::Mechanism, F, mode;
rtol=1e-10, btol=1e-10,
undercut=1.0, no_progress_undercut=1.0)
(mode == :friction) && (idx = 1)
(mode == :impact) && (idx = 2)
opts = SolverOptions(;
rtol, btol, undercut, no_progress_undercut)
initialize!(mechanism, :block2d,
position=[0, 0], velocity=[0, 0],
orientation=0, angular_velocity=0)
x0 = get_minimal_state(mechanism)
u0 = zeros(3)
u0[idx] += F
_, ∇u = get_minimal_gradients!(mechanism, x0, u0; opts)
Dojo.step_minimal_coordinates!(mechanism, x0, u0; opts)
z1 = Dojo.get_next_state(mechanism)
x1 = maximal_to_minimal(mechanism, z1)
∂x∂F = ∇u[idx,idx]
Δx = x1[idx] - x0[idx]
return Δx, ∂x∂F
end
# ### Gravity = Friction = 1 for nice plots
mech = get_mechanism(:block2d;
timestep=0.1, gravity=-1.0,
friction_coefficient=1.0, contact=true)
# ### Force range
F_ref = 0.5:0.01:1.5
tolerances = [1e-4, 1e-6, 1e-8, 1e-10]
# ### Gradient plots
gradient_plot = plot(layout=(2,2), size=(800,600), legend=:topleft);
# ### Impact plots
for btol in tolerances
gradients = [get_gradients(mech, F, :impact; btol) for F = F_ref]
x = [r[1] for r in gradients]
∇x = [r[2] for r in gradients]
plot!(gradient_plot[1,1], F_ref, x, xlabel="Fz", ylabel="z", linewidth=3.0, linestyle=:dot,
label="Dojo btol ="*Dojo.scn(btol))
plot!(gradient_plot[2,1], F_ref, ∇x, xlabel="Fz", ylabel="∇z", linewidth=3.0, linestyle=:dot,
label="Dojo btol ="*Dojo.scn(btol)[2:end])
end
# ### Friction plots
for btol in tolerances
gradients = [get_gradients(mech, F, :friction; btol) for F = F_ref]
x = [r[1] for r in gradients]
∇x = [r[2] for r in gradients]
plot!(gradient_plot[1,2], F_ref, x, xlabel="Fx", ylabel="x", linewidth=3.0, linestyle=:dot,
label="Dojo btol ="*Dojo.scn(btol))
plot!(gradient_plot[2,2], F_ref, ∇x, xlabel="Fx", ylabel="∇x", linewidth=3.0, linestyle=:dot,
label="Dojo btol ="*Dojo.scn(btol)[2:end])
end
# ### Show plots
display(gradient_plot) # left: Impact, right: Friction | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2654 | # ### Setup
# PKG_SETUP_2
using Dojo
using DojoEnvironments
using Random
using LinearAlgebra
using Plots
seed=100
Random.seed!(seed)
# ### Define simulation function
function simulation_loop(timestep, tsim;
gravity=0.0, springs=0.0, dampers=0.0, ϵ=1.0e-6)
display(timestep)
mech = get_mechanism(:humanoid;
timestep, gravity, springs, dampers,
contact_feet=false)
## Initialize bodies with random velocities
for body in mech.bodies
v = LinearAlgebra.normalize(randn(3))
set_maximal_velocities!(body; v=v)
end
storage = simulate!(mech, tsim;
record=true, opts=SolverOptions(btol=ϵ))
return mech, storage
end
# ### Simulation
timesteps = [0.05, 0.01, 0.005]
tsim = 10.0
storages = []
for timestep in timesteps
mech, storage = simulation_loop(timestep, tsim)
## visualize(mech, storage, visualize_floor=false)
push!(storages, storage)
end
# ## Plots
color = [:magenta, :orange, :cyan];
mech, _ = simulation_loop(0.01, 0.01)
conservation_plot = plot(layout=(3,1), size=(800,500), legend=:topleft);
# ### Energy
energies = [Dojo.mechanical_energy(mech, storage)[2:end] for storage in storages]
energy_plot = plot(xlabel="time (s)", ylabel="energy drift");
for (i, energy) in enumerate(energies)
time = [step * timesteps[i] for step = 1:length(energy)]
plot!(conservation_plot[1,1], time, energy .- energy[1]; width=2.0, color=color[i],
xlabel="time (s)", ylabel="energy drift", label="h = $(timesteps[i])")
end
# ### Momentum
momenta = [Dojo.momentum(mech, storage)[2:end] for storage in storages];
# Linear
momenta_linear = [[Vector(momentum_i)[1:3] for momentum_i in momentum] for momentum in momenta]
for (i, momentum) in enumerate(momenta_linear)
time = [step * timesteps[i] for step = 1:length(momentum)]
plot!(conservation_plot[2,1], time, hcat([momentum_i - momentum[1] for momentum_i in momentum]...)'; width=2.0, color=color[i],
xlabel="time (s)", ylabel="linear mom. drift", label=["h = $(timesteps[i])" "" ""])
end
# Angular
momenta_angular = [[Vector(momentum_i)[4:6] for momentum_i in momentum] for momentum in momenta]
momentum_angular_plot = plot(ylims=(-1.0e-10, 1.0e-10), xlabel="time (s)", ylabel="angular momentum drift");
for (i, momentum) in enumerate(momenta_angular)
time = [j * timesteps[i] for j in 1:length(momentum)]
plot!(conservation_plot[3,1], time, hcat([momentum_i - momentum[1] for momentum_i in momentum]...)'; width=2.0, color=color[i],
xlabel="time (s)", ylabel="angular mom. drift", label=["h = $(timesteps[i])" "" ""])
end
# ### Show plots
display(conservation_plot) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1163 | # ### Setup
# PKG_SETUP_2
using Dojo
using DojoEnvironments
# ### Parameters
friction_coefficient = 0.25
x0 = [-1.5, -0.50, 0.25]
q0 = one(Quaternion)
v0 = [4, 0.80, 0.0]
ω0 = zeros(3)
# ### Create blocks for comparison
mech_linear = get_mechanism(:block; friction_coefficient, contact_type=:linear, color=orange);
mech_nonlinear = get_mechanism(:block; friction_coefficient, contact_type=:nonlinear, color=cyan);
# ### Simulate block with linear friction
initialize!(mech_linear, :block; position=x0, velocity=v0, orientation=q0, angular_velocity=ω0)
storage_linear = simulate!(mech_linear, 4.0; record=true)
# ### Simulate block with nonlinear friction
initialize!(mech_nonlinear, :block; position=x0, velocity=v0, orientation=q0, angular_velocity=ω0)
storage_nonlinear = simulate!(mech_nonlinear, 4.0; record=true)
# ### Visualize
vis = Visualizer()
set_camera!(vis, cam_pos=[-0.01, 0.0, 100.0], zoom=30)
set_light!(vis, ambient=0.65, direction="Positive")
vis, animation = visualize(mech_linear, storage_linear; vis, name=:linear, return_animation=true);
vis = visualize(mech_nonlinear, storage_nonlinear; vis, name=:nonlinear, animation)
render(vis)
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 443 | # ### Setup
# PKG_SETUP_2
using Dojo
using DojoEnvironments
using Plots
# ### Simulate block
mech = get_mechanism(:block)
storage = simulate!(mech, 5, record=true)
vis = visualize(mech, storage)
render(vis)
# ### Contact interpenetration
distances = get_sdf(mech, storage) # distance from floor to each contact
minimum(minimum(distances)) # minimum distance of any corner to the ground
# ### Exemplary plot of one corner
plot(distances[1]) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1853 | using Dojo
using DojoEnvironments: Z_AXIS
using LinearAlgebra
# Parameters
origin = Origin{Float64}()
pbody = Box(1.0, 1.0, 1.0, 1.0)
cbody = Dojo.Sphere(0.5, 1.0)
joint1 = JointConstraint(Floating(origin, pbody))
joint2 = JointConstraint(Floating(origin, cbody))
bodies = [pbody, cbody]
joints = [joint1, joint2]
side = 1.0
contact_origins = [
[[ side / 2.0; side / 2.0; -side / 2.0]]
[[ side / 2.0; -side / 2.0; -side / 2.0]]
[[-side / 2.0; side / 2.0; -side / 2.0]]
[[-side / 2.0; -side / 2.0; -side / 2.0]]
[[ side / 2.0; side / 2.0; side / 2.0]]
[[ side / 2.0; -side / 2.0; side / 2.0]]
[[-side / 2.0; side / 2.0; side / 2.0]]
[[-side / 2.0; -side / 2.0; side / 2.0]]
]
normals = fill(Z_AXIS,8)
friction_coefficients = fill(0.5,8)
box_contacts = contact_constraint(pbody, normals;
friction_coefficients, contact_origins, contact_type=:nonlinear)
sphere_contact = contact_constraint(cbody, Z_AXIS;
friction_coefficient=0.5, contact_radius=0.5)
collision = SphereBoxCollision{Float64,2,3,6}(
szeros(3), 1.0, 1.0, 2 * 1.0, 0.5
)
friction_parameterization = [
1.0 0.0
0.0 1.0
]
body_body_contact = NonlinearContact{Float64,8}(0.5, friction_parameterization, collision)
contacts = [
box_contacts...,
sphere_contact,
ContactConstraint((body_body_contact, cbody.id, pbody.id), name=:body_body)
]
mech = Mechanism(origin, bodies, joints, contacts;
gravity=-9.81, timestep=0.01)
mech.bodies[1].state.x2 = [0.0, 0.0, 1.5]
q = LinearAlgebra.normalize(rand(4))
mech.bodies[1].state.q2 = Quaternion(q...)
mech.bodies[2].state.x2 = [0.3, 0.25, 3.0]
storage = simulate!(mech, 5.0; record=true,
opts=SolverOptions(rtol=1.0e-5, btol=1.0e-5))
visualize(mech, storage)
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1625 | using Dojo
using DojoEnvironments: Z_AXIS, Y_AXIS
using LinearAlgebra
# Parameters
origin = Origin{Float64}()
pbody = Capsule(0.5, 2.0, 1.0, orientation_offset=Quaternion(sqrt(2.0) / 2.0, sqrt(2.0) / 2.0, 0.0, 0.0))
cbody = Dojo.Sphere(0.5, 1.0)
joint1 = JointConstraint(Floating(origin, pbody))
joint2 = JointConstraint(Floating(pbody, cbody))
bodies = [pbody, cbody]
joints = [joint1]
capsule_contact1 = contact_constraint(pbody, Z_AXIS,
friction_coefficient=1.0,
contact_origin=Y_AXIS,
contact_radius=0.5)
capsule_contact2 = contact_constraint(pbody, Z_AXIS,
friction_coefficient=1.0,
contact_origin=-Y_AXIS,
contact_radius=0.5)
sphere_contact = contact_constraint(cbody, Z_AXIS,
friction_coefficient=1.0,
contact_radius=0.5)
collision = SphereCapsuleCollision{Float64,2,3,6}(
szeros(3), Y_AXIS, -Y_AXIS, 0.5, 0.5,
)
friction_parameterization = [
1.0 0.0
0.0 1.0
]
body_body_contact = NonlinearContact{Float64,8}(0.5, friction_parameterization, collision)
contacts = [
capsule_contact1;
capsule_contact2;
sphere_contact;
ContactConstraint((body_body_contact, cbody.id, pbody.id), name=:body_body)
]
mech = Mechanism(origin, bodies, joints, contacts;
gravity=-9.81, timestep=0.05)
mech.bodies[1].state.x2 = [0.25, 0.25, 1.5]
q = LinearAlgebra.normalize(rand(4))
mech.bodies[1].state.q2 = Quaternion(q...)
mech.bodies[2].state.x2 = [0.0, 0.5, 4.0]
storage = simulate!(mech, 2.5, record=true;
opts=SolverOptions(rtol=1.0e-5, btol=1.0e-5))
visualize(mech, storage) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 986 | using Dojo
using DojoEnvironments: Z_AXIS
using LinearAlgebra
# Parameters
origin = Origin{Float64}()
pbody = Dojo.Sphere(0.5, 1.0)
cbody = Dojo.Sphere(0.5, 1.0)
joint = JointConstraint(Fixed(origin, pbody))
bodies = [pbody, cbody]
joints = [joint]
sphere_contact = contact_constraint(cbody, Z_AXIS,
friction_coefficient=1.0, contact_radius=0.5)
collision = SphereSphereCollision{Float64,2,3,6}(
szeros(3), szeros(3), pbody.shape.r, cbody.shape.r)
friction_parameterization = [
1.0 0.0
0.0 1.0
]
body_body_contact = NonlinearContact{Float64,8}(0.5, friction_parameterization, collision)
contacts = [
sphere_contact;
ContactConstraint((body_body_contact, pbody.id, cbody.id), name=:body_body)
]
mech = Mechanism(origin, bodies, joints, contacts;
gravity=-9.81, timestep=0.1)
mech.bodies[1].state.x2 = [0.0, 0.0, 0.0]
mech.bodies[2].state.x2 = [randn(2)/10..., 2.0]
storage = simulate!(mech, 3.0; record=true)
visualize(mech, storage) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2550 | using Dojo
using DojoEnvironments: Z_AXIS
using LinearAlgebra
# Parameters
origin = Origin{Float64}()
box = Box(0.2, 1.0, 1.0, 1.0)
left_finger = Dojo.Sphere(0.1, 0.1; color=RGBA(1,0,0,1))
right_finger = Dojo.Sphere(0.1, 0.1; color=RGBA(1,0,0,1))
joint1 = JointConstraint(PlanarAxis(origin, box,[1;0;0]))
joint2 = JointConstraint(FixedOrientation(origin, left_finger))
joint3 = JointConstraint(FixedOrientation(origin, right_finger))
bodies = [box, left_finger, right_finger]
joints = [joint1, joint2, joint3]
side = 1.0
contact_origins = [
[[ side / 2.0; side / 2.0; -side / 2.0]]
[[ side / 2.0; -side / 2.0; -side / 2.0]]
[[-side / 2.0; side / 2.0; -side / 2.0]]
[[-side / 2.0; -side / 2.0; -side / 2.0]]
[[ side / 2.0; side / 2.0; side / 2.0]]
[[ side / 2.0; -side / 2.0; side / 2.0]]
[[-side / 2.0; side / 2.0; side / 2.0]]
[[-side / 2.0; -side / 2.0; side / 2.0]]
]
normals = fill(Z_AXIS,8)
friction_coefficients = fill(0.5,8)
collision = SphereBoxCollision{Float64,2,3,6}(
szeros(3), 1.0, 1.0, 2 * 1.0, 0.1
)
friction_parameterization = [
1.0 0.0
0.0 1.0
]
body_body_contact = NonlinearContact{Float64,8}(1.5, friction_parameterization, collision)
contacts = [
ContactConstraint((body_body_contact, left_finger.id, box.id), name=:body_body1)
ContactConstraint((body_body_contact, right_finger.id, box.id), name=:body_body2)
]
mech = Mechanism(origin, bodies, joints, contacts;
gravity=-9.81, timestep=0.01)
function velocity_controller!(mechanism,v_des)
vy, vz = box.state.v15[2:3]
ω = box.state.ω15[1]
Δvy = v_des[1] - vy
Δvz = v_des[2] - vz
Δω = v_des[3] - ω
left_y = 1.2 +Δω +0.5Δvy
left_z = 1.2+0.1 +0.5Δvz
right_y = -1.2 -Δω +0.5Δvy
right_z = 0+0.1 +0.5Δvz
set_input!(joint2, [0;left_y;left_z]*9.81)
set_input!(joint3, [0;right_y;right_z]*9.81)
end
function position_controller!(mechanism,x_des)
y, z = box.state.x2[2:3]
θ = box.state.q2.v1*2 # small angle approximation
v_des = x_des - [y;z;θ]
velocity_controller!(mechanism, v_des)
end
function controller!(mechanism,k)
position_controller!(mechanism,[0.2*(1-cos(k/50));0.75+0.2*sin(k/50);0])
end
mech.bodies[1].state.x2 = [0.0, 0.0, 0.75]
mech.bodies[2].state.x2 = [0.0, -0.601, 0.5]
mech.bodies[3].state.x2 = [0.0, 0.601,1.0]
storage = simulate!(mech, 5.0, controller!; record=true)
visualize(mech, storage)
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 3932 | # ### Setup
# PKG_SETUP
using Dojo
using DojoEnvironments
using Plots
using JLD2
using ForwardDiff
using LinearAlgebra
# ### Include methods
include("utilities.jl")
# ### Parameters
# Toss data from https://github.com/DAIRLab/contact-nets, distances scaled by factor 20.
# We multiplied all the distance by distance_scaling for better data scaling.
# We must rescale the gravity term accordingly since gravity contains length (g == kg.m.s^-2).
distance_scaling = 20.0
opts = SolverOptions(btol=3e-4, rtol=3e-4, undercut=3.0)
model = :block
N = 100
mech_kwargs = Dict(
:timestep => 1/148, :gravity => -9.81 * distance_scaling,
:friction_coefficient => 0.16, :edge_length => 0.1 * distance_scaling)
# ### Load dataset
dataset = jldopen(joinpath(@__DIR__, "data", "datasets", "real_block.jld2"))
storages = dataset["storages"]
JLD2.close(dataset)
function parameter_stack(θ)
## [friction_coefficient; contact_radius; contact_origin]
return [
θ[1]; 0; +θ[2:4];
θ[1]; 0; +θ[5:7];
θ[1]; 0; +θ[8:10];
θ[1]; 0; +θ[11:13];
θ[1]; 0; +θ[14:16];
θ[1]; 0; +θ[17:19];
θ[1]; 0; +θ[20:22];
θ[1]; 0; +θ[23:25];
]
end
data_mask = ForwardDiff.jacobian(x -> parameter_stack(x), zeros(25));
# ### Optimization Objective: Evaluation & Gradient
timesteps = 50:52
function f0(d; storages=storages, timesteps=timesteps)
mechanism = get_mechanism(model; mech_kwargs...)
f = 0.0
for i = 1:100
fi = loss(mechanism, parameter_stack(d), storages[i], timesteps;
opts, derivatives=false)
f += fi
end
return f
end
function fgH0(d; storages=storages, timesteps=timesteps)
mechanism = get_mechanism(model; mech_kwargs...)
f = 0.0
nd = sum(Dojo.data_dim.(mechanism.contacts))
g = zeros(nd)
H = zeros(nd,nd)
for i = 1:100
fi, gi, Hi = loss(mechanism, parameter_stack(d), storages[i], timesteps;
opts, derivatives=true)
f += fi
g += gi
H += Hi
end
return f, data_mask' * g, data_mask' * H * data_mask
end
# ### Initial guess
guess = [0.40,
+2.00, +2.00, -2.00,
+2.00, -2.00, -2.00,
-2.00, +2.00, -2.00,
-2.00, -2.00, -2.00,
+2.00, +2.00, +2.00,
+2.00, -2.00, +2.00,
-2.00, +2.00, +2.00,
-2.00, -2.00, +2.00,
]
guess_error = f0(guess)
# ### Solve
lower_bound = [0.00,
+0.05, +0.05, -2.00,
+0.05, -2.00, -2.00,
-2.00, +0.05, -2.00,
-2.00, -2.00, -2.00,
+0.05, +0.05, +0.05,
+0.05, -2.00, +0.05,
-2.00, +0.05, +0.05,
-2.00, -2.00, +0.05,
]
upper_bound = [0.80,
+2.00, +2.00, -0.05,
+2.00, -0.05, -0.05,
-0.05, +2.00, -0.05,
-0.05, -0.05, -0.05,
+2.00, +2.00, +2.00,
+2.00, -0.05, +2.00,
-0.05, +2.00, +2.00,
-0.05, -0.05, +2.00,
]
solution = quasi_newton_solve(f0, fgH0, guess; iter=20, gtol=1e-8, ftol=1e-6,
lower_bound, upper_bound, reg=1e-9)
# ### Result
solution_parameters = solution[1]
solution_error = f0(solution_parameters)
# ### Visualize
vis = Visualizer()
storage = storages[1]
mech_kwargs = Dict(
:timestep => 1/148, :gravity => -9.81 * distance_scaling, :color => RGBA(1,0,0,0.5),
:friction_coefficient => 0.16, :edge_length => 0.1 * distance_scaling)
mech = get_mechanism(model; mech_kwargs...)
vis, animation = visualize(mech, storage; vis, return_animation=true, name=:original)
position = storage.x[1][1]-[0;0;solution_parameters[2]]
orientation = storage.q[1][1]
velocity = storage.v[1][1]
angular_velocity = storage.ω[1][1]
edge_length = 2*sum(abs.(solution_parameters[2:25]))/24 # mean edge length for visualization
mech_kwargs = Dict(
:timestep => 1/148, :gravity => -9.81 * distance_scaling, :color => RGBA(0,1,0,0.5),
:friction_coefficient => solution_parameters[1], :edge_length => edge_length)
mech = get_mechanism(model; mech_kwargs...)
set_data!(mech.contacts, parameter_stack(solution_parameters)) # set actual learned contact points
initialize!(mech, model; position, velocity, orientation, angular_velocity)
storage = simulate!(mech, length(storage)/148; record=true, opts)
visualize(mech, storage; vis, animation, name=:learned)
render(vis)
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 3311 | # ### Setup
# PKG_SETUP
using Dojo
using Plots
using DojoEnvironments
using JLD2
using LinearAlgebra
# ### Include methods
include("utilities.jl")
# ### Parameters
model = :sphere
N = 10
timesteps = 10:12 # at which trajectory will be used for learning
mech_kwargs = Dict(
:timestep => 0.02, :gravity => -9.81,
:friction_coefficient => 0.2, :radius => 0.50)
# ### Generate dataset
mech = get_mechanism(model; mech_kwargs...)
xlims = [[0,0,0], [1,1,0.2]]
vlims = [-1*ones(3), 1*ones(3)]
ωlims = [-5*ones(3), 5*ones(3)]
storages = []
for i = 1:N
position = xlims[1] + rand(3) .* (xlims[2] - xlims[1])
velocity = vlims[1] + rand(3) .* (vlims[2] - vlims[1])
angular_velocity = ωlims[1] + rand(3) .* (ωlims[2] - ωlims[1])
initialize!(mech, model; position, velocity, angular_velocity)
storage = simulate!(mech, 2; record=true)
push!(storages, storage)
## visualize(mech, storage)
end
# ### Save dataset
jldsave(joinpath(@__DIR__, "data", "datasets", "synthetic_sphere.jld2"); storages)
# ### Save and load dataset
dataset = jldopen(joinpath(@__DIR__, "data", "datasets", "synthetic_sphere.jld2"))
storages = dataset["storages"]
JLD2.close(dataset)
# ### Optimization Objective: Evaluation & Gradient
function parameter_stack(θ)
## [friction_coefficient; contact_radius; contact_origin]
return [θ; zeros(3)]
end
function f0(θ; storages=storages, timesteps=timesteps)
mechanism = get_mechanism(model; mech_kwargs...)
f = 0.0
for i in eachindex(storages)
fi = loss(mechanism, parameter_stack(θ), storages[i], timesteps; derivatives=false)
f += fi
end
return f
end
function fgH0(θ; storages=storages, timesteps=timesteps)
mechanism = get_mechanism(model; mech_kwargs...)
f = 0.0
nd = sum(Dojo.data_dim.(mechanism.contacts))
g = zeros(nd)
H = zeros(nd,nd)
for i in eachindex(storages)
fi, gi, Hi = loss(mech, parameter_stack(θ), storages[i], timesteps; derivatives=true)
f += fi
g += gi
H += Hi
end
return f, g[1:2], H[1:2,1:2] # We only care about the first two parameters
end
# ### Cost Landscape
X = 0:0.02:0.4
Y = 0.47:0.005:0.53
surface(X, Y, (X, Y) -> f0([X, Y]; storages))
# ### Initial guess
guess = [0.0, 1.0]
guess_error = f0(guess)
# ### Solve
lower_bound = [0, 0.05]
upper_bound = [0.8, 1]
solution = quasi_newton_solve(f0, fgH0, guess; iter=20, gtol=1e-8, ftol=1e-6,
lower_bound, upper_bound, reg=1e-9)
# ### Result
solution_parameters = solution[1]
solution_error = f0(solution_parameters)
# ### Visualize
vis = Visualizer()
storage = storages[1]
mech_kwargs = Dict(
:timestep => 0.02, :gravity => -9.81, :color => RGBA(1,0,0,0.5),
:friction_coefficient => 0.2, :radius => 0.50)
mech = get_mechanism(model; mech_kwargs...)
vis, animation = visualize(mech, storage; vis, return_animation=true, name=:original)
position = storage.x[1][1]-[0;0;solution_parameters[2]]
orientation = storage.q[1][1]
velocity = storage.v[1][1]
angular_velocity = storage.ω[1][1]
mech_kwargs = Dict(
:timestep => 0.02, :gravity => -9.81, :color => RGBA(0,1,0,0.5),
:friction_coefficient => solution_parameters[1], :radius => solution_parameters[2])
mech = get_mechanism(model; mech_kwargs...)
initialize!(mech, model; position, velocity, angular_velocity)
storage = simulate!(mech, 2; record=true)
visualize(mech, storage; vis, animation, name=:learned)
render(vis) | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 2806 | # Taken from Nocedal and Wright, Algorithm 6.1
function quasi_newton_solve(f, fgH, x0; ftol=-Inf, gtol=1e-4, iter=100, α0=1.0,
lower_bound=-Inf, upper_bound=Inf, reg=1e-3, reg_min=1e-9, reg_max=1e6)
x = copy(x0)
X = [copy(x0)]
ls_failure = false
for k = 1:iter
fe, ge, He = fgH(x)
He += reg * I
if ls_failure
reg = clamp(reg * 2, reg_min, reg_max)
else
reg = clamp(reg / 1.5, reg_min, reg_max)
end
((norm(ge, Inf) < gtol) || (fe < ftol)) && break
p = - He \ ge
α, ls_failure = clamped_linesearch(f, x, p, fe; α0=α0, lower_bound, upper_bound)
x = clamp.(x + α*p, lower_bound, upper_bound)
push!(X, copy(x))
println("k:", k, " f:", Dojo.scn(fe, digits=3))
end
return x, X
end
function clamped_linesearch(f, x, p, fprev; α0=1.0, iter=4,
lower_bound=-Inf, upper_bound=Inf)
α = α0
ls_failure = false
for k = 1:iter
xc = clamp.(x + α*p, lower_bound, upper_bound)
(f(xc) <= fprev) && break
α /= 3
(k == iter) && (α = 0.001 / norm(p,Inf); ls_failure = true)
end
return α, ls_failure
end
function get_contact_gradients!(mechanism::Mechanism, z::AbstractVector, θ::AbstractVector;
opts=SolverOptions())
z_next = contact_step!(mechanism, z, θ; opts)
jacobian_state, jacobian_contact = Dojo.get_contact_gradients(mechanism)
return z_next, jacobian_state, jacobian_contact
end
function contact_step!(mechanism::Mechanism, z::AbstractVector, θ::AbstractVector;
opts=SolverOptions())
set_data!(mechanism.contacts, θ)
nu = input_dimension(mechanism)
step!(mechanism, z, zeros(nu), opts=opts)
end
function loss(mechanism::Mechanism, θ::AbstractVector{T}, storage::Storage{T,N},
timesteps::UnitRange{Int}; opts=SolverOptions(), derivatives::Bool=false) where {T,N}
nz = maximal_dimension(mechanism, attjac=true)
nd = length(θ)
Q = Diagonal([ones(3); 1e-1ones(3); ones(4); 1e-1ones(3)])
cost = 0.0
gradient = zeros(nd)
hessian = zeros(nd,nd)
d_contact = zeros(nz,nd)
z_prediction = get_maximal_state(storage, timesteps[1])
for i in timesteps
z_true = get_maximal_state(storage, i+1)
if derivatives
z_prediction, ∂_state, ∂_contact = get_contact_gradients!(mechanism, z_prediction, θ; opts)
attjac = attitude_jacobian(z_prediction, 1)
d_contact = ∂_contact + ∂_state * d_contact
gradient += (attjac * d_contact)' * Q * (z_prediction - z_true)
hessian += (attjac * d_contact)' * Q * (attjac * d_contact)
else
z_prediction = contact_step!(mechanism, z_prediction, θ; opts)
end
cost += 0.5 * (z_prediction - z_true)'* Q *(z_prediction - z_true)
end
if derivatives
return cost, gradient, hessian
else
return cost
end
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 816 | using Dojo
using DojoEnvironments
using JLD2
function convert_csv_to_jld2()
timestep = 1/148
mechanism = get_mechanism(:block; timestep)
storages = []
for k = 0:569
csv_path = joinpath(@__DIR__, "tosses_csv", "$(k).csv")
toss = split.(readlines(csv_path), ",")
toss = [parse.(Float64, t) for t in toss]
N = length(toss)
z = Vector{Vector{Float64}}()
for i=1:N-1
z_i = toss[1+(i-1)]
z_ip1 = toss[1+i]
x1 = z_i[1:3]
q1 = z_i[4:7]
x2 = z_ip1[1:3]
q2 = z_ip1[4:7]
v15 = (x2 - x1) / timestep
ω15 = Dojo.angular_velocity(Quaternion(q1...), Quaternion(q2...), timestep)
push!(z, [x2; v15; q2; ω15])
end
push!(storages, generate_storage(mechanism, z))
end
jldsave(joinpath(@__DIR__, "..", "datasets", "real_block.jld2"); storages)
return
end
convert_csv_to_jld2() | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 7432 | module Dojo
# constants
global const REG = 1.0e-10::Float64
global const X_AXIS = [1;0;0]
global const Y_AXIS = [0;1;0]
global const Z_AXIS = [0;0;1]
#TODO: remove
using FiniteDiff
using LinearAlgebra
using Random
using StaticArrays
using SparseArrays
using StaticArrays: SUnitRange
using Quaternions
using Statistics
using Colors
using Colors: RGBA, RGB
using FFMPEG
using LightXML
using MeshCat
import MeshCat: render
using Meshing
using GeometryBasics
using GraphBasedSystems
using CoordinateTransformations
using DocStringExtensions
using PrecompileTools
# Utilities
include(joinpath("utilities", "methods.jl"))
include(joinpath("utilities", "custom_static.jl"))
include(joinpath("utilities", "normalize.jl"))
# Orientation
include(joinpath("orientation", "quaternion.jl"))
include(joinpath("orientation", "mrp.jl"))
include(joinpath("orientation", "axis_angle.jl"))
include(joinpath("orientation", "mapping.jl"))
include(joinpath("orientation", "rotate.jl"))
# Graph objects
include(joinpath("mechanism", "node.jl"))
include(joinpath("mechanism", "edge.jl"))
include(joinpath("mechanism", "id.jl"))
# Bodies
include(joinpath("bodies", "shapes.jl"))
include(joinpath("bodies", "state.jl"))
include(joinpath("bodies", "constructor.jl"))
include(joinpath("bodies", "origin.jl"))
include(joinpath("bodies", "set.jl"))
# Mechanism
include(joinpath("joints", "constraints.jl"))
include(joinpath("contacts", "constructor.jl"))
include(joinpath("contacts", "contact.jl"))
include(joinpath("mechanism", "constructor.jl"))
include(joinpath("mechanism", "gravity.jl"))
include(joinpath("mechanism", "state.jl"))
include(joinpath("mechanism", "system.jl"))
include(joinpath("mechanism", "methods.jl"))
include(joinpath("mechanism", "set.jl"))
include(joinpath("mechanism", "get.jl"))
include(joinpath("mechanism", "urdf.jl"))
include(joinpath("mechanism", "traversal.jl"))
# Simulation
include(joinpath("simulation", "step.jl"))
include(joinpath("simulation", "storage.jl"))
include(joinpath("simulation", "simulate.jl"))
# Mechanics
include(joinpath("mechanics", "momentum.jl"))
include(joinpath("mechanics", "energy.jl"))
# Joints
include(joinpath("joints", "orthogonal.jl"))
include(joinpath("joints", "joint.jl"))
include(joinpath("joints", "translational", "constructor.jl"))
include(joinpath("joints", "translational", "impulses.jl"))
include(joinpath("joints", "translational", "input.jl"))
include(joinpath("joints", "translational", "springs.jl"))
include(joinpath("joints", "translational", "dampers.jl"))
include(joinpath("joints", "translational", "minimal.jl"))
include(joinpath("joints", "rotational", "constructor.jl"))
include(joinpath("joints", "rotational", "impulses.jl"))
include(joinpath("joints", "rotational", "input.jl"))
include(joinpath("joints", "rotational", "springs.jl"))
include(joinpath("joints", "rotational", "dampers.jl"))
include(joinpath("joints", "rotational", "minimal.jl"))
include(joinpath("joints", "limits.jl"))
include(joinpath("joints", "prototypes.jl"))
include(joinpath("joints", "minimal.jl"))
include(joinpath("joints", "impulses.jl"))
# Contacts
include(joinpath("contacts", "constraints.jl"))
include(joinpath("contacts", "cone.jl"))
include(joinpath("contacts", "collisions", "collision.jl"))
include(joinpath("contacts", "collisions", "point_to_segment.jl"))
include(joinpath("contacts", "collisions", "point_to_box_v2.jl"))
include(joinpath("contacts", "collisions", "sphere_halfspace.jl"))
include(joinpath("contacts", "collisions", "sphere_sphere.jl"))
include(joinpath("contacts", "collisions", "sphere_capsule.jl"))
include(joinpath("contacts", "collisions", "sphere_box.jl"))
include(joinpath("contacts", "collisions", "string.jl"))
include(joinpath("contacts", "velocity.jl"))
include(joinpath("contacts", "impact.jl"))
include(joinpath("contacts", "linear.jl"))
include(joinpath("contacts", "nonlinear.jl"))
include(joinpath("contacts", "utilities.jl"))
# Solver
include(joinpath("solver", "linear_system.jl"))
include(joinpath("solver", "centering.jl"))
include(joinpath("solver", "complementarity.jl"))
include(joinpath("solver", "violations.jl"))
include(joinpath("solver", "options.jl"))
include(joinpath("solver", "initialization.jl"))
include(joinpath("solver", "correction.jl"))
include(joinpath("solver", "mehrotra.jl"))
include(joinpath("solver", "line_search.jl"))
# Integrator
include(joinpath("integrators", "integrator.jl"))
include(joinpath("integrators", "constraint.jl"))
# Visualizer
include(joinpath("visuals", "visualizer.jl"))
include(joinpath("visuals", "set.jl"))
include(joinpath("visuals", "convert.jl"))
include(joinpath("visuals", "colors.jl"))
# Data
include(joinpath("mechanism", "data.jl"))
# Gradients
include(joinpath("gradients", "contact.jl"))
include(joinpath("gradients", "finite_difference.jl"))
include(joinpath("gradients", "state.jl"))
include(joinpath("gradients", "data.jl"))
include(joinpath("gradients", "utilities.jl"))
# Precompilation
include("precompile.jl")
# Bodies
export
Body,
Origin,
Box,
Capsule,
Cylinder,
Sphere,
Pyramid,
Mesh,
CombinedShapes,
get_body,
get_node,
set_external_force!,
add_external_force!
# Joints
export
Rotational,
Translational,
JointConstraint,
Floating,
Fixed,
Prismatic,
Planar,
FixedOrientation,
Revolute,
Cylindrical,
PlanarAxis,
FreeRevolute,
Orbital,
PrismaticOrbital,
PlanarOrbital,
FreeOrbital,
Spherical,
CylindricalFree,
PlanarFree,
get_joint,
nullspace_mask
# Contacts
export
ContactConstraint,
ImpactContact,
LinearContact,
NonlinearContact,
get_contact,
get_sdf,
contact_location,
damper_impulses,
contact_constraint
# Collision
export
SphereHalfSpaceCollision,
SphereSphereCollision,
SphereCapsuleCollision,
SphereBoxCollision,
StringCollision,
distance,
contact_point,
contact_normal,
contact_tangent
# Inputs
export
set_input!,
add_input!,
input_dimension
# Mechanism
export
Mechanism,
initialize!,
set_floating_base,
zero_coordinates!,
zero_velocities!
# Maximal
export
set_maximal_state!,
set_maximal_configurations!,
set_maximal_velocities!,
get_maximal_state,
get_maximal_gradients!,
maximal_dimension
# Minimal
export
set_minimal_state!,
set_minimal_coordinates!,
set_minimal_velocities!,
get_minimal_state,
get_minimal_gradients!,
minimal_coordinates,
minimal_velocities,
minimal_dimension
# Maximal <-> Minimal
export
maximal_to_minimal,
minimal_to_maximal
# Simulation
export
simulate!,
step!,
generate_storage
# Orientation
export
Quaternion,
attitude_jacobian
# Data
export
get_data,
set_data!,
get_solution
# Gradients
export
maximal_to_minimal_jacobian,
minimal_to_maximal_jacobian
# Mechanics
export
kinetic_energy,
potential_energy,
mechanical_energy,
momentum
# Solver
export
mehrotra!,
SolverOptions
# Linear System "Ax = b"
export
full_matrix
# Visuals
export
Visualizer,
visualize,
render,
set_background!,
set_floor!,
set_surface!,
set_light!,
set_camera!,
RGBA,
orange,
cyan,
magenta
# Static
export
szeros,
sones,
srand
# Utilities
export
Storage,
X_AXIS,
Y_AXIS,
Z_AXIS
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1825 | @setup_workload begin
@compile_workload begin
# One full simulation
origin = Origin()
body = Cylinder(0.1, 1, 1)
joint = JointConstraint(Revolute(origin, body, [1;0;0]; child_vertex=[0;0;1/2]))
mechanism = Mechanism(origin, [body], [joint])
controller!(mechanism, k) = set_input!(joint, [0])
set_minimal_coordinates!(mechanism, joint, [pi/4])
set_minimal_velocities!(mechanism, joint, [0.2])
storage = simulate!(mechanism, mechanism.timestep * 2, controller!, record=true)
# Common shapes
mesh = Mesh("", 1, rand(3,3))
box = Box(1,1,1,1.0)
capsule = Capsule(1,1,1.0)
cylinder = Cylinder(1, 1, 1.0)
sphere = Sphere(1,1.0)
pyramid = Pyramid(1,1,1.0)
# Common joints
joint_axis = [1;0;0]
JointConstraint(Floating(origin, mesh))
JointConstraint(Fixed(origin, box))
JointConstraint(Prismatic(origin, capsule, joint_axis))
JointConstraint(Planar(origin, cylinder, joint_axis))
JointConstraint(FixedOrientation(origin, sphere))
JointConstraint(Revolute(origin, pyramid, joint_axis))
JointConstraint(Cylindrical(origin, mesh, joint_axis))
JointConstraint(PlanarAxis(origin, box, joint_axis))
JointConstraint(FreeRevolute(origin, capsule, joint_axis))
JointConstraint(Orbital(origin, cylinder, joint_axis))
JointConstraint(PrismaticOrbital(origin, sphere, joint_axis))
JointConstraint(PlanarOrbital(origin, pyramid, joint_axis))
JointConstraint(FreeOrbital(origin, mesh, joint_axis))
JointConstraint(Spherical(origin, box))
JointConstraint(CylindricalFree(origin, capsule, joint_axis))
JointConstraint(PlanarFree(origin, cylinder, joint_axis))
end
end | Dojo | https://github.com/dojo-sim/Dojo.jl.git |
|
[
"MIT"
] | 0.7.5 | 104b6a1a358da9b1348ab7cd66ad685ecaca13d4 | code | 1403 | """
Body{T} <: Node{T}
A rigid body object
id: unique identifying number
name: unique identifying name
mass: inertial property (kilograms)
inertia: inertia matrix (kilograms meter^2)
state: State; representation of the system's: position, linear velocity, orientation, and angular velocity
shape: Shape; geometry information about the Body
"""
mutable struct Body{T} <: Node{T}
id::Int64
name::Symbol
mass::T
inertia::SMatrix{3,3,T,9}
state::State{T}
shape::Shape{T}
function Body(mass::Real, inertia::AbstractMatrix;
name::Symbol=Symbol("body_" * randstring(4)),
shape::Shape=EmptyShape())
T = promote_type(eltype.((mass, inertia))...)
new{T}(getGlobalID(), name, mass, inertia, State{T}(), shape)
end
end
function Base.show(io::IO, mime::MIME{Symbol("text/plain")}, body::Body)
summary(io, body)
println(io, "")
println(io, " id: "*string(body.id))
println(io, " name: "*string(body.name))
println(io, " mass: "*string(body.mass))
println(io, " inertia: "*string(body.inertia))
end
Base.length(::Body) = 6
# warn that body has poor inertial properties
function check_body(body::Body)
if norm(body.mass) == 0 || norm(body.inertia) == 0
@info "Bad inertial properties detected"
end
#TODO check condition number and potentially adapt
end
| Dojo | https://github.com/dojo-sim/Dojo.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.