diff --git a/docs/reduced-order-dynamics.md b/docs/reduced-order-dynamics.md index 64988e4..d472bdd 100644 --- a/docs/reduced-order-dynamics.md +++ b/docs/reduced-order-dynamics.md @@ -196,6 +196,14 @@ switch separately and moves the boundary value only by about the residual. File-backed GGV runs, and GGVs that lap evaluation generates, solve speed slices in separate processes, one per slice up to the CPU count. Lateral samples within each slice retain their continuation order. +SLSQP's finite-difference Jacobians dominate a GGV solve, so the constraint +Jacobians are built by `engines/dynpy/jacobian.py` with the same steps and +quotients SciPy uses, but every column point is handed to +`model.evaluate_batch` first. The 3DOF model evaluates those rows as arrays, +including the tire calls, and the scalar `evaluate` reads them from a cache. +Batch rows match row-by-row evaluation to rounding, so the solve follows the +same path. Other fidelities batch by looping rows until they get their own +vectorized path. GGV checks independent tire-force inversion at the solved loads, then verifies load and wheel-torque balance. Near tire peaks, transient evaluation starting from static loads can select a different saturated branch. A valid QSS point diff --git a/engines/dynpy/aero.py b/engines/dynpy/aero.py index 5da6127..7c939d6 100644 --- a/engines/dynpy/aero.py +++ b/engines/dynpy/aero.py @@ -133,3 +133,34 @@ def wrench(self, heights: FloatArray, velocity: FloatArray, density: float) -> t force = -drag * velocity / max(speed, 1e-6) + np.array([0., 0., -downforce]) moment = np.array([mx, my, mz]) + cross(self.reference_m, force) return force, moment + + def wrench_batch( + self, heights: FloatArray, velocity: FloatArray, density: float, + ) -> tuple[FloatArray, FloatArray]: + """## Batched Aero Wrench + + Row-wise ``wrench`` for ``(n, 4)`` heights and ``(n, 3)`` velocities. + + Returns + ------- + tuple[FloatArray, FloatArray] + ``(n, 3)`` body-frame forces and moments about the CG. + """ + def bracket(grid: FloatArray, height: FloatArray) -> tuple[NDArray[np.intp], FloatArray]: + index = np.clip(np.searchsorted(grid, height) - 1, 0, len(grid) - 2) + return index, np.clip((height - grid[index]) / (grid[index + 1] - grid[index]), 0, 1) + + i, x = bracket(self.front_grid, np.mean(heights[:, :2], axis=1)) + j, y = bracket(self.rear_grid, np.mean(heights[:, 2:], axis=1)) + x, y = x[:, None], y[:, None] + raw = ((1-x)*(1-y)*self.loads[:, i, j].T + x*(1-y)*self.loads[:, i+1, j].T + + (1-x)*y*self.loads[:, i, j+1].T + x*y*self.loads[:, i+1, j+1].T) + # sqrt of a stacked dot matches np.linalg.norm on each row bit for bit. + speed = np.sqrt((velocity[:, None, :] @ velocity[:, :, None])[:, 0, 0]) + drag, downforce, mx, my, mz = (raw * max(density, 0) / self.reference_density_kg_m3 * ( + speed / self.reference_speed_mps + )[:, None]**2).T + force = -drag[:, None] * velocity / np.maximum(speed, 1e-6)[:, None] + force[:, 2] -= downforce + moment = np.column_stack((mx, my, mz)) + np.cross(self.reference_m, force) + return force, moment diff --git a/engines/dynpy/jacobian.py b/engines/dynpy/jacobian.py new file mode 100644 index 0000000..203cd9c --- /dev/null +++ b/engines/dynpy/jacobian.py @@ -0,0 +1,80 @@ +"""Forward-difference Jacobians whose columns can be evaluated as one batch.""" + +from __future__ import annotations + +import warnings +from collections.abc import Callable, Sequence + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +FloatArray = NDArray[np.float64] + +# SciPy's 2-point step: sqrt(machine epsilon), the default SLSQP ``eps``. +_STEP = float(np.finfo(np.float64).eps ** 0.5) + + +def forward_difference_jacobian( + fun: Callable[[FloatArray], ArrayLike], x0: ArrayLike, lower: ArrayLike, upper: ArrayLike, *, + prefetch: Callable[[Sequence[FloatArray]], None] | None = None, +) -> FloatArray: + """## Forward-Difference Jacobian + + The Jacobian SLSQP builds for a constraint that has no ``jac``: SciPy's + ``approx_derivative(fun, x0, method="2-point", abs_step=sqrt(eps), + bounds=(lower, upper))`` after the same clip to bounds. The steps and + quotients are reproduced exactly, so the result is bit for bit the same. + The difference is ``prefetch``: it receives every point before ``fun`` + is called at any of them, so a caller can evaluate the expensive part of + all columns at once and let ``fun`` read the results from a cache. + + Parameters + ---------- + fun : callable + Vector function of the unknowns. + x0 : ArrayLike + Point at which to differentiate. + lower, upper : ArrayLike + Bounds on the unknowns. Steps turn or shrink to stay inside them. + prefetch : callable or None + Called once with ``[x0, x0 + h_0 e_0, ...]`` before any ``fun`` call. + + Returns + ------- + FloatArray + ``(m, n)`` Jacobian of the ``m`` outputs by the ``n`` unknowns. + """ + x = np.array(x0, dtype=float) + low = np.broadcast_to(np.asarray(lower, dtype=float), x.shape) + high = np.broadcast_to(np.asarray(upper, dtype=float), x.shape) + if np.any(x < low) or np.any(x > high): + warnings.warn("Values in x were outside bounds during a minimize step, clipping to bounds", + RuntimeWarning, stacklevel=2) + x = np.clip(x, low, high) + sign = (x >= 0).astype(float) * 2 - 1 + step = np.full(x.shape, _STEP) + # A step lost to rounding falls back to one relative to |x|. + step = np.where((x + step) - x == 0, _STEP * sign * np.maximum(1.0, np.abs(x)), step) + if not np.all((low == -np.inf) & (high == np.inf)): + lower_room, upper_room = x - low, high - x + outside = (x + step < low) | (x + step > high) + fits = np.abs(step) <= np.maximum(lower_room, upper_room) + step[outside & fits] *= -1 + forward = (upper_room >= lower_room) & ~fits + step[forward] = upper_room[forward] + backward = (upper_room < lower_room) & ~fits + step[backward] = -lower_room[backward] + points = [] + for index in range(x.size): + point = x.copy() + point[index] = x[index] + step[index] + points.append(point) + if prefetch is not None: + prefetch([x, *points]) + f0 = np.atleast_1d(np.asarray(fun(x), dtype=float)) + jacobian = np.empty((x.size, f0.size)) + for index, point in enumerate(points): + jacobian[index] = (np.atleast_1d(np.asarray(fun(point), dtype=float)) - f0) / ( + (x[index] + step[index]) - x[index] + ) + return jacobian.T diff --git a/engines/dynpy/models.py b/engines/dynpy/models.py index 8782ba6..fa87c45 100644 --- a/engines/dynpy/models.py +++ b/engines/dynpy/models.py @@ -19,6 +19,7 @@ from __future__ import annotations from abc import ABC, abstractmethod +from collections.abc import Sequence from dataclasses import dataclass, field from typing import ClassVar, Literal @@ -407,6 +408,50 @@ def evaluate( self._last_output = output return output + def evaluate_batch( + self, states: ArrayLike, inputs: Sequence[ModelInputs], *, + normal_loads_n: ArrayLike | None = None, + algebraic_slips: ArrayLike | None = None, + ) -> list[ModelOutput]: + """## Batched Force Evaluation + + Evaluate many independent points, such as the columns of a + finite-difference Jacobian, in one call. Fidelities that vectorize a + case override this; the rest evaluate each point in turn. + + Parameters + ---------- + states : ArrayLike + One state per row, shape ``(n, state_size)``. + inputs : Sequence[ModelInputs] + One input set per row. + normal_loads_n, algebraic_slips : ArrayLike or None + Trial loads and slips per row, shape ``(n, 4)``, as in ``evaluate``. + + Returns + ------- + list[ModelOutput] + ``[evaluate(state, inputs, ...) for each row]``, to rounding. + + Raises + ------ + ValueError, RuntimeError + Any row that ``evaluate`` would reject. + """ + x = np.asarray(states, dtype=float) + if x.ndim != 2 or len(inputs) != len(x): + raise ValueError("Batched states need shape (n, state_size) and one ModelInputs per row.") + loads = None if normal_loads_n is None else np.asarray(normal_loads_n, dtype=float) + slips = None if algebraic_slips is None else np.asarray(algebraic_slips, dtype=float) + return [ + self.evaluate( + state, row_inputs, + normal_loads_n=None if loads is None else loads[row], + algebraic_slips=None if slips is None else slips[row], + ) + for row, (state, row_inputs) in enumerate(zip(x, inputs, strict=True)) + ] + def algebraic_residual(self, inputs: ModelInputs, output: ModelOutput) -> FloatArray: """## Algebraic Force Balance @@ -837,6 +882,203 @@ def _body_state( ) return body_coordinates, body_velocities + def evaluate_batch( + self, states: ArrayLike, inputs: Sequence[ModelInputs], *, + normal_loads_n: ArrayLike | None = None, + algebraic_slips: ArrayLike | None = None, + ) -> list[ModelOutput]: + """## Batched Planar QSS Evaluation + + Vectorizes the QSS case, where trial loads and slips are both given and + no inner load or slip iteration runs. Every other case, and the 6DOF + and higher subclasses, evaluate row by row. See the base method. + """ + if self.dof != 3 or normal_loads_n is None or algebraic_slips is None: + return VehicleDynamicsSystem.evaluate_batch( + self, states, inputs, normal_loads_n=normal_loads_n, algebraic_slips=algebraic_slips, + ) + return self._evaluate_planar_qss_batch( + np.asarray(states, dtype=float), inputs, + np.asarray(normal_loads_n, dtype=float), np.asarray(algebraic_slips, dtype=float), + ) + + def _evaluate_planar_qss_batch( + self, x: FloatArray, inputs: Sequence[ModelInputs], loads: FloatArray, slips: FloatArray, + ) -> list[ModelOutput]: + """Row-for-row vectorization of ``evaluate`` with trial loads and slips. + + Each step mirrors the scalar path and its 3DOF hooks; the batch test + holds the two together. + """ + rows = len(x) + if (x.shape != (rows, self.state_size) or len(inputs) != rows + or loads.shape != (rows, 4) or slips.shape != (rows, 4)): + raise ValueError("Batched 3DOF QSS needs (n, 6) states, n inputs and (n, 4) loads and slips.") + if not np.all(np.isfinite(x)): + raise ValueError("Vehicle state contains non-finite values.") + if not np.all(np.isfinite(loads)) or np.any(loads < 0.0): + raise ValueError("Trial loads require four nonnegative finite values in 3/6/10 DOF.") + if not np.all(np.isfinite(slips)): + raise ValueError("Trial slips require four finite values in 3/6 DOF.") + p = self.parameters + coordinates, velocities = x[:, :3], x[:, 3:] + zeros = np.zeros(rows) + body_coordinates = np.column_stack((coordinates[:, 0], coordinates[:, 1], zeros, zeros, zeros, + coordinates[:, 2])) + body_velocities = np.column_stack((velocities[:, 0], velocities[:, 1], zeros, zeros, zeros, + velocities[:, 2])) + rotation = _body_to_world_rotation_batch(body_coordinates[:, 3:6]) + + # _vertical_forces: weight, the aero wrench and its off-centerline roll moment. + aero_force, aero_moment = self._aero_load_batch(body_velocities, body_coordinates, rotation) + positions = p.corner_positions + front_x = float(np.mean(positions[:2, 0])) + rear_x = float(np.mean(positions[2:, 0])) + downforce = -aero_force[:, 2] + front_aero = (-rear_x * downforce + aero_moment[:, 1]) / (front_x - rear_x) + rear_aero = downforce - front_aero + suspension_forces = np.asarray(p.static_wheel_loads_n, dtype=float) + np.column_stack( + (front_aero / 2.0, front_aero / 2.0, rear_aero / 2.0, rear_aero / 2.0) + ) + front_share = self._front_roll_stiffness_fraction() + # Stacked matmul reproduces the scalar path's BLAS dot products bit for bit. + roll = aero_moment[:, 0] + (positions[:, 1] @ suspension_forces[:, :, None])[:, 0] + front_left = -front_share * roll / p.track_front_m + rear_left = -(1.0 - front_share) * roll / p.track_rear_m + suspension_forces += np.column_stack((front_left, -front_left, rear_left, -rear_left)) + roll_basis = self._roll_moment_load_transfer(1.0, front_share) + + evaluator = p.kinematics + states_by_rack: dict[float, VehicleKinematicState] = {} + kinematics = [] + for row_inputs in inputs: + rack = row_inputs.rack_displacement_m + if rack is None: + rack = evaluator.rack_from_steering(row_inputs.steering_rad) + if rack not in states_by_rack: + states_by_rack[rack] = evaluator.at(np.zeros(4), rack) + kinematics.append(states_by_rack[rack]) + offsets = np.stack([k.contact_patch_offsets_m for k in kinematics]) + steering = np.stack([k.toe_rad for k in kinematics]) + camber = np.stack([k.camber_rad for k in kinematics]) + corner_positions = positions + offsets + # 3DOF jounce speed is zero, so articulation adds no contact-patch velocity. + corner_velocities = body_velocities[:, None, :3] + np.cross(body_velocities[:, None, 3:6], corner_positions) + cos_delta, sin_delta = np.cos(steering), np.sin(steering) + wheel_longitudinal_speed = corner_velocities[..., 0] * cos_delta + corner_velocities[..., 1] * sin_delta + wheel_lateral_speed = -corner_velocities[..., 0] * sin_delta + corner_velocities[..., 1] * cos_delta + slip_angles = -np.arctan2(wheel_lateral_speed, np.maximum(np.abs(wheel_longitudinal_speed), 0.25)) + + # _tire_wrench with prescribed slip. + fx_tire, fy_tire = np.empty((rows, 4)), np.empty((rows, 4)) + tire_moments = np.empty((rows, 4, 3)) + radii = np.asarray(p.wheel_radius_m, dtype=float) + for axle, tire in enumerate((p.front_tire, p.rear_tire)): + corners = slice(2 * axle, 2 * axle + 2) + speed = wheel_longitudinal_speed[:, corners] + my_zero = tire.rolling_moment(loads[:, corners], 0.0, speed) + my_slope = tire.rolling_moment(loads[:, corners], 1.0, speed) - my_zero + if np.any(radii[corners] - my_slope <= 0): + raise ValueError("Tire rolling moment gives a nonpositive wheel torque lever.") + fx_tire[:, corners], fy_tire[:, corners], mx, my, mz = tire.evaluate( + loads[:, corners], slip_angles[:, corners], slips[:, corners], camber[:, corners], speed, + ) + tire_moments[:, corners] = np.stack((mx, my, mz), axis=-1) + wheel_moments_body = np.stack(( + tire_moments[..., 0] * cos_delta - tire_moments[..., 1] * sin_delta, + tire_moments[..., 0] * sin_delta + tire_moments[..., 1] * cos_delta, + tire_moments[..., 2], + ), axis=-1) + fx_body = fx_tire * cos_delta - fy_tire * sin_delta + fy_body = fx_tire * sin_delta + fy_tire * cos_delta + + # _algebraic_load_transfer: planar pitch and roll closure at the moved contact patches. + wheelbase = np.mean(corner_positions[:, :2, 0], axis=1) - np.mean(corner_positions[:, 2:, 0], axis=1) + pitch_moment = np.sum(corner_positions[..., 2] * fx_body + wheel_moments_body[..., 1], axis=1) + roll_moment = np.sum(-corner_positions[..., 2] * fy_body + wheel_moments_body[..., 0], axis=1) + offset = corner_positions - positions + pitch_moment -= (offset[:, None, :, 0] @ suspension_forces[:, :, None])[:, 0, 0] + roll_moment += (offset[:, None, :, 1] @ suspension_forces[:, :, None])[:, 0, 0] + pitch_basis = np.array([0.5, 0.5, -0.5, -0.5]) / wheelbase[:, None] + roll_bases = np.tile(roll_basis, (rows, 1)) + roll_bases[:, :2] *= (p.track_front_m / (corner_positions[:, 0, 1] - corner_positions[:, 1, 1]))[:, None] + roll_bases[:, 2:] *= (p.track_rear_m / (corner_positions[:, 2, 1] - corner_positions[:, 3, 1]))[:, None] + basis = np.stack((pitch_basis, roll_bases), axis=-1) + moments = np.concatenate(( + corner_positions[:, None, :, 1] @ basis, -corner_positions[:, None, :, 0] @ basis, + ), axis=1) + reactions = np.linalg.solve(moments, np.column_stack((-roll_moment, -pitch_moment))[..., None]) + algebraic_load_transfer = (basis @ reactions)[..., 0] + + wheel_forces_body = np.stack((fx_body, fy_body, loads), axis=-1) + gravity_body = (rotation.transpose(0, 2, 1) @ np.array([0.0, 0.0, -p.mass_kg * G])) + body_force = np.sum(wheel_forces_body, axis=1) + gravity_body + aero_force + body_moment = ( + np.sum(np.cross(corner_positions, wheel_forces_body) + wheel_moments_body, axis=1) + aero_moment + ) + omega = body_velocities[:, 3:6] + body_linear_accel = body_force / p.mass_kg - np.cross(omega, body_velocities[:, :3]) + inertia = p.inertia + body_angular_accel = np.linalg.solve( + inertia, (body_moment - np.cross(omega, (inertia @ omega[..., None])[..., 0]))[..., None], + )[..., 0] + generalized_acceleration = np.column_stack(( + body_linear_accel[:, 0], body_linear_accel[:, 1], body_angular_accel[:, 2], + )) + yaw = coordinates[:, 2] + coordinate_derivative = np.column_stack(( + np.cos(yaw) * velocities[:, 0] - np.sin(yaw) * velocities[:, 1], + np.sin(yaw) * velocities[:, 0] + np.cos(yaw) * velocities[:, 1], + velocities[:, 2], + )) + derivative = np.concatenate((coordinate_derivative, generalized_acceleration), axis=1) + zero_corners = np.zeros(4) + outputs = [ + ModelOutput( + derivative=derivative[row], + generalized_acceleration=generalized_acceleration[row], + body_force_n=body_force[row], + body_moment_nm=body_moment[row], + wheel_forces_body_n=wheel_forces_body[row], + wheel_moments_tire_nm=tire_moments[row], + wheel_moments_body_nm=wheel_moments_body[row], + normal_loads_n=loads[row].copy(), + slip_angles_rad=slip_angles[row], + slip_ratios=slips[row].copy(), + suspension_forces_n=suspension_forces[row], + geometric_vertical_forces_n=zero_corners.copy(), + algebraic_load_transfer_n=algebraic_load_transfer[row], + jounce_m=state.jounce_m, + jounce_speed_mps=zero_corners.copy(), + contact_patch_positions_body_m=corner_positions[row], + contact_patch_tangents=state.contact_patch_tangents, + wheel_center_offsets_m=state.wheel_center_offsets_m, + camber_rad=state.camber_rad, + toe_rad=state.toe_rad, + caster_rad=state.caster_rad, + kpi_rad=state.kpi_rad, + mechanical_trail_m=state.mechanical_trail_m, + scrub_radius_m=state.scrub_radius_m, + instant_link_coefficients=state.instant_links.coefficient_matrix, + ) + for row, state in enumerate(kinematics) + ] + if outputs: + self._last_output = outputs[-1] + return outputs + + def _aero_load_batch( + self, body_velocities: FloatArray, body_coordinates: FloatArray, rotation: FloatArray, + ) -> tuple[FloatArray, FloatArray]: + """Row-wise ``_aero_load`` for stacked states and their rotations.""" + aero = self.parameters.aero + rows = len(body_velocities) + if aero is None: + return np.zeros((rows, 3)), np.zeros((rows, 3)) + heights = (aero.nominal_cg_height_m + body_coordinates[:, 2:3] + + (rotation @ aero.height_points_m.T)[:, 2]) + return aero.wrench_batch(heights, body_velocities[:, :3], self.parameters.rho_air_kg_m3) + def _vertical_forces( self, @@ -1410,3 +1652,16 @@ def _euler_rates(roll: float, pitch: float, body_rates: FloatArray) -> FloatArra ] ) return transform @ body_rates + + +def _body_to_world_rotation_batch(euler_rad: FloatArray) -> FloatArray: + """Row-wise ``_body_to_world_rotation`` for an ``(n, 3)`` array of roll, pitch, yaw.""" + roll, pitch, yaw = euler_rad[:, 0], euler_rad[:, 1], euler_rad[:, 2] + cr, sr = np.cos(roll), np.sin(roll) + cp, sp = np.cos(pitch), np.sin(pitch) + cy, sy = np.cos(yaw), np.sin(yaw) + return np.stack(( + np.stack((cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr), axis=-1), + np.stack((sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr), axis=-1), + np.stack((-sp, cp * sr, cp * cr), axis=-1), + ), axis=1) diff --git a/engines/dynpy/qss.py b/engines/dynpy/qss.py index 8359c70..cec4eeb 100644 --- a/engines/dynpy/qss.py +++ b/engines/dynpy/qss.py @@ -3,7 +3,7 @@ from __future__ import annotations from dataclasses import dataclass, replace -from typing import Literal, Mapping +from typing import Literal, Mapping, Sequence import numpy as np from numpy.typing import NDArray @@ -656,6 +656,23 @@ def _algebraic_slip_slopes(model: ReducedVehicleModel, output: ModelOutput) -> F return slopes + +def _algebraic_slip_slopes_batch(model: ReducedVehicleModel, outputs: Sequence[ModelOutput]) -> FloatArray: + """Row-wise ``_algebraic_slip_slopes`` for many outputs in one tire call per axle.""" + loads = np.array([output.normal_loads_n for output in outputs]) + alphas = np.array([output.slip_angles_rad for output in outputs]) + slips = np.array([output.slip_ratios for output in outputs]) + cambers = np.array([output.camber_rad for output in outputs]) + slopes = np.empty((len(outputs), 4)) + for axle, tire in enumerate((model.parameters.front_tire, model.parameters.rear_tire)): + corners = slice(2 * axle, 2 * axle + 2) + fx = tire.forces( + loads[:, corners, None], alphas[:, corners, None], + slips[:, corners, None] + np.array([-1e-5, 1e-5]), cambers[:, corners, None], + )[0] + slopes[:, corners] = (fx[..., 1] - fx[..., 0]) / 2e-5 + return slopes + def _tire_state_error( model: ReducedVehicleModel, inputs: ModelInputs, output: ModelOutput, ) -> str: diff --git a/simulations/envelope/ggv/ggv_generation.py b/simulations/envelope/ggv/ggv_generation.py index 6856273..74cac37 100644 --- a/simulations/envelope/ggv/ggv_generation.py +++ b/simulations/envelope/ggv/ggv_generation.py @@ -3,13 +3,13 @@ from __future__ import annotations import csv +from collections import OrderedDict +from collections.abc import Callable, Sequence from dataclasses import dataclass, replace -from functools import lru_cache from datetime import datetime import os from common.vehicle_io import repo_root from pathlib import Path -from collections.abc import Callable, Sequence from typing import Any, Literal, Mapping, cast os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib") @@ -22,11 +22,12 @@ from scipy.optimize import minimize from engines.dynpy.models import DOFModel, ModelInputs, ModelOutput, ReducedVehicleModel +from engines.dynpy.jacobian import forward_difference_jacobian from engines.dynpy.vector import cross from engines.dynpy.qss import ( QSSResult, solve_acceleration_trim, _algebraic_residual, _trim_state_and_inputs, _generalized_acceleration_target, _residual_scales, - _tire_state_error, _algebraic_slip_slopes, + _tire_state_error, _algebraic_slip_slopes, _algebraic_slip_slopes_batch, ) @@ -757,19 +758,51 @@ def _solve_envelope_limit( guess = np.array([seed.get(name, coast if name == "path_ax_mps2" else 0.) for name in names]) / scale_array guess = np.clip(guess, np.array(bounds)[:, 0], np.array(bounds)[:, 1]) - @lru_cache(maxsize=256) - def evaluate(values: tuple[float, ...]): + def trial(values: tuple[float, ...]) -> tuple[FloatArray, ModelInputs, FloatArray | None, FloatArray | None]: physical = np.asarray(values) * scale_array lateral = float(physical[-1]) if mode == "lateral" else ay state, inputs = _trim_state_and_inputs( model, physical[:model.dof], speed_mps=speed, yaw_rate_radps=lateral / speed, rack_input=True, ) - output = model.evaluate( - state, inputs, - normal_loads_n=physical[model.dof:model.dof + 4] if model.dof < 14 else None, - algebraic_slips=physical[model.dof + 4:model.dof + 8] if model.dof < 10 else None, - ) - return state, inputs, output + return (state, inputs, physical[model.dof:model.dof + 4] if model.dof < 14 else None, + physical[model.dof + 4:model.dof + 8] if model.dof < 10 else None) + + # Model evaluations shared by the objective, both constraints and their Jacobians. + evaluated: OrderedDict[tuple[float, ...], tuple[FloatArray, ModelInputs, ModelOutput]] = OrderedDict() + batched_slopes: dict[tuple[float, ...], FloatArray] = {} + + def remember(key: tuple[float, ...], value: tuple[FloatArray, ModelInputs, ModelOutput]) -> None: + evaluated[key] = value + if len(evaluated) > 256: + batched_slopes.pop(evaluated.popitem(last=False)[0], None) + + def evaluate(values: tuple[float, ...]) -> tuple[FloatArray, ModelInputs, ModelOutput]: + if values in evaluated: + evaluated.move_to_end(values) + return evaluated[values] + state, inputs, loads, slips = trial(values) + result = state, inputs, model.evaluate(state, inputs, normal_loads_n=loads, algebraic_slips=slips) + remember(values, result) + return result + + def prefetch(points: Sequence[FloatArray]) -> None: + # Evaluate a Jacobian's columns in one batch; constraints then read them from the cache. + keys = list(dict.fromkeys(key for key in map(tuple, points) if key not in evaluated)) + if len(keys) < 2: + return + trials = [trial(key) for key in keys] + try: + outputs = model.evaluate_batch( + np.array([row[0] for row in trials]), [row[1] for row in trials], + normal_loads_n=None if trials[0][2] is None else np.array([row[2] for row in trials]), + algebraic_slips=None if trials[0][3] is None else np.array([row[3] for row in trials]), + ) + except (ValueError, RuntimeError): + return # The scalar path reports the rejected point when the solver reaches it. + for key, row, output in zip(keys, trials, outputs, strict=True): + remember(key, (row[0], row[1], output)) + if model.dof < 10: + batched_slopes.update(zip(keys, _algebraic_slip_slopes_batch(model, outputs))) def equality(values: FloatArray) -> FloatArray: state, inputs, output = evaluate(tuple(values)) @@ -796,7 +829,8 @@ def inequality(values: FloatArray) -> FloatArray: slip - tire.coefficients["KPUMIN"] - 1e-9, tire.coefficients["KPUMAX"] - slip - 1e-9)) if model.dof < 10: - constraints.extend(_algebraic_slip_slopes(model, output) / force_scale) + slopes = batched_slopes.get(tuple(values)) + constraints.extend((_algebraic_slip_slopes(model, output) if slopes is None else slopes) / force_scale) if model.dof == 14: for load, tire in zip(output.normal_loads_n, model.parameters.tires): constraints.append((load - max(1e-6, load_fraction * tire.fz_min_n)) / force_scale) @@ -807,6 +841,16 @@ def inequality(values: FloatArray) -> FloatArray: def objective(values: FloatArray) -> float: return float(values[-1]) * (1. if mode == "brake" else -np.sign(ay) if mode == "lateral" else -1.) + def constraint_specs(active_bounds: Sequence[tuple[float, float]]) -> list[dict[str, Any]]: + # SLSQP's own finite differences, with each Jacobian's model calls batched. + lower, upper = np.asarray(active_bounds, dtype=float).T + + def jacobian(fun: Callable[[FloatArray], FloatArray]) -> Callable[[FloatArray], FloatArray]: + return lambda values: forward_difference_jacobian(fun, values, lower, upper, prefetch=prefetch) + + return [{"type": "eq", "fun": equality, "jac": jacobian(equality)}, + {"type": "ineq", "fun": inequality, "jac": jacobian(inequality)}] + for attempt in range(2 if initial_unknowns is not None else 1): if attempt: # Back off a tire peak only when direct continuation fails. @@ -815,8 +859,7 @@ def objective(values: FloatArray) -> float: if name.startswith("slip_"): guess[index] *= .9 result = minimize( # type: ignore[call-overload] - objective, guess, method="SLSQP", bounds=bounds, - constraints=[{"type": "eq", "fun": equality}, {"type": "ineq", "fun": inequality}], + objective, guess, method="SLSQP", bounds=bounds, constraints=constraint_specs(bounds), options={"ftol": 1e-9, "maxiter": 100}, ) if not result.success and mode == "lateral" and initial_unknowns is None: @@ -832,8 +875,7 @@ def objective(values: FloatArray) -> float: # Avoid zero-load stagnation while retaining strict equilibrium checks. interior = minimize( # type: ignore[call-overload] objective, load_guess, method="SLSQP", bounds=seed_bounds, - constraints=[{"type": "eq", "fun": equality}, {"type": "ineq", "fun": inequality}], - options={"ftol": 1e-7, "maxiter": 100}, + constraints=constraint_specs(seed_bounds), options={"ftol": 1e-7, "maxiter": 100}, ) if (not interior.success or not np.all(np.isfinite(interior.x)) or not np.linalg.norm(equality(interior.x)) <= 1e-5 diff --git a/tests/test_dynpy_batch.py b/tests/test_dynpy_batch.py new file mode 100644 index 0000000..c0fdc6e --- /dev/null +++ b/tests/test_dynpy_batch.py @@ -0,0 +1,238 @@ +"""Batched model evaluation and the batched Jacobians the GGV solver builds from it.""" + +from dataclasses import replace +import warnings + +import numpy as np +import pytest +from scipy.optimize._numdiff import approx_derivative + +from engines.dynpy import Vehicle +from engines.dynpy.jacobian import forward_difference_jacobian +from engines.dynpy.models import ModelOutput, create_model +from engines.dynpy.qss import _algebraic_slip_slopes, _algebraic_slip_slopes_batch, _trim_state_and_inputs +import simulations.envelope.ggv.ggv_generation as ggv +from simulations.envelope.vehicle_yaml import load_vehicle_yaml, project_vehicle_yaml + +# Batched rows must match the scalar model to rounding. In practice they are bit +# for bit equal; the tolerance only leaves room for a different CPU's SIMD paths. +RTOL, ATOL = 1e-12, 1e-9 + + +@pytest.fixture(scope="module") +def vehicle(): + return Vehicle.from_yaml() + + +def _qss_rows(model, rows, *, seed=0, shared_rack=False): + """Trial QSS points like a GGV solve visits: random sideslip, steer, yaw rate, loads and slips.""" + rng = np.random.default_rng(seed) + static = np.asarray(model.parameters.static_wheel_loads_n) + states, inputs, loads, slips = [], [], [], [] + rack = rng.normal(0., .01) + for _ in range(rows): + values = np.r_[rng.normal(0., .05), rack if shared_rack else rng.normal(0., .01), 0., np.zeros(model.dof - 3)] + state, row_inputs = _trim_state_and_inputs( + model, values[:model.dof], speed_mps=rng.uniform(4., 30.), yaw_rate_radps=rng.normal(0., .5), + rack_input=True, + ) + state[2] = rng.uniform(-np.pi, np.pi) if model.dof == 3 else state[2] + states.append(state) + inputs.append(replace(row_inputs, wheel_torques_nm=tuple(rng.normal(0., 100., 4)))) + loads.append(static * rng.uniform(.2, 1.8, 4)) + slips.append(rng.normal(0., .05, 4)) + return np.array(states), inputs, np.array(loads), np.array(slips) + + +def _assert_outputs_match(batch: list[ModelOutput], reference: list[ModelOutput]) -> None: + assert len(batch) == len(reference) + for row, expected in zip(batch, reference, strict=True): + for name in ModelOutput.__dataclass_fields__: + np.testing.assert_allclose(getattr(row, name), getattr(expected, name), rtol=RTOL, atol=ATOL, + err_msg=name) + + +@pytest.mark.parametrize("shared_rack", (False, True)) +def test_planar_qss_batch_matches_scalar_rows(vehicle, shared_rack): + model = vehicle.model(3) + states, inputs, loads, slips = _qss_rows(model, 24, shared_rack=shared_rack) + batch = model.evaluate_batch(states, inputs, normal_loads_n=loads, algebraic_slips=slips) + reference = [model.evaluate(s, i, normal_loads_n=n, algebraic_slips=k) + for s, i, n, k in zip(states, inputs, loads, slips, strict=True)] + _assert_outputs_match(batch, reference) + + +def test_planar_qss_batch_covers_steering_input_unloaded_corners_and_no_aero(vehicle): + model = vehicle.model(3) + states, inputs, loads, slips = _qss_rows(model, 6, seed=1) + # Steering instead of rack, one corner off the ground and one exactly on it. + inputs = [replace(row, rack_displacement_m=None, steering_rad=.03 * k) for k, row in enumerate(inputs)] + loads[0, 3], loads[1, 2] = 0., 1e-9 + for candidate in (model, create_model(3, replace(model.parameters, aero=None))): + batch = candidate.evaluate_batch(states, inputs, normal_loads_n=loads, algebraic_slips=slips) + reference = [candidate.evaluate(s, i, normal_loads_n=n, algebraic_slips=k) + for s, i, n, k in zip(states, inputs, loads, slips, strict=True)] + _assert_outputs_match(batch, reference) + + +@pytest.mark.parametrize("dof", (6, 10, 14)) +def test_other_fidelities_batch_by_rows(vehicle, dof): + model = vehicle.model(dof) + states, inputs, loads, slips = _qss_rows(model, 3, seed=2) + kwargs = {"normal_loads_n": loads if dof < 14 else None, "algebraic_slips": slips if dof < 10 else None} + batch = model.evaluate_batch(states, inputs, **kwargs) + reference = [model.evaluate(s, i, normal_loads_n=kwargs["normal_loads_n"][r] if dof < 14 else None, + algebraic_slips=slips[r] if dof < 10 else None) + for r, (s, i) in enumerate(zip(states, inputs, strict=True))] + _assert_outputs_match(batch, reference) + + +def test_row_by_row_batch_rejects_mismatched_rows(vehicle): + model = vehicle.model(6) + states, inputs, loads, _ = _qss_rows(model, 3, seed=2) + with pytest.raises(ValueError): + model.evaluate_batch(states, inputs[:2], normal_loads_n=loads) + + +def test_planar_batch_without_trial_values_uses_the_scalar_path(vehicle, monkeypatch): + model = vehicle.model(3) + states, inputs, loads, _ = _qss_rows(model, 2, seed=3) + calls = [] + original = type(model).evaluate + + def counted(self, *args, **kwargs): + calls.append(kwargs.get("algebraic_slips")) + return original(self, *args, **kwargs) + + monkeypatch.setattr(type(model), "evaluate", counted) + model.evaluate_batch(states, inputs, normal_loads_n=loads) + assert calls == [None, None] + + +@pytest.mark.parametrize("change", ("negative_load", "nonfinite_slip", "nonfinite_state", "shape", "inputs")) +def test_planar_batch_rejects_what_the_scalar_model_rejects(vehicle, change): + model = vehicle.model(3) + states, inputs, loads, slips = _qss_rows(model, 3, seed=4) + if change == "negative_load": + loads[1, 0] = -1. + elif change == "nonfinite_slip": + slips[2, 3] = np.nan + elif change == "nonfinite_state": + states[0, 4] = np.inf + elif change == "shape": + loads = loads[:, :3] + else: + inputs = inputs[:2] + with pytest.raises(ValueError): + model.evaluate_batch(states, inputs, normal_loads_n=loads, algebraic_slips=slips) + + +def test_aero_wrench_batch_matches_rows(vehicle): + aero = vehicle.model(3).parameters.aero + assert aero is not None + rng = np.random.default_rng(5) + # Heights inside, below and above the CFD grids exercise the clamped brackets. + span = (min(aero.front_grid[0], aero.rear_grid[0]) - .05, max(aero.front_grid[-1], aero.rear_grid[-1]) + .05) + heights = rng.uniform(*span, (40, 4)) + velocity = rng.normal(0., 15., (40, 3)) + velocity[0] = 0. + force, moment = aero.wrench_batch(heights, velocity, 1.1) + for row in range(40): + expected = aero.wrench(heights[row], velocity[row], 1.1) + np.testing.assert_allclose(force[row], expected[0], rtol=RTOL, atol=ATOL) + np.testing.assert_allclose(moment[row], expected[1], rtol=RTOL, atol=ATOL) + + +def test_slip_slopes_batch_matches_rows(vehicle): + model = vehicle.model(3) + states, inputs, loads, slips = _qss_rows(model, 8, seed=6) + outputs = model.evaluate_batch(states, inputs, normal_loads_n=loads, algebraic_slips=slips) + np.testing.assert_allclose(_algebraic_slip_slopes_batch(model, outputs), + [_algebraic_slip_slopes(model, output) for output in outputs], rtol=RTOL, atol=ATOL) + + +def _vector_function(x): + return np.array([np.sin(x[0]) * x[1], x[1] ** 3 - x[2], np.exp(.3 * x[2]) + x[0] * x[2]]) + + +@pytest.mark.parametrize("x0, lower, upper", [ + ((.3, -1.2, 2.), (-np.inf,) * 3, (np.inf,) * 3), + ((.3, -1.2, 2.), (-1., -2., -3.), (1., 2., 3.)), + # On an upper bound: the step turns around. On a lower bound: it stays forward. + ((1., -2., 0.), (-1., -2., -3.), (1., 2., 3.)), + # A box narrower than the step: forward or backward to the wider side. + ((.5, 1.5e-9, 1e3), (.5 - 1e-10, 0., 1e3 - 1.), (.5 + 3e-10, 2e-9, 1e3)), + ((0., -0., 1e-300), (-np.inf, -1., 0.), (np.inf, 1., 1.)), +]) +def test_forward_difference_matches_scipy_slsqp_jacobian(x0, lower, upper): + x0 = np.asarray(x0, dtype=float) + expected = approx_derivative(_vector_function, x0, method="2-point", abs_step=np.finfo(float).eps ** .5, + bounds=(np.asarray(lower), np.asarray(upper))) + np.testing.assert_array_equal(forward_difference_jacobian(_vector_function, x0, lower, upper), expected) + + +def test_forward_difference_prefetches_every_point_first_and_clips_like_slsqp(): + events = [] + + def fun(x): + events.append(("call", tuple(x))) + return _vector_function(x) + + with pytest.warns(RuntimeWarning, match="outside bounds"): + jacobian = forward_difference_jacobian(fun, [2., 0., 0.], -np.ones(3), np.ones(3), + prefetch=lambda points: events.append(("batch", [*map(tuple, points)]))) + # One batch of the clipped point and its three steps, then fun at exactly those points. + kind, batch = events[0] + assert kind == "batch" and batch[0] == (1., 0., 0.) and len(batch) == 4 + assert events[1:] == [("call", point) for point in batch] + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + expected = approx_derivative(_vector_function, np.array([1., 0., 0.]), method="2-point", + abs_step=np.finfo(float).eps ** .5, bounds=(-np.ones(3), np.ones(3))) + np.testing.assert_array_equal(jacobian, expected) + + +@pytest.mark.parametrize("mode, ay", (("drive", 8.), ("brake", 15.), ("lateral", 30.))) +def test_ggv_boundary_is_unchanged_by_batched_jacobians(vehicle, monkeypatch, mode, ay): + model = vehicle.model(3) + arguments = dict(speed=15., ay=ay, ax_bounds=(-3.2 * ggv.G, 2.8 * ggv.G), mode=mode, + max_abs_beta_rad=.25, max_abs_steering_rad=.5, enforce_tire_load_range=True) + parameters = project_vehicle_yaml(load_vehicle_yaml()).ggv + batched = ggv._solve_envelope_limit(parameters, model, **arguments) + + def refuse(*args, **kwargs): + raise RuntimeError("no batch") + + # A rejected batch leaves every point to the scalar model, which is the unbatched solve. + monkeypatch.setattr(type(model), "evaluate_batch", refuse) + scalar = ggv._solve_envelope_limit(parameters, model, **arguments) + assert batched is not None and scalar is not None + assert batched.unknowns.keys() == scalar.unknowns.keys() + for name, value in scalar.unknowns.items(): + assert batched.unknowns[name] == pytest.approx(value, rel=1e-9, abs=1e-9), name + + +def test_ggv_jacobian_columns_reach_the_model_as_one_batch(vehicle, monkeypatch): + model = vehicle.model(3) + batches, scalar_calls = [], [] + batch, evaluate = type(model).evaluate_batch, type(model).evaluate + + def counted_batch(self, states, *args, **kwargs): + batches.append(len(states)) + return batch(self, states, *args, **kwargs) + + def counted_evaluate(self, *args, **kwargs): + scalar_calls.append(1) + return evaluate(self, *args, **kwargs) + + monkeypatch.setattr(type(model), "evaluate_batch", counted_batch) + monkeypatch.setattr(type(model), "evaluate", counted_evaluate) + result = ggv._solve_envelope_limit( + project_vehicle_yaml(load_vehicle_yaml()).ggv, model, speed=15., ay=8., ax_bounds=(-3.2 * ggv.G, 2.8 * ggv.G), + mode="drive", max_abs_beta_rad=.25, max_abs_steering_rad=.5, enforce_tire_load_range=True, + ) + assert result is not None + unknowns = len(result.unknowns) - 1 # steering_rad is reported, not solved. + assert batches and max(batches) == unknowns + # Each Jacobian costs one batch, not one model call per column. + assert len(scalar_calls) < sum(batches)