Skip to content

SyntheticArm: a robot arm with a fault at a known time

SyntheticArm makes a labelled joint stream from the URDF of a robot arm, with a fault that starts at a known time. It is a robot dataset by nature, so its examples are robot arms. The overview of the section is on Datasets.

A robot arm with a fault at a known time

A labelled joint stream from the real URDF of a Panda arm. Torque is the turning force the motors apply at each joint; on a moving arm it is not free, it is fixed by the motion through the arm's own dynamics. The stream has a periodic motion, torques from the library's inverse dynamics, sensor noise, and from second 2 a 5 kg payload on the last link.

import numpy as np
from dense_armor.core.signals.datasets import SyntheticArm

ds = SyntheticArm("test/fixtures/urdf/panda.urdf", period_s=2.0, rate_hz=50.0, n_cycles=2,
                  fault_at_s=2.0, fault="payload", payload_mass=5.0, seed=0)
r0, r1 = [], []
for sig, y in ds.stream():
    q, qd, qdd = ds.trajectory(sig.t)
    r = float(sig["tau_1"] - ds.nominal_torque(q, qd, qdd)[1])
    (r1 if y else r0).append(r)
print(ds.payload_link, round(np.mean(r0), 3), round(np.std(r0), 3), round(np.mean(r1), 2))
panda_link7 -0.004 0.051 -12.54

The residual is what is left of the measured torque once the expected one is subtracted:

\[r = \tau_{\text{meas}} - \tau_{\text{model}}.\]

On a healthy arm it is noise: mean -0.004 N·m and standard deviation 0.051 N·m, exactly the torque noise the stream adds. On a faulty arm it carries the fault: it jumps to a mean of -12.54 N·m.

The expected torque comes from the arm's inverse dynamics,

\[\tau = M(q)\,\ddot q + C(q, \dot q)\,\dot q + g(q),\]

with \(q\) the joint positions, \(\dot q\) the joint velocities, \(\ddot q\) the joint accelerations, \(M(q)\) the mass matrix (how the arm's inertia couples the joints), \(C(q, \dot q)\,\dot q\) the Coriolis and centrifugal torques, and \(g(q)\) the gravity torques. The payload adds its own gravity torque

\[\tau_{\text{payload}} = m\,g\,J_z(q),\]

where \(m\) is the payload mass, \(g\) the acceleration of gravity and \(J_z(q)\) the vertical row of the Jacobian of the link that carries the payload (here panda_link7, the flange): the vertical speed of that link for a unit joint velocity. y is 0 before the fault and 1 after, so the stream also scores detectors.

A model that does not learn the fault

A recursive least-squares model estimates the residual offset, the constant value the model adds to its prediction to best fit the samples it has seen; on a healthy arm it is about zero. Protected asks an anomaly detector before each sample and skips learning on the ones the detector flags; the detector is a Hampel scorer wrapped in AnomalyGate, which also keeps it from learning flagged samples. The same model without protection is shown next to it for comparison.

from dense_armor.roles.anomaly_detector import AnomalyGate
from dense_armor.roles.protection import Protected
from dense_armor.core.online.anomaly.filters import HampelScorer
from dense_armor.core.signals.datasets import SyntheticArm
from dense_armor.core.online.learn.online_dynamics import RecursiveLeastSquares

ds = SyntheticArm("test/fixtures/urdf/panda.urdf", period_s=2.0, rate_hz=50.0, n_cycles=2,
                  fault_at_s=2.0, fault="payload", payload_mass=5.0, seed=0)
gate = AnomalyGate(HampelScorer(radius=10, n_sigmas=5.0, feature="r"))
prot = Protected(model=RecursiveLeastSquares(feature_keys=["one"]), detector=gate)
bare = RecursiveLeastSquares(feature_keys=["one"])
for sig, y in ds.stream():
    q, qd, qdd = ds.trajectory(sig.t)
    x = {"r": float(sig["tau_1"] - ds.nominal_torque(q, qd, qdd)[1]), "one": 1.0}
    gate.learn_one(x)
    prot.learn_one(x, x["r"])
    bare.learn_one(x, x["r"])
print(round(prot.model.predict_one({"one": 1.0}), 3), round(bare.predict_one({"one": 1.0}), 3))
-0.003 -6.271

After the fault, the protected model still says the healthy offset is -0.003 N·m; the unprotected one has averaged the fault in and says -6.271 N·m, about half of the -12.5 N·m step because half of its samples came after the fault. In the test suite the same run flags 99 of the 100 faulty samples and 1 of the 100 healthy ones. A model protected this way can be used to keep estimating "normal" while the robot is in trouble.

API reference

synthetic_arm

Labelled joint stream from a real URDF, with a fault after a chosen time.

The arm follows a periodic sinusoidal trajectory inside the joint limits of the URDF. Torques come from inverse dynamics,

tau = mass_matrix(q) @ qdd + bias_forces(q, qd) + gravity_forces(q),

computed by :class:~dense_armor.dynamics.urdf_dynamics.RigidBodyModel from the same URDF file. Gaussian sensor noise is added to q, qd and tau. From fault_at_s a fault adds a torque:

  • "friction": a viscous term b * qd[j] on one joint;
  • "payload": an extra mass m at the origin of the last link of the chain, whose gravity torque is m * g * J_z(q), with J_z the vertical row of the link's translational Jacobian (the same V = m g z convention as gravity_forces).

The label y is 0 before fault_at_s and 1 after.

Examples:

>>> from dense_armor.core.signals.datasets import SyntheticArm
>>> ds = SyntheticArm(
...     "test/fixtures/urdf/panda.urdf",
...     period_s=1.0, rate_hz=50.0,
...     fault_at_s=0.5, fault="payload", seed=0,
... )

SyntheticArm

SyntheticArm(
    urdf_path: str | Path,
    period_s: float,
    rate_hz: float,
    n_cycles: int = 4,
    fault_at_s: float | None = None,
    fault: str | None = None,
    fault_joint: int | None = None,
    friction_b: float = 20.0,
    payload_mass: float = 2.0,
    payload_link: str | None = None,
    noise_std: tuple[float, float, float] = (
        0.001,
        0.005,
        0.05,
    ),
    seed: int | None = 0,
)

Periodic joint stream from a URDF with an optional fault.

Parameters:

Name Type Description Default
urdf_path str | Path

URDF readable by :class:~dense_armor.dynamics.urdf_dynamics.RigidBodyModel.

required
period_s float

period of one sinusoidal cycle, in seconds.

required
rate_hz float

sampling rate, in Hz.

required
n_cycles int

number of cycles generated.

4
fault_at_s float | None

time from the start when the fault begins, in seconds. None means no fault.

None
fault str | None

"friction" or "payload". Required when fault_at_s is given.

None
fault_joint int | None

index of the joint with the "friction" fault. Default: the last joint.

None
friction_b float

viscous coefficient for "friction", in N m s.

20.0
payload_mass float

mass added for "payload", in kg.

2.0
payload_link str | None

link carrying the payload. Default: the last link of the longest chain.

None
noise_std tuple[float, float, float]

standard deviation of the Gaussian sensor noise on q (rad), qd (rad/s) and tau (N m).

(0.001, 0.005, 0.05)
seed int | None

seed of the random generator.

0

Raises:

Type Description
ValueError

on bad arguments.

Examples:

>>> from dense_armor.core.signals.datasets import SyntheticArm
>>> ds = SyntheticArm(
...     "test/fixtures/urdf/panda.urdf",
...     period_s=1.0, rate_hz=50.0,
...     fault_at_s=0.5, fault="payload", seed=0,
... )
Source code in dense_armor/core/signals/datasets/synthetic_arm.py
def __init__(
    self,
    urdf_path: str | Path,
    period_s: float,
    rate_hz: float,
    n_cycles: int = 4,
    fault_at_s: float | None = None,
    fault: str | None = None,
    fault_joint: int | None = None,
    friction_b: float = 20.0,
    payload_mass: float = 2.0,
    payload_link: str | None = None,
    noise_std: tuple[float, float, float] = (1e-3, 5e-3, 5e-2),
    seed: int | None = 0,
) -> None:
    if period_s <= 0:
        raise ValueError(f"period_s must be > 0, got {period_s}")
    if rate_hz <= 0:
        raise ValueError(f"rate_hz must be > 0, got {rate_hz}")
    if n_cycles < 1:
        raise ValueError(f"n_cycles must be >= 1, got {n_cycles}")
    if fault_at_s is not None and fault not in ("friction", "payload"):
        raise ValueError(f"fault must be 'friction' or 'payload', got {fault!r}")
    self.urdf_path = Path(urdf_path)
    self.period_s = float(period_s)
    self.rate_hz = float(rate_hz)
    self.n_cycles = n_cycles
    self.fault_at_s = fault_at_s
    self.fault = fault
    self.friction_b = float(friction_b)
    self.payload_mass = float(payload_mass)
    self.noise_std = tuple(noise_std)
    self.seed = seed
    (
        self.model,
        self.payload_link,
        self._mass_matrix,
        self._bias,
        self._gravity,
        self._jac,
    ) = _dynamics(self.urdf_path, payload_link)
    self.n_joints = int(self.model.n)
    if fault_joint is None:
        fault_joint = self.n_joints - 1
    if not 0 <= fault_joint < self.n_joints:
        raise ValueError(
            f"fault_joint must be in [0, {self.n_joints}), got {fault_joint}"
        )
    self.fault_joint = int(fault_joint)
    self.q_min, self.q_max = _joint_limits(self.urdf_path, self.n_joints)
    span = np.maximum(self.q_max - self.q_min, 1e-3)
    self.amplitude = 0.3 * span
    self.mid = 0.5 * (self.q_min + self.q_max)
    freqs = 1.0 + 0.25 * np.arange(self.n_joints)
    phases = 0.5 * np.arange(self.n_joints)
    self.freqs = freqs
    self.phases = phases
    self.n_samples = round(n_cycles * period_s * rate_hz)
    self.dt = 1.0 / rate_hz

trajectory

trajectory(
    t: float,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]

Sinusoidal position, velocity and acceleration at t.

Parameters:

Name Type Description Default
t float

time from the start, in seconds.

required

Returns:

Type Description
tuple[ndarray, ndarray, ndarray]

(q, qd, qdd), three arrays of shape (n_joints,).

Source code in dense_armor/core/signals/datasets/synthetic_arm.py
def trajectory(self, t: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Sinusoidal position, velocity and acceleration at ``t``.

    Args:
        t: time from the start, in seconds.

    Returns:
        ``(q, qd, qdd)``, three arrays of shape ``(n_joints,)``.
    """
    w = 2.0 * np.pi / self.period_s
    phase = w * self.freqs * t + self.phases
    q = self.mid + self.amplitude * np.sin(phase)
    qd = self.amplitude * self.freqs * w * np.cos(phase)
    qdd = -self.amplitude * self.freqs**2 * w**2 * np.sin(phase)
    return q, qd, qdd

nominal_torque

nominal_torque(
    q: ndarray, qd: ndarray, qdd: ndarray
) -> np.ndarray

Inverse dynamics of the arm, without noise or fault.

Parameters:

Name Type Description Default
q ndarray

joint positions.

required
qd ndarray

joint velocities.

required
qdd ndarray

joint accelerations.

required

Returns:

Type Description
ndarray

``mass_matrix(q) @ qdd + bias_forces(q, qd)

ndarray
  • gravity_forces(q)``.
Source code in dense_armor/core/signals/datasets/synthetic_arm.py
def nominal_torque(
    self, q: np.ndarray, qd: np.ndarray, qdd: np.ndarray
) -> np.ndarray:
    """Inverse dynamics of the arm, without noise or fault.

    Args:
        q: joint positions.
        qd: joint velocities.
        qdd: joint accelerations.

    Returns:
        ``mass_matrix(q) @ qdd + bias_forces(q, qd)
        + gravity_forces(q)``.
    """
    M = as_default_array(self._mass_matrix(q))
    b = as_default_array(self._bias(q, qd))
    g = as_default_array(self._gravity(q))
    return M @ qdd + b + g

payload_torque

payload_torque(q: ndarray) -> np.ndarray

Gravity torque of the payload mass, m * g * J_z(q).

Source code in dense_armor/core/signals/datasets/synthetic_arm.py
def payload_torque(self, q: np.ndarray) -> np.ndarray:
    """Gravity torque of the payload mass, ``m * g * J_z(q)``."""
    jz = as_default_array(self._jac(q))[2]
    return self.payload_mass * 9.81 * jz

stream

stream() -> Iterator[tuple[Signal, int]]

Yield (Signal, y) pairs at rate_hz.

Each :class:Signal has channels q_j, qd_j, tau_j for every joint; t is the sample time in seconds; y is 0 before fault_at_s and 1 after.

Yields:

Type Description
tuple[Signal, int]

(signal, label) pairs in time order.

Source code in dense_armor/core/signals/datasets/synthetic_arm.py
def stream(self) -> Iterator[tuple[Signal, int]]:
    """Yield ``(Signal, y)`` pairs at ``rate_hz``.

    Each :class:`Signal` has channels ``q_j``, ``qd_j``, ``tau_j``
    for every joint; ``t`` is the sample time in seconds; ``y`` is
    ``0`` before ``fault_at_s`` and ``1`` after.

    Yields:
        ``(signal, label)`` pairs in time order.
    """
    rng = np.random.default_rng(self.seed)
    names: list[str] = []
    units: list[str] = []
    for j in range(self.n_joints):
        names += [f"q_{j}", f"qd_{j}", f"tau_{j}"]
        units += ["rad", "rad/s", "N*m"]
    for i in range(self.n_samples):
        t = i * self.dt
        q, qd, qdd = self.trajectory(t)
        tau = self.nominal_torque(q, qd, qdd) + self._fault_term(q, qd, t)
        vals: list[float] = []
        for j in range(self.n_joints):
            vals.append(q[j] + rng.normal(0.0, self.noise_std[0]))
            vals.append(qd[j] + rng.normal(0.0, self.noise_std[1]))
            vals.append(tau[j] + rng.normal(0.0, self.noise_std[2]))
        sig = Signal(
            values=as_default_array(vals),
            names=names,
            units=units,
            t=t,
        )
        y = 0
        if self.fault_at_s is not None and t >= self.fault_at_s:
            y = 1
        yield sig, y

Details

  • SyntheticArm: sinusoidal joint trajectories at 30 % of each joint's range, inverse dynamics with RigidBodyModel, compiled once per URDF and process; faults: "friction" (viscous b * qd on one joint) or "payload" (a mass on the last link of the longest chain, or on payload_link).
  • Protected passes the timestamp only to models that accept it; HampelScorer.threshold is its n_sigmas, which AnomalyGate uses to decide.
  • Protected passes the timestamp only to models that accept it; HampelScorer.threshold is its n_sigmas, which AnomalyGate uses to decide.