Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
dipla_planner.hpp
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/* Additional author attribution: Copyright 2026 Akshat Jain */
19
20/**
21 * @file dipla_planner.hpp
22 * @brief Public planning, synthetic-survey, and comparison APIs for Diplacam.
23 * @details
24 * The production path conditions a finite-grid Gaussian-process belief from
25 * synthetic observations and samples eight waypoints with a native DDIM loop
26 * backed by ONNX Runtime. The opt-in comparison path plans over the same belief
27 * with the native greedy/CMA-ES reference; it is not an automatic fallback.
28 * Coordinates are local east/north metres. This header intentionally exposes
29 * fixed-size production contracts while hiding Eigen, ONNX Runtime, and planner
30 * implementation state from callers.
31 */
32#pragma once
33
34#include "dipla_contract.h"
35#include <array>
36#include <cstdint>
37#include <functional>
38#include <memory>
39#include <optional>
40#include <string>
41
42namespace dipla {
43/** Number of cells in the supported 51-by-51 world grid. */
44constexpr std::size_t cells = DIPLA_GRID_SIDE * DIPLA_GRID_SIDE;
45/** Number of ordered control points returned by either planner. */
46constexpr std::size_t points = DIPLA_WAYPOINT_COUNT;
47/** Flattened XYZ diffusion noise, grouped by coordinate axis. */
48using Noise = std::array<double, DIPLA_COORDINATE_COUNT * points>;
49/** Eight ordered XYZ waypoints in local east/north/metre coordinates. */
50using Waypoints = std::array<std::array<double, DIPLA_COORDINATE_COUNT>, points>;
51
52/** @brief Startup-only synthetic experiment settings shared by both planners. */
54 /** Independent diffusion stream seed; retained across worker survey resets. */
55 std::uint64_t diffusion_seed = 123;
56 /** Independent sensor stream seed; reset only for a new survey. */
57 std::uint64_t sensor_noise_seed = 149;
58 /** Reference horizontal inset, in grid cells. */
59 static constexpr unsigned default_margin_cells = 2;
60 /** Horizontal inset for both comparison controls and published targets. */
62 /** Initial scalar field estimate, independent of the comparison threshold. */
63 double gp_prior_mean = 0.2;
64 /** Positive Matern marginal variance in squared field units. */
65 double gp_kernel_variance = 0.0079;
66 /** Positive Matern spatial length scale in metres. */
67 double gp_lengthscale_m = 4.78;
68 /** Full synthetic sensor field of view in degrees, strictly between 0 and 180. */
69 double sensor_fov_deg = 60.0;
70 /** Positive independent measurement variance used for noise and likelihood. */
71 double sensor_noise_variance = 0.01;
72 /** @brief Reject nonfinite values and incompatible margins before allocation. */
73 void validate() const;
74};
75
76/**
77 * @brief Apply the configured horizontal flight margin.
78 * @details Raw model outputs remain unchanged until the application prepares
79 * a flight route. The default two-cell inset clips XY to 4..96 metres without
80 * modifying model Z.
81 * @param route Complete finite route to constrain in place.
82 * @param margin_cells Horizontal inset in grid cells, inclusive range 0..24.
83 * @throws std::runtime_error If the margin is invalid or any coordinate is nonfinite.
84 */
86
87/**
88 * @brief Load the ONNX Runtime C API before constructing an inference session.
89 * @details Searches executable-relative directories in order, trying
90 * architecture-specific runtime names before generic names on ARM64. The
91 * optional directory is searched last and is normally resolved from the model
92 * settings INI by the application entry point. The loaded handle is retained
93 * for process lifetime so every shared session retains a valid runtime API.
94 * @param onnx_lib_path Optional final directory to search; empty skips it.
95 * @throws std::runtime_error If no candidate exists, cannot load, or exposes an
96 * incompatible API.
97 */
98void initialize_runtime(const std::string& onnx_lib_path = {});
99
100/**
101 * @brief Fixed-shape posterior summary consumed by the diffusion model.
102 * @details Arrays use row-major grid order: index `row * 51 + column`. Keeping
103 * this transport type independent of Eigen makes the ONNX boundary explicit.
104 */
105struct Belief {
106 /** Posterior mean at each grid cell. */
107 std::array<double, cells> mean{};
108 /** Posterior marginal variance at each grid cell. */
109 std::array<double, cells> variance{};
110};
111
112/**
113 * @brief Bounded parameters for the comparison-only CMA-ES planner.
114 * @details This planner shares the observed belief but does not load the ONNX
115 * model. The limits are checked by Survey::compare before expensive planning.
116 */
118 /** Smallest complete comparison population. */
119 static constexpr int population_size = 12;
120 /** Largest accepted cooperative budget in milliseconds. */
121 static constexpr int max_budget_ms = 4000;
122 /** Largest accepted evaluation allowance. */
123 static constexpr int max_evaluations = 3000;
124 /** Cooperative wall-clock budget in milliseconds, inclusive range 1..4000. */
125 int budget_ms = 1000;
126 /** Maximum objective evaluations, inclusive range 12..3000. */
127 int maxfevals = 300;
128 /** Positive deterministic seed used by the native optimizer. */
129 int seed = 55;
130 /** Confidence-bound field importance threshold. */
131 double utility_threshold = 0.3;
132 /** Nonnegative confidence multiplier. */
133 double confidence_beta = 1.0;
134 /** Positive initial horizontal optimizer standard deviation in metres. */
135 double step_xy_m = 20.0;
136 /** @brief Validate the complete comparison policy before planning. */
137 void validate() const;
138};
139
140/** @brief Model identity and execution limits for a diffusion network.
141 * @details A graph and its preprocessing/tensor contract form one assignment.
142 * The timeout applies to the complete 20-pass sampler, not separately to each
143 * pass; otherwise a nominal budget could expand twentyfold. */
145 /** Optional integrity-checked model descriptor path. */
146 std::string descriptor;
147 /** CPU inference threads, bounded to 1..32; one avoids competing with other MORA workers by default. */
148 unsigned threads = 1;
149 /** Whole-plan cooperative deadline in milliseconds; zero leaves supervision to the caller. */
150 unsigned timeout_ms = 0;
151 /** Optional verified encoder/denoiser bundle; empty retains the original graph. */
153};
154
155/**
156 * @brief Owns an ONNX session and samples eight metre-valued control points.
157 * @details Construction validates metadata and tensors; serialize sampling on one instance.
158 */
159class Network {
160public:
161 /**
162 * @brief Load and validate a deployment model.
163 * @details Construction performs the expensive one-time graph, metadata,
164 * input-name, element-type, and shape checks before the object can sample.
165 * @param model Path to the ONNX model.
166 * @param metadata Path to its bounded deployment JSON metadata.
167 * @param options Optional descriptor and bounded ONNX execution policy.
168 * @throws std::exception If files, metadata, runtime, or tensor contracts are invalid.
169 */
170 Network(const std::string& model, const std::string& metadata,
171 const NetworkOptions& options = {});
172 /**
173 * @brief Releases the owned ONNX session and inference buffers.
174 * @details Pimpl ownership ensures runtime objects are destroyed with the network.
175 */
177
178 /**
179 * @brief Run the complete deterministic DDIM sampler for a supplied noise vector.
180 * @details Belief channels and position are normalized according to model
181 * metadata; the eight XYZ outputs are converted back to metres. The supplied
182 * noise is not mutated, so identical inputs produce identical waypoints.
183 * @param belief Posterior mean and variance on the fixed world grid.
184 * @param position Current local east, north, and actual altitude in metres.
185 * @param noise Initial 24-value standard-normal sample, grouped as X/Y/Z.
186 * @return Eight ordered XYZ waypoints in metres.
187 * @throws std::runtime_error If inputs are nonfinite/out of bounds or inference fails.
188 * @pre One caller at a time owns this network; reusable tensors are mutable.
189 * @note Returned Z is part of the trained tensor contract. The fixed-height
190 * demo publishes only XY and must not substitute predicted Z for actual AGL.
191 */
192 Waypoints sample(const Belief& belief, const std::array<double, 3>& position,
193 const Noise& noise);
194private:
195 /** Opaque owner of ONNX resources and reusable tensor storage. */
196 struct State;
197 /** Exclusive ownership keeps the runtime session lifetime tied to this object. */
198 std::unique_ptr<State> state_;
199};
200
201/**
202 * @brief Maintains a synthetic field, GP posterior, and planning comparisons.
203 * @details Field truth is private to the observation source. Callers receive
204 * only posterior statistics; monotonically increasing observation numbers
205 * prevent replaying a shot from conditioning the belief twice.
206 */
207class Survey {
208public:
209 /**
210 * @brief Load the complete finite-grid synthetic field.
211 * @details The field is retained privately and the GP prior is initialized
212 * once; only observations and posterior summaries are exposed to callers.
213 * @param field CSV containing one sample for each supported even-coordinate cell.
214 * @param options Startup GP, synthetic sensor, seed and flight-margin policy.
215 * @throws std::exception If the file is malformed, oversized, or incomplete.
216 */
217 explicit Survey(const std::string& field, const ExperimentOptions& options = {});
218 /**
219 * @brief Releases field and covariance storage.
220 * @details The private pimpl owns the dense posterior and synthetic truth.
221 */
223
224 /**
225 * @brief Assimilate one synthetic observation at a local pose.
226 * @details Builds the supplied-altitude footprint, adds independently seeded
227 * Gaussian sensor noise and applies one GP conditioning update. At the
228 * demo height both injected noise and likelihood use the configured
229 * positive variance, 0.01 in the default profile.
230 * Non-increasing shot numbers are
231 * discarded before any expensive matrix work. The full truth field never
232 * becomes a network input: only the footprint conditions the belief.
233 * @param east Local east coordinate in metres.
234 * @param north Local north coordinate in metres.
235 * @param number Nonzero, strictly increasing shot number.
236 * @param height Model-domain sensor height; defaults to the original 2 m experiment.
237 * @return True if the sensor footprint covered at least one grid cell; false
238 * for a duplicate, stale, zero, or otherwise non-increasing number.
239 * @throws std::runtime_error If coordinates are nonfinite or outside the field.
240 * @note The low-height noise floor avoids extrapolating the reference law
241 * to a negative variance; this remains a synthetic sensor experiment.
242 */
243 bool observe(double east, double north, std::uint32_t number,
244 double height = DIPLA_DEMO_HEIGHT_MM / DIPLA_MM_PER_M);
245
246 /**
247 * @brief Run the explicitly requested native CMA-ES comparison planner.
248 * @details Planning operates on a covariance copy and must not mutate the
249 * observation posterior. It returns no route if cancellation or the deadline
250 * prevents completion; a partial route is never published.
251 * @param position Current local east, north, and altitude in metres.
252 * @param options Validated comparison search, utility, budget and seed policy.
253 * @param cancelled Optional cooperative cancellation predicate.
254 * @return Complete eight-waypoint route, or `std::nullopt` on interruption.
255 * @throws std::runtime_error If position or budget is invalid, or planning fails.
256 */
257 std::optional<Waypoints> compare(const std::array<double, 3>& position,
258 const CmaesOptions& options = {},
259 const std::function<bool()>& cancelled = {}) const;
260
261 /**
262 * @brief Copy the current GP marginal mean and variance into fixed-size storage.
263 * @details Converts Eigen's internal vectors to the stable public row-major arrays.
264 * @return Snapshot of posterior mean and nonnegative marginal variances.
265 */
266 Belief belief() const;
267 /**
268 * @brief Return the sum of posterior marginal variances.
269 * @details Uses the covariance trace as a compact scalar uncertainty measure.
270 * @return Sum of diagonal covariance entries.
271 */
272 double total_variance() const;
273 /**
274 * @brief Return the FNV-1a digest of the input CSV bytes.
275 * @details This is diagnostic provenance, not cryptographic authentication.
276 * @return 64-bit FNV-1a digest.
277 */
278 std::uint64_t field_digest() const;
279private:
280 /** Opaque owner of field truth, posterior mean/covariance, and replay state. */
281 struct State;
282 /** Exclusive ownership keeps private truth and dense GP state out of the API. */
283 std::unique_ptr<State> state_;
284};
285}
~Network()
Releases the owned ONNX session and inference buffers.
Network(const std::string &model, const std::string &metadata, const NetworkOptions &options={})
Load and validate a deployment model.
std::unique_ptr< State > state_
Waypoints sample(const Belief &belief, const std::array< double, 3 > &position, const Noise &noise)
Run the complete deterministic DDIM sampler for a supplied noise vector.
Belief belief() const
Copy the current GP marginal mean and variance into fixed-size storage.
double total_variance() const
Return the sum of posterior marginal variances.
std::uint64_t field_digest() const
Return the FNV-1a digest of the input CSV bytes.
bool observe(double east, double north, std::uint32_t number, double height=DIPLA_DEMO_HEIGHT_MM/DIPLA_MM_PER_M)
Assimilate one synthetic observation at a local pose.
std::unique_ptr< State > state_
Survey(const std::string &field, const ExperimentOptions &options={})
Load the complete finite-grid synthetic field.
~Survey()
Releases field and covariance storage.
std::optional< Waypoints > compare(const std::array< double, 3 > &position, const CmaesOptions &options={}, const std::function< bool()> &cancelled={}) const
Run the explicitly requested native CMA-ES comparison planner.
Fixed model geometry and C/C++ local transport units, not runtime settings.
#define DIPLA_WAYPOINT_COUNT
#define DIPLA_MM_PER_M
#define DIPLA_DEMO_HEIGHT_MM
#define DIPLA_GRID_SIDE
void apply_flight_margin(Waypoints &route, unsigned margin_cells)
Apply the configured horizontal flight margin.
void initialize_runtime(const std::string &onnx_lib_path)
Load the ONNX Runtime C API before constructing an inference session.
std::array< double, DIPLA_COORDINATE_COUNT *points > Noise
constexpr std::size_t cells
std::array< std::array< double, DIPLA_COORDINATE_COUNT >, points > Waypoints
constexpr std::size_t points
Fixed-shape posterior summary consumed by the diffusion model.
std::array< double, cells > variance
std::array< double, cells > mean
Bounded parameters for the comparison-only CMA-ES planner.
void validate() const
Validate the complete comparison policy before planning.
static constexpr int max_evaluations
static constexpr int max_budget_ms
static constexpr int population_size
Startup-only synthetic experiment settings shared by both planners.
static constexpr unsigned default_margin_cells
void validate() const
Reject nonfinite values and incompatible margins before allocation.
std::uint64_t sensor_noise_seed
Model identity and execution limits for a diffusion network.
Runtime-owned ONNX session and reusable input/output storage.
Validated capture and reporting policy, fixed before the sample loop.
Definition earcam.c:137