Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
8 changes: 8 additions & 0 deletions docs/reduced-order-dynamics.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions engines/dynpy/aero.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
80 changes: 80 additions & 0 deletions engines/dynpy/jacobian.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading