JinraeKim / FSimZoo.jl

Predefined environments and controllers for FlightSims.jl
MIT License
5 stars 0 forks source link

Convenience method for integrated environments? #30

Open willsharpless opened 4 months ago

willsharpless commented 4 months ago

Hi Jinrae,

Your package suite looks great and useful, thanks for making it. Is there a convenience method for defining an integrated environment for a custom model? I took a look at backstepping_position_controller_static_allocator_multicopter.jl but it looks difficult.

I would like to combine a LeeQuadcopter to model the crazyflie drone and to start would like to test it using the LQR controller for RPYT controls. Is that possible? On that note, is there an automatic way to generate the LQR controller with ForwardDiff.jl or something?

JinraeKim commented 4 months ago

@willsharpless Thank you for your interest.

When using FlightSims, the only rule is to define an Env with State (the structure of state) and Dynamics!(defining the underlying dynamics).

In practice, I usually define my own AbstractEnv for each case, which consists of multiple predefined envs. FSimZoo.jl mostly provides "the predefined envs that are used frequently".

In this regard, you can also define your own 1) predefined Envs if they are used frequently, or 2) some (integrated) Envs built on top of other Envs.

I am not aware of RPYT but we can use FlightSims.jl to perform numerical simulation of controller + multicopter for sure (as I've done this so many times).

+) You can use apply_inputs if you often change controllers. This is a very convenient wrapper, and I'm now a bit surprised that I didn't add any good examples of using this to README.md. You can avoid defining many integrated Envs for different controllers with apply_inputs (See FSimBase.jl). See the below illustrative code for your information.

function my_lqr(X, p, t; Q, R)  # you should follow these function arguments: (state, param, t; kwargs...)
    (; p, v, q, ω) = X
    u = LQR(p, v, q, ω, Q, R)
    return u
end

function sim(Q, R; tf=1)  # Q, R: weight matrices of quadratic costs in LQR
    env = LeeHexacopter()
    X0 = State(env)()
    simulator = Simulator(
                          X0,
                          apply_inputs(FSimZoo._Dynamics!(env); u=(X, p, t) ->  my_lqr(X, p, t; Q, R);  # https://github.com/JinraeKim/FSimZoo.jl/blob/437623eb6f99f0c0109b49ca6baa57fd9792aa14/src/environments/multicopters/multicopters.jl#L151
                          tf,
                          savestep=0.01,  # saving data at each savestep
                         )
    df = solve(simulator)  # See `df.time`, `df.sol`
    return df
end