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
map_progress.h
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/**
19 * @file map_progress.h
20 * @brief Report monotonic progress, stage timings, and explicit interruption.
21 * @details Progress percentages are estimates while work is active and remain
22 * below 100 until the caller confirms completion. This avoids presenting a
23 * slow finalization or canceled run as a successful dataset.
24 */
25#ifndef PANGEA_MAP_PROGRESS_H
26#define PANGEA_MAP_PROGRESS_H
27
28#include <algorithm>
29#include <chrono>
30#include <cmath>
31#include <condition_variable>
32#include <iomanip>
33#include <iostream>
34#include <limits>
35#include <mutex>
36#include <sstream>
37#include <stdexcept>
38#include <string>
39#include <thread>
40#include <utility>
41
42namespace pangea_survey {
43/**
44 * @brief Thread-safe progress reporter for staged map work.
45 * @details A reporter thread emits a heartbeat even when a computation has no
46 * fine-grained updates. Destruction joins that thread and reports interruption
47 * unless @ref finish was called.
48 */
50 using Clock = std::chrono::steady_clock;
51 std::string label_, stage_ = "Preparing", detail_;
52 Clock::time_point started_ = Clock::now(), stageStarted_ = started_;
53 double first_ = 0, last_ = 0, fraction_ = 0, estimateSeconds_ = 0;
54 bool complete_ = false, closing_ = false, changed_ = true;
55 bool timedStage_ = false;
56 std::mutex mutex_;
57 std::condition_variable wake_;
58 std::thread reporter_;
59
60 /** @brief Emit at most one elapsed-time record for the active timed stage.
61 * @param now Current monotonic time.
62 * @param status Terminal stage label.
63 * @details Disarm reporting after emission so teardown cannot repeat it. */
64 void stageTiming(Clock::time_point now, const char* status) {
65 if (!timedStage_) return;
66 std::ostringstream text;
67 text.imbue(std::locale::classic());
68 text << "TIMING stage=" << std::quoted(stage_) << " wall_seconds="
69 << std::chrono::duration<double>(now - stageStarted_).count()
70 << " status=" << status << '\n';
71 const auto line = text.str();
72 std::cout.write(line.data(), static_cast<std::streamsize>(line.size()));
73 timedStage_ = false;
74 }
75
76 /** @brief Estimate overall progress from reported work and stage time.
77 * @param now Current monotonic time.
78 * @return Estimated percentage; 100 is reserved for explicit completion.
79 * @details The time estimate approaches the stage endpoint without
80 * claiming all its work is done. Prefer measured progress when greater. */
81 double percentage(Clock::time_point now) const {
82 const double elapsed = std::chrono::duration<double>(now - stageStarted_).count();
83 const double guess = estimateSeconds_ > 0 ? .9 * elapsed / (elapsed + estimateSeconds_) : 0;
84 return complete_ ? 100 : std::min(99.9, first_ + (last_ - first_) * std::max(fraction_, guess));
85 }
86 /** @brief Format an elapsed duration at whole-second precision.
87 * @param value Nonnegative interval.
88 * @return Hours, minutes and seconds without wrapping hours at a day. */
89 static std::string duration(Clock::duration value) {
90 const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(value).count();
91 std::ostringstream text;
92 text << std::setfill('0') << std::setw(2) << seconds / 3600 << ':'
93 << std::setw(2) << seconds / 60 % 60 << ':' << std::setw(2) << seconds % 60;
94 return text.str();
95 }
96 /** @brief Format a consistent progress snapshot under the state mutex.
97 * @param now Monotonic time shared by all elapsed fields on the line.
98 * @return Complete line including its newline.
99 * @details Distinguish an interrupted shutdown from completed publication. */
100 std::string line(Clock::time_point now) const {
101 std::ostringstream text;
102 text << label_ << ": " << std::fixed << std::setprecision(1) << percentage(now)
103 << "% " << (complete_ ? "| complete" : "(estimated) | " + stage_)
104 << " | elapsed " << duration(now - started_);
105 if (!complete_) text << " | stage " << duration(now - stageStarted_);
106 if (!detail_.empty()) text << " | " << detail_;
107 if (closing_ && !complete_) text << " | stopped before completion; check status/errors";
108 return text.str() + '\n';
109 }
110 /** @brief Run the progress reporter until teardown.
111 * @details Wake on changes or every five seconds so a long stage remains
112 * observable. Emit a last snapshot even when stopped early. */
113 void report() {
114 std::unique_lock<std::mutex> lock(mutex_);
115 while (!closing_) {
116 changed_ = false;
117 const auto text = line(Clock::now());
118 std::cout.write(text.data(), static_cast<std::streamsize>(text.size()));
119 std::cout.flush();
120 wake_.wait_for(lock, std::chrono::seconds(5), [&] { return closing_ || changed_; });
121 }
122 const auto text = line(Clock::now());
123 std::cout.write(text.data(), static_cast<std::streamsize>(text.size()));
124 std::cout.flush();
125 }
126public:
127 /**
128 * @brief Start reporting progress under a human-readable label.
129 * @param[in] label Prefix shown on each progress line.
130 */
131 explicit MapProgress(std::string label = "Map progress") : label_(std::move(label)),
132 reporter_([this] { report(); }) {}
133 /** @brief Signal the reporter to emit its final status, then join it.
134 * @details Drop the state mutex before joining so the reporter can exit. */
136 {
137 std::lock_guard<std::mutex> lock(mutex_);
138 stageTiming(Clock::now(), "interrupted");
139 closing_ = true;
140 }
141 wake_.notify_one();
142 reporter_.join();
143 }
144 /**
145 * @brief Begin a monotonic percentage range for one named stage.
146 * @param[in] name Stage label.
147 * @param[in] first First percentage assigned to the stage.
148 * @param[in] last Upper percentage bound, at most 99.9 until finish.
149 * @param[in] estimateSeconds Optional duration used only for a bounded estimate.
150 * @throws std::runtime_error If bounds are invalid or progress would move backward.
151 */
152 void stage(const std::string& name, double first, double last, double estimateSeconds = 0) {
153 if (!std::isfinite(first) || !std::isfinite(last) || !std::isfinite(estimateSeconds) ||
154 first < 0 || last < first || last > 99.9 || estimateSeconds < 0)
155 throw std::runtime_error("Invalid map progress stage");
156 {
157 std::lock_guard<std::mutex> lock(mutex_);
158 if (complete_ || first < percentage(Clock::now()))
159 throw std::runtime_error("Map progress stage would go backwards");
160 stageTiming(Clock::now(), "finished");
161 first_ = first; last_ = last; fraction_ = 0; estimateSeconds_ = estimateSeconds;
162 stage_ = name; detail_.clear(); stageStarted_ = Clock::now(); changed_ = true;
163 timedStage_ = true;
164 }
165 wake_.notify_one();
166 }
167 /**
168 * @brief Advance the current stage without allowing its fraction to regress.
169 * @param[in] fraction Stage completion estimate in the closed interval [0, 1].
170 * @param[in] detail Optional current item or count shown to the operator.
171 * @throws std::runtime_error If @p fraction is nonfinite or outside [0, 1].
172 */
173 void update(double fraction, const std::string& detail = {}) {
174 if (!std::isfinite(fraction) || fraction < 0 || fraction > 1)
175 throw std::runtime_error("Invalid map progress fraction");
176 std::lock_guard<std::mutex> lock(mutex_);
177 fraction_ = std::max(fraction_, fraction);
178 if (!detail.empty()) detail_ = detail;
179 }
180 /** @brief Replace the operator-facing detail without changing progress. */
181 void detail(const std::string& text) {
182 std::lock_guard<std::mutex> lock(mutex_);
183 detail_ = text;
184 }
185 /** @brief Mark the entire operation complete and permit 100 percent output. */
186 void finish() {
187 {
188 std::lock_guard<std::mutex> lock(mutex_);
189 stageTiming(Clock::now(), "finished");
190 complete_ = true; stage_ = "Complete"; detail_.clear(); changed_ = true;
191 }
192 wake_.notify_one();
193 }
194 /** @brief Exercise stage progress, monotonic updates, and completion behavior.
195 * @throws std::runtime_error If a progress invariant fails.
196 * @details Sample estimated progress at fixed synthetic offsets instead
197 * of waiting for a long stage in real time. */
198 static void selfTest() {
199 const auto require = [](bool value) {
200 if (!value) throw std::runtime_error("Map progress regression failed");
201 };
202 {
203 MapProgress progress("Progress self-test");
204 progress.stage("Capture", 0, 35);
205 progress.update(.5);
206 require(progress.percentage(progress.stageStarted_) == 17.5);
207 progress.update(.25);
208 require(progress.percentage(progress.stageStarted_) == 17.5);
209 progress.update(1);
210 require(progress.percentage(progress.stageStarted_) == 35);
211 progress.stage("Dense reconstruction", 35, 80, 900);
212 const auto later = progress.stageStarted_ + std::chrono::seconds(900);
213 require(std::abs(progress.percentage(later) - 55.25) < 1e-9);
214 require(progress.percentage(later + std::chrono::hours(10000)) < 80);
215 progress.stage("Publication", 80, 99);
216 progress.update(1);
217 require(progress.percentage(progress.stageStarted_) == 99);
218 require(progress.line(progress.stageStarted_).find("(estimated)") != std::string::npos);
219 bool rejected = false;
220 try { progress.update(std::numeric_limits<double>::quiet_NaN()); }
221 catch (const std::runtime_error&) { rejected = true; }
222 require(rejected);
223 progress.finish();
224 require(progress.percentage(progress.stageStarted_) == 100);
225 require(progress.line(progress.stageStarted_).find("| complete") != std::string::npos);
226 }
227 struct CaptureOutput {
228 std::ostringstream text;
229 std::streambuf* previous = std::cout.rdbuf(text.rdbuf());
230 ~CaptureOutput() { std::cout.rdbuf(previous); }
231 };
232 std::string heartbeatOutput, interruptedOutput;
233 {
234 CaptureOutput capture;
235 {
236 MapProgress progress;
237 progress.stage("Long calculation", 0, 99, 1);
238 std::this_thread::sleep_for(std::chrono::milliseconds(5500));
239 progress.finish();
240 }
241 heartbeatOutput = capture.text.str();
242 }
243 require(heartbeatOutput.find("(estimated) | Long calculation") != std::string::npos &&
244 heartbeatOutput.find("| stage 00:00:05") != std::string::npos &&
245 heartbeatOutput.find("TIMING stage=\"Long calculation\" wall_seconds=") != std::string::npos &&
246 heartbeatOutput.find("100.0% | complete") != std::string::npos);
247 {
248 CaptureOutput capture;
249 {
250 MapProgress progress;
251 progress.stage("Rejected output", 0, 99);
252 progress.update(1);
253 }
254 interruptedOutput = capture.text.str();
255 }
256 require(interruptedOutput.find("stopped before completion") != std::string::npos &&
257 interruptedOutput.find("status=interrupted") != std::string::npos &&
258 interruptedOutput.find("100.0%") == std::string::npos);
259 std::cout << "PASS: monotonic estimated progress, bounded long-stage guesses, five-second heartbeat, "
260 "explicit interruption and completion-only 100%.\n";
261 }
262};
263}
264#endif
static bool capture(struct transport *transport, FILE *file, const struct capture_settings *settings)
Capture to the camera's SD card and download the resulting JPEG.
Clock::time_point stageStarted_
static void selfTest()
Exercise stage progress, monotonic updates, and completion behavior.
static std::string duration(Clock::duration value)
Format an elapsed duration at whole-second precision.
void stage(const std::string &name, double first, double last, double estimateSeconds=0)
Begin a monotonic percentage range for one named stage.
void stageTiming(Clock::time_point now, const char *status)
Emit at most one elapsed-time record for the active timed stage.
void finish()
Mark the entire operation complete and permit 100 percent output.
Clock::time_point started_
void report()
Run the progress reporter until teardown.
void update(double fraction, const std::string &detail={})
Advance the current stage without allowing its fraction to regress.
std::chrono::steady_clock Clock
double percentage(Clock::time_point now) const
Estimate overall progress from reported work and stage time.
std::string line(Clock::time_point now) const
Format a consistent progress snapshot under the state mutex.
MapProgress(std::string label="Map progress")
Start reporting progress under a human-readable label.
~MapProgress()
Signal the reporter to emit its final status, then join it.
std::condition_variable wake_
void detail(const std::string &text)
Replace the operator-facing detail without changing progress.
static uint64_t rejected
Definition pose_log.c:81
static double seconds(Clock::duration duration)
Convert a monotonic interval without truncating fractional seconds.
Definition survey.cpp:100