Tutorial#

Important

Capacity vs. active count (the custom Warp examples and the full API). Factor and state batches are constructed with their capacity (how many factors / states their buffers hold) and start with zero active entries: call set_num_active_factors(n) / set_num_active_states(n) before solving, and again whenever the problem size changes. See Capacity and active count. pycunls.ProblemBuilder (the first two examples) does this for you.

Overview#

This tutorial walks through four complete pycunls examples, each demonstrating a different optimization pattern. The first two build their problems with pycunls.ProblemBuilder from NumPy arrays:

  1. Add the states from their initial values (add_states).

  2. Add the factors from their measurements and the states each one connects (add_factors).

  3. Solve (solve: checks the problem, then runs a minimizer) and read the states back as NumPy.

The two custom Warp examples use the full API, which the builder sets up underneath (the flow of the Introduction and Quick Start):

  1. Allocate state data on the GPU (Warp arrays).

  2. Wrap the GPU memory in one or more state batch objects.

  3. Build one or more factor batch objects from observations.

  4. Add state batches and factor batches to a Problem.

  5. Run a minimizer and inspect MinimizerSummary.

The examples increase in complexity. For problems with gross outliers, see Robust Estimation with RANSAC and python/examples/ransac_pnp.py; for visual-inertial bundle adjustment, see IMU factor and python/examples/imu_bundle_adjustment.py; for frame-by-frame inertial PnP with RANSAC, see python/examples/tartan_vio.py; for the full custom-type contract (needed by RANSAC), see Custom Factors and States (Python and C++).

Full source code for all examples lives in the python/examples/ directory.

Note

Using cuNLS from C++. The C++ versions of these examples (and a custom factor written as a CUDA kernel) are in C++ Tutorial.

Sparse Bundle Adjustment#

  • Source: python/examples/sparse_bundle_adjustment.py

SBA problem statement#

This is the Python version of the C++ bundle adjustment example (see Sparse Bundle Adjustment for the full mathematical formulation). Given \(M\) cameras with poses \(T_1, \ldots, T_M \in \mathrm{SE}(3)\) (world_from_camera) and \(N\) 3D landmarks \(\mathbf{p}_1, \ldots, \mathbf{p}_N \in \mathbb{R}^3\), we minimize the sum of squared reprojection errors across all \(K\) observations:

\[\min_{T_1,\ldots,T_M,\; \mathbf{p}_1,\ldots,\mathbf{p}_N} \frac{1}{2} \sum_{k=1}^{K} \left\| \pi(T_{i_k}, \mathbf{p}_{j_k}) - \mathbf{z}_k \right\|^2\]

Poses \(T_0\) and \(T_1\) are held constant as gauge anchors (frame and scale).

SBA API used#

Class

Role

ProblemBuilder

Builds the problem from NumPy arrays, checks it, solves it and returns the states as NumPy.

SE3StateBatch

Camera poses (world_from_camera) on the SE(3) manifold; the first two are constant (frame and scale gauge).

VectorStateBatch3

3D landmark coordinates in \(\mathbb{R}^3\).

ReprojectionFactorBatch

Normalized reprojection residual and Jacobians of each (pose, point) pair.

SBA code walkthrough#

Step 1 — Generate synthetic data. bundle_adjustment_scene returns ground-truth SE(3) poses and 3D points, a perturbed initial guess (pose 0 stays exact) and the normalized observation of every point in every camera, as NumPy arrays. The data comes from python/examples/example_utils/datasets.py; the generators are ordinary NumPy code and are not part of the lesson.

# 1. Synthetic data: ground-truth cameras and points, a perturbed initial
#    guess, and the normalized observation of every point in every camera.
scene = datasets.bundle_adjustment_scene(num_poses=6, num_points=800)
num_poses, num_points = len(scene.gt_poses), len(scene.gt_points)

Step 2 — Add the state batches. add_states takes the class and the initial values ((N, 4, 4) row-major poses, (M, 3) points); constant lists the states held fixed. It returns a handle for connecting factors and reading the solution.

# 2. Two state batches: camera poses (0 and 1 constant: frame and scale
#    gauge) and 3D points.
pb = pycunls.ProblemBuilder()
cameras = pb.add_states(pycunls.SE3StateBatch, scene.initial_poses,  # (N, 4, 4)
                        constant=[0, 1])
points = pb.add_states(pycunls.VectorStateBatch3, scene.initial_points)  # (M, 3)

Step 3 — Add the reprojection factors. add_factors takes the class, its measurement arrays (pycunls.describe lists them) and connect: which states each factor reads. A reprojection factor reads [pose, point] from two batches, so connect has one (handle, indices) pair per slot. Shapes, state types and index ranges are checked here, with the fix in the message.

# 3. One reprojection factor per observation. Its two state slots live in
#    different batches, so connect gives one (handle, indices) pair per slot:
#    observation k is point pt_ids[k] seen by camera cam_ids[k] (camera-major).
cam_ids = np.repeat(np.arange(num_poses), num_points)
pt_ids = np.tile(np.arange(num_points), num_poses)
pb.add_factors(pycunls.ReprojectionFactorBatch, scene.observations,  # (N * M, 2)
               connect=[(cameras, cam_ids), (points, pt_ids)])

Step 4 — Solve on the Schur complement. Options go by name (fields of MinimizerOptions and LevenbergMarquardtMinimizerOptions). Eliminating the points is a setting of the underlying Problem (pb.problem), the full API the builder created. solve runs pycunls.diagnose first and writes the solution into the state arrays.

# 4. Solve with Levenberg-Marquardt on the Schur complement: the points are
#    eliminated, the reduced camera system is factored. The elimination is a
#    setting of the underlying pycunls.Problem (pb.problem; points.batch is
#    the VectorStateBatch3).
pb.problem.set_eliminated_state_batches([points.batch])
result = pb.solve(max_num_iterations=80, state_tolerance=1e-8, cost_tolerance=1e-8,
                  initial_lambda=1e-3,
                  linear_system=pycunls.LinearSystemType.SchurComplement)

Step 5 — Read back and validate. result[points] is the solved (M, 3) NumPy array; result.converged and result.message say how the solve ended.

# 5. Results: the solved points as NumPy, compared with the ground truth.
optimized_points = result[points]
mse_before = metrics.mse(scene.initial_points, scene.gt_points)
mse_after = metrics.mse(optimized_points, scene.gt_points)
report.print_summary("Sparse Bundle Adjustment (pycunls)", result.summary,
                     Point_MSE=f"{mse_before:.6f} -> {mse_after:.6f}")
print(result.message)
report.check(result.converged, result.message)
report.check(mse_after < 0.1 * mse_before, "point error did not decrease")


Pose Graph Optimization#

  • Source: python/examples/pose_graph_optimization.py

PGO problem statement#

This is the Python version of the C++ pose graph example (see Pose Graph Optimization for the full mathematical formulation). A chain of \(N\) SE(3) poses is connected by \(N{-}1\) between constraints. The residual for constraint \(i\) is:

\[r_i = \mathrm{Log}\!\left( \Delta_i \, T_i^{-1} \, T_{i+1} \right) \in \mathbb{R}^6\]

Pose \(T_0\) is held constant as a gauge anchor.

PGO API used#

Class

Role

ProblemBuilder

Builds, checks and solves the problem from NumPy arrays.

SE3StateBatch

The pose chain; the first pose is constant.

SE3BetweenFactorBatch

Relative-transform residual and its Jacobians w.r.t. both poses.

PGO code walkthrough#

Step 1 — Generate the pose chain and its measurements. pose_chain returns a ground-truth chain, the relative transform between each consecutive pair, and a perturbed initial guess. The data comes from python/examples/example_utils/datasets.py; the generators are ordinary NumPy code and are not part of the lesson.

# 1. Synthetic data: ground-truth chain, its relative measurements, a
#    perturbed initial guess.
chain = datasets.pose_chain(num_poses=201)
num_poses = len(chain.gt_poses)

Step 2 — Build the graph. One state batch with pose 0 constant; factor \(i\) connects [T_i, T_{i+1}] through an (N-1, 2) edge array. Note the between convention: Delta_i = T_{i+1}^-1 T_i.

# 2. The graph: states from their initial values, factors from their
#    measurements and the states each one connects. Between factor i reads
#    [T_i, T_{i+1}] and measures Delta_i = T_{i+1}^-1 T_i.
pb = pycunls.ProblemBuilder()
poses = pb.add_states(pycunls.SE3StateBatch, chain.initial_poses,  # (N, 4, 4)
                      constant=[0])  # the gauge anchor
edges = np.stack([np.arange(num_poses - 1), np.arange(1, num_poses)], axis=1)  # (N-1, 2)
pb.add_factors(pycunls.SE3BetweenFactorBatch, chain.deltas, connect=(poses, edges))

Step 3 — Solve with Levenberg-Marquardt. The checks run first: without constant=[0] the builder would warn about the gauge freedom of the chain.

# 3. Solve with Levenberg-Marquardt (the default method). diagnose() runs
#    first: a missing anchor, NaN data or a wrong state type raise or warn
#    here. Each step factors the normal equations with BlockSparseCholesky
#    (the default; exact steps).
result = pb.solve(max_num_iterations=60, state_tolerance=1e-8, cost_tolerance=1e-8,
                  initial_lambda=1e-3)

Step 4 — Read back and check. result.evaluate() prints the residual statistics per factor batch (RMS, worst factor), the first thing to look at when a solve disappoints.

# 4. Results: the solved poses as NumPy, the outcome, residuals per batch.
optimized = result[poses]  # (N, 4, 4)
summary = result.summary
report.print_summary("Pose Graph Optimization (pycunls)", summary,
                     Num_poses=num_poses, Num_factors=len(edges))
print(result.message)
print(result.evaluate())
report.check(result.converged, result.message)
report.check(summary.final_cost < 1e-3 * summary.initial_cost, "cost did not decrease")
# Position error against the ground truth; along an open chain it grows
# slowly with the distance from the anchor (float32 composition).
before = np.abs(chain.initial_poses[:, :3, 3] - chain.gt_poses[:, :3, 3]).max()
after = np.abs(optimized[:, :3, 3] - chain.gt_poses[:, :3, 3]).max()
print(f"  Max position error: {before:.3f} -> {after:.4f}")
report.check(after < 0.1 * before, "position error did not decrease")

Step 5 — The full API underneath. The builder’s objects stay reachable for real-time use, where batches are allocated once and re-solved with changing active counts (see Quick Start and python/examples/tartan_vio.py).

# 5. Underneath is an ordinary pycunls.Problem: pb.problem, poses.batch (the
#    SE3StateBatch) and poses.data (the Warp array the solve updates) are the
#    full API, e.g. for real-time re-solves with fixed buffers (see
#    tartan_vio.py and the quick start).


Custom Warp Factor#

  • Source: python/examples/custom_warp_factor.py

Note

For the full evaluate / plus contract (items, factor_ids_ptr, num_factor_ids, num_replicas), a self-contained custom factor and state, and how to use them with the RANSAC minimizers, see Custom Factors and States (Python and C++).

Custom Warp factor problem statement#

This is a Python port of the C++ custom factor example (see Custom Factor). It builds a chain of scalar states connected by difference constraints implemented as an NVIDIA Warp kernel through WarpFactorBatch (from pycunls.warp):

\[r_i = (x_{i+1} - x_i) - m_i, \qquad i = 0, \ldots, N{-}2\]

A prior factor anchors \(x_0\) to its observed value:

\[r_{\mathrm{prior}} = x_0 - x_0^{\mathrm{obs}}\]

Warp factor API used#

Class

Role

VectorStateBatch1

Stores all \(N\) scalar states in \(\mathbb{R}^1\).

WarpFactorBatch

Base class for user-defined factors evaluated via Warp kernels. Provides wrap_array and make_warp_stream helpers.

PriorVectorFactorBatch1

Built-in prior factor that anchors \(x_0\).

Problem

Assembles the factor graph.

LevenbergMarquardtMinimizer

Solves the nonlinear system.

Warp factor code walkthrough#

The solve lives in run_chain_example, which main calls twice: Part 1 with ScalarDiffFactor, Part 2 with the residual-only factor and numeric Jacobians.

Step 1 — Define the Warp kernel. One thread per item: one factor evaluated at one set of states. Item t reads the measurement of its factor ids[t] and its own two state values (through the state pointer table, with state_value), and writes row t. The regular minimizers evaluate each factor once (ids[t] == t); the RANSAC minimizers evaluate many items per factor (see Custom Factors and States (Python and C++)).

@wp.kernel
def scalar_diff_kernel(measurements: wp.array(dtype=wp.float32),
                       ids: wp.array(dtype=wp.int32),
                       state_pointers: wp.array(dtype=wp.uint64),
                       residuals: wp.array(dtype=wp.float32),
                       jacobians: wp.array(dtype=wp.float32),
                       write_jacobians: int):
    t = wp.tid()                                                # item
    left = state_value(state_pointers, 2 * t, 0)                # x_i
    right = state_value(state_pointers, 2 * t + 1, 0)           # x_{i+1}
    residuals[t] = (right - left) - measurements[ids[t]]        # measurement of its factor
    if write_jacobians != 0:
        jacobians[2 * t] = -1.0                                 # d r / d x_i
        jacobians[2 * t + 1] = 1.0                              # d r / d x_{i+1}

Step 2 — Subclass WarpFactorBatch. evaluate receives raw device pointers. factor_ids gives the factor of every item (t % num_active_factors when cuNLS passes none), the state pointer table (2 * n addresses, item t’s states at 2t and 2t + 1) is wrapped as a wp.uint64 array for the kernel, and the kernel runs on cuNLS’s stream. When jacobians_ptr is 0 only residuals are wanted. The constructor passes the capacity (measurements the buffer holds) to the base class; num_active_factors is the active count, 0 until set_num_active_factors.

class ScalarDiffFactor(WarpFactorBatch):
    """residual = (x_right - x_left) - m; one residual, two scalar states."""

    def __init__(self, measurements, capacity):
        # capacity: measurements the buffer holds (fixed). self.num_active_factors is the
        # active count: 0 until set_num_active_factors().
        super().__init__(residual_size=1, state_sizes=[1, 1], capacity=capacity)
        self.measurements = measurements

    def evaluate(self, *args):
        """Item t looks up its factor's data by ids[t] and reads its state through the
        pointer table (see WarpFactorBatch.items)."""
        return self.launch(scalar_diff_kernel, self.items(*args), [self.measurements])

Step 3 — The state reader. state_value lives in example_utils/gpu.py and is reusable for any Warp factor: it reads one component of the state a table entry points to.

@wp.func
def state_value(state_pointers: wp.array(dtype=wp.uint64), slot: int, component: int) -> float:
    """Component ``component`` of the state that ``state_pointers[slot]`` points to."""
    state = wp.array(ptr=state_pointers[slot], shape=(component + 1,), dtype=float)
    return state[component]

Step 4 — Generate synthetic data. scalar_chain returns a monotonic chain, exact consecutive differences and a noisy initial guess. The data comes from python/examples/example_utils/datasets.py; the generators are ordinary NumPy code and are not part of the lesson.

# 1. Synthetic data: monotonic chain, exact differences, noisy initial guess.
chain = datasets.scalar_chain(num_states=256)
num_states = len(chain.gt)

Step 5 — Upload to the GPU. States, the prior target and the measurements (read inside the Warp kernel) go to Warp arrays.

# 2. Upload states, the anchor value and the measurements as Warp arrays.
states_gpu = wp.array(chain.initial, dtype=wp.float32)
prior_gpu = wp.array(chain.gt[:1], dtype=wp.float32)
measurements_wp = wp.array(chain.measurements, dtype=wp.float32)

Step 6 — Build states, factors and state pointers. Difference factors read [x_i, x_{i+1}]; the built-in prior anchors x_0. Every batch starts with 0 active entries and is activated with set_num_active_states / set_num_active_factors.

# 3. Scalar states; one difference factor per pair (x_i, x_{i+1}); a
#    built-in prior anchoring x_0.
#    Capacity vs. active count. A batch is constructed with its capacity: how many states (or
#    factors) its bound device buffers hold. The capacity is fixed for the batch's lifetime;
#    size it once for the largest problem you expect. Right after construction nothing is
#    active: set_num_active_states / set_num_active_factors set the active count, how many of
#    the first slots the next solve uses (a solve without it throws). The setter is host-only
#    (no allocation, no device work) and may change the count between solves up to the capacity,
#    which is what lets a real-time application allocate once and reuse the same buffers every
#    frame while the problem size changes. This example solves every slot once, so each active
#    count equals its capacity.
states_capacity = num_states  # every slot solved: active = capacity
states = pycunls.VectorStateBatch1(states_gpu, states_capacity)
states.set_num_active_states(num_states)  # active count
diff_pointers = []
for i in range(num_states - 1):
    diff_pointers.append(states.state_device_ptr(i))
    diff_pointers.append(states.state_device_ptr(i + 1))
num_diff_factors = num_states - 1
diff_capacity = num_diff_factors  # used by the difference factor in step 4
prior_capacity = 1
prior = pycunls.PriorVectorFactorBatch1(prior_gpu, prior_capacity)
num_prior_factors = 1
prior.set_num_active_factors(num_prior_factors)

Step 7 — Assemble the problem. Part 2 registers the residual-only variant (same file, ScalarDiffResidualOnlyFactor) with JacobianMode.numeric; the prior keeps its analytic Jacobian (see Numeric (finite-difference) Jacobians).

# 4. Problem. Part 2 overrides the Jacobian mode of the difference factors
#    only; the prior keeps its analytic Jacobian.
problem = pycunls.Problem()
problem.add_state_batch(states)
if use_numeric_jacobian:
    diff = ScalarDiffResidualOnlyFactor(measurements_wp, diff_capacity)
    diff.set_num_active_factors(num_diff_factors)  # active count
    problem.add_factor_batch(diff, diff_pointers,
                             jacobian_mode_override=pycunls.JacobianMode.numeric)
else:
    diff = ScalarDiffFactor(measurements_wp, diff_capacity)
    diff.set_num_active_factors(num_diff_factors)  # active count
    problem.add_factor_batch(diff, diff_pointers)
problem.add_factor_batch(prior, [states.state_device_ptr(0)])
assert problem.check_consistency(), "Problem consistency check failed"

Step 8 — Solve with Levenberg-Marquardt. Same solver as in the previous examples. The uploads ran on Warp’s stream and the solve runs on its own CudaStream, so Warp’s stream is synchronized first; minimize synchronizes its stream before returning.

# 5. Solve with Levenberg-Marquardt.
options = pycunls.LevenbergMarquardtMinimizerOptions()
options.base_options.max_num_iterations = 50
options.base_options.state_tolerance = 1e-8
options.base_options.cost_tolerance = 1e-8
options.initial_lambda = 1e-3
stream = pycunls.CudaStream()
wp.synchronize_stream(wp.get_stream())  # uploads ran on Warp's stream: finish them first
summary = pycunls.LevenbergMarquardtMinimizer(options).minimize(stream, problem)  # syncs

Step 9 — Report and check. Compare with the ground truth and check.

# 6. Report and check.
mse_before = metrics.mse(chain.initial, chain.gt)
mse_after = metrics.mse(states_gpu.numpy(), chain.gt)
report.print_summary(title, summary, State_MSE=f"{mse_before:.6f} -> {mse_after:.6f}")
report.check(mse_after < 0.01 * mse_before, "state error did not decrease")


Custom Warp State#

  • Source: python/examples/custom_warp_state.py

Custom Warp state problem statement#

This example demonstrates WarpStateBatch (from pycunls.warp) by defining a positive-scalar manifold where the Plus (retraction) operation is multiplicative:

\[x \oplus \delta = x \cdot \exp(\delta)\]

This makes the tangent space the reals (\(\delta \in \mathbb{R}\)), while states stay strictly positive — the natural parameterization for quantities like scales, variances, or rates.

A chain of positive scalars is connected by log-ratio between-factors:

\[r_{\mathrm{prior}} = \log(x_0) - \log(t_0), \qquad r_i = \log(x_{i+1} / x_i) - m_i\]

All Jacobians equal \(\pm 1\) because the problem is linear in the tangent (log) space.

Warp state API used#

Class

Role

WarpStateBatch

Base class for user-defined state batches with a Warp-based Plus. Provides wrap_array and make_warp_stream helpers.

WarpFactorBatch

Base class for the custom log-prior and log-ratio factors.

Problem

Assembles the factor graph.

LevenbergMarquardtMinimizer

Solves the nonlinear system.

Warp state code walkthrough#

Step 1 — Define the Plus kernel. The retraction \(x \oplus \delta = x\,e^{\delta}\) keeps every state positive.

@wp.kernel
def positive_plus_kernel(x: wp.array(dtype=wp.float32), delta: wp.array(dtype=wp.float32),
                         x_plus_delta: wp.array(dtype=wp.float32)):
    i = wp.tid()
    x_plus_delta[i] = x[i] * wp.exp(delta[i])

Step 2 — Subclass WarpStateBatch. plus receives num_replicas contiguous copies of the batch (1 for the regular minimizers, one per hypothesis for RANSAC). Every state is independent, so all copies are one flat launch over num_replicas * num_active_states states (num_active_states is the active count, at most the capacity).

class PositiveScalarStateBatch(WarpStateBatch):
    """Ambient size 1 (the positive value), tangent size 1 (delta in R)."""

    def __init__(self, data, capacity, **kwargs):
        super().__init__(data, ambient_size=1, tangent_size=1, capacity=capacity, **kwargs)

    def plus(self, x_ptr, delta_ptr, x_plus_delta_ptr, stream_handle, num_replicas):
        # The arrays hold num_replicas contiguous copies of the active states
        # (num_active_states, at most the capacity); every state is independent,
        # so all copies are one flat launch.
        n = self.num_active_states * num_replicas
        wp.launch(positive_plus_kernel, dim=n,
                  inputs=[self.wrap_array(x_ptr, wp.float32, n),
                          self.wrap_array(delta_ptr, wp.float32, n),
                          self.wrap_array(x_plus_delta_ptr, wp.float32, n)],
                  stream=self.make_warp_stream(stream_handle))

Step 3 — Define the factors. Two custom factors in log space: a prior on x_0 and a log-ratio between consecutive states. Both follow the same item pattern as in the custom factor example: measurement by ids[t], states and outputs by t.

@wp.kernel
def log_ratio_kernel(measurements: wp.array(dtype=wp.float32), ids: wp.array(dtype=wp.int32),
                     state_pointers: wp.array(dtype=wp.uint64),
                     residuals: wp.array(dtype=wp.float32), jacobians: wp.array(dtype=wp.float32),
                     write_jacobians: int):
    t = wp.tid()
    left = state_value(state_pointers, 2 * t, 0)
    right = state_value(state_pointers, 2 * t + 1, 0)
    residuals[t] = wp.log(right) - wp.log(left) - measurements[ids[t]]
    if write_jacobians != 0:
        jacobians[2 * t] = -1.0
        jacobians[2 * t + 1] = 1.0
class LogRatioBetweenFactor(WarpFactorBatch):
    """residual = log(x_right / x_left) - m; two states."""

    def __init__(self, measurements, capacity):
        super().__init__(residual_size=1, state_sizes=[1, 1], capacity=capacity)
        self.measurements = measurements

    def evaluate(self, res_ptr, jac_ptr, sp_ptr, stream_handle, factor_ids_ptr, num_factor_ids):
        n = num_factor_ids
        ids = self.factor_ids(factor_ids_ptr, n)
        state_pointers = self.wrap_array(sp_ptr, wp.uint64, 2 * n)  # [2t], [2t + 1]
        write_jacobians = 1 if jac_ptr != 0 else 0
        jacobians = (self.wrap_array(jac_ptr, wp.float32, 2 * n) if write_jacobians
                     else wp.zeros(1, dtype=wp.float32, device=self._device))
        wp.launch(log_ratio_kernel, dim=n,
                  inputs=[self.measurements, ids, state_pointers,
                          self.wrap_array(res_ptr, wp.float32, n), jacobians, write_jacobians],
                  stream=self.make_warp_stream(stream_handle))
        return True

Step 4 — Generate synthetic data. positive_chain returns a growing positive chain, its log-ratio measurements and a noisy initial guess. The data comes from python/examples/example_utils/datasets.py; the generators are ordinary NumPy code and are not part of the lesson.

# 1. Synthetic data: growing positive chain, log-ratio measurements, noisy guess.
chain = datasets.positive_chain(num_states=128)
num_states = len(chain.gt)

Step 5 — Upload to the GPU. States and factor data go to Warp arrays.

# 2. Upload states and factor data as Warp arrays.
states_gpu = wp.array(chain.initial, dtype=wp.float32)
log_ratios_wp = wp.array(chain.measurements, dtype=wp.float32)
prior_wp = wp.array(chain.gt[:1], dtype=wp.float32)

Step 6 — Build the custom state and factor batches. The custom state batch wraps the Warp array; the factors read [x_i, x_{i+1}] and x_0. Custom batches follow the same capacity rule as the built-in ones: 0 active entries until set_num_* is called.

# 3. The custom state batch and the two custom factor batches.
#    Capacity vs. active count. A batch is constructed with its capacity: how many states (or
#    factors) its bound device buffers hold. The capacity is fixed for the batch's lifetime;
#    size it once for the largest problem you expect. Right after construction nothing is
#    active: set_num_active_states / set_num_active_factors set the active count, how many of
#    the first slots the next solve uses (a solve without it throws). The setter is host-only
#    (no allocation, no device work) and may change the count between solves up to the capacity,
#    which is what lets a real-time application allocate once and reuse the same buffers every
#    frame while the problem size changes. This example solves every slot once, so each active
#    count equals its capacity.
states_capacity = num_states  # every slot solved: active = capacity
between_capacity = num_states - 1
prior_capacity = 1
states = PositiveScalarStateBatch(states_gpu, states_capacity)
between = LogRatioBetweenFactor(log_ratios_wp, between_capacity)
prior = LogPriorFactor(prior_wp, prior_capacity)
num_between_factors = between_capacity
num_prior_factors = 1
states.set_num_active_states(num_states)  # active counts
between.set_num_active_factors(num_between_factors)
prior.set_num_active_factors(num_prior_factors)
between_pointers = []
for i in range(num_states - 1):
    between_pointers.append(states.state_device_ptr(i))
    between_pointers.append(states.state_device_ptr(i + 1))

Step 7 — Assemble the problem. Register the state batch and both factor batches.

# 4. Problem.
problem = pycunls.Problem()
problem.add_state_batch(states)
problem.add_factor_batch(between, between_pointers)
problem.add_factor_batch(prior, [states.state_device_ptr(0)])
assert problem.check_consistency(), "Problem consistency check failed"

Step 8 — Solve with Levenberg-Marquardt. Same solver as in the previous examples; every step goes through the custom plus.

# 5. Solve with Levenberg-Marquardt.
options = pycunls.LevenbergMarquardtMinimizerOptions()
options.base_options.max_num_iterations = 30
options.base_options.state_tolerance = 1e-8
options.base_options.cost_tolerance = 1e-8
options.initial_lambda = 1e-3
stream = pycunls.CudaStream()
wp.synchronize_stream(wp.get_stream())  # uploads ran on Warp's stream: finish them first
summary = pycunls.LevenbergMarquardtMinimizer(options).minimize(stream, problem)  # syncs

Step 9 — Report and check. Errors are compared in log space; all states must stay positive.

# 6. Report and check (errors measured in log space).
optimized = states_gpu.numpy()
mse_before = metrics.mse(np.log(chain.initial), np.log(chain.gt))
mse_after = metrics.mse(np.log(optimized), np.log(chain.gt))
report.print_summary(
    "Custom Warp State Batch Example (positive-scalar manifold)", summary,
    Num_states=num_states, Log_MSE=f"{mse_before:.6f} -> {mse_after:.6f}",
    Range_gt=f"[{chain.gt.min():.2f}, {chain.gt.max():.2f}]",
    Range_opt=f"[{optimized.min():.2f}, {optimized.max():.2f}]")
report.check(mse_after < 0.01 * mse_before and optimized.min() > 0,
             "log error did not decrease or a state left the manifold")