Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions src/roboticstoolbox/blocks/uav.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,9 @@ def __init__(
:type groundcheck: bool
:param speedcheck: Check for non-positive rotor speed, defaults to True
:type speedcheck: bool
:param x0: Initial state, defaults to None
:type x0: array_like(6) or array_like(12), optional
:param x0: Initial state, defaults to None. A four-value state is
``[x, y, z, yaw]`` with zero pitch, roll and velocities.
:type x0: array_like(3), array_like(4), array_like(6) or array_like(12), optional
:param blockargs: |BlockOptions|
:type blockargs: dict
"""
Expand Down Expand Up @@ -227,7 +228,7 @@ def _initial_state(x0: Any) -> NDArray:
return np.r_[x0, np.zeros((6,))]
elif len(x0) == 4:
# assume x,y,z,yaw
return np.r_[x0[:3], 0, 0, x0[3], np.zeros((6,))]
return np.r_[x0[:3], x0[3], 0, 0, np.zeros((6,))]
elif len(x0) == 3:
# assume x,y,z
return np.r_[x0[:3], np.zeros((9,))]
Expand Down Expand Up @@ -333,7 +334,7 @@ def deriv(self, t: Any, inports: Any, x: Any) -> Any:
z = x[0:3] # position in {W}
n = x[3:6] # RPY angles {W}
v = x[6:9] # velocity in {W}
o = x[9:12] # angular velocity in {W}
o = x[9:12] # angular velocity in {B}

# PREPROCESS ROTATION AND WRONSKIAN MATRICES
phi = n[0] # yaw
Expand Down Expand Up @@ -388,16 +389,20 @@ def deriv(self, t: Any, inports: Any, x: Any) -> Any:
# cos(the) sin(psi)*sin(the) cos(psi)*sin(the)] / cos(the);

# ROTOR MODEL
T = np.zeros((3, 4))
Q = np.zeros((3, 4))
tau = np.zeros((3, 4))
T = np.zeros((3, self.nrotors))
Q = np.zeros((3, self.nrotors))
tau = np.zeros((3, self.nrotors))

a1s = self.a1s
b1s = self.b1s

# Rotor positions and angular velocity use body axes; express the
# translational velocity in that same frame before adding them.
v_body = R.T @ v

for i in range(0, self.nrotors): # for each rotor
# Relative motion
Vr = np.cross(o, self.D[:, i]) + v
Vr = np.cross(o, self.D[:, i]) + v_body
mu = sqrt(np.sum(Vr[0:2] ** 2)) / (
abs(w[i]) * model["r"]
) # Magnitude of mu, planar components
Expand Down
89 changes: 89 additions & 0 deletions tests/test_multirotor_inflow_frame.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""Rotor aerodynamics use relative velocity expressed in the airframe."""

import numpy as np
import numpy.testing as nt
import pytest
from spatialmath.base import rotx, roty, rotz

from roboticstoolbox.blocks.quad_model import quadrotor
from roboticstoolbox.blocks.uav import MultiRotor


@pytest.mark.parametrize("world_yaw", [0.0, 1.1, -1.7])
@pytest.mark.parametrize("tilted", [False, True])
@pytest.mark.parametrize("translating", [False, True])
@pytest.mark.parametrize("rotating", [False, True])
def test_global_yaw_rotation_preserves_body_dynamics(
world_yaw: float, tilted: bool, translating: bool, rotating: bool
) -> None:
block = MultiRotor(quadrotor, groundcheck=False)
state = np.zeros(12)
state[:3] = [1.2, -0.7, -4]
if tilted:
state[3:6] = [0.2, -0.15, 0.25]
if translating:
state[6:9] = [2.1, -0.7, 0.5]
if rotating:
state[9:] = [0.11, -0.16, 0.08]
rotors = 800 * np.array([1.03, -0.97, 1.01, -0.99])
original = state.copy()
derivative = block.deriv(0, [rotors], state)
flapping = np.array([block.a1s, block.b1s])

# Rotate the entire experiment about world gravity. Body axes, angular
# velocity and rotor commands are unchanged; world vectors must rotate.
rotation = rotz(world_yaw)
transformed = state.copy()
transformed[:3] = rotation @ state[:3]
transformed[3] += world_yaw
transformed[6:9] = rotation @ state[6:9]
actual = block.deriv(0, [rotors], transformed)
expected = derivative.copy()
expected[:3] = rotation @ derivative[:3]
expected[6:9] = rotation @ derivative[6:9]

nt.assert_allclose(actual, expected, atol=1e-12)
nt.assert_allclose([block.a1s, block.b1s], flapping, atol=1e-12)
nt.assert_array_equal(state, original)


@pytest.mark.parametrize("yaw", [0.0, np.pi / 2, -0.9])
@pytest.mark.parametrize("tilted", [False, True])
def test_forward_airflow_matches_independent_force_balance(
yaw: float, tilted: bool
) -> None:
block = MultiRotor(quadrotor, groundcheck=False)
state = np.zeros(12)
state[2] = -3
state[3] = yaw
if tilted:
state[4:6] = [-0.2, 0.3]
rotation = rotz(state[3]) @ roty(state[4]) @ rotx(state[5])
forward_speed = 2.0
state[6:9] = rotation @ np.array([forward_speed, 0, 0])
rotor_speed = np.sqrt(quadrotor["M"] * quadrotor["g"] / (4 * quadrotor["b"]))
rotors = rotor_speed * np.array([1, -1, 1, -1])

# No body rotation or normal inflow: all rotors have the same longitudinal
# flap angle. Sum their tilted thrust, then add world gravity.
advance = forward_speed / (rotor_speed * quadrotor["r"])
flap = (
(8 * quadrotor["theta0"] / 3 + 2 * quadrotor["theta1"])
* advance
/ (1 - advance**2 / 2)
)
thrust = (
-quadrotor["M"] * quadrotor["g"] * np.array([np.sin(flap), 0, np.cos(flap)])
)
expected_acceleration = [0, 0, quadrotor["g"]] + rotation @ thrust / quadrotor["M"]
# The hubs are all at height h, so their horizontal thrust has this net
# pitching moment; symmetric in-plane lever arms and drag torques cancel.
expected_angular = np.array([0, quadrotor["h"] * thrust[0], 0]) / np.diag(
quadrotor["J"]
)

actual = block.deriv(0, [rotors], state)
nt.assert_allclose(actual[6:9], expected_acceleration, atol=1e-12)
nt.assert_allclose(actual[9:], expected_angular, atol=1e-12)
nt.assert_allclose(block.a1s, flap, atol=1e-12)
nt.assert_allclose(block.b1s, 0, atol=1e-12)
64 changes: 64 additions & 0 deletions tests/test_multirotor_initial_heading.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""The four-value initial pose specifies yaw without tilting the airframe."""

import bdsim
import numpy as np
import numpy.testing as nt
import pytest

from roboticstoolbox.blocks.quad_model import quadrotor
from roboticstoolbox.blocks.uav import MultiRotor


@pytest.mark.parametrize("yaw", [0.0, 0.6, -1.1, np.pi / 2])
@pytest.mark.parametrize("use_parameter", [False, True])
def test_short_pose_preserves_heading(yaw: float, use_parameter: bool) -> None:
initial = [1.2, -0.7, -3.0, yaw]
if use_parameter:
block = MultiRotor(quadrotor)
block.set_param("x0", initial)
else:
block = MultiRotor(quadrotor, x0=initial)

state = block.getstate0()
nt.assert_allclose(state, np.r_[initial, np.zeros(8)])
nt.assert_allclose(block.output(0, [], state)[0]["x"], [*initial, 0, 0])


@pytest.mark.parametrize("yaw", [0.0, np.pi / 3, -0.8])
def test_heading_only_initial_pose_can_hover(yaw: float) -> None:
block = MultiRotor(quadrotor, x0=[1, 2, -3, yaw], groundcheck=False)
speed = np.sqrt(quadrotor["M"] * quadrotor["g"] / (4 * quadrotor["b"]))
rotors = speed * np.array([1, -1, 1, -1])

# Equal, alternating rotors balance gravity and all moments. A yaw change
# keeps the thrust vertical, so all twelve state derivatives remain zero.
nt.assert_allclose(block.deriv(0, [rotors], block.getstate0()), 0, atol=1e-12)


@pytest.mark.parametrize("use_parameter", [False, True])
def test_heading_only_hover_in_a_real_diagram(use_parameter: bool) -> None:
sim = bdsim.BDSim(graphics=False, animation=False, quiet=True)
bd = sim.blockdiagram()
initial = [1.0, 2.0, -3.0, np.pi / 3]
block = bd.MULTIROTOR(
quadrotor, x0=None if use_parameter else initial, groundcheck=False
)
if use_parameter:
block.set_param("x0", initial)
speed = np.sqrt(quadrotor["M"] * quadrotor["g"] / (4 * quadrotor["b"]))
rotors = bd.CONSTANT(speed * np.array([1, -1, 1, -1]))
pose = bd.FUNCTION(lambda state: state["x"], nin=1, nout=1)
bd.connect(rotors, block)
bd.connect(block, pose)
bd.compile()
result = sim.run(bd, T=0.2, dt=0.02, watch=[pose[0]])

expected = np.tile([*initial, 0, 0], (len(result.t), 1))
nt.assert_allclose(result.y, expected, atol=1e-10)


@pytest.mark.parametrize("size", [3, 6, 12])
def test_other_initial_state_forms_keep_their_order(size: int) -> None:
initial = np.arange(size, dtype=float) / 10
block = MultiRotor(quadrotor, x0=initial)
nt.assert_array_equal(block.getstate0(), np.r_[initial, np.zeros(12 - size)])
61 changes: 61 additions & 0 deletions tests/test_multirotor_rotor_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""The dynamics sum every rotor in an even-rotor airframe model."""

import numpy as np
import numpy.testing as nt
import pytest
from spatialmath.base import rotx, roty, rotz

from roboticstoolbox.blocks.quad_model import quadrotor
from roboticstoolbox.blocks.uav import MultiRotor


@pytest.mark.parametrize("nrotors", [2, 4, 6, 8])
@pytest.mark.parametrize("thrust_ratio", [0.8, 1.0, 1.2])
def test_symmetric_rotors_balance_force_and_moments(
nrotors: int, thrust_ratio: float
) -> None:
model = dict(quadrotor, nrotors=nrotors)
block = MultiRotor(model, groundcheck=False)
speed = np.sqrt(thrust_ratio * model["M"] * model["g"] / (nrotors * model["b"]))
rotors = speed * (-1.0) ** np.arange(nrotors)
state = np.zeros(12)
state[2] = -3

expected = np.zeros(12)
expected[8] = model["g"] * (1 - thrust_ratio)
nt.assert_allclose(block.deriv(0, [rotors], state), expected, atol=1e-12)
nt.assert_allclose(block.a1s, np.zeros(nrotors), atol=1e-12)
nt.assert_allclose(block.b1s, np.zeros(nrotors), atol=1e-12)


@pytest.mark.parametrize("nrotors", [2, 4, 6, 8])
@pytest.mark.parametrize("last_rotor", [False, True])
def test_one_rotor_increment_matches_its_force_and_lever_arm(
nrotors: int, last_rotor: bool
) -> None:
model = dict(quadrotor, nrotors=nrotors)
block = MultiRotor(model, groundcheck=False)
squared_speeds = np.full(nrotors, model["M"] * model["g"] / (nrotors * model["b"]))
selected = nrotors - 1 if last_rotor else 0
increment = 13000.0
squared_speeds[selected] += increment
rotors = np.sqrt(squared_speeds) * (-1.0) ** np.arange(nrotors)
state = np.zeros(12)
state[:6] = [1, -2, -3, 0.5, -0.2, 0.3]
rotation = rotz(state[3]) @ roty(state[4]) @ rotx(state[5])

angle = 2 * np.pi * selected / nrotors
additional_force = model["b"] * increment
force = np.array([0, 0, -model["M"] * model["g"] - additional_force])
moment = np.array(
[
-model["d"] * np.sin(angle) * additional_force,
model["d"] * np.cos(angle) * additional_force,
(-1.0) ** selected * model["k"] * increment,
]
)
expected = np.zeros(12)
expected[6:9] = [0, 0, model["g"]] + rotation @ force / model["M"]
expected[9:] = moment / np.diag(model["J"])

nt.assert_allclose(block.deriv(0, [rotors], state), expected, atol=1e-12)
Loading