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.cpp
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.cpp
22 * @brief Turn a synthetic survey's GP belief into eight model or comparison points.
23 * @details
24 * Three responsibilities deliberately meet here without becoming one algorithm:
25 * - Survey owns the hidden field and Gaussian-process (GP) posterior. Only a
26 * sensor footprint may reveal truth; planners receive the resulting belief.
27 * - Network adapts that belief to the exported ONNX denoiser and performs the
28 * complete deterministic DDIM reverse process, returning raw XYZ in metres.
29 * - apply_flight_margin() prepares either planner's route for publication,
30 * without changing the sampler's numerically testable model contract.
31 *
32 * The flight controller, not this file, decides when a route has been flown.
33 * Keeping inference, flight preparation, and mission progress separate lets us
34 * compare the sampler with the Python reference without importing flight policy
35 * into the maths. There is one neural network here, not a second flight network.
36 *
37 * @par When adapting a model
38 * Grid geometry, axis order, world scaling, tensor bindings, normalizations,
39 * and the diffusion schedule form one contract. Update and test them together;
40 * a tensor with the right shape can still describe entirely the wrong world.
41 *
42 * @warning Reused network tensors and mutable survey state require serialized
43 * ownership. Fixed tensor buffers do not make ONNX Runtime or the GP heap-free;
44 * the dense covariance alone occupies about 51.6 MiB.
45 * @see dipla_planner.hpp Public ownership, input, and result contracts.
46 */
47#include "dipla_planner.hpp"
48#include <chrono>
50#include <jsonbourne.h>
55#include <algorithm>
56#include <charconv>
57#include <cmath>
58#include <cstddef>
59#include <filesystem>
60#include <fstream>
61#include <limits>
62#include <sstream>
63#include <stdexcept>
64#include <string_view>
65#include <vector>
66
67namespace dipla {
68/**
69 * @details Delegate runtime discovery to the shared loader so Diplacam uses the
70 * same library-selection and process-lifetime rules as other ONNX consumers.
71 * Keeping an error buffer here turns the C API's bounded diagnostic into a C++
72 * exception before a Network can acquire a session from an unavailable runtime.
73 * @see Network::Network
74 */
75void initialize_runtime(const std::string& onnx_lib_path) {
76 std::array<char, 16384> error{};
77 if (!onnx_runtime_open(onnx_lib_path.c_str(), error.data(), error.size()))
78 throw std::runtime_error(error.data());
79}
80
81namespace {
82constexpr std::size_t metadata_byte_limit = 16 * 1024;
83constexpr std::size_t metadata_arena_bytes = 64 * 1024;
84constexpr std::size_t runtime_error_capacity = 16 * 1024;
85constexpr std::size_t field_byte_limit = 2 * 1024 * 1024;
86constexpr std::size_t field_row_byte_limit = 256;
87constexpr double field_alignment_tolerance_m = 1e-9;
88constexpr std::uint64_t fnv_offset_basis = UINT64_C(14695981039346656037);
89constexpr std::uint64_t fnv_prime = UINT64_C(1099511628211);
90constexpr double xy_half_extent_m = DIPLA_FIELD_EXTENT_M / 2.0;
91constexpr double model_z_half_range_m = (DIPLA_MODEL_Z_MAX_M - DIPLA_MODEL_Z_MIN_M) / 2.0;
92
93/** @brief One named training-time affine normalization. */
94struct Normalization {
95 double center = 0; /**< Training center. */
96 double scale = 1; /**< Positive training scale. */
97};
98
99bool inside_field(double east, double north) {
100 return std::isfinite(east) && std::isfinite(north) && east >= 0 && east <= DIPLA_FIELD_EXTENT_M &&
101 north >= 0 && north <= DIPLA_FIELD_EXTENT_M;
102}
103
104std::size_t cell_index(std::size_t row, std::size_t column) { return row * DIPLA_GRID_SIDE + column; }
105
106/**
107 * @brief Find a unique required member of a metadata object.
108 * @details Length-aware comparison handles decoded keys without accepting
109 * embedded-NUL prefixes or ambiguous duplicate members. Different JSON tools
110 * can choose different winners for duplicate keys; rejecting them avoids that
111 * disagreement at the model boundary rather than guessing which export wins.
112 * @param[in] tree JSON object containing the requested key.
113 * @param[in] key Required member name, compared in full.
114 * @return Required member view backed by the caller's parser storage.
115 * @throws std::runtime_error If the object or member is absent, mistyped, or duplicated.
116 * @warning Do not retain the returned reference beyond the parser arena's lifetime.
117 */
118const jsonbourne_val& metadata_member(const jsonbourne_val& tree, std::string_view key) {
119 if (tree.type != JSONBOURNE_TYPE_OBJ) throw std::runtime_error("Expected metadata object");
120 const auto& object = *static_cast<const jsonbourne_obj*>(tree.ptr);
121 const jsonbourne_val* found = nullptr;
122 for (const auto* member = object.first; member; member = member->next) {
123 if (std::string_view(member->key->str, member->key->len) != key) continue;
124 if (found) throw std::runtime_error("Duplicate metadata member: " + std::string(key));
125 found = member->val;
126 }
127 if (!found) throw std::runtime_error("Missing metadata member: " + std::string(key));
128 return *found;
129}
130
131/**
132 * @brief Convert a JSON number without locale dependence or implicit coercion.
133 * @details Metadata must mean the same thing on the development PC and MORA.
134 * Parsing the entire numeric token avoids locale surprises and silently
135 * accepting a usable-looking prefix, a quoted number, or a nonfinite value.
136 * @param[in] node Required numeric value backed by live parser storage.
137 * @return Finite double, with the complete token consumed.
138 * @throws std::runtime_error If the type, conversion, or range is invalid.
139 */
140double metadata_number(const jsonbourne_val& node) {
141 if (node.type != JSONBOURNE_TYPE_NUM) throw std::runtime_error("Expected metadata number");
142 const auto& number = *static_cast<const jsonbourne_num*>(node.ptr);
143 double value = 0;
144 const auto result = std::from_chars(number.str, number.str + number.len, value);
145 if (result.ec != std::errc{} || result.ptr != number.str + number.len || !std::isfinite(value))
146 throw std::runtime_error("Invalid metadata number");
147 return value;
148}
149
150/**
151 * @brief Extract a finite numeric object member.
152 * @details Reuse the same lookup and conversion rules for world geometry,
153 * normalization, and scheduling; none should quietly accept weaker metadata.
154 * @param[in] tree Metadata object.
155 * @param[in] key Required member name.
156 * @return Checked numeric value.
157 * @throws std::runtime_error If lookup or finite-number conversion fails.
158 * @see metadata_member
159 * @see metadata_number
160 */
161double finite_number(const jsonbourne_val& tree, std::string_view key) {
162 return metadata_number(metadata_member(tree, key));
163}
164
165/**
166 * @brief Extract an integer token without accepting fractions or exponents.
167 * @details Dimensions and step counts are discrete contract fields. Requiring
168 * an actual integer token makes accidental exporter changes visible instead
169 * of rounding or coercing them into something that merely fits a tensor.
170 * @param[in] tree Metadata object.
171 * @param[in] key Required member name.
172 * @return Checked integer value.
173 * @throws std::runtime_error If the member is not a representable integer token.
174 */
175int metadata_integer(const jsonbourne_val& tree, std::string_view key) {
176 const auto& node = metadata_member(tree, key);
177 if (node.type != JSONBOURNE_TYPE_NUM) throw std::runtime_error("Expected metadata integer");
178 const auto& number = *static_cast<const jsonbourne_num*>(node.ptr);
179 int value = 0;
180 const auto result = std::from_chars(number.str, number.str + number.len, value);
181 if (result.ec != std::errc{} || result.ptr != number.str + number.len)
182 throw std::runtime_error("Invalid metadata integer: " + std::string(key));
183 return value;
184}
185
186}
187
188/**
189 * @brief Runtime-owned ONNX session and reusable input/output storage.
190 * @details Bind once and reuse across all twenty denoising calls and later
191 * plans. This avoids rebuilding application-side tensors in the hot loop;
192 * it does not promise allocation-free execution inside ONNX Runtime.
193 * @invariant The session borrows member buffers whose addresses remain stable
194 * until the session is closed by the destructor.
195 * @warning A State is single-owner mutable workspace, not a concurrent sampler.
196 */
198 /** @brief Own the paired encoder and cached denoiser plus their bound tensors. */
202 std::array<std::vector<float>, ONNX_TENSOR_LIMIT> values;
203
204 /** @brief Validate the split model contract and open both runtime sessions.
205 * @param directory Directory containing split graphs and their descriptors.
206 * @param source Source graph path used to validate the cache identity.
207 * @param inputs Canonical model inputs against which the split bindings are checked.
208 * @param outputs Canonical model outputs against which the split bindings are checked.
209 * @param options Runtime options shared by both sessions.
210 * @throws std::runtime_error On identity, binding or runtime initialization failure.
211 * @details Check that the artifacts belong together before binding shared
212 * buffers. Close the encoder explicitly if the second session cannot open. */
213 ConditioningCache(const std::string& directory, const std::string& source,
214 const onnx_tensor* inputs, const onnx_tensor* outputs,
216 const std::filesystem::path root(directory);
217 std::array<char, runtime_error_capacity> error{};
218 struct Identities {
219 std::array<std::string, 3> hashes;
220 unsigned seen = 0;
221 } identities;
222 const auto identify = [](void* context, const char* key, const char* value) {
223 auto& parsed = *static_cast<Identities*>(context);
224 const std::array<std::string_view, 3> keys{{"source_sha256", "encoder_descriptor_sha256", "denoiser_descriptor_sha256"}};
225 const auto found = std::find(keys.begin(), keys.end(), key);
226 if (found == keys.end()) return false;
227 const auto index = static_cast<std::size_t>(found - keys.begin());
228 if (parsed.seen & (1U << index)) return false;
229 parsed.seen |= 1U << index;
230 parsed.hashes[index] = value;
231 return parsed.hashes[index].size() == 64 &&
232 std::all_of(parsed.hashes[index].begin(), parsed.hashes[index].end(),
233 [](char digit) { return (digit >= '0' && digit <= '9') || (digit >= 'a' && digit <= 'f'); });
234 };
235 std::array<char, 2049> manifest{};
236 std::size_t length = 0;
237 if (!ini_read_file((root / "bundle.ini").c_str(), manifest.data(), manifest.size(), &length) ||
238 !ini_parse(manifest.data(), length, identify, &identities) || identities.seen != 7)
239 throw std::runtime_error("Invalid conditioning cache bundle identity");
240 const std::array<std::filesystem::path, 3> identified{{source, root / "encoder.ini", root / "denoiser.ini"}};
241 for (std::size_t index = 0; index < identified.size(); ++index) {
242 std::array<char, 65> digest{};
243 if (!inference_file_sha256(identified[index].c_str(), digest.data()) || digest.data() != identities.hashes[index])
244 throw std::runtime_error("Conditioning cache source/descriptor hash mismatch");
245 }
246 if (!inference_model_read(&encoder_model, (root / "encoder.ini").c_str(), (root / "encoder.onnx").c_str(), error.data(), error.size()) ||
247 !inference_model_read(&denoiser_model, (root / "denoiser.ini").c_str(), (root / "denoiser.onnx").c_str(), error.data(), error.size()))
248 throw std::runtime_error(error.data());
249 if (std::string(encoder_model.adapter) != "dipla_ddim_cache_v1" ||
250 std::string(denoiser_model.adapter) != "dipla_ddim_cache_v1" || encoder_model.input_count != 3 ||
251 !encoder_model.output_count || encoder_model.output_count > ONNX_TENSOR_LIMIT - 2 ||
252 denoiser_model.input_count != encoder_model.output_count + 2 || denoiser_model.output_count != 1)
253 throw std::runtime_error("Unsupported conditioning cache tensor contract");
254 const auto bind = [](onnx_tensor& target, const onnx_tensor& actual) {
255 if (target.type != actual.type || target.rank != actual.rank || target.bytes != actual.bytes)
256 throw std::runtime_error("Conditioning cache tensor mismatch");
257 for (std::size_t axis = 0; axis < target.rank; ++axis)
258 if (target.dimensions[axis] != actual.dimensions[axis])
259 throw std::runtime_error("Conditioning cache shape mismatch");
260 target.data = actual.data;
261 };
262 for (std::size_t index = 0; index < encoder_model.input_count; ++index) {
263 auto& target = encoder_model.inputs[index];
264 const onnx_tensor* actual = nullptr;
265 for (std::size_t candidate = 2; candidate < 5; ++candidate)
266 if (std::string(target.name) == inputs[candidate].name) actual = &inputs[candidate];
267 if (!actual) throw std::runtime_error("Unknown conditioning input");
268 bind(target, *actual);
269 }
270 std::size_t bytes = 0;
271 for (std::size_t index = 0; index < encoder_model.output_count; ++index) {
272 auto& output = encoder_model.outputs[index];
273 if (output.type != ONNX_FLOAT32 || output.bytes > 4U * 1024U * 1024U - bytes)
274 throw std::runtime_error("Conditioning cache exceeds 4 MiB float32 budget");
275 bytes += output.bytes;
276 values[index].resize(output.bytes / sizeof(float));
277 output.data = values[index].data();
278 }
279 for (std::size_t index = 0; index < denoiser_model.input_count; ++index) {
280 auto& target = denoiser_model.inputs[index];
281 const onnx_tensor* actual = nullptr;
282 for (std::size_t candidate = 0; candidate < 2; ++candidate)
283 if (std::string(target.name) == inputs[candidate].name) actual = &inputs[candidate];
284 for (std::size_t candidate = 0; candidate < encoder_model.output_count; ++candidate)
285 if (std::string(target.name) == encoder_model.outputs[candidate].name) actual = &encoder_model.outputs[candidate];
286 if (!actual) throw std::runtime_error("Unknown cached denoiser input");
287 bind(target, *actual);
288 }
289 if (std::string(denoiser_model.outputs[0].name) != outputs[0].name)
290 throw std::runtime_error("Unexpected cached denoiser output");
291 bind(denoiser_model.outputs[0], outputs[0]);
292 if (!onnx_session_open(&encoder, (root / "encoder.onnx").c_str(), encoder_model.inputs, encoder_model.input_count,
293 encoder_model.outputs, encoder_model.output_count, &options, error.data(), error.size()))
294 throw std::runtime_error(error.data());
295 if (!onnx_session_open(&denoiser, (root / "denoiser.onnx").c_str(), denoiser_model.inputs, denoiser_model.input_count,
296 denoiser_model.outputs, denoiser_model.output_count, &options, error.data(), error.size())) {
298 throw std::runtime_error(error.data());
299 }
300 }
301
302 /** @brief Release sessions before their borrowed tensor storage is destroyed. */
307 };
308 std::unique_ptr<ConditioningCache> conditioning_cache;
309 /** Shared session borrowing this state's fixed buffers. */
311 /** Whole-plan cooperative deadline; zero disables the local timer. */
312 unsigned timeout_ms = 0;
313 /** Float32 graph input: eight X values, then eight Y, then eight Z, not interleaved XYZ. */
314 std::array<float, DIPLA_COORDINATE_COUNT * points> candidate{};
315 /** Noise prediction written by the ONNX graph for each reverse step. */
316 std::array<float, DIPLA_COORDINATE_COUNT * points> predicted{};
317 /** NCHW map input: mean, variance, marker; each channel uses row * 51 + column. */
318 std::array<float, DIPLA_MAP_CHANNEL_COUNT * cells> maps{};
319 /** Normalized current pose tensor, ordered east/north/altitude. */
320 std::array<float, 3> position{};
321 /** Normalized scalar total-variance tensor. */
322 std::array<float, 1> total{};
323 /** Current reverse-diffusion step. */
324 std::array<int64_t, 1> timestep{};
325 /** Trained cumulative-alpha schedule used by the deterministic DDIM update. */
326 std::array<double, DIPLA_DIFFUSION_STEPS> alpha{};
327 /** Center/scale pairs for mean, variance, and log1p(total variance), in that order. */
329
330 /**
331 * @brief Validate the export contract before binding a reusable ONNX session.
332 * @details Reject mismatched geometry, schedules, and tensors at startup,
333 * when there is still a useful file error to report, rather than after a
334 * plausible-looking but mis-scaled route reaches the application.
335 * @param[in] model ONNX graph path.
336 * @param[in] metadata Deployment JSON describing training-time preprocessing.
337 * @param[in] policy Optional integrity descriptor, thread count, and deadline policy.
338 * @pre initialize_runtime() has successfully selected a compatible runtime.
339 * @throws std::exception If reading, allocation, validation, or session creation fails.
340 * @note Parser views are temporary. Copy only checked numeric values into
341 * members; nothing in the session may borrow the constructor's JSON arena.
342 */
343 State(const std::string& model, const std::string& metadata, const NetworkOptions& policy)
344 : timeout_ms(policy.timeout_ms) {
345 std::ifstream input(metadata, std::ios::binary);
346 if (!input) throw std::runtime_error("Cannot open metadata: " + metadata);
347 // Read one byte beyond the accepted 16 KiB to detect oversize input
348 // without loading an arbitrary file. The arena separately bounds the
349 // decoded tree; a small JSON file can still contain many tiny nodes.
350 std::array<char, metadata_byte_limit + 1> contents{};
351 input.read(contents.data(), contents.size());
352 if (input.bad()) throw std::runtime_error("Cannot read metadata: " + metadata);
353 const auto size = static_cast<std::size_t>(input.gcount());
354 if (size > metadata_byte_limit) throw std::runtime_error("Metadata too large");
355 // JSON nodes need proper alignment, not merely enough bytes. The
356 // module builds JSONbourne with a separate 16-container depth limit.
357 alignas(std::max_align_t) std::array<unsigned char, metadata_arena_bytes> storage;
358 jsonbourne_read_err parsed{};
359 const auto* tree = jsonbourne_read_buf(contents.data(), size, JSONBOURNE_READ_NOFLAG,
360 nullptr, storage.data(), storage.size(), nullptr, &parsed);
361 if (!tree && parsed.code == JSONBOURNE_READ_ERROR_MEMORY_ALLOCATION)
362 throw std::runtime_error("Metadata JSON exceeds 64 KiB storage limit");
363 if (!tree && parsed.code == JSONBOURNE_READ_ERROR_DEPTH)
364 throw std::runtime_error("Metadata JSON exceeds 16-level nesting limit");
365 if (!tree) throw std::runtime_error("Invalid metadata JSON at byte " + std::to_string(parsed.pos));
366 const auto& world = metadata_member(*tree, "world");
367 const auto& diffusion = metadata_member(*tree, "diffusion");
368 /** @todo Centralize the supported world and schedule contract. Changing
369 * these checks alone is not model support: update the public sizes,
370 * tensor shapes, grid indexing, sampler loop, and coordinate transforms
371 * together, then rerun the reference cases. Until then, reject drift. */
372 if (metadata_integer(world, "grid") != DIPLA_GRID_SIDE || finite_number(world, "xy_scale_m") != DIPLA_FIELD_EXTENT_M ||
373 finite_number(world, "z_min_m") != DIPLA_MODEL_Z_MIN_M || finite_number(world, "z_max_m") != DIPLA_MODEL_Z_MAX_M ||
374 metadata_integer(diffusion, "T") != DIPLA_DIFFUSION_STEPS || metadata_integer(diffusion, "num_waypoints") != points)
375 throw std::runtime_error("Unsupported model world/schedule contract");
376 // Centers may be signed, but every scale must be positive: a zero
377 // divisor breaks normalization and a negative one reverses its meaning.
378 struct Transform { const char* center; const char* scale; Normalization& destination; };
379 const Transform transforms[] = {
380 {"mean_center", "mean_scale", mean_normalization},
381 {"var_center", "var_scale", variance_normalization},
382 {"total_variance_center", "total_variance_scale", total_normalization}
383 };
384 const auto& scales = metadata_member(*tree, "normalization");
385 for (const auto& transform : transforms) {
386 transform.destination.center = finite_number(scales, transform.center);
387 transform.destination.scale = finite_number(scales, transform.scale);
388 if (transform.destination.scale <= 0) throw std::runtime_error("Invalid normalization scale");
389 }
390 const auto& schedule_node = metadata_member(diffusion, "alphas_cumprod");
391 // The denoiser predicts noise for this schedule; changing or reordering
392 // alpha levels is an algorithm change, not an interchangeable setting.
393 if (schedule_node.type != JSONBOURNE_TYPE_ARR) throw std::runtime_error("Expected diffusion schedule array");
394 const auto& schedule = *static_cast<const jsonbourne_arr*>(schedule_node.ptr);
395 if (schedule.len != alpha.size())
396 throw std::runtime_error("Incomplete diffusion schedule");
397 double previous = 1.0;
398 const auto* entry = schedule.first;
399 for (std::size_t index = 0; index < alpha.size(); ++index) {
400 const double value = metadata_number(*entry->val);
401 if (!std::isfinite(value) || value <= 0 || value >= previous)
402 throw std::runtime_error("Invalid diffusion schedule");
403 alpha[index] = value;
404 previous = value;
405 entry = entry->next;
406 }
407 // Names, element types, ranks, and axis order are the export ABI. A
408 // correctly sized buffer is not enough if X and waypoint axes swap.
409 const onnx_tensor inputs[] = {
410 {"x", ONNX_FLOAT32, 3, {1,DIPLA_COORDINATE_COUNT,points}, candidate.data(), sizeof(candidate)},
411 {"t", ONNX_INT64, 1, {1}, timestep.data(), sizeof(timestep)},
412 /** @todo Derive this shape from the same supported-grid contract
413 * as maps and Belief; do not independently make only the binding dynamic. */
414 {"meanvarmarker_map", ONNX_FLOAT32, 4, {1,DIPLA_MAP_CHANNEL_COUNT,DIPLA_GRID_SIDE,DIPLA_GRID_SIDE}, maps.data(), sizeof(maps)},
415 {"current_position", ONNX_FLOAT32, 2, {1,DIPLA_COORDINATE_COUNT}, position.data(), sizeof(position)},
416 {"total_variance_condition", ONNX_FLOAT32, 2, {1,1}, total.data(), sizeof(total)}
417 };
418 const onnx_tensor outputs[] = {
419 {"noise_pred", ONNX_FLOAT32, 3, {1,DIPLA_COORDINATE_COUNT,points}, predicted.data(), sizeof(predicted)}
420 };
421 std::array<char, runtime_error_capacity> error{};
422 if (!policy.descriptor.empty()) {
423 // JSON describes the maths; the optional descriptor also binds
424 // graph bytes and the adapter/tensor ABI. Check both so a swapped
425 // export cannot borrow a familiar filename and pass unnoticed.
426 // Integrity checking is not authentication of the model's author.
427 inference_model bundle{};
428 if (!inference_model_read(&bundle, policy.descriptor.c_str(), model.c_str(), error.data(), error.size()))
429 throw std::runtime_error(error.data());
430 if (std::string(bundle.adapter) != "dipla_ddim_v1" || bundle.input_count != std::size(inputs) || bundle.output_count != std::size(outputs))
431 throw std::runtime_error("Unsupported Diplacam model descriptor adapter");
432 const auto matches = [](const onnx_tensor& declared, const onnx_tensor& expected) {
433 if (std::string(declared.name) != expected.name || declared.type != expected.type ||
434 declared.rank != expected.rank || declared.bytes != expected.bytes) return false;
435 for (std::size_t axis = 0; axis < declared.rank; ++axis)
436 if (declared.dimensions[axis] != expected.dimensions[axis]) return false;
437 return true;
438 };
439 for (std::size_t index = 0; index < std::size(inputs); ++index)
440 if (!matches(bundle.inputs[index], inputs[index])) throw std::runtime_error("Diplacam descriptor input mismatch");
441 if (!matches(bundle.outputs[0], outputs[0])) throw std::runtime_error("Diplacam descriptor output mismatch");
442 }
443 const onnx_session_options options{policy.threads, nullptr};
444 if (!policy.conditioning_cache.empty()) {
445 conditioning_cache = std::make_unique<ConditioningCache>(policy.conditioning_cache, model, inputs, outputs, options);
446 } else if (!onnx_session_open(&session, model.c_str(), inputs, std::size(inputs), outputs, std::size(outputs), &options,
447 error.data(), error.size())) throw std::runtime_error(error.data());
448 }
449
450 /**
451 * @brief Close the session while every borrowed member buffer is still alive.
452 * @details Destructor bodies run before member destruction. Explicit closure
453 * here preserves that order even though session is declared before its buffers.
454 */
459};
460
461/**
462 * @details Build the entire private state before exposing a usable Network.
463 * The pimpl keeps runtime and tensor implementation types out of the public API.
464 */
465Network::Network(const std::string& model, const std::string& metadata, const NetworkOptions& options)
466 : state_(std::make_unique<State>(model, metadata, options)) {}
467/** @details Destroy State through its owner so the session closes before its buffers disappear. */
468Network::~Network() = default;
469
470/**
471 * @details
472 * This is the complete sampler, not one neural-network pass. Conditioning
473 * inputs stay fixed while twenty noise predictions reconstruct one route.
474 * The caller supplies initial noise so numerical tests can compare identical
475 * inputs without depending on C++ and NumPy generating identical random streams.
476 *
477 * @par Precision matters
478 * Match the reference's float32 graph boundary and double-precision DDIM
479 * arithmetic. Moving casts or simplifying apparently equivalent expressions
480 * can change the trajectory over twenty steps; check reference parity first.
481 *
482 * @note The deadline is cooperative and covers the whole plan. It is not a
483 * hard real-time guarantee or a fresh allowance for each network call.
484 * @see apply_flight_margin Application-owned XY padding, intentionally absent here.
485 */
486Waypoints Network::sample(const Belief& belief, const std::array<double, 3>& position, const Noise& noise) {
487 auto& state = *state_;
488 // One absolute budget covers preprocessing and every reverse step. Resetting
489 // it inside the loop would permit a much longer plan than the owner requested.
490 const std::uint64_t deadline = state.timeout_ms ? onnx_monotonic_us() + std::uint64_t(state.timeout_ms) * 1000 : 0;
491 for (double value : position) if (!std::isfinite(value)) throw std::runtime_error("Nonfinite position");
492 if (!inside_field(position[0], position[1]))
493 throw std::runtime_error("Position outside field");
494 // The third map channel is a one-hot pose marker; clearing all channels
495 // first prevents a previous sample's marker leaking into this inference.
496 std::fill(state.maps.begin(), state.maps.end(), 0.0f);
497 double total = 0;
498 // The model sees normalized float32 cell channels, but total variance is
499 // summed from the original doubles before its separate log1p transform.
500 // Preserve this boundary to match the reference, not just its algebra.
501 for (std::size_t cell = 0; cell < cells; ++cell) {
502 if (!std::isfinite(belief.mean[cell]) || !std::isfinite(belief.variance[cell]) || belief.variance[cell] < 0)
503 throw std::runtime_error("Invalid belief cell");
504 state.maps[cell] = (static_cast<float>(belief.mean[cell]) - static_cast<float>(state.mean_normalization.center)) /
505 static_cast<float>(state.mean_normalization.scale);
506 state.maps[cells + cell] = (static_cast<float>(belief.variance[cell]) - static_cast<float>(state.variance_normalization.center)) /
507 static_cast<float>(state.variance_normalization.scale);
508 total += belief.variance[cell];
509 if (!std::isfinite(state.maps[cell]) || !std::isfinite(state.maps[cells + cell]))
510 throw std::runtime_error("Belief normalization overflow");
511 }
512 // East selects a column and north a row: the marker is [y, x], not [x, y].
513 // nearbyint matches NumPy's ties-to-even rounding under the default FP
514 // rounding mode; clamping keeps boundary poses inside the 51-by-51 map.
515 const auto column = static_cast<std::size_t>(std::clamp(std::nearbyint(position[0] / DIPLA_GRID_STEP_M), 0.0, double(DIPLA_GRID_SIDE - 1U)));
516 const auto row = static_cast<std::size_t>(std::clamp(std::nearbyint(position[1] / DIPLA_GRID_STEP_M), 0.0, double(DIPLA_GRID_SIDE - 1U)));
517 state.maps[2 * cells + cell_index(row, column)] = 1;
518 // Pass actual altitude, even in the 2 m demo outside the trained 10..40 m
519 // band. Pretending to be at 10 m would misdescribe the aircraft to the model;
520 // preserving this input does not establish model quality at low altitude.
521 /** @todo Share XY and Z normalization bounds with metadata validation and
522 * output denormalization. These are training scales, not flight-height settings. */
523 state.position = {{static_cast<float>(position[0] / xy_half_extent_m - 1.0), static_cast<float>(position[1] / xy_half_extent_m - 1.0),
524 static_cast<float>((position[2] - DIPLA_MODEL_Z_MIN_M) / model_z_half_range_m - 1.0)}};
525 state.total[0] = static_cast<float>((std::log1p(total) - state.total_normalization.center) / state.total_normalization.scale);
526 if (!std::isfinite(state.total[0])) throw std::runtime_error("Variance normalization overflow");
527 if (state.conditioning_cache) {
528 std::array<char, 1024> error{};
529 if (!onnx_session_run(&state.conditioning_cache->encoder, deadline, error.data(), error.size()))
530 throw std::runtime_error(error.data());
531 }
532 Noise current = noise;
533 for (double value : current) if (!std::isfinite(value)) throw std::runtime_error("Nonfinite noise");
534 // The graph predicts noise, not clean coordinates. Each reverse DDIM step
535 // estimates x0, clamps that estimate to the trained normalized range, then
536 // advances to the previous cumulative-alpha level without adding new noise
537 // (DDIM eta = 0). Clipping x0 is part of the reference algorithm, not the
538 // flight margin; removing it changes all subsequent reverse steps.
539 for (int step = static_cast<int>(state.alpha.size()) - 1; step >= 0; --step) {
540 for (std::size_t coordinate = 0; coordinate < current.size(); ++coordinate) {
541 state.candidate[coordinate] = static_cast<float>(current[coordinate]);
542 if (!std::isfinite(state.candidate[coordinate])) throw std::runtime_error("Sampler overflow");
543 }
544 state.timestep[0] = step;
545 std::array<char, 1024> error{};
546 auto* session = state.conditioning_cache ? &state.conditioning_cache->denoiser : &state.session;
547 if (!onnx_session_run(session, deadline, error.data(), error.size()))
548 throw std::runtime_error(error.data());
549 const double alpha = state.alpha[static_cast<std::size_t>(step)];
550 for (std::size_t coordinate = 0; coordinate < current.size(); ++coordinate) {
551 const double predicted = state.predicted[coordinate];
552 if (!std::isfinite(predicted)) throw std::runtime_error("Nonfinite network output");
553 const double clean = std::clamp((current[coordinate] - std::sqrt(1.0 - alpha) * predicted) /
554 std::sqrt(alpha), -1.0, 1.0);
555 // Step zero has no earlier alpha level: the clean estimate is
556 // already the result. Do not index alpha[-1] for a final update.
557 current[coordinate] = step == 0 ? clean :
558 std::sqrt(state.alpha[static_cast<std::size_t>(step - 1)]) * clean +
559 std::sqrt(1.0 - state.alpha[static_cast<std::size_t>(step - 1)]) * predicted;
560 }
561 }
563 for (std::size_t waypoint = 0; waypoint < points; ++waypoint) {
564 // Repack axis-major model output into waypoint-major application XYZ.
565 // Keep raw XY in 0..100 m and model Z in 10..40 m for reference parity;
566 // the publication boundary chooses flight XY padding and fixed height.
567 /** @todo Derive these inverse transforms from the same supported-world
568 * contract as input normalization. Changing just one direction rescales routes. */
569 result[waypoint] = {{(current[waypoint] + 1.0) * xy_half_extent_m,
570 (current[points + waypoint] + 1.0) * xy_half_extent_m,
571 (current[2 * points + waypoint] + 1.0) * model_z_half_range_m + DIPLA_MODEL_Z_MIN_M}};
572 }
573 return result;
574}
575
577 if (flight_margin_cells * 2ULL >= DIPLA_GRID_SIDE - 1U ||
578 !std::isfinite(gp_prior_mean) || !std::isfinite(gp_kernel_variance) || gp_kernel_variance <= 0 ||
579 !std::isfinite(gp_lengthscale_m) || gp_lengthscale_m <= 0 ||
581 !std::isfinite(sensor_noise_variance) || sensor_noise_variance <= 0)
582 throw std::runtime_error("Invalid Diplacam experiment settings");
583}
584
587 maxfevals > max_evaluations || seed < 1 || !std::isfinite(utility_threshold) ||
588 !std::isfinite(confidence_beta) || confidence_beta < 0 ||
589 !std::isfinite(step_xy_m) || step_xy_m <= 0)
590 throw std::runtime_error("Invalid CMA-ES comparison settings");
591}
592
593/**
594 * @details Both planners pass here once before publication. The inset is an
595 * application policy, not model normalization or a change to the raw sampler.
596 * Validate the entire route, including Z, before changing any coordinate.
597 * @see Network::sample
598 */
599void apply_flight_margin(Waypoints& route, unsigned margin_cells) {
600 if (margin_cells * 2ULL >= DIPLA_GRID_SIDE - 1U) throw std::runtime_error("Invalid flight margin");
601 const double inset = margin_cells * DIPLA_GRID_STEP_M;
602 for (const auto& point : route)
603 for (double coordinate : point)
604 if (!std::isfinite(coordinate)) throw std::runtime_error("Nonfinite flight waypoint");
605 for (auto& point : route) {
606 point[0] = std::clamp(point[0], inset, DIPLA_FIELD_EXTENT_M - inset);
607 point[1] = std::clamp(point[1], inset, DIPLA_FIELD_EXTENT_M - inset);
608 }
609}
610
611/**
612 * @brief Private storage for the synthetic field and its GP posterior.
613 * @details Keep truth beside the synthetic observation source, not in the
614 * network's inputs: the planner should learn through measurements, not peek at
615 * the answer sheet. The mean and full covariance evolve together in place.
616 * @invariant Only accepted increasing observation numbers advance replay state.
617 * @warning The covariance is dense. Additional copies are substantial allocations
618 * on MORA's shared 512 MB board, even when the public Belief stays small.
619 */
621 /** Immutable validated experiment snapshot; never reloaded mid-survey. */
623 /** Fixed 51-by-51 grid geometry. */
625 /** Dense prior/posterior covariance; one matrix is about 51.6 MiB. */
627 /** Configured prior/posterior mean, independent of the comparison threshold. */
629 /** Private synthetic ground truth used only by the observation operator. */
631 /** Highest accepted observation identifier. */
632 std::uint32_t last_number = 0;
633 /** Independent configured sensor stream, never advanced by diffusion sampling. */
634 std::mt19937_64 sensor_generator;
635 /** FNV-1a over data-row bytes with LF separators; excludes the CSV header. */
636 std::uint64_t digest = fnv_offset_basis;
637 /**
638 * @brief Load the complete synthetic lattice without inventing missing truth.
639 * @details Numeric rows outside the deployed even-coordinate grid are
640 * ignored after parsing. Selected cells must appear exactly once; silently
641 * averaging duplicates or filling holes would change the experiment.
642 * @param[in] path CSV with complete coverage of the selected 51-by-51 grid.
643 * @param[in] experiment Immutable GP and synthetic sensor policy.
644 * @throws std::exception For file-system, allocation, reading, or data-validation failures.
645 * @note The 2 MiB file and 256-character row limits bound accepted input,
646 * not the dense covariance or every transient allocation made by streams.
647 */
648 explicit State(const std::string& path, const ExperimentOptions& experiment)
649 : options(experiment), sensor_generator(options.sensor_noise_seed) {
650 options.validate();
651 if (std::filesystem::file_size(path) > field_byte_limit) throw std::runtime_error("Field CSV too large");
652 std::ifstream input(path);
653 std::string line;
654 if (!std::getline(input, line) || (line != "x,y,count" && line != "x,y,count\r"))
655 throw std::runtime_error("Field must be numeric x,y,count CSV, not an LFS pointer");
656 std::array<bool, cells> seen{};
657 std::size_t rows = 0;
658 while (std::getline(input, line)) {
659 if (line.size() > field_row_byte_limit) throw std::runtime_error("Field CSV row too long");
660 // Hash before replacing commas, including ignored rows and any CR.
661 // getline removes LF, so restore a logical LF for every data row.
662 // This is a provenance aid, not a byte-exact whole-file hash: the
663 // header is excluded and a missing final LF is normalized away.
664 for (unsigned char byte : line) { digest ^= byte; digest *= fnv_prime; }
665 digest ^= '\n'; digest *= fnv_prime;
666 if (line.empty() || line == "\r") continue;
667 std::replace(line.begin(), line.end(), ',', ' ');
668 std::istringstream values(line);
669 double east = 0, north = 0, count = 0;
670 std::string trailing;
671 if (!(values >> east >> north >> count) || (values >> trailing) ||
672 !std::isfinite(east) || !std::isfinite(north) || !std::isfinite(count))
673 throw std::runtime_error("Invalid field CSV row");
674 // Research maps may contain a finer one-metre grid; only exact
675 // even-coordinate samples belong to the deployed two-metre lattice.
676 if (!inside_field(east, north) ||
677 std::abs(std::remainder(east, DIPLA_GRID_STEP_M)) > field_alignment_tolerance_m ||
678 std::abs(std::remainder(north, DIPLA_GRID_STEP_M)) > field_alignment_tolerance_m) continue;
679 // Match Belief and the network maps: north is the row, east the
680 // column. Transposing here gives a valid-looking but rotated survey.
681 const auto cell = cell_index(static_cast<std::size_t>(std::llround(north / DIPLA_GRID_STEP_M)),
682 static_cast<std::size_t>(std::llround(east / DIPLA_GRID_STEP_M)));
683 if (seen[cell]) throw std::runtime_error("Duplicate field grid cell");
684 seen[cell] = true;
685 truth[static_cast<int>(cell)] = count;
686 ++rows;
687 }
688 if (!input.eof() || rows != cells) throw std::runtime_error("Field must cover all 2601 grid cells");
689 covariance = aipp::initialize_covariance(grid, options.gp_kernel_variance, options.gp_lengthscale_m);
690 mean = aipp::Vector::Constant(cells, options.gp_prior_mean);
691 }
692};
693
694/**
695 * @details A new Survey starts a fresh belief and sensor random stream. Keep
696 * the same instance across route chunks; reconstruct only for a new survey,
697 * otherwise previously acquired knowledge disappears along with the covariance.
698 */
699Survey::Survey(const std::string& field, const ExperimentOptions& options)
700 : state_(std::make_unique<State>(field, options)) {}
701/** @details Release private truth and the dense posterior together through their owning State. */
702Survey::~Survey() = default;
703
704/**
705 * @details Measurement generation and GP conditioning must describe the same
706 * sensor: observe the footprint, add Gaussian noise with its declared variance,
707 * and use that variance as the update's likelihood. Adding noise only to the
708 * belief, or conditioning on exact truth, would be a different experiment.
709 * @note The default remains the original 2 m experiment. Resized worker frames
710 * supply the same model-domain height used for network pose conditioning.
711 * @warning Updates are in place, not transactional. A GP arithmetic failure
712 * throws; the owner must treat that survey as failed, not retry as if untouched.
713 * @see Survey::belief
714 */
715bool Survey::observe(double east, double north, std::uint32_t number, double height) {
716 auto& state = *state_;
717 // A retried pose is not another independent sensor reading: conditioning
718 // twice would create false certainty even though the field value is unchanged.
719 // Reject before drawing noise as well: retries must not shift the sensor
720 // random stream and thereby change every later accepted measurement.
721 if (!number || number <= state.last_number) return false;
722 if (!inside_field(east, north) || !std::isfinite(height) || height <= 0 || height > DIPLA_MODEL_Z_MAX_M)
723 throw std::runtime_error("Observation outside field");
724 const auto sensor = aipp::build_sensor(state.grid, {east, north, height},
725 state.options.sensor_fov_deg, state.options.sensor_noise_variance);
726 // The research altitude-noise formula is not extrapolated below its training
727 // band, where it would become negative at the 2 m demo. The configured
728 // positive variance drives both sampled noise and GP likelihood.
729 auto measured = aipp::observe(sensor, state.truth);
730 const auto sensor_noise = aipp::sample_sensor_noise(sensor, state.sensor_generator);
731 for (int index = 0; index < measured.size(); ++index) measured[index] += sensor_noise[index];
732 // Truth is consumed only through the footprint operator; planning receives
733 // the posterior rather than privileged access to unmeasured field cells.
734 aipp::condition(state.covariance, &state.mean, sensor, &measured);
735 if (!state.mean.allFinite() || !state.covariance.allFinite()) throw std::runtime_error("GP update failed");
736 // Consume the identifier only after a successful finite update. Even an
737 // empty footprint is consumed, so retrying it cannot later become new evidence.
738 state.last_number = number;
739 return !sensor.rows.empty();
740}
741
742/*
743 * This is an explicitly selected alternative to diffusion, never an
744 * automatic rescue for a failed neural plan. Use the same configured sensor
745 * and fixed 2 m height so the comparison changes the planner,
746 * not the measurement model. The supplied altitude is checked for compatibility
747 * before planning at exactly 2 m.
748 *
749 * The underlying greedy search copies covariance for hypothetical updates;
750 * the observed posterior must remain untouched. Budget that extra dense matrix.
751 * A completed greedy seed may survive a refinement deadline; an incomplete seed
752 * or caller cancellation must not become a partial published route.
753 *
754 * Deadline and cancellation are cooperative polling, not hard preemption.
755 * Serialize this call with observations on the same Survey, despite its const API.
756 * Pass successful results through apply_flight_margin before publication.
757 */
758std::optional<Waypoints> Survey::compare(const std::array<double, 3>& position,
759 const CmaesOptions& comparison,
760 const std::function<bool()>& cancelled) const {
761 for (double value : position) if (!std::isfinite(value)) throw std::runtime_error("Nonfinite comparison position");
762 comparison.validate();
763 const double height_m = DIPLA_DEMO_HEIGHT_MM / DIPLA_MM_PER_M;
764 if (position[0] < 0 || position[0] > DIPLA_FIELD_EXTENT_M ||
765 position[1] < 0 || position[1] > DIPLA_FIELD_EXTENT_M ||
766 std::abs(position[2] - height_m) > DIPLA_HEIGHT_TOLERANCE_M)
767 throw std::runtime_error("Invalid CMA-ES comparison position");
768 const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(comparison.budget_ms);
770 options.zmin = options.zmax = height_m;
771 options.observation_variance = state_->options.sensor_noise_variance;
772 options.angle_of_view = state_->options.sensor_fov_deg;
773 options.margin_cells = state_->options.flight_margin_cells;
774 options.horizon = static_cast<int>(points);
776 options.threshold = comparison.utility_threshold;
777 options.beta = comparison.confidence_beta;
778 options.step_xy = comparison.step_xy_m;
779 options.maxfevals = comparison.maxfevals;
780 // Round up to enough population generations to use the evaluation allowance;
781 // the evaluation cap remains authoritative, rather than rounding the budget down.
782 options.maxiter = (comparison.maxfevals + options.popsize - 1) / options.popsize;
783 options.seed = comparison.seed;
784 // The library optimizer is cooperative. This closure gives both its
785 // deadline and caller cancellation the same inexpensive polling point.
786 options.keep_planning = [&] {
787 return std::chrono::steady_clock::now() < deadline && (!cancelled || !cancelled());
788 };
789 const auto controls = aipp::plan(state_->grid, state_->mean, state_->covariance,
790 {position[0], position[1], height_m}, options);
791 if (controls.size() != points || (cancelled && cancelled())) return std::nullopt;
792 Waypoints route{};
793 for (std::size_t slot = 0; slot < points; ++slot) {
794 if (!controls[slot].allFinite()) throw std::runtime_error("Nonfinite CMA-ES waypoint");
795 route[slot] = {{controls[slot].x(), controls[slot].y(), height_m}};
796 }
797 return route;
798}
799
800/**
801 * @details Publish a value snapshot, not aliases into the mutable GP. The
802 * denoiser needs per-cell means and marginal variances, whereas conditioning
803 * needs the correlations in the full covariance; keep those responsibilities
804 * separate rather than expanding every model request into a matrix copy.
805 * @note Clamp negative diagonal round-off only in the exported summary. This
806 * does not repair the internal covariance or validate its positive semidefiniteness.
807 */
810 // Publish only marginal variance. Copying dense covariance for every request
811 // would move about 51.6 MiB and expose mutable GP internals unnecessarily.
812 for (std::size_t cell = 0; cell < cells; ++cell) {
813 result.mean[cell] = state_->mean[static_cast<int>(cell)];
814 result.variance[cell] = std::max(0.0, state_->covariance(static_cast<int>(cell), static_cast<int>(cell)));
815 }
816 return result;
817}
818
819/**
820 * @details The trace sums uncertainty over cells, not the uncertainty of their
821 * sum (which would include cross-covariances). Keep it consistent with the
822 * model's total-variance conditioning; it is not a calibrated route-quality score.
823 * @note This diagnostic reads the raw trace, unlike belief()'s clipped marginals.
824 */
825double Survey::total_variance() const { return state_->covariance.trace(); }
826
827/**
828 * @details Identify the loaded data rows without exposing the hidden field.
829 * FNV-1a is a lightweight diagnostic fingerprint, not collision-resistant
830 * integrity checking or authentication. See State's loader for newline handling.
831 */
832std::uint64_t Survey::field_digest() const { return state_->digest; }
833}
Allocation-free flat key=value mechanics; callers own schemas and storage.
static bool ini_read_file(const char *filename, char *buffer, size_t capacity, size_t *length)
Read a nonempty regular file smaller than capacity and append NUL.
Definition bounded_ini.h:98
static bool ini_parse(char *buffer, size_t length, ini_field_handler handler, void *context)
Destructively parse flat fields with blank lines and #/; comment lines.
static uint32_t session
size_t size
Definition chdk_pipe.c:143
uint8_t bytes[CHDK_CONTROL_REPLY_SIZE]
Definition chdk_pipe.c:144
static Vector Constant(std::size_t count, double value)
Allocate a constant.
Definition compat.hpp:93
static Vector Zero(std::size_t count)
Allocate zeros.
Definition compat.hpp:91
~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.
#define DIPLA_FIELD_EXTENT_M
#define DIPLA_MAP_CHANNEL_COUNT
#define DIPLA_DIFFUSION_STEPS
#define DIPLA_MM_PER_M
#define DIPLA_MODEL_Z_MIN_M
#define DIPLA_COORDINATE_COUNT
#define DIPLA_HEIGHT_TOLERANCE_M
#define DIPLA_DEMO_HEIGHT_MM
#define DIPLA_GRID_SIDE
#define DIPLA_MODEL_Z_MAX_M
#define DIPLA_GRID_STEP_M
Native finite-grid GP sensor model and trajectory-planning API.
Public planning, synthetic-survey, and comparison APIs for Diplacam.
struct jsonbourne_val jsonbourne_val
Forward name for values referenced by recursive container entries.
Definition jsonbourne.h:214
struct jsonbourne_num jsonbourne_num
Original number spelling, retained so reading never rounds through a double.
struct jsonbourne_obj jsonbourne_obj
Ordered object members; len must exactly match the linked-list length.
@ JSONBOURNE_TYPE_NUM
Definition jsonbourne.h:180
@ JSONBOURNE_TYPE_OBJ
Definition jsonbourne.h:181
@ JSONBOURNE_TYPE_ARR
Definition jsonbourne.h:182
@ JSONBOURNE_READ_ERROR_DEPTH
Definition jsonbourne.h:281
@ JSONBOURNE_READ_ERROR_MEMORY_ALLOCATION
Definition jsonbourne.h:279
@ JSONBOURNE_READ_NOFLAG
Definition jsonbourne.h:154
jsonbourne_val * jsonbourne_read_buf(const void *src, size_t len, jsonbourne_read_flag flg, const jsonbourne_read_limits *limits, void *buf, size_t cap, size_t *required, jsonbourne_read_err *err)
Read a DOM into aligned caller storage without heap allocation.
bool inference_file_sha256(const char *filename, char digest[65])
Hash a stable nonempty regular file using bounded streaming scratch.
bool inference_model_read(struct inference_model *model, const char *descriptor, const char *graph, char *error, size_t capacity)
Load a bounded descriptor and verify its exact graph digest; hashes are not authentication.
Integrity-checked model contracts and independently owned tensor workspaces.
JSON reader, writer and DOM utilities for Linux C11 with a C++11-compatible API.
uint8_t row[LWIR_MAX_WIDTH *3U]
Definition lwir_image.c:63
struct jpeg_error_mgr error
Definition lwir_image.c:60
std::vector< Point > plan(const Grid &grid, const Vector &mean, const Matrix &covariance, const Point &start, const PlannerOptions &options)
Run greedy route selection followed by optional CMA-ES refinement.
Matrix initialize_covariance(const Grid &grid, double sigma2, double lengthscale)
Initialize a dense Matérn-3/2 GP covariance matrix.
Vector sample_sensor_noise(const Sensor &sensor, std::mt19937_64 &generator)
Draw independent zero-mean noise using each sensor row's variance.
math::Matrix Matrix
Sensor build_sensor(const Grid &grid, const Point &pose, double angle, double observation_variance)
Build one block-averaged sensor footprint at a pose.
math::Vector Vector
void condition(Matrix &covariance, Vector *mean, const Sensor &sensor, const Vector *measurement)
Apply a Gaussian linear-observation update in place.
Vector observe(const Sensor &sensor, const Vector &field)
Apply the sensor's block averages to a full-grid field.
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
double number(const std::string &text, const std::string &name)
Read a complete finite numeric route field.
Definition route.h:141
bool onnx_runtime_open(const char *library_directory, char *error, size_t capacity)
Initialize one process-lifetime runtime/environment using explicit local search roots.
Process-wide runtime ownership shared by independent model sessions.
bool onnx_session_run(struct onnx_session *session, uint64_t deadline_us, char *error, size_t capacity)
Run once; deadline is absolute CLOCK_MONOTONIC microseconds, or zero for none.
bool onnx_session_open(struct onnx_session *session, const char *model, const struct onnx_tensor *inputs, size_t input_count, const struct onnx_tensor *outputs, size_t output_count, const struct onnx_session_options *options, char *error, size_t capacity)
Validate graph contracts and bind reusable caller buffers; failure releases acquired resources.
uint64_t onnx_monotonic_us(void)
Read the clock used by inference deadlines.
void onnx_session_close(struct onnx_session *session)
Cancel/wait for an active run and release resources; repeated closes are harmless.
Bounded tensor bindings and cooperative execution policy, independent of CAM semantics.
#define ONNX_TENSOR_LIMIT
@ ONNX_FLOAT32
@ ONNX_INT64
static size_t count
Definition pose_log.c:79
static FILE * output
Definition pose_log.c:77
Rectangular, evenly spaced local map grid.
Search, utility, and optimizer controls for the reference planner.
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.
void validate() const
Reject nonfinite values and incompatible margins before allocation.
Model identity and execution limits for a diffusion network.
std::array< std::vector< float >, ONNX_TENSOR_LIMIT > values
ConditioningCache(const std::string &directory, const std::string &source, const onnx_tensor *inputs, const onnx_tensor *outputs, const onnx_session_options &options)
Validate the split model contract and open both runtime sessions.
~ConditioningCache()
Release sessions before their borrowed tensor storage is destroyed.
Runtime-owned ONNX session and reusable input/output storage.
~State()
Close the session while every borrowed member buffer is still alive.
std::array< float, 1 > total
std::array< float, 3 > position
std::array< float, DIPLA_COORDINATE_COUNT *points > predicted
Normalization total_normalization
std::array< int64_t, 1 > timestep
std::array< double, DIPLA_DIFFUSION_STEPS > alpha
std::array< float, DIPLA_COORDINATE_COUNT *points > candidate
Normalization variance_normalization
Normalization mean_normalization
std::array< float, DIPLA_MAP_CHANNEL_COUNT *cells > maps
State(const std::string &model, const std::string &metadata, const NetworkOptions &policy)
Validate the export contract before binding a reusable ONNX session.
std::unique_ptr< ConditioningCache > conditioning_cache
Private storage for the synthetic field and its GP posterior.
std::mt19937_64 sensor_generator
const ExperimentOptions options
State(const std::string &path, const ExperimentOptions &experiment)
Load the complete synthetic lattice without inventing missing truth.
std::uint32_t last_number
Parsed descriptor with self-referencing tensor-name pointers; do not copy after parsing.
struct onnx_tensor inputs[ONNX_TENSOR_LIMIT]
struct onnx_tensor outputs[ONNX_TENSOR_LIMIT]
Ordered array elements; explicit length supports bounded traversal.
Definition jsonbourne.h:240
Optional read result; coordinates describe the parser's failure cursor.
Definition jsonbourne.h:290
jsonbourne_read_code code
Definition jsonbourne.h:291
Explicit execution limits so each model cannot create an unbounded CPU pool.
Noncopyable caller-owned session; zero-initialize and serialize open/run/close ownership.
Named concrete tensor view; its aligned backing storage must outlive the session.
enum onnx_element_type type
int64_t dimensions[ONNX_RANK_LIMIT]
const char * name
Validated capture and reporting policy, fixed before the sample loop.
Definition earcam.c:137
One timestamped geographic position for a replay annotation.
struct usher_control_result result
Definition usher.c:377