SplineTrajectoryAPI

API referenceAPI 文档

3 headers

Construction, evaluation and differentiation for minimum-control-effort trajectories. Interfaces are grouped by task; the three independent spline solvers share one reference below.最小控制量轨迹的构造、求值与梯度计算。按使用任务组织接口,三套独立样条实现的公共接口统一说明。

Durations · waypoints · boundaries时长 · 插值点 · 边界T, P, bc
→SplineBuild / update构造 / 更新→PPolyNDEvaluate / sample求值 / 采样↔Costs & gradients代价与梯度Optimizer · Hull

Quick start快速开始#

Requires C++17 and Eigen ≥ 3.3. Build the repository examples with CMake ≥ 3.12:需要 C++17、Eigen ≥ 3.3。使用 CMake ≥ 3.12 构建仓库示例:

git clone https://github.com/Bziyue/SplineTrajectory.git
cd SplineTrajectory
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
cmake --build build --parallel
./build/examples/trajectory_sampling
./build/examples/basic_optimizer

Repository / README · Build and CMake integration · Runnable examples代码仓库 · 中文 README · 构建与 CMake 集成 · 完整示例

SplineInput contains durations, waypoint rows and endpoint derivatives. spline.update(input) interpolates every waypoint. In optimization, the same values initialize the selected variables: the default mask allows durations and inner waypoints to change, while endpoints and boundary derivatives stay fixed.SplineInput 保存时长、途经点行和端点导数。spline.update(input) 插值所有途经点;用于优化时,同样的数据作为选中变量的初值。默认允许时长和内部途经点改变,端点位置与边界导数固定。

Build a trajectory and sample position, velocity and acceleration构造轨迹并采样位置、速度、加速度C++17
#include "SplineTrajectory.hpp"
#include <iostream>

int main() {
    using Spline = SplineTrajectory::QuinticSplineND<3>;
    SplineTrajectory::SplineInput<3> input;
    input.durations = {1.2, 1.5};
    input.waypoints.resize(3, 3);
    input.waypoints << 0, 0, 0,
                      1, 0.5, 0,
                      2, 0, 0;
    input.start_time = 2.0;
    // Endpoint velocity and acceleration default to zero.
    Spline spline;
    if (const auto status = spline.update(input); !status) {
        std::cerr << status.message << '\n';
        return 1;
    }

    auto trajectory = spline.copyPolynomial();
    auto sampler = trajectory.makeSampler<2>();
    for (int i = 0; i <= 10; ++i) {
        const double t = trajectory.startTime() + trajectory.duration() * i / 10.0;
        const auto pva = sampler.evaluateDerivatives(t);
        std::cout << t << " p: " << pva[0].transpose()
                  << " v: " << pva[1].transpose()
                  << " a: " << pva[2].transpose() << '\n';
    }
}

Times use the trajectory’s own axis: this example starts at 2 seconds. The copied polynomial owns its data; keep it alive while using its sampler. Next: optimize with L-BFGS and save the final trajectory, or choose a spline order.查询时间沿用轨迹时间轴:此例从第 2 秒开始。拷贝得到的多项式独立持有数据,使用 sampler 时保持它存活。下一步:接入 L-BFGS 并保存最终轨迹,或选择样条阶数。

Spline selection样条选型#

Type类型Degree / K次数 / KObjective最小化目标Clamped endpoints夹持端点导数
CubicSplineND<DIM> 3 / 4 ∫ ‖p″(t)‖² dt Velocity v速度 v
QuinticSplineND<DIM> 5 / 6 ∫ ‖p‴(t)‖² dt v, av, a
SepticSplineND<DIM> 7 / 8 ∫ ‖p⁽⁴⁾(t)‖² dt v, a, jv, a, j

N = segments, D / DIM = spatial dimension, K = coefficients per segment, M = query count, R = highest requested derivative. Spline means the selected solver. Vector, WaypointMatrix, CoefficientMatrix, Polynomial and Gradients are its public aliases. All library names are in SplineTrajectory.N 为段数,D / DIM 为空间维度,K 为每段系数数,M 为查询数,R 为最高查询导数阶数。Spline 代表选定样条类;Vector、WaypointMatrix、CoefficientMatrix、Polynomial、Gradients 是其公开类型别名。库类型均位于 SplineTrajectory 命名空间。

Common types, data & errors通用类型、数据与错误#

Type / data类型 / 数据Contract契约
Status code, static message, optional index (−1 if absent). ok() / bool tests success; Status::success() creates OK.包含 code、静态文本 message、可选 index(无位置时为 −1)。ok() / bool 判断成功,Status::success() 创建成功状态。
StatusOr<T> Owns a value or a failure; check success before value(). std::move(result).value() moves the result out.拥有值或错误;value() 前检查成功状态。std::move(result).value() 可移出结果。
ErrorCode Ok, InvalidInput, DimensionMismatch, InvalidState, OutOfRange, ResourceLimit, NumericalFailure, NotPrepared, SamplingNotPrepared, GradientMismatch
DerivativeOrderAccepts int or Deriv; defaults to position, supports equality. Supported orders are listed for each operation.接受 int 或 Deriv,默认位置阶,支持相等比较。各接口支持的阶数见对应说明。
Deriv Pos=0, Vel=1, Acc=2, Jerk=3, Snap=4, Crackle=5, Pop=6
Coordinates & storage坐标与存储 Times are physical seconds; coordinates and spatial units are caller-defined. Waypoints: (N+1) × D. Coefficients: (N·K) × D, piece-major and ascending local-time powers.时间为物理秒数;坐标系和空间单位由调用方定义。插值点为 (N+1) × D;系数为 (N·K) × D,先分段、段内按局部时间升幂排列。
Input preconditions输入前置条件 Use positive segment durations and one waypoint row per knot. Query values and gradients after a successful update.段时长为正,每个时间节点对应一行途经点。成功更新后即可查询数值和梯度。
Recoverable failures可恢复失败 Spline construction reports knot/factorization failures. Optimizer preparation/evaluation validates its boundary inputs and final cost/gradient; callbacks can explicitly reject. Failed evaluate() returns infinity and clears the output gradient.样条构造报告时间节点或分解失败。优化器在准备/求值边界验证输入与最终代价/梯度,并传播回调拒绝;失败的 evaluate() 返回无穷代价并清零输出梯度。
Lifetime & concurrency生命周期与并发 Borrowed segments/samplers require an alive, unchanged polynomial. Reacquire after update, assignment or move. Const queries may run concurrently; spline backward(), optimizer and hull workspaces require exclusive access.借用分段/采样器要求源多项式存活且不变;更新、赋值或移动后重新取得。const 查询可并发;样条 backward()、优化器和凸包工作区需独占访问。

Spline construction & gradients样条构造与梯度#

#include "SplineTrajectory.hpp"

The following signatures apply to CubicSplineND, QuinticSplineND and SepticSplineND. Declare an empty Spline spline;, then initialize it with update() and check success before querying. Subsequent updates reuse the same object.以下签名适用于 CubicSplineND、QuinticSplineND 与 SepticSplineND。先用 Spline spline; 声明空对象,再调用 update() 初始化,确认成功后进行查询;后续更新继续复用该对象。

Construction & in-place update构造与原位更新#

update(input)#

Build an interpolating spline from one input object. Use this form when the same data will also initialize an optimizer.用一个输入对象构造插值样条。同一份数据还可用于初始化优化器。

Status update(const SplineInput<DIM>& input);
input
Physical data: durations, waypoints, boundary and start_time.物理输入:durations、waypoints、boundary 和 start_time。

Returns返回Status — reports whether construction succeeded.报告构造是否成功。

Spline()#

Create an empty spline, then call update() to build its polynomial. Later updates reuse this object.创建空样条,再调用 update() 构造多项式;后续更新复用这个对象。

Spline();

update(durations, waypoints, start_time, boundary)#

Build the spline from separate duration, waypoint and boundary arguments.分别传入段时长、途经点和边界条件,构造样条。

Status update(
    const std::vector<double>& durations,
    const WaypointMatrix& waypoints,
    double start_time,
    const BoundaryConditions<DIM>& boundary = {});
durations
N positive segment durations, in seconds.N 个正的段时长,单位为秒。
waypoints
All waypoint rows, shaped (N+1) × DIM, including endpoints.全部途经点,形状为 (N+1) × DIM,包含两端点。
start_time
Start on the trajectory time axis, in seconds.轨迹时间轴上的起点,单位为秒。
boundary
Endpoint derivatives; omitted values are zero.端点导数;省略时各项为零。

Returns返回Status — reports whether construction succeeded.报告构造是否成功。

updateFromBreakpoints(knots, waypoints, boundary)#

Use this form when the time at every waypoint is already known. Adjacent knot differences become segment durations.已知每个途经点的到达时刻时使用;相邻时间节点之差就是段时长。

Status updateFromBreakpoints(
    const std::vector<double>& knots,
    const WaypointMatrix& waypoints,
    const BoundaryConditions<DIM>& boundary = {});
knots
N+1 strictly increasing trajectory times. The first is start_time.N+1 个严格递增的轨迹时刻,第一个时刻就是起点时间。
waypoints
All waypoint rows, shaped (N+1) × DIM, including endpoints.全部途经点,形状为 (N+1) × DIM,包含两端点。
boundary
Endpoint derivatives; omitted values are zero.端点导数;省略时各项为零。

Returns返回Status — reports whether construction succeeded.报告构造是否成功。

BoundaryConditions<DIM>#

Endpoint derivatives default to zero. Cubic uses v; quintic uses v and a; septic uses v, a and j. Endpoint positions are the first and last waypoint rows.端点导数默认零。三次使用 v,五次使用 v/a,七次使用 v/a/j。端点位置对应途经点矩阵的首行和末行。

BoundaryConditions<DIM> boundary;
boundary.start.v = start_velocity;
boundary.end.v = end_velocity;

Both update forms reuse fixed-topology storage and recompute coefficients/factors. Failure invalidates the polynomial but retains workspace for retry; any update invalidates borrowed views. The two runnable examples below describe the same trajectory using durations or trajectory times. Both explicitly supply the same boundary conditions; omitting them uses zero endpoint derivatives.两种更新形式均复用固定拓扑存储,重新计算系数与分解。失败使多项式失效但保留重试工作区;任何更新均使借用视图失效。以下两个可运行示例分别使用段时长和轨迹时间,表示同一条轨迹。两者显式传入相同边界条件;省略时端点导数默认为零。

Initialize from segment durations使用段时长初始化C++17
#include "SplineTrajectory.hpp"
#include <iostream>

int main() {
    using Spline = SplineTrajectory::QuinticSplineND<3>;
    Spline::WaypointMatrix waypoints(3, 3);
    waypoints << 0, 0, 0,  1, 0.5, 0,  2, 0, 0;
    SplineTrajectory::BoundaryConditions<3> bc;
    bc.start.v << 0.2, 0, 0;

    const std::vector<double> durations{1.2, 1.5};
    Spline spline;
    const auto status = spline.update(durations, waypoints, 0.0, bc);
    if (!status) { std::cerr << status.message; return 1; }
    std::cout << spline.polynomial().evaluate(0.5).transpose() << '\n';
}
Initialize from trajectory times使用轨迹时间初始化C++17
#include "SplineTrajectory.hpp"
#include <iostream>

int main() {
    using Spline = SplineTrajectory::QuinticSplineND<3>;
    Spline::WaypointMatrix waypoints(3, 3);
    waypoints << 0, 0, 0,  1, 0.5, 0,  2, 0, 0;
    SplineTrajectory::BoundaryConditions<3> bc;
    bc.start.v << 0.2, 0, 0;

    const std::vector<double> knots{0.0, 1.2, 2.7};
    Spline spline;
    const auto status = spline.updateFromBreakpoints(knots, waypoints, bc);
    if (!status) { std::cerr << status.message; return 1; }
    std::cout << spline.polynomial().evaluate(0.5).transpose() << '\n';
}

Topology, ownership & data access拓扑、所有权与数据访问#

Method方法Return / shape返回 / 形状Meaning说明
isValid() bool Latest construction published a polynomial; not a numerical rescan.最近构造已发布有效多项式;不是一次数值复查。
dimension(), numSegments(), numWaypoints() int, int, int Spatial dimension D, segments N, waypoints N+1.空间维度 D、段数 N、插值点数 N+1。
startTime(), endTime(), duration() double Seconds on the caller’s time axis.调用方时间轴上的秒数。
waypoints(), durations(), breakpoints(), boundary() Const referencesconst 引用 Borrow (N+1) × D, N durations, N+1 knots and boundary data. Valid until the next mutation.借用 (N+1) × D 点、N 个时长、N+1 个时间节点及边界数据;有效期到下次变更。
polynomial() const Polynomial& No copy; source lifetime/update rules apply. Borrowing from a temporary is deleted.无复制,遵循源生命周期与更新规则。禁止从临时对象借用。
copyPolynomial() Polynomial Independent owning snapshot; copies storage and may allocate.独立拥有数据的快照,复制存储并可能分配。
kDimension, kDegree, kCoefficientCount, kMinDerivativeOrder static constexpr int D, degree, K and minimized derivative order S.D、多项式次数、K 和最小化导数阶 S。

Energy and analytical gradients能量与解析梯度#

energy()#

Unweighted ∫ ‖p⁽ˢ⁾(t)‖² dt.未加权 ∫ ‖p⁽ˢ⁾(t)‖² dt。

double energy() const;

Returns返回double

energyGradient()#

Complete energy gradient. Owning form prepares buffers; reference form overwrites.完整能量梯度。返回值版本准备缓冲;引用版本覆盖输出。

Gradients energyGradient() const;
void energyGradient(Gradients& output) const;
output
Optional owning output. Overwritten and resized when needed; matching storage is reused.可选的拥有型输出;覆盖写入,按需调整尺寸,尺寸匹配时复用。

Returns返回Gradients / void

energyGradientAdd(output, weight)#

Adds weighted gradients to initialized output without clearing it.将加权梯度累加到已初始化输出,不清零。

void energyGradientAdd(Gradients& output, double weight = 1.0) const;
output
Initialized gradient storage, e.g. prepared by output.setZero(N).已初始化的梯度存储,可先用 output.setZero(N) 准备。
weight
Multiplier on the added energy gradient; defaults to 1.累加梯度的权重,默认 1。

Returns返回void

energyCoefficientPartials()#

∂E/∂C at fixed durations.固定时长下的 ∂E/∂C。

CoefficientMatrix energyCoefficientPartials() const;
void energyCoefficientPartials(CoefficientMatrix& output) const;
output
Optional owning output; the reference overload overwrites and reuses matching storage.可选的拥有型输出;引用重载覆盖写入并复用匹配的存储。

Returns返回(N·K) × D

energyDurationPartials()#

Direct ∂E/∂T at fixed coefficients.固定系数时的直接偏导 ∂E/∂T。

Eigen::VectorXd energyDurationPartials() const;
void energyDurationPartials(Eigen::VectorXd& output) const;
output
Optional owning output; the reference overload overwrites and reuses matching storage.可选的拥有型输出;引用重载覆盖写入并复用匹配的存储。

Returns返回N

energyDurationGradient()#

Total dE/dT, including coefficient dependence on interpolation durations.完整 dE/dT,包括插值系数随时长的变化。

Eigen::VectorXd energyDurationGradient() const;
void energyDurationGradient(Eigen::VectorXd& output) const;
output
Optional owning output; the reference overload overwrites and reuses matching storage.可选的拥有型输出;引用重载覆盖写入并复用匹配的存储。

Returns返回N

energyWaypointGradient()#

Total gradient for all waypoint positions, including endpoints.全部途经点位置的总梯度,包含两端。

WaypointMatrix energyWaypointGradient() const;
void energyWaypointGradient(WaypointMatrix& output) const;
output
Optional owning output; the reference overload overwrites and reuses matching storage.可选的拥有型输出;引用重载覆盖写入并复用匹配的存储。

Returns返回(N+1) × D

energyBoundaryGradient()#

Only start/end v/a/j gradients; unsupported higher derivatives are zero.仅含 start/end 的 v/a/j 导数梯度;不支持的高阶字段为零。

BoundaryConditions<DIM> energyBoundaryGradient() const;
void energyBoundaryGradient(BoundaryConditions<DIM>& output) const;
output
Optional owning output; the reference overload overwrites and reuses matching storage.可选的拥有型输出;引用重载覆盖写入并复用匹配的存储。

Returns返回BoundaryConditions<DIM>

Each partial/gradient getter also has a void method(Output& output) const overload with the corresponding output type. Overwrite overloads resize outputs automatically and reuse matching storage. output.size() reports the segment count. For accumulation, prepare matching zero gradients with output.setZero(N); output.setZero() clears existing values.各偏导/梯度取值方法也提供 void method(Output& output) const 引用重载,输出类型与返回值版本一致。覆盖接口自动调整输出尺寸,尺寸相同时复用存储。output.size() 返回段数。累加前可用 output.setZero(N) 准备对应段数的零梯度;output.setZero() 清零现有值。

Gradients::addWaypoint(index, partial)#

Adds a D-element row, column or Eigen expression to waypoint row 0…N, including both endpoints.将 D 维行、列或 Eigen 表达式累加到第 0…N 行途经点梯度,包含两端。

template<class Derived>
void addWaypoint(int index, const Eigen::MatrixBase<Derived>& partial);
index
Waypoint row 0…N.途经点行号 0…N。
partial
A DIM-element row, column or Eigen expression.DIM 维行、列或 Eigen 表达式。

Returns返回void

Type / helper类型 / 辅助方法Meaning含义
Spline::GradientsOwns waypoints: (N+1) × D, durations: N and boundary.start/end.v/a/j. setZero(N) prepares storage; setZero() clears existing values.拥有 waypoints:(N+1) × D、durations:N 及 boundary.start/end.v/a/j。setZero(N) 准备存储,setZero() 清零现有值。

Custom-cost adjoint自定义代价的伴随反传#

backward(gdC, gdT)#

Propagate a coefficient-space cost to all waypoints, durations and endpoint derivatives.将系数空间代价反传到全部途经点、段时长和端点导数。

Gradients backward(const CoefficientMatrix& gdC, const Eigen::VectorXd& gdT);
void backward(const CoefficientMatrix& gdC, const Eigen::VectorXd& gdT,
              Gradients& output);
gdC
Loss partials for local power coefficients, shaped (N·K) × DIM.对局部幂系数的代价偏导,形状为 (N·K) × DIM。
gdT
N direct duration partials holding coefficients fixed; use zero for absent terms.固定系数时的 N 项独立时长偏导,无此项时传零。
output
Optional owning output; overwritten, resized when needed and reused.可选的拥有型输出,覆盖写入,按需调整尺寸并复用。

Returns返回Owning Gradients, or void with an output argument.返回拥有型 Gradients;传入输出参数时返回 void。

dL/dT = ∂L/∂T | C + (∂C/∂T)ᵀ · ∂L/∂C

Gradients::size()#

Segment count; zero for a default-constructed output.当前段数;默认构造时为零。

int size() const;

Returns返回int

Gradients::setZero()#

Clear all gradients, including boundaries. Without N, retain current sizes; with N, prepare zero gradients for N segments. Matching sizes reuse storage.清零全部梯度,包括边界。不传 N 时保留当前尺寸;传入 N 时准备 N 段的零梯度。尺寸相同时复用存储。

void setZero();
void setZero(int segments);
segments
Optional segment count; sets up zeroed gradient storage for that topology.可选段数;为对应拓扑准备零梯度存储。

Returns返回void

Input / field输入 / 字段Type / shape类型 / 形状Meaning含义
gdC CoefficientMatrix · (N·K) × D Partials of the loss with respect to ascending local-time coefficients.代价对局部时间升幂系数的偏导。
gdT Eigen::VectorXd · N Independent duration partials holding C fixed; zeros if no explicit duration term.固定 C 的独立时长偏导;没有显式时长项时传零。
output.waypoints WaypointMatrix · (N+1) × D Total gradient for all waypoint positions.全部途经点位置的总梯度。
output.durations Eigen::VectorXd · N Total physical-duration gradient, including gdT.包含 gdT 的完整物理时长梯度。
output.boundary.start / end EndpointDerivatives<DIM> Each contains v/a/j gradients; positions are in waypoints.各自包含 v/a/j 梯度;位置梯度在 waypoints 中。

backward() reuses construction factors and requires exclusive access to the spline. The reference form resizes and overwrites the output, reusing matching storage. For energy alone, prefer the direct energyGradient(); backward(energyCoefficientPartials(), energyDurationPartials()) expresses the same chain rule.backward() 复用构造分解,需独占样条。引用版本自动调整尺寸并覆盖输出,尺寸相同时复用存储。仅能量项优先使用直接的 energyGradient();backward(energyCoefficientPartials(), energyDurationPartials()) 表达相同链式法则。

Spline::Gradients g;
spline.backward(gdC, gdT, g);   // auto-size and overwrite / 自动调整尺寸并覆盖
spline.energyGradientAdd(g, 0.5); // add energy / 累加能量

Evaluation & polynomial transforms求值与多项式变换#

#include "SplineTrajectory.hpp"

PPolyND<DIM, MaxCoefficients> owns piecewise-polynomial data. Capacity is not degree; the actual coefficient count may be smaller. The spline’s Polynomial alias uses K as its static capacity.PPolyND<DIM, MaxCoefficients> 拥有分段多项式数据。容量不是次数,实际系数数可以更小。样条的 Polynomial 别名使用 K 作为静态容量。

Scalar, batch & multi-derivative queries单点、批量与多阶求值#

evaluate(t, order)#

Evaluate one derivative at one time.在一个时刻计算指定阶导数。

Vector evaluate(double t, DerivativeOrder order = Deriv::Pos) const;
t
Time on the trajectory axis, including its start_time.轨迹时间轴上的时刻,包含起点时间 start_time。
order
Derivative order: Pos=0, Vel=1, Acc=2, …; defaults to position.导数阶数:Pos=0、Vel=1、Acc=2 等,默认位置。

Returns返回A DIM-vector; no allocation.DIM 维向量,不分配内存。

evaluateDerivatives<R>(t)#

Evaluate position through derivative R in one call.一次计算位置至 R 阶导数。

template<int R>
Derivatives<R> evaluateDerivatives(double t) const;
t
Time on the trajectory axis, including its start_time.轨迹时间轴上的时刻,包含起点时间 start_time。
R
Highest derivative order; result indices 0…R correspond to position and successive derivatives.最高导数阶;结果下标 0…R 对应位置及各阶导数。

Returns返回std::array<Vector, R+1>

evaluate(times, order)#

Evaluate a batch and return a new result matrix.批量求值并返回新结果矩阵。

PointMatrix evaluate(const std::vector<double>& times,
                     DerivativeOrder order = Deriv::Pos) const;
times
M query times on the trajectory axis; output rows follow input order.轨迹时间轴上的 M 个查询时刻,输出行与输入顺序一致。
order
Derivative order: Pos=0, Vel=1, Acc=2, …; defaults to position.导数阶数:Pos=0、Vel=1、Acc=2 等,默认位置。

Returns返回Owning M × DIM matrix, one query per row.拥有型 M × DIM 矩阵,每行一个查询点。

evaluate(times, output, order)#

Write batch results into caller-provided output, reusing matching storage.将批量结果写入调用方输出,复用尺寸匹配的存储。

void evaluate(const std::vector<double>& times, PointMatrix& output,
              DerivativeOrder order = Deriv::Pos) const;
void evaluate(const std::vector<double>& times, Eigen::Ref<PointMatrix> output,
              DerivativeOrder order = Deriv::Pos) const;
times
M query times on the trajectory axis; output rows follow input order.轨迹时间轴上的 M 个查询时刻,输出行与输入顺序一致。
output
Owning matrices resize as needed; Eigen::Ref writes to an existing M × DIM region.拥有型矩阵按需调整尺寸;Eigen::Ref 写入已有 M × DIM 区域。
order
Derivative order: Pos=0, Vel=1, Acc=2, …; defaults to position.导数阶数:Pos=0、Vel=1、Acc=2 等,默认位置。

Returns返回void

evaluateDerivatives<R>(times)#

Return batch results for position through derivative R.返回整批位置至 R 阶导数。

template<int R>
DerivativeBatch<R> evaluateDerivatives(const std::vector<double>& times) const;
times
M query times on the trajectory axis; output rows follow input order.轨迹时间轴上的 M 个查询时刻,输出行与输入顺序一致。
R
Highest derivative order; result indices 0…R correspond to position and successive derivatives.最高导数阶;结果下标 0…R 对应位置及各阶导数。

Returns返回R+1 owning matrices, each M × DIM.R+1 个拥有型矩阵,每个为 M × DIM。

evaluateDerivatives<R>(times, output)#

Reuse batch storage for all requested derivative orders.复用所有所需导数阶的批量存储。

template<int R>
void evaluateDerivatives(const std::vector<double>& times,
                         DerivativeBatch<R>& output) const;
times
M query times on the trajectory axis; output rows follow input order.轨迹时间轴上的 M 个查询时刻,输出行与输入顺序一致。
output
R+1 matrices; each is overwritten and reuses matching storage.R+1 个矩阵;逐个覆盖写入并复用匹配存储。
R
Highest derivative order; result indices 0…R correspond to position and successive derivatives.最高导数阶;结果下标 0…R 对应位置及各阶导数。

Returns返回void

Single-order batch overloads accept either int or Deriv; evaluate(times) defaults to position. Multi-order results use the derivative order as the index: [0] position, [1] velocity, [2] acceleration. Output buffers must not alias source storage.单阶批量重载接受 int 或 Deriv,evaluate(times) 默认求位置。多阶结果按导数阶数索引:[0] 位置、[1] 速度、[2] 加速度。输出缓冲不得与源存储重叠。

Runnable sampling example可运行的采样示例C++17
#include "SplineTrajectory.hpp"
#include <iostream>

int main() {
    using Spline = SplineTrajectory::QuinticSplineND<3>;
    Spline::WaypointMatrix waypoints(3, 3);
    waypoints << 0, 0, 0,  1, 0.5, 0,  2, 0, 0;
    Spline spline;
    if (const auto status = spline.update({1.2, 1.5}, waypoints, 0.0); !status) return 1;
    const auto &poly = spline.polynomial();
    const std::vector<double> times{0.0, 0.5, 1.2, 2.7};

    auto pva = poly.evaluateDerivatives<2>(0.5);
    Spline::WaypointMatrix velocity(times.size(), 3);
    poly.evaluate(times, velocity, SplineTrajectory::Deriv::Vel);
    auto sampler = poly.makeSampler<2>();
    auto position = sampler.evaluate(0.5);
    auto batch = sampler.evaluateDerivatives(times);
    std::cout << position.transpose() << '\n' << batch[1] << '\n';
    return pva[1].isApprox(velocity.row(1).transpose()) ? 0 : 1;
}

Sampler, segment lookup & local timeSampler、分段定位与局部时间#

makeSampler<R>()#

Reuses derivative coefficients across calls. Orders must be in [0,R]. Source must stay alive and unchanged. Dynamic capacity may allocate at sampler construction.跨调用复用导数系数。阶数须在 [0,R]。源须存活且不变;动态容量采样器在构造时可能分配。

template<int R>
Sampler<R> makeSampler() const &;
R
Highest derivative order; result indices 0…R correspond to position and successive derivatives.最高导数阶;结果下标 0…R 对应位置及各阶导数。

Returns返回A sampler borrowing the polynomial and owning its cursor and derivative cache.借用多项式、独立持有游标和导数缓存的 sampler。

poly[i].evaluateLocal(local_t, order)#

No piece search. Requires a valid index. Segment also exposes index/startTime/endTime/duration/coefficients.不查找分段,要求索引有效。Segment 还提供 index/startTime/endTime/duration/coefficients。

Segment operator[](int index) const &;
// Segment:
Vector evaluateLocal(double local_t, DerivativeOrder order = Deriv::Pos) const;
i
Zero-based segment index.从零开始的段号。
local_t
Seconds from the beginning of segment i.相对第 i 段起点的秒数。
order
Derivative order: Pos=0, Vel=1, Acc=2, …; defaults to position.导数阶数:Pos=0、Vel=1、Acc=2 等,默认位置。

Returns返回Vector

API / behavior接口 / 行为Time / state时间 / 状态When to use用途与约束
poly.evaluate… Trajectory time; source has no cursor轨迹时间;源不持有游标 Scalar queries locate independently. Batches reuse a local cursor: current piece, next piece, then lookup. No order pre-scan.单点独立定位;批量复用局部游标,依次检查当前段、下一段,否则重新查找。不预扫描顺序。
Knots & extrapolation节点与外推 Right-sided interior knots内节点取右段 The final knot selects the last piece. Outside the domain, extrapolate the endpoint polynomial. Supported derivatives above the actual degree are zero.最后节点取末段。域外延拓端点多项式;合法请求高于实际次数时返回零。

Use a separate sampler per concurrent traversal. Sorted, reverse and arbitrary time order are all supported; a sampler is a performance choice, not a different numerical API.每个并发遍历使用独立采样器。顺序、倒序和任意时间顺序均支持;Sampler 是性能选择,不是不同的数值接口。

Polynomial construction, geometry & transforms多项式构造、几何与变换#

PPolyND::create(knots, coefficients, coefficient_count)#

Construct an owning polynomial from known coefficients.从已知系数构造拥有型分段多项式。

static PPolyND create(const std::vector<double>& knots,
                      const CoefficientMatrix& coefficients, int coefficient_count);
knots
N+1 increasing trajectory times.N+1 个递增轨迹时刻。
coefficients
(N·K) × DIM rows, grouped by segment and ascending local power.(N·K) × DIM,按段排列,段内为局部时间升幂系数。
coefficient_count
K coefficients per segment.每段的系数数 K。

Returns返回PPolyND

PPolyND::update(knots, coefficients, coefficient_count)#

Replace polynomial data, using the same arguments as create(). Reuse the existing object.使用与 create() 相同的参数覆盖多项式数据,复用已有对象。

void update(const std::vector<double>& knots,
            const CoefficientMatrix& coefficients, int coefficient_count);

Returns返回void

derivative(order)#

Owning derivative polynomial; nonnegative order, zero above degree.独立导数多项式;阶数非负,高于次数时生成零多项式。

StatusOr<PPolyND> derivative(DerivativeOrder order = Deriv::Vel) const;
order
Nonnegative derivative order; defaults to velocity.非负导数阶,默认为速度。

Returns返回StatusOr<PPolyND>

extractInterval(start, end)#

Nonempty interval within the source domain; preserves the original time axis. Translates coefficients at the clipped first piece.源范围内的非空区间;保留原时间轴,并平移首个裁剪段的局部系数。

StatusOr<PPolyND> extractInterval(double start, double end) const;
start, end
Start and end on the source trajectory axis; start < end.原轨迹时间轴上的区间起止时刻,start < end。

Returns返回StatusOr<PPolyND>

rebased(new_start)#

Owning copy on an explicit new time origin, preserving local coefficients.显式平移至新起点的拥有型副本,局部系数不变。

StatusOr<PPolyND> rebased(double new_start) const;
new_start
New origin on the trajectory time axis, in seconds.新的轨迹起点时刻,单位为秒。

Returns返回StatusOr<PPolyND>

appendRebased(suffix)#

Accepts arbitrary origins and shifts the suffix to this polynomial’s end. Equal coefficient counts; no continuity enforcement.接受任意起点,将后缀平移到当前轨迹末端。要求系数数相同,不强制连续性。

StatusOr<PPolyND> appendRebased(const PPolyND& suffix) const;
suffix
Polynomial to append; its start is shifted to this polynomial’s end.要拼接的多项式,其起点平移到当前多项式末端。

Returns返回StatusOr<PPolyND>

length(...)#

Approximate arc length via left-endpoint speed samples, dt > 0; allocates sample times.用左端点速度采样近似弧长,dt > 0;分配时间序列。

StatusOr<double> length(double dt = 0.01) const;
StatusOr<double> length(double start, double end, double dt = 0.01) const;
dt
Positive sampling step in seconds.正的采样步长,单位为秒。
start, end
Optional interval on the trajectory axis; omitted means the full trajectory.可选的轨迹时间区间,省略时计算整条轨迹。

Returns返回StatusOr<double>

generateTimeSequence(...)#

Positive finite dt and start ≤ end; includes both endpoints. Returns errors for unrepresentable count/progression.dt 正且有限,start ≤ end;包括两端点。不可表示的样本数或时间递增返回错误。

StatusOr<std::vector<double>> generateTimeSequence(double dt) const;
StatusOr<std::vector<double>> generateTimeSequence(
    double start, double end, double dt) const;
dt
Positive time step in seconds.正的时间步长,单位为秒。
start, end
Optional time range; omitted means the full trajectory.可选时间范围,省略时使用整条轨迹。

Returns返回StatusOr<std::vector<double>>

PPolyND::zero(knots, coefficient_count)#

Create a zero polynomial on the given knots; coefficient_count defaults to 1.在指定时间节点上创建零多项式,coefficient_count 默认为 1。

static PPolyND zero(const std::vector<double>& knots, int coefficient_count = 1);

Returns返回PPolyND

PPolyND::constant(knots, value)#

Create a constant polynomial equal to value over the knot range.在时间节点范围内创建恒等于 value 的常量多项式。

static PPolyND constant(const std::vector<double>& knots, const Vector& value);

Returns返回PPolyND

Method方法Return返回Behavior / precondition行为 / 前置条件
isValid / dimension / degree / coefficientCount / numSegments Scalar values标量值 Inspect initialization and actual polynomial topology. clear() invalidates data and views.查看初始化与实际多项式拓扑。clear() 使数据与视图失效。
coefficients / breakpoints / startTime / endTime / duration Const references / secondsconst 引用 / 秒数 Read storage and physical time axis. begin/end iterate borrowed Segment proxies.读取存储与物理时间轴。begin/end 遍历借用的 Segment 代理。

PPolyND::copyOf(source)#

Independent copy from another coefficient capacity; the destination capacity must fit the source coefficient count. An invalid source produces an empty polynomial.从另一系数容量的多项式独立复制;目标容量须容纳源系数数。无效源得到空多项式。

template<int SourceCapacity>
static PPolyND copyOf(const PPolyND<DIM, SourceCapacity>& source);
source
Polynomial to copy, possibly with another coefficient capacity.要复制的多项式,可使用不同的系数容量。

Returns返回PPolyND

Curve and derivative comparison曲线与导数对照#

Cubic · 3Quintic · 5Septic · 7
Spline comparison / 样条对照

Four 1D waypoints at t = 0, 1, 2.4, 3.5 s, with positions 0, 1, −0.35, 0.6. Each spline uses zero supported endpoint derivatives. Shading marks the selected piece; local time is t_local = t − t_start. The chart breaks at derivative discontinuities.一维插值点时间为 0、1、2.4、3.5 秒,位置为 0、1、−0.35、0.6。各样条支持的端点导数均设为零。阴影标记当前段;局部时间为 t_local = t − t_start。图线在导数不连续处断开。

Fixed example coefficients were calculated by the C++ library. The browser evaluates these coefficients; it does not run the spline solver. Spatial units are caller-defined.固定示例系数由 C++ 库计算。浏览器仅对这些系数求值,不执行样条求解。空间单位由调用方定义。

Trajectory optimizer轨迹优化器#

#include "SplineOptimizer.hpp"

Preparation & external solver workflow准备与外部求解流程#

SplineOptimizer<Spline, Parameterization> supplies a cost and gradient; it does not run an iterative solver. A prepared optimizer owns its reference input, layout and working storage. It is noncopyable, movable and exclusive to one synchronous evaluation at a time.SplineOptimizer<Spline, Parameterization> 提供代价与梯度,不执行迭代求解。准备后的优化器拥有参考输入、布局与工作存储;不可复制,可移动,同一时刻仅进行一次同步求值。

Deliver in this order: solver final x → successful update(x) → task constraint acceptance → copyPolynomial() → control-thread sampler. evaluate() changes the candidate; polynomial() is the last built trial, not an automatically accepted solution. Keep the saved snapshot alive and unchanged.交付顺序:求解器最终 x → update(x) 成功 → 规划约束验收 → copyPolynomial() → 控制线程采样。evaluate() 会改变候选;polynomial() 是最后构建的试探轨迹,不会自动成为接受解。保存的快照须存活且不变。

  1. prepare()Validate and allocate验证并准备存储
  2. initialGuess()Copy initial coordinates复制初始坐标
  3. evaluate()External trial loop外部候选迭代
  4. update()Restore accepted x恢复接受解 x

prepare(input, options, objective)#

Copies inputs, encodes initial coordinates and prepares library buffers/capabilities. No objective reference is retained. Prepare user-owned cost resources separately.复制输入,编码初始坐标并准备库工作区及采样能力,不保留 objective 引用。用户代价资源另行提前准备。

template<class Objective>
Status prepare(const SplineInput<DIM>& input, const Objective& objective);
template<class Objective>
Status prepare(const SplineInput<DIM>& input, const OptimizerOptions& options,
               const Objective& objective);
input
Initial physical trajectory data.初始物理轨迹数据。
options
Optional weights, optimization mask and integration settings.可选的权重、优化掩码与积分设置。
objective
User-defined callable costs, or NoObjective for built-in costs only.用户定义的可调用代价;仅用内置代价时传 NoObjective。

Returns返回Status

initialGuess()#

Get the initial decision vector after prepare(). Pass this vector to the numerical solver.prepare() 后取得初始决策向量,交给数值求解器。

Eigen::VectorXd initialGuess() const;

Returns返回Eigen::VectorXd

evaluate(x, gradient, objective, executor)#

x must have decisionDimension() entries. Owning g resizes/reuses. With matching output, fixed-topology evaluation and rejected-candidate retry do not allocate library storage.x 须匹配 decisionDimension();拥有型 g 按需调整尺寸或复用。输出匹配时,固定拓扑评价及失败重试不分配库内存。

template<class Objective, class Executor = SerialExecutor>
EvaluationResult evaluate(const Eigen::VectorXd& x, Eigen::VectorXd& gradient,
                          Objective& objective, const Executor& executor = {});
x
Candidate vector with decisionDimension() entries.包含 decisionDimension() 项的候选决策向量。
gradient
Overwritten decision gradient; owning storage resizes or reuses as needed.覆盖写入的决策梯度,拥有型存储按需调整尺寸或复用。
objective
The callable cost container.可调用代价容器。
executor
Optional integration executor; serial by default.可选积分执行器,默认串行。

Returns返回EvaluationResult {cost, status}

update(x)#

The accepted vector may differ from the last trial. Rebuild before consuming the result; no objective evaluation.接受向量可能不同于最后试探向量。消费结果前重建,不计算目标代价。

Status update(const Eigen::VectorXd& x);
x
The final decision vector returned by the solver.求解器返回的最终决策向量。

Returns返回Status

Method方法Input / output输入 / 输出Contract契约
problem / layout / activeMask / parameters / polynomial Borrowed views借用视图 Problem/layout/mask survive trial evaluations; parameters/polynomial do not. Repreparation or movement invalidates all views. copyPolynomial() owns a snapshot.problem/layout/mask 可跨试探求值;parameters/polynomial 不可。重新准备或移动使全部视图失效。copyPolynomial() 返回独立快照。
isPrepared / decisionDimension / energy / recordedSamples bool / int / StatusOr<double> / const SampleBuffer& Energy is unweighted and rejects invalid/nonfinite results. Samples are exposed only after a successful recording evaluation.能量不乘权重,拒绝无效或非有限结果。仅成功记录采样的评价提供记录。
Complete optimization: custom costs → L-BFGS → final trajectory完整优化:自定义代价 → L-BFGS → 最终轨迹C++17
#include "SplineOptimizer.hpp"
#include <gcopter/lbfgs.hpp>
#include <iostream>
#include <numeric>

using Spline = SplineTrajectory::QuinticSplineND<3>;
using Optimizer = SplineTrajectory::SplineOptimizer<Spline>;

struct VelocityCost {
    static constexpr int kDerivativeOrder = 1;
    double weight = 0.02;

    double operator()(const SplineTrajectory::IntegralPointInfo&,
                      const SplineTrajectory::IntegralState<3>& state,
                      SplineTrajectory::IntegralGradient<3>& gradient) const {
        gradient.v += 2.0 * weight * state.v;
        return weight * state.v.squaredNorm();
    }
};

struct TargetDurationCost {
    double target = 5.0;
    double weight = 0.2;

    double operator()(const SplineTrajectory::ParameterView<Spline>& state,
                      SplineTrajectory::ParameterGradientView<Spline>& gradient) const {
        const double duration = std::accumulate(
            state.durations.begin(), state.durations.end(), 0.0);
        const double error = duration - target;
        gradient.durations.array() += 2.0 * weight * error;
        return weight * error * error;
    }
};

struct Objective {
    VelocityCost integral;
    TargetDurationCost parameter;
};

int main() {
    SplineTrajectory::SplineInput<3> input;
    input.durations = {1.2, 1.5};
    input.waypoints.resize(3, 3);
    input.waypoints << 0, 0, 0,  1, 0.5, 0,  2, 0, 0;
    SplineTrajectory::OptimizerOptions options;
    options.energy_weight = 0.02;
    options.duration_weight = 0.5;
    options.integration_steps = 32;
    Objective objective;
    Optimizer optimizer;
    if (const auto status = optimizer.prepare(input, options, objective); !status) {
        std::cerr << status.message << '\n';
        return 1;
    }

    auto x = optimizer.initialGuess();
    struct Context { Optimizer& optimizer; Objective& objective; } context{optimizer, objective};
    auto evaluate = [](void* instance, const Eigen::VectorXd& variables,
                       Eigen::VectorXd& gradient) {
        auto& ctx = *static_cast<Context*>(instance);
        return ctx.optimizer.evaluate(variables, gradient, ctx.objective).cost;
    };
    lbfgs::lbfgs_parameter_t parameters;
    parameters.g_epsilon = 1e-6;
    parameters.past = 5;
    parameters.delta = 1e-9;
    parameters.max_iterations = 500;
    double cost = 0.0;
    const int result = lbfgs::lbfgs_optimize(
        x, cost, evaluate, nullptr, nullptr, &context, parameters);
    if (result < 0) {
        std::cerr << lbfgs::lbfgs_strerror(result) << '\n';
        return 1;
    }
    if (const auto status = optimizer.update(x); !status) {
        std::cerr << status.message << '\n';
        return 1;
    }
    // Check application constraints here before accepting the trajectory.
    auto trajectory = optimizer.copyPolynomial();
    auto sampler = trajectory.makeSampler<2>();
    const auto pva = sampler.evaluateDerivatives(
        trajectory.startTime() + 0.5 * trajectory.duration());
    std::cout << "Final cost: " << cost << "\nPosition: " << pva[0].transpose()
              << "\nVelocity: " << pva[1].transpose() << '\n';
}

The example uses the GCOPTER L-BFGS header bundled in benchmarks/planners/upstream/GCOPTER/gcopter/include. Save the program as main.cpp; with the repository at external/SplineTrajectory, use this application CMake file:示例使用仓库内 benchmarks/planners/upstream/GCOPTER/gcopter/include 下的 GCOPTER L-BFGS。将程序保存为 main.cpp,仓库放在 external/SplineTrajectory,应用的 CMake 文件如下:

cmake_minimum_required(VERSION 3.12)
project(spline_app LANGUAGES CXX)
set(BUILD_TESTING OFF CACHE BOOL "" FORCE)
set(SPLINE_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
add_subdirectory(external/SplineTrajectory EXCLUDE_FROM_ALL)
add_executable(spline_app main.cpp)
target_link_libraries(spline_app PRIVATE SplineTrajectory::SplineTrajectory)
target_include_directories(spline_app SYSTEM PRIVATE
    external/SplineTrajectory/benchmarks/planners/upstream/GCOPTER/gcopter/include)

Build with cmake -S . -B build and cmake --build build --target spline_app. Other solvers use the same evaluate(x, gradient, objective) callback. After solving, call update(x) with the solver’s final vector, check application constraints, then save copyPolynomial().执行 cmake -S . -B build 和 cmake --build build --target spline_app 即可构建。其他求解器同样调用 evaluate(x, gradient, objective)。求解后,用最终向量调用 update(x),验收规划约束,再通过 copyPolynomial() 保存。

Physical input, masks & layout物理输入、掩码与布局#

Spline construction interpolates every input waypoint. In optimization, mask-selected values are initial guesses. Defaults let durations and interior waypoints change; endpoints and boundary derivatives stay fixed as direct coordinates. Auxiliary maps may explicitly transform fixed values.普通样条构建插值所有输入点。优化时,mask 选中的值是初值;默认允许时长和内部途经点改变,端点及边界导数保持为固定直接坐标。辅助映射可以显式变换固定值。

Type / field类型 / 字段Shape / default形状 / 默认值Meaning含义
SplineInput<DIM>durations: N; waypoints: (N+1) × DAlso boundary.start/end.v/a/j and start_time. No mask in physical input.还含 boundary.start/end.v/a/j 与 start_time;物理输入不持有 mask。
OptimizerOptionsenergy_weight=0, duration_weight=0, integration_steps=64, record_samples=false, mask={}Weights finite/nonnegative; both are opt-in. Steps positive. NoObjective alone adds no energy or duration cost.权重有限非负,均需显式启用;步数为正。NoObjective 本身不启用能量或时长代价。
options.mask.durations / waypointsN / N+1Empty selects all durations / interior points. Explicit nonzero entries select coordinates, including endpoints. none(N) disables direct coordinates; interiorWaypoints(N) selects only interior points.空掩码选择全部时长/内部点;显式非零项选中相应坐标,含端点。none(N) 关闭直接坐标;interiorWaypoints(N) 仅选内部点。
options.mask.start / endBoundaryDerivativeMask {v,a,j}All false by default; unsupported derivative selections fail preparation.默认全 false;选中不支持的导数会导致准备失败。
DecisionLayoutdurations, waypoints, boundary_offset, auxiliary_offset, dimensionOrder: durations → waypoints → start derivatives → end derivatives → auxiliary. Point records include full waypoint index, offset and mapped dof.顺序为时长→途经点→起点导数→终点导数→辅助变量;点记录含完整下标、偏移和映射自由度。

Callable objective members可调用代价成员#

Define Objective in your application and give each cost a callable member such as integral or parameter. Each cost implements operator(), returns its cost and adds its partial derivatives. Return double for a numeric cost, or EvaluationResult when it can report failure. NoObjective selects only the enabled built-in costs.Objective 由用户定义,通过 integral、parameter 等可调用成员组合代价。每项代价实现 operator(),返回代价值并累加偏导。纯数值代价返回 double;需要报告失败时返回 EvaluationResult。NoObjective 仅使用已开启的内置代价。

struct VelocityCost {
    static constexpr int kDerivativeOrder = 1;
    double weight = 0.02;

    double operator()(const SplineTrajectory::IntegralPointInfo&,
                      const SplineTrajectory::IntegralState<3>& state,
                      SplineTrajectory::IntegralGradient<3>& gradient) const {
        gradient.v += 2.0 * weight * state.v;
        return weight * state.v.squaredNorm();
    }
};

struct TargetDurationCost {
    double target = 5.0;
    double weight = 0.2;

    double operator()(const SplineTrajectory::ParameterView<Spline>& state,
                      SplineTrajectory::ParameterGradientView<Spline>& gradient) const {
        const double duration = std::accumulate(
            state.durations.begin(), state.durations.end(), 0.0);
        const double error = duration - target;
        gradient.durations.array() += 2.0 * weight * error;
        return weight * error * error;
    }
};

struct Objective {
    VelocityCost integral;
    TargetDurationCost parameter;
};

objective.integral#

Pointwise obstacles/dynamics. Unweighted integrand and p/v/a/j/s, trajectory_time partials. Optional kDerivativeOrder on this functor, default 4; allowed 0…4.逐点避障/动力学代价;未加权被积函数及 p/v/a/j/s、trajectory_time 偏导。此 Functor 可声明 kDerivativeOrder,默认 4,范围 0…4。

double operator()(const IntegralPointInfo& point,
                  const IntegralState<D>& state, IntegralGradient<D>& gradient) const;
point
Integration location and time.积分位置与时间信息。
state
Position and derivatives through the declared order.位置及所声明阶数以内的导数。
gradient
Unweighted integrand partials to add.要累加的未加积分权重的被积函数偏导。

Returns返回double cost, or EvaluationResult when reporting failure.double 代价值;需要报告失败时使用 EvaluationResult。

objective.sample#

Cross-sample position coupling. positions: M × D contiguous rows; trajectory_times: M. Return whole batch cost, no automatic quadrature weighting.跨点位置耦合;positions 为 M × D 连续行,trajectory_times 为 M 项。返回整批代价,不自动加积分权重。

double operator()(const Optimizer::SampleBuffer& samples,
                  SampleGradientView<Spline>& gradient) const;
samples
Segment-major quadrature records.按段排列的积分采样记录。
gradient
Position and explicit time partials, one row per record.位置与显式时间偏导,每行对应一条记录。

Returns返回double cost, or EvaluationResult when reporting failure.double 代价值;需要报告失败时使用 EvaluationResult。

objective.coefficient#

Hull/control costs. coefficients, independent durations and start_time partials before the spline adjoint.凸包/控制点代价;在样条伴随前累加 coefficients、独立 durations 和 start_time 偏导。

double operator()(const ParameterView<Spline>& state,
                  CoefficientGradientView<Spline>& gradient);
state
Current polynomial and physical parameters.当前多项式与物理参数。
gradient
Coefficient and independent-time partials to add.要累加的系数与独立时间偏导。

Returns返回double cost, or EvaluationResult when reporting failure.double 代价值;需要报告失败时使用 EvaluationResult。

objective.parameter#

Physical costs after adjoint: waypoints, durations, boundary.start/end.v/a/j, start_time. Same access paths as state; addWaypoint(i, partial) accepts rows or columns.伴随后物理代价:waypoints、durations、boundary.start/end.v/a/j、start_time,与输入访问路径对齐;addWaypoint 接受行或列。

double operator()(const ParameterView<Spline>& state,
                  ParameterGradientView<Spline>& gradient) const;
state
Current physical parameters.当前物理参数。
gradient
Waypoint, duration, boundary and start-time partials to add.要累加的途经点、时长、边界与起点时间偏导。

Returns返回double cost, or EvaluationResult when reporting failure.double 代价值;需要报告失败时使用 EvaluationResult。

objective.decision#

Direct regularization in decision coordinates; adds to already mapped gradients.决策坐标的直接正则项,累加至已映射梯度。

double operator()(const DecisionView& state,
                  Eigen::Ref<Eigen::VectorXd> gradient) const;
state
Decision coordinates and layout.决策坐标与布局。
gradient
Decision-space partials to add.要累加的决策坐标偏导。

Returns返回double cost, or EvaluationResult when reporting failure.double 代价值;需要报告失败时使用 EvaluationResult。

Requirement / entry需求 / 入口operator() argumentsoperator() 参数Contract契约
energy_weight / duration_weightBuilt-in options内置配置Smoothness and linear total duration. Defaults zero; additional duration costs go in parameter.平滑及线性总时长代价,默认零;额外时长代价放 parameter。

Prepare any cost-owned resources before solving. See the complete program and the optimizer guide.用户代价持有的资源在求解前准备。可直接使用上方的完整程序,更多协议说明见优化器指南。

Here Spline is QuinticSplineND<3>. The integral cost returns the velocity-squared integrand and adds its velocity partial. The parameter cost returns a total-duration penalty and adds the same partial to every segment duration. Built-in and custom costs are summed; set a built-in weight to zero to omit that term.这里 Spline 为 QuinticSplineND<3>。积分代价返回速度平方被积函数,并累加速度偏导;参数代价返回总时长罚项,并向每段时长累加同一个偏导。内置代价与自定义代价相加;某项内置权重设为零即可关闭该项。

Callback data and gradient fields回调数据与梯度字段#

Views borrow the optimizer’s data for the callback. Add partials to the supplied fields; the optimizer composes the remaining chain rule. ParameterView is read-only, and gradient views write to existing storage.视图在回调期间借用优化器数据。向对应字段累加偏导,余下的链式求导由优化器完成。ParameterView 只读,梯度视图写入现有存储。

Type / field类型 / 字段Meaning含义
ParameterView<Spline>polynomial; durations: N physical seconds; waypoints: (N+1) × D; boundary.start/end.v/a/j; start_time: trajectory origin.polynomial;durations:N 个物理秒数;waypoints:(N+1) × D;boundary.start/end.v/a/j;start_time:轨迹起点时间。
CoefficientGradientView<Spline>coefficients: (N·K) × D; durations: N partials with coefficients held fixed; start_time: scalar partial. Runs before the spline adjoint.coefficients:(N·K) × D;durations:保持系数不变时的 N 项时长偏导;start_time:标量偏导。位于样条伴随之前。
ParameterGradientView<Spline>waypoints, durations, boundary, start_time mirror the physical input. addWaypoint(i, partial) accepts a row, column or Eigen expression. Runs after the spline adjoint.waypoints、durations、boundary、start_time 与物理输入对齐。addWaypoint(i, partial) 接受行、列或 Eigen 表达式。位于样条伴随之后。
IntegralState<D> / IntegralGradient<D>p/v/a/j/s: D-vectors for position through snap. kDerivativeOrder declares the highest derivative used by the cost (default 4). Write partials only through that order; they are unweighted integrand partials; trajectory_time is the explicit time partial.p/v/a/j/s:位置至 snap 的 D 维向量。kDerivativeOrder 声明代价使用的最高导数阶(默认 4),偏导也写至该阶;梯度为未加积分权重的被积函数偏导,trajectory_time 表示显式时间偏导。
SampleGradientView<Spline>positions: M × D, one contiguous row per sample; trajectory_times: M explicit time partials. Row i corresponds to samples[i]. The callback returns the whole batch cost.positions:M × D,每个样本一行且行内连续;trajectory_times:M 项显式时间偏导。第 i 行对应 samples[i],回调返回整批代价。
DecisionViewvariables: current decision vector; layout: offsets and dimensions. The output vector accumulates partials in decision coordinates.variables:当前决策向量;layout:偏移与维度。输出向量累加决策坐标上的偏导。
MutableParameters<Spline>Auxiliary-map references to durations, waypoints, boundary and start_time; update values while keeping their shapes.辅助映射引用 durations、waypoints、boundary、start_time;保持形状并更新数值。

IntegralPointInfo describes one quadrature point. With N segments and L = integration_steps, records are ordered by segment, then step; M = N·(L+1). Every segment includes both endpoints, so an inner waypoint appears twice.IntegralPointInfo 描述一个积分点。设 N 为段数、L 为 integration_steps,记录先按段、再按步排列,总数 M = N·(L+1)。每段都包含两端点,因此内部途经点出现两次。

Type / field类型 / 字段Meaning含义
IntegralPointInfo::segment_index / segment_countZero-based segment index and total count N.从零开始的段号与总段数 N。
step_index / step_count / alphaStep index 0…L; count L; normalized segment position alpha = step_index / L.步下标 0…L、步数 L、段内归一化位置 alpha = step_index / L。
segment_duration / step_size / segment_time / trajectory_timeSegment duration T; step size T/L; elapsed segment time αT; time on the caller’s trajectory axis, including start_time. All in seconds.段时长 T、步长 T/L、段内经过时间 αT,以及包含 start_time 的轨迹时间,单位均为秒。
isSegmentStart/End() / isTrajectoryStart/End() / waypointIndex()Endpoint predicates; waypointIndex() returns 0…N at a waypoint and −1 between waypoints.段端点与轨迹端点判断;waypointIndex() 在途经点返回 0…N,其余位置返回 −1。
Optimizer::IntegralSamplepoint: IntegralPointInfo; p/v: position/velocity; trap_weight: ½ at segment endpoints, otherwise 1; b_p: 1 × K local power basis. The quadrature measure is trap_weight * point.step_size.point:IntegralPointInfo;p/v:位置/速度;trap_weight:段端点为 ½,其余为 1;b_p:1 × K 局部幂基。积分权重为 trap_weight * point.step_size。
Optimizer::SampleBuffer / recordedSamples()M records. A sample cost prepares recording automatically; otherwise set record_samples = true. Read records after a successful evaluation, before the next optimizer update, evaluation or prepare.共 M 条记录。存在 sample 代价时自动准备记录;其他情况设置 record_samples = true。成功评价后读取,在下一次 update、评价或 prepare 前使用。

To visit each waypoint only once in a discrete batch cost, skip point.isSegmentStart() && !point.isTrajectoryStart() and leave those gradient rows zero. Integral costs use both endpoint records with their trapezoidal weights.离散批量代价若需每个途经点只计一次,可跳过 point.isSegmentStart() && !point.isTrajectoryStart(),并将对应梯度行留零。积分代价使用两份端点记录及其梯形权重。

Time, spatial & auxiliary maps时间、空间与辅助映射#

Parameterization holds time, space and auxiliary. Defaults are QuadInvTimeMap, IdentitySpatialMap<D>, NoAuxiliaryMap. makeOptimizer<Spline>(maps) owns maps by value; std::ref/std::cref explicitly borrow longer-lived objects. Keep dimensions/inverse semantics fixed until reprepare.Parameterization 持有 time、space、auxiliary;默认 QuadInvTimeMap、IdentitySpatialMap<D>、NoAuxiliaryMap。makeOptimizer<Spline>(maps) 按值拥有映射;std::ref/std::cref 显式借用长生命周期对象。重新准备前不改变维度或逆映射语义。

time.forward(tau)#

Decode one time coordinate into a positive segment duration in seconds.将一个时间坐标解码为正的段时长,单位为秒。

double forward(double tau) const;

Returns返回double

time.inverse(duration)#

Encode an initial physical duration during prepare().prepare() 时将初始物理时长编码为决策坐标。

double inverse(double duration) const;

Returns返回double

time.backward(tau, duration, grad_duration)#

Pull a duration partial back to its time coordinate. The duration is the cached value before auxiliary transformations.将时长偏导传回时间坐标,duration 为辅助变换前缓存的时长。

double backward(double tau, double duration, double grad_duration) const;

Returns返回double

space.dimension(waypoint_index)#

Return the number of decision coordinates for waypoint 0…N, including endpoints.返回第 0…N 个途经点所需的决策坐标数,包含两端点。

int dimension(int waypoint_index) const;

Returns返回int

space.forward(x, waypoint_index)#

Decode one waypoint’s coordinate slice into a physical position. Vector is Spline::Vector.将一个途经点的决策切片解码为物理位置,Vector 为 Spline::Vector。

Vector forward(const Eigen::Ref<const Eigen::VectorXd>& x,
               int waypoint_index) const;

Returns返回Vector

space.inverse(point, waypoint_index)#

Encode an initial physical waypoint into dimension(waypoint_index) coordinates.将初始物理途经点编码为 dimension(waypoint_index) 个坐标。

Eigen::VectorXd inverse(const Vector& point, int waypoint_index) const;

Returns返回Eigen::VectorXd

space.backward(x, gradient, waypoint_index, output)#

Pull the physical position partial back to this waypoint’s coordinates, overwriting output.将物理位置偏导传回该途经点的决策坐标,覆盖写入 output。

void backward(const Eigen::Ref<const Eigen::VectorXd>& x, const Vector& gradient,
              int waypoint_index, Eigen::Ref<Eigen::VectorXd> output) const;

Returns返回void

auxiliary.dimension()#

Return the number of additional decision coordinates.返回额外决策坐标的维度。

int dimension() const;

Returns返回int

auxiliary.initial(reference)#

Build the initial auxiliary coordinates from the reference input during prepare().prepare() 时从参考输入生成初始辅助坐标。

StatusOr<Eigen::VectorXd> initial(const SplineInput<D>& reference) const;

Returns返回StatusOr<Eigen::VectorXd>

auxiliary.apply(z, state)#

Transform physical parameters using auxiliary coordinates z, preserving their topology.使用辅助坐标 z 变换物理参数,保持拓扑不变。

Status apply(const Eigen::Ref<const Eigen::VectorXd>& z,
             MutableParameters<Spline>& state) const;

Returns返回Status

auxiliary.backward(z, state, gradient, grad_z)#

Add auxiliary-coordinate partials to grad_z and pull physical gradients back before the time and spatial maps. Put costs in parameter or decision.向 grad_z 累加辅助坐标偏导,并在时间、空间映射之前传回物理梯度。代价放在 parameter 或 decision。

Status backward(const Eigen::Ref<const Eigen::VectorXd>& z,
    const ParameterView<Spline>& state, ParameterGradientView<Spline>& gradient,
    Eigen::Ref<Eigen::VectorXd> grad_z) const;

Returns返回Status

Map映射Behavior行为
Return contracts返回契约Total time/spatial maps return values/void; rejecting maps may return StatusOr/Status. Auxiliary apply/backward return Status.全域时间/空间映射返回值或 void;可能拒绝的映射可返回 StatusOr/Status。辅助 apply/backward 返回 Status。
Type / field类型 / 字段Meaning含义
QuadInvTimeMapDefault smooth map from unconstrained coordinates to positive durations. Use with an unconstrained solver such as L-BFGS.默认平滑映射,将无约束坐标映射到正时长,适合 L-BFGS 等无约束求解器。
IdentityTimeMapDecision coordinates are physical durations; forward, inverse and gradient are unchanged. Useful when the solver enforces positive duration bounds.决策坐标直接表示物理时长,正向、逆向和梯度均原样传递,适合由求解器设置时长正下界的场景。
IdentitySpatialMap<D>D Cartesian coordinates per active waypoint; positions and their gradients pass through unchanged.每个选中途经点使用 D 个笛卡尔坐标,位置及梯度原样传递。
NoAuxiliaryMapDefault: no extra coordinates or physical-parameter transformations.默认不增加辅助坐标或物理参数变换。
Choose direct duration coordinates选择直接时长坐标C++17
#include "SplineOptimizer.hpp"
#include <iostream>

int main() {
    using Spline = SplineTrajectory::QuinticSplineND<3>;
    struct Maps {
        SplineTrajectory::IdentityTimeMap time;
        SplineTrajectory::IdentitySpatialMap<3> space;
        SplineTrajectory::NoAuxiliaryMap auxiliary;
    };
    auto optimizer = SplineTrajectory::makeOptimizer<Spline>(Maps{});
    SplineTrajectory::SplineInput<3> input;
    input.durations = {1.2, 1.5};
    input.waypoints.resize(3, 3);
    input.waypoints << 0, 0, 0,  1, 0.5, 0,  2, 0, 0;
    SplineTrajectory::OptimizerOptions options;
    options.duration_weight = 0.5;
    SplineTrajectory::NoObjective objective;
    if (!optimizer.prepare(input, options, objective)) return 1;
    const auto x = optimizer.initialGuess();
    Eigen::VectorXd gradient;
    const auto result = optimizer.evaluate(x, gradient, objective);
    if (!result) return 1;
    // With IdentityTimeMap, the first two coordinates are durations in seconds.
    std::cout << "Durations: " << x.head(2).transpose()
              << "\nDuration gradient: " << gradient.head(2).transpose() << '\n';
    return (x.head(2).isApprox(Eigen::Vector2d(1.2, 1.5)) &&
            gradient.head(2).isApprox(Eigen::Vector2d(0.5, 0.5))) ? 0 : 1;
}

The physical cost code stays the same when maps change. Preparation uses inverse; evaluation decodes with forward, applies the auxiliary map, computes costs, then calls the maps’ backward functions. A start_time gradient reaches decision variables through an auxiliary map.更换映射时,物理代价代码保持一致。准备时调用 inverse;评价时通过 forward 解码、应用辅助映射并计算代价,再由各映射的 backward 传回决策梯度。start_time 偏导通过辅助映射传到决策变量。

Parallel evaluation & gradient checking并行求值与梯度校验#

checkGradients(optimizer, x, objective, step, tolerance)#

Allocating central differences, then restores the base candidate. Positive finite step/tolerance; tolerance applies to the Euclidean error norm. Returns status, analytical/numerical vectors, relative/error norms and worst component.分配内存做中心差分,随后恢复基准候选。step/tolerance 正且有限;容差用于欧氏误差范数。返回状态、解析/数值向量、相对/范数误差与最差分量。

template<class Optimizer, class Objective>
GradientCheckResult checkGradients(
    Optimizer& optimizer, const Eigen::VectorXd& x, Objective& objective,
    double step = 1e-6, double tolerance = 1e-4);
optimizer, x, objective
Prepared optimizer, decision vector and costs to check.已准备的优化器、待检查决策向量与代价。
step
Central-difference step, default 1e-6.中心差分步长,默认 1e-6。
tolerance
Absolute Euclidean gradient-error tolerance, default 1e-4.梯度欧氏误差的绝对容差,默认 1e-4。

Returns返回GradientCheckResult

API接口Behavior行为
SerialExecutor Default sequential segment execution.默认顺序执行各段。
OpenMPExecutor OpenMP static segment loop when enabled; serial otherwise. Integral callbacks must be thread-safe; exceptions must not escape worker callbacks.启用 OpenMP 时静态并行处理各段,否则串行。积分回调需线程安全,异常不可逃出工作线程回调。
Type / field类型 / 字段Meaning含义
GradientCheckResultstatus; vectors analytical, numerical; error_norm (Euclidean), relative_error, max_absolute_error, max_error_index. Success uses the absolute error_norm tolerance.status;向量 analytical、numerical;欧氏误差 error_norm、relative_error、max_absolute_error、max_error_index。通过条件使用 error_norm 的绝对容差。

Convex-hull conversion & gradients凸包转换与梯度#

#include "SplineConvexHull.hpp"

Factories and workspace reuse便利工厂与工作区复用#

toBezier(poly, derivative_order, subdivision_depth)#

Create and update a Bezier hull workspace in one call.一步创建并更新 Bezier 凸包工作区。

template<int DIM, int MaxCoefficients>
ConvexHullWorkspace<DIM> toBezier(
    const PPolyND<DIM, MaxCoefficients>& poly,
    DerivativeOrder derivative_order = Deriv::Pos, int subdivision_depth = 0);
poly
Source polynomial, with N segments and K coefficients per segment.源多项式,含 N 段,每段 K 个系数。
derivative_order
Derivative order: Pos=0, Vel=1, Acc=2, …; defaults to position.导数阶数:Pos=0、Vel=1、Acc=2 等,默认位置。
subdivision_depth
Depth d produces 2^d pieces per source segment.深度 d 将每个源段分为 2^d 个分片。

Returns返回ConvexHullWorkspace<DIM>

toMINVO(poly, derivative_order, subdivision_depth)#

Create an updated MINVO workspace. Arguments have the same meaning as toBezier().创建已更新的 MINVO 工作区,参数含义与 toBezier() 相同。

template<int DIM, int MaxCoefficients>
ConvexHullWorkspace<DIM> toMINVO(
    const PPolyND<DIM, MaxCoefficients>& poly,
    DerivativeOrder derivative_order = Deriv::Pos, int subdivision_depth = 0);

Returns返回ConvexHullWorkspace<DIM>

ConvexHullWorkspace::fromPPoly(poly, options)#

Owning configured and updated workspace; may allocate and synchronize kernel acquisition. Does not retain a source reference.返回已配置并数值更新、拥有存储的工作区;可能分配并同步获取转换核。不保留源引用。

template<int MaxCoefficients>
static ConvexHullWorkspace fromPPoly(
    const PPolyND<DIM, MaxCoefficients>& poly, HullOptions options = {});
poly
Source polynomial, with N segments and K coefficients per segment.源多项式,含 N 段,每段 K 个系数。
options
Hull basis, derivative order and subdivision depth.凸包基、导数阶数和细分深度。

Returns返回ConvexHullWorkspace

hull.prepare(...)#

Prepares topology and shared immutable kernel; controls are not valid yet. May allocate and lock the kernel cache.准备拓扑与共享不可变核,控制点尚无效。可能分配并锁定核缓存。

void prepare(int segments, int coefficient_count, HullOptions options = {});
template<int MaxCoefficients>
void prepare(const PPolyND<DIM, MaxCoefficients>& poly, HullOptions options = {});
segments, coefficient_count
N source segments and K coefficients per segment; alternatively pass poly.源段数 N 与每段系数数 K,也可直接传 poly。
options
Hull basis, derivative order and subdivision depth.凸包基、导数阶数和细分深度。

Returns返回void

hull.update(poly)#

Returns void; requires configured matching topology. Refreshes controls/time and adjoint caches without allocation or locking.返回 void,要求已配置且拓扑匹配。无分配、无锁地更新控制点/时间与伴随缓存。

template<int MaxCoefficients>
void update(const PPolyND<DIM, MaxCoefficients>& poly);
poly
Source polynomial, with N segments and K coefficients per segment.源多项式,含 N 段,每段 K 个系数。

Returns返回void

hull.update(poly, options)#

Prepare when topology or options change, then update. Matching configurations reuse storage.拓扑或配置变化时准备工作区,再更新;配置匹配时复用存储。

template<int MaxCoefficients>
void update(const PPolyND<DIM, MaxCoefficients>& poly, HullOptions options);
poly
Source polynomial, with N segments and K coefficients per segment.源多项式,含 N 段,每段 K 个系数。
options
Hull basis, derivative order and subdivision depth.凸包基、导数阶数和细分深度。

Returns返回void

API / options接口 / 选项Return / meaning返回 / 含义
HullOptions {basis, derivative_order, subdivision_depth} Default Bezier, position (0), depth 0. Derivative order is between 0 and source degree. MINVO result degree must be 0…7. Supported depth is 0…16; caller owns feasible memory/index bounds.默认 Bezier、位置(0)、深度 0。导数阶在 0 到源次数之间;MINVO 结果次数须为 0…7。支持深度 0…16,调用方负责可用内存与索引范围。
isPrepared / isValid / matches(poly, options) Separate topology readiness, numeric readiness and topology/options matching. Each concurrent computation needs its own mutable workspace.分别判断拓扑就绪、数值就绪、拓扑/选项匹配。每个并发计算使用独立可变工作区。
Runnable control-cost adjoint example可运行的控制点代价反传示例C++17
#include "SplineConvexHull.hpp"
#include <iostream>

int main() {
    using Spline = SplineTrajectory::QuinticSplineND<3>;
    Spline::WaypointMatrix waypoints(3, 3);
    waypoints << 0, 0, 0,  1, 0.5, 0,  2, 0, 0;
    Spline spline;
    if (const auto status = spline.update({1.2, 1.5}, waypoints, 0.0); !status) return 1;
    SplineTrajectory::ConvexHullWorkspace<3> hull;
    hull.prepare(spline.polynomial(), {SplineTrajectory::ConvexHullBasis::Bezier, 0, 1});
    hull.update(spline.polynomial());

    // L = 0.5 * ||controls||^2, dL/dControls = controls.
    auto dControls = hull.controls().eval();
    auto partials = hull.backward(dControls);
    auto gradients = spline.backward(partials.coefficients, partials.durations);
    std::cout << hull.numPieces() << '\n' << gradients.durations.transpose() << '\n';
}

Prepare user-owned hull workspaces and control-gradient matrices before solving, then call strict update(poly) inside the callback. update(poly, options) is a convenience overload that prepares on a mismatch and may allocate then; matching repetitions reuse storage. See the example.求解前显式准备用户持有的凸包和控制点梯度矩阵,回调内调用固定拓扑 update(poly)。便捷重载 update(poly, options) 仅在不匹配时准备,届时可能分配;匹配时复用。见示例。

Controls and child-piece metadata控制点与子段元数据#

Depth d creates H = N · 2^d child pieces. If the derivative polynomial has degree q, each piece has Q = q+1 controls. Controls are stored in piece-major row order.深度 d 产生 H = N · 2^d 个子段。若导数多项式次数为 q,则每个子段有 Q = q+1 个控制点,按子段优先顺序存储。

Method / field方法 / 字段Shape / return形状 / 返回Contract契约
controls() const CoefficientMatrix& · (H·Q) × D Borrow all controls after update.更新后借用全部控制点。
piece(i)Borrowed proxy借用代理info() and controls() access one piece’s metadata and contiguous control rows.通过 info() 和 controls() 读取该分片元数据与连续控制点行。
pieceControls(i) Q × D Borrow a block; requires valid piece index and updated workspace.借用行块,要求合法子段索引与已更新工作区。
pieceInfo(i) / pieceInfos() const PieceInfo& / const std::vector<PieceInfo>& Contains source_segment, subdivision_index, source_fraction_begin/end, physical start_time and duration. Reconfiguration invalidates references.包含源段号、细分号、源段归一化区间、物理起点与时长。重新配置使引用失效。
numPieces / controlsPerPiece / piecesPerSegment / numSourceSegments H / Q / 2^d / N Topology sizes.拓扑规模。
basis / derivativeOrder / degree / sourceDegree / subdivisionDepth Basis / DerivativeOrder / integers DerivativeOrder supports .value() and equality. q is differentiated degree.DerivativeOrder 支持 .value() 和相等比较;q 为求导后的次数。
powerToControlMatrix(basis, degree) Eigen::MatrixXd Owning B with b = B a, where b contains controls and a contains normalized ascending-power coefficients.返回独立 B,满足 b = B a,其中 b 为控制点,a 为归一化升幂系数。
Type / field类型 / 字段Meaning含义
PieceInfo::source_segment / subdivision_indexZero-based source segment and subdivision index within that segment.从零开始的源段号及该源段内的细分号。
source_fraction_begin / source_fraction_endNormalized interval within the source segment, from 0 to 1.在源段内的归一化区间,范围为 0 到 1。
start_time / durationPiece start on the trajectory axis and physical duration, in seconds.分片在轨迹时间轴上的起点与物理时长,单位为秒。

Control and explicit-time pullbacks控制点与显式时间反传#

hull.backward(gdControls)#

Returns an owning BackwardResult; allocates.返回拥有的 BackwardResult,分配输出。

BackwardResult backward(const CoefficientMatrix& gdControls);
gdControls
Control-point partials, matching the rows of hull.controls().控制点偏导,行数与 hull.controls() 一致。

Returns返回(H·Q)×D → {coefficients: (N·K)×D, durations: N}

hull.backward(gdControls, gdC, gdT)#

Overwrites owning outputs, resizing as needed and reusing matching storage.覆盖拥有型输出,按需调整尺寸,同尺寸复用。

void backward(const CoefficientMatrix& gdControls,
              CoefficientMatrix& gdC, Eigen::VectorXd& gdT);
gdControls
Control-point partials, matching the rows of hull.controls().控制点偏导,行数与 hull.controls() 一致。
gdC
Source coefficient partials, shaped (N·K) × DIM.源系数偏导,形状为 (N·K) × DIM。
gdT
N independent source-duration partials.N 项独立源段时长偏导。

Returns返回void

hull.backwardAdd(gdControls, gdC, gdT)#

Adds to initialized buffers. Suitable inside the optimizer’s coefficient stage.累加到已初始化缓冲,适用于优化器 coefficient 阶段。

void backwardAdd(const CoefficientMatrix& gdControls,
                 Eigen::Ref<CoefficientMatrix> gdC, Eigen::Ref<Eigen::VectorXd> gdT);
gdControls
Control-point partials, matching the rows of hull.controls().控制点偏导,行数与 hull.controls() 一致。
gdC
Source coefficient partials, shaped (N·K) × DIM.源系数偏导,形状为 (N·K) × DIM。
gdT
N independent source-duration partials.N 项独立源段时长偏导。

Returns返回void

hull.backwardPieceTimesAdd(gStart, gDuration, gdT, gStartTime)#

Adds explicit child-piece time partials; separate from the control adjoint.累加子段显式时间偏导,独立于控制点伴随。

void backwardPieceTimesAdd(
    const Eigen::Ref<const Eigen::VectorXd>& piece_start_gradients,
    const Eigen::Ref<const Eigen::VectorXd>& piece_duration_gradients,
    Eigen::Ref<Eigen::VectorXd> source_duration_gradients,
    double& source_start_time_gradient) const;
gStart, gDuration
One explicit start-time and duration partial per hull piece.每个凸包分片一项显式起点时间与时长偏导。
gdT, gStartTime
Source duration and common-start-time gradients to accumulate into.累加输出的源段时长与整体起点时间梯度。

Returns返回void

All adjoints require an updated workspace and matching finite inputs. Overwrite/Add outputs must not alias inputs or workspace storage. Keep both gdC and gdT: normalization uses aₖ = Tᵏcₖ, so conversion depends explicitly on duration. Pass the resulting pair through spline.backward() for total physical gradients.所有伴随要求工作区已更新、输入匹配且有限。Overwrite/Add 输出不得与输入或工作区重叠。保留 gdC 与 gdT 两者:归一化使用 aₖ = Tᵏcₖ,转换显式依赖时长。将两者传给 spline.backward() 得到完整物理梯度。

hull.backward(gdControls, output)#

Overwrites BackwardResult.coefficients and .durations, reusing matching storage.覆盖 BackwardResult.coefficients 和 .durations,尺寸匹配时复用。

void backward(const CoefficientMatrix& gdControls, BackwardResult& output);
gdControls
Control-point partials, matching the rows of hull.controls().控制点偏导,行数与 hull.controls() 一致。
output
Owning coefficient and duration partials.拥有型系数与时长偏导。

Returns返回void

hull.backwardAdd(gdControls, gradient)#

Adds both partials to CoefficientGradientView; use directly inside a coefficient cost.将两项偏导累加到 CoefficientGradientView,可直接在 coefficient 代价中使用。

template<class GradientView>
void backwardAdd(const CoefficientMatrix& gdControls, GradientView& gradient);
gdControls
Control-point partials, matching the rows of hull.controls().控制点偏导,行数与 hull.controls() 一致。
gradient
The coefficient stage’s CoefficientGradientView.coefficient 阶段的 CoefficientGradientView。

Returns返回void

hull.backwardPieceTimesAdd(gStart, gDuration, gradient)#

Adds explicit piece-time partials to the view’s durations and start_time.将分片显式时间偏导累加到视图的 durations 和 start_time。

template<class GradientView>
void backwardPieceTimesAdd(
    const Eigen::Ref<const Eigen::VectorXd>& piece_start_gradients,
    const Eigen::Ref<const Eigen::VectorXd>& piece_duration_gradients,
    GradientView& gradient) const;

Returns返回void

Bezier subdivision and convex boundsBezier 细分与凸包约束#

Bezier convex bounds / Bezier 凸包约束

Dark line: one fixed quintic trajectory. Shading: convex hull of each child piece’s controls. Subdivision changes the bounds, not the curve. Control data comes from the C++ Bezier conversion; browser subdivision uses de Casteljau at 1/2. This figure does not compare MINVO.深色线是固定五次轨迹;阴影是各子段控制点的凸包。细分改变包络,不改变轨迹。控制点来自 C++ Bezier 转换;浏览器采用 1/2 处 de Casteljau 细分。此图不作 MINVO 对比。

If every position control of a piece is inside one convex corridor, the whole curve piece is inside it. Derivative controls give conservative velocity/acceleration bounds. Use trajectory collision checks for nonconvex ESDF free space, and evaluate the required constraints on the final trajectory.若一段的全部位置控制点位于同一凸走廊,整段曲线就在走廊内。导数控制点可给出保守速度/加速度界。非凸 ESDF 自由空间采用轨迹碰撞检测,并在最终轨迹上检查所需约束。