Local preservation snapshot, not a new deployment or simulation acceptance.
234 lines
11 KiB
Python
234 lines
11 KiB
Python
"""Two finite-inertia belts and passive, coupled Coulomb contact traction.
|
|
|
|
PhysX supplies normal loads and integrates the chassis. This module returns
|
|
forces and moments only. Contact reaction also acts on each belt's inertia;
|
|
coast removes motor effort, brake dissipates belt motion. No chassis velocity
|
|
or pose is assigned by this model.
|
|
"""
|
|
|
|
import math
|
|
|
|
import numpy as np
|
|
|
|
|
|
class TrackDynamics:
|
|
def __init__(self, profile, mass_kg):
|
|
self.profile = profile
|
|
self.mass_kg = mass_kg
|
|
if not math.isfinite(mass_kg) or mass_kg <= 0:
|
|
raise ValueError("Invalid chassis mass")
|
|
inertia = np.asarray(profile["chassis_inertia_kg_m2"], dtype=float)
|
|
if inertia.shape != (3,) or not np.all(np.isfinite(inertia)) or min(inertia) <= 0:
|
|
raise ValueError("Invalid chassis inertia")
|
|
self.inverse_inertia = np.diag(1 / inertia)
|
|
positive = (
|
|
"drive_sprocket_effective_radius_m",
|
|
"max_drive_torque_nm",
|
|
"max_drive_power_w",
|
|
"max_brake_torque_nm",
|
|
"max_hold_torque_nm",
|
|
"lock_capture_speed_mps",
|
|
"belt_equivalent_inertia_kg",
|
|
"velocity_gain_n_per_mps",
|
|
"velocity_integral_gain_n_per_m",
|
|
"slip_regularization_mps",
|
|
"integration_step_seconds",
|
|
"max_step_seconds",
|
|
)
|
|
if any(not math.isfinite(profile[k]) or profile[k] <= 0 for k in positive):
|
|
raise ValueError("Track dynamics parameters must be finite and positive")
|
|
for key in (
|
|
"static_friction_coefficient",
|
|
"friction_coefficient",
|
|
"rolling_resistance_coefficient",
|
|
):
|
|
if not math.isfinite(profile[key]) or profile[key] < 0:
|
|
raise ValueError("Invalid contact resistance")
|
|
self.belt_mps = np.zeros(2)
|
|
self.integral_force_n = np.zeros(2)
|
|
|
|
def step(
|
|
self,
|
|
target,
|
|
contacts,
|
|
rotation,
|
|
linear,
|
|
angular,
|
|
centre,
|
|
dt,
|
|
mode="drive",
|
|
*,
|
|
external_wrench=None,
|
|
held_sides=None,
|
|
):
|
|
"""Contacts: (side, world point, world normal, normal load N, friction).
|
|
|
|
Viscous regularization is isotropic in the contact plane, capped by one
|
|
friction circle. Its slip power is non-positive. There is no separate
|
|
unlimited lateral stabilizer or prescribed yaw response.
|
|
"""
|
|
p = self.profile
|
|
if mode not in {"drive", "coast", "brake", "hold"}:
|
|
raise ValueError("Unknown track actuator mode")
|
|
if not math.isfinite(dt) or not 0 < dt <= p["max_step_seconds"]:
|
|
raise ValueError("Unsupported track physics step")
|
|
target = np.asarray(target, dtype=float)
|
|
if target.shape != (2,) or not np.all(np.isfinite(target)):
|
|
raise ValueError("Invalid side target")
|
|
held = np.zeros(2, dtype=bool) if held_sides is None else np.asarray(held_sides, dtype=bool)
|
|
if held.shape != (2,) or np.any(held & (np.abs(target) > 1e-8)):
|
|
raise ValueError("A held side must have zero speed intent")
|
|
linear, angular = np.array(linear, dtype=float), np.array(angular, dtype=float)
|
|
rotation, centre = np.asarray(rotation, dtype=float), np.asarray(centre, dtype=float)
|
|
if rotation.shape != (3, 3) or any(v.shape != (3,) for v in (linear, angular, centre)):
|
|
raise ValueError("Invalid rigid body state shape")
|
|
if not all(np.all(np.isfinite(v)) for v in (rotation, linear, angular, centre)):
|
|
raise ValueError("Invalid rigid body state")
|
|
if not np.allclose(rotation.T @ rotation, np.eye(3), atol=1e-5) or not np.isclose(
|
|
np.linalg.det(rotation), 1.0, atol=1e-5
|
|
):
|
|
raise ValueError("Rigid body rotation must be orthonormal")
|
|
external = (
|
|
np.zeros(6) if external_wrench is None else np.asarray(external_wrench, dtype=float)
|
|
)
|
|
if external.shape != (6,) or not np.all(np.isfinite(external)):
|
|
raise ValueError("Invalid external predictor wrench")
|
|
belt_axis = rotation[:, 1]
|
|
inverse_inertia = rotation @ self.inverse_inertia @ rotation.T
|
|
directions, laterals, points, sides, limits, loads = [], [], [], [], [], []
|
|
for side, point, normal, load, friction in contacts:
|
|
point, normal = np.asarray(point), np.asarray(normal)
|
|
if point.shape != (3,) or normal.shape != (3,):
|
|
raise ValueError("Invalid support contact shape")
|
|
if side not in (0, 1) or load < 0 or friction < 0:
|
|
raise ValueError("Invalid support contact")
|
|
if not np.all(np.isfinite([*point, *normal, load, friction])):
|
|
raise ValueError("Non-finite contact")
|
|
norm = np.linalg.norm(normal)
|
|
if norm < 1e-8:
|
|
raise ValueError("Missing contact normal")
|
|
normal = normal / norm
|
|
# Belt circulation follows the track's XZ perimeter. At the nose
|
|
# it can produce upward traction on a riser. Projecting chassis-X
|
|
# into the contact plane incorrectly removes this force entirely.
|
|
direction = np.cross(belt_axis, normal)
|
|
norm = np.linalg.norm(direction)
|
|
if norm < 1e-6:
|
|
continue # A lateral sidewall is not the circulating tread.
|
|
direction /= norm
|
|
directions.append(direction)
|
|
laterals.append(np.cross(normal, direction))
|
|
points.append(point)
|
|
sides.append(side)
|
|
limits.append(friction * load)
|
|
loads.append(load)
|
|
directions = np.asarray(directions).reshape((-1, 3))
|
|
laterals = np.asarray(laterals).reshape((-1, 3))
|
|
offsets = np.asarray(points).reshape((-1, 3)) - centre
|
|
sides, limits = np.asarray(sides, dtype=int), np.asarray(limits)
|
|
normal_by_side = np.bincount(sides, weights=loads, minlength=2)
|
|
# A captured shaft lock transfers contact to PhysX static/dynamic
|
|
# friction. Do not add a second custom traction force on that belt.
|
|
limits = np.where(held[sides], 0.0, limits)
|
|
lock_capture_energy = float(
|
|
np.sum(0.5 * p["belt_equivalent_inertia_kg"] * self.belt_mps[held] ** 2)
|
|
)
|
|
self.belt_mps[held] = 0.0
|
|
self.integral_force_n[held] = 0.0
|
|
count = max(1, math.ceil(dt / p["integration_step_seconds"]))
|
|
h = dt / count
|
|
force = np.zeros(3)
|
|
torque = np.zeros(3)
|
|
motor_average = np.zeros(2)
|
|
reaction_average = np.zeros(2)
|
|
slip_power = motor_power = 0.0
|
|
radius = p["drive_sprocket_effective_radius_m"]
|
|
max_force = p["max_drive_torque_nm"] / radius
|
|
max_brake = p["max_brake_torque_nm"] / radius
|
|
if mode != "drive":
|
|
self.integral_force_n[:] = 0.0
|
|
for _ in range(count):
|
|
velocities = linear + np.cross(angular, offsets)
|
|
vx = np.einsum("ij,ij->i", velocities, directions)
|
|
vy = np.einsum("ij,ij->i", velocities, laterals)
|
|
slip = self.belt_mps[sides] - vx
|
|
speed = np.hypot(slip, vy)
|
|
scale = limits / np.maximum(p["slip_regularization_mps"], speed)
|
|
fx, fy = scale * slip, -scale * vy
|
|
contact_force = directions * fx[:, None] + laterals * fy[:, None]
|
|
reaction = np.bincount(sides, weights=fx, minlength=2)
|
|
rolling = (
|
|
normal_by_side
|
|
* p["rolling_resistance_coefficient"]
|
|
* np.tanh(self.belt_mps / p["slip_regularization_mps"])
|
|
)
|
|
if mode == "drive":
|
|
cap = np.minimum(
|
|
max_force, p["max_drive_power_w"] / np.maximum(np.abs(self.belt_mps), 1e-6)
|
|
)
|
|
error = target - self.belt_mps
|
|
effort = p["velocity_gain_n_per_mps"] * error + self.integral_force_n
|
|
motor = np.clip(effort, -cap, cap)
|
|
# Integrate only when it does not deepen saturation. This
|
|
# removes steady speed droop without bypassing torque/power.
|
|
integrating = (effort == motor) | (error * (effort - motor) < 0)
|
|
self.integral_force_n = np.clip(
|
|
self.integral_force_n
|
|
+ integrating * error * p["velocity_integral_gain_n_per_m"] * h,
|
|
-max_force,
|
|
max_force,
|
|
)
|
|
elif mode == "hold":
|
|
# Bounded shaft braking can reach zero speed; a viscous
|
|
# damper cannot hold a nonzero load without continuous creep.
|
|
free_speed = (
|
|
self.belt_mps - (reaction + rolling) * h / p["belt_equivalent_inertia_kg"]
|
|
)
|
|
motor = -np.clip(
|
|
p["belt_equivalent_inertia_kg"] * free_speed / h, -max_brake, max_brake
|
|
)
|
|
elif mode == "brake":
|
|
motor = np.clip(
|
|
-p["velocity_gain_n_per_mps"] * self.belt_mps, -max_brake, max_brake
|
|
)
|
|
else:
|
|
motor = np.zeros(2)
|
|
motor[held] = 0.0
|
|
rolling[held] = 0.0
|
|
sub_force = contact_force.sum(axis=0)
|
|
sub_torque = np.cross(offsets, contact_force).sum(axis=0)
|
|
force += sub_force / count
|
|
torque += sub_torque / count
|
|
motor_average += motor / count
|
|
reaction_average += reaction / count
|
|
slip_power += float(np.sum(-fx * slip + fy * vy)) / count
|
|
motor_power += float(np.dot(motor, self.belt_mps)) / count
|
|
self.belt_mps += (motor - reaction - rolling) / p["belt_equivalent_inertia_kg"] * h
|
|
# Predictor inside the contact integrator only. PhysX receives the
|
|
# averaged wrench and remains the sole chassis state integrator.
|
|
# Include measured normal reactions and gravity in the predictor.
|
|
# Ignoring them would predict a freely pitching body on a slope,
|
|
# creating artificial slip inside this substep. They are already
|
|
# applied by PhysX, and are never part of the returned wrench.
|
|
linear += (sub_force + external[:3]) / self.mass_kg * h
|
|
angular += inverse_inertia @ (sub_torque + external[3:]) * h
|
|
return (
|
|
force,
|
|
torque,
|
|
{
|
|
"mode": mode,
|
|
"held_sides": held.tolist(),
|
|
"lock_capture_energy_j": lock_capture_energy,
|
|
"belt_mps": self.belt_mps.tolist(),
|
|
"normal_load_n": normal_by_side.tolist(),
|
|
"motor_force_n": motor_average.tolist(),
|
|
"speed_integral_force_n": self.integral_force_n.tolist(),
|
|
"contact_reaction_n": reaction_average.tolist(),
|
|
"motor_power_w": motor_power,
|
|
"slip_power_w": slip_power,
|
|
"force_n": force.tolist(),
|
|
"torque_nm": torque.tolist(),
|
|
"contact_count": len(sides),
|
|
},
|
|
)
|