diff --git a/CMakeLists.txt b/CMakeLists.txt index 2ed22b08e..6cedf8f73 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -107,6 +107,7 @@ include(cmake/dependencies.cmake) # e.g. core/include/Core/raylib_render.hpp) that links against them. Required # unconditionally: apps/multi_view_tls_registration (step2) is raylib-based. include(cmake/raylib.cmake) +include(cmake/step1_run_report.cmake) # ============================================================================ # Core Library diff --git a/apps/lidar_odometry_step_1/CMakeLists.txt b/apps/lidar_odometry_step_1/CMakeLists.txt index 30446b3bd..518add39d 100644 --- a/apps/lidar_odometry_step_1/CMakeLists.txt +++ b/apps/lidar_odometry_step_1/CMakeLists.txt @@ -60,6 +60,7 @@ target_include_directories( target_link_libraries( lidar_odometry_step_1 PRIVATE + step1_run_report # core_raylib_utils brings in core_raylib (core, raylib), raylib_widgets and rlImGui. core_raylib_utils imgui_raylib @@ -118,7 +119,8 @@ target_include_directories( target_link_libraries( drag_folder_with_mandeye_data_and_drop_here-precision_forestry - PRIVATE + PRIVATE + step1_run_report vqf Fusion unordered_dense::unordered_dense @@ -148,4 +150,4 @@ endif() hdmapping_install_app( lidar_odometry_step_1 - drag_folder_with_mandeye_data_and_drop_here-precision_forestry) \ No newline at end of file + drag_folder_with_mandeye_data_and_drop_here-precision_forestry) diff --git a/apps/lidar_odometry_step_1/lidar_odometry.cpp b/apps/lidar_odometry_step_1/lidar_odometry.cpp index 9afd403f6..aab62bae8 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry.cpp @@ -15,6 +15,25 @@ namespace fs = std::filesystem; +// One metadata lookup per completed cache file, never per point or per rendered frame. +static bool save_cache_data(LidarOdometryParams& params, const std::string& path, const std::vector& points) +{ + const auto start = RunReport::Clock::now(); + if (!save_vector_data(path, points)) + { + if (params.run_report) + params.run_report->fail("Cache write failed: " + path); + return false; + } + if (params.run_report) + return params.run_report->cacheFile( + path, + std::chrono::duration(RunReport::Clock::now() - start).count(), + fs::path(path).filename().string().starts_with("session_chunk_") ? "export" : "initial", + points.size() * (std::is_trivially_copyable_v ? sizeof(Point3Di) : sizeof(Point3DiDisk))); + return true; +} + static void release_freed_heap() { #if defined(__GLIBC__) @@ -99,6 +118,10 @@ bool load_data( Imu& imu_data, bool debugMsg) { + if (!params.run_report || params.run_report->live().status != "running") + params.run_report = std::make_shared( + input_file_names.empty() ? fs::path{} : fs::path(input_file_names.front()).parent_path(), params.points_global_spill_directory); + RunReport::Scope timing(params.run_report.get(), RunReport::Stage::Loading); HDMAP_ZONE_SCOPE("load_data"); std::sort(input_file_names.begin(), input_file_names.end()); std::vector csv_files, laz_files; @@ -331,6 +354,10 @@ bool load_data( return std::get<0>(a).first < std::get<0>(b).first; }); + // The IMU timestamps are already sorted; publishing their span needs no point-cloud reads or extra scan. + if (params.run_report && !imu_data.empty()) + params.run_report->setRecordingSpan(std::get<0>(imu_data.front()).first, std::get<0>(imu_data.back()).first); + // --- Precompute calibration once (major optimization) const auto combinedCalibration = MLvxCalib::CombineIntoCalibration(idToSn, preloadedCalibration); @@ -467,6 +494,7 @@ bool load_data( void calculate_trajectory(Trajectory& trajectory, Imu& imu_data, LidarOdometryParams& params, bool debugMsg) { + RunReport::Scope timing(params.run_report.get(), RunReport::Stage::Initialization); HDMAP_ZONE_SCOPE("calculate_trajectory"); const float RAD_TO_DEG = 180.0f / static_cast(M_PI); @@ -638,6 +666,7 @@ bool compute_step_1( std::vector& worker_data, const std::atomic& pause) { + RunReport::Scope timing(params.run_report.get(), RunReport::Stage::Cache); HDMAP_ZONE_SCOPE("compute_step_1"); ++params.initial_points_revision; int number_of_initial_points = 0; @@ -853,10 +882,11 @@ bool compute_step_1( std::string original_points_cache_filename = "original_points_" + std::to_string(worker_data.size()) + ".cache"; wd.original_points_cache_file_name = wdp_cache / original_points_cache_filename; - if (!save_vector_data(wd.original_points_cache_file_name.string(), points)) + if (!save_cache_data(params, wd.original_points_cache_file_name.string(), points)) { std::cout << "problem with save_vector_data file '" << wd.original_points_cache_file_name.string() << "'" << std::endl; std::cout << __FILE__ << " " << __LINE__ << std::endl; + return false; } std::string intermediate_points_cache_filename = "intermediate_points_" + std::to_string(worker_data.size()) + ".cache"; @@ -864,32 +894,39 @@ bool compute_step_1( if (intermediate_points.size() > 0) { - if (!save_vector_data(wd.intermediate_points_cache_file_name.string(), intermediate_points)) - std::cout << "problem with save_vector_data for file '" << wd.intermediate_points_cache_file_name.string() << "'" - << std::endl; + if (!save_cache_data(params, wd.intermediate_points_cache_file_name.string(), intermediate_points)) + return false; } else // ensure we always have intermediate points { - if (!save_vector_data(wd.intermediate_points_cache_file_name.string(), points)) - std::cout << "problem with save_vector_data for file '" << wd.intermediate_points_cache_file_name.string() << "'" - << std::endl; + if (!save_cache_data(params, wd.intermediate_points_cache_file_name.string(), points)) + return false; } } if (pause) + { + if (params.run_report) + params.run_report->pause(true); while (pause) std::this_thread::sleep_for(std::chrono::seconds(1)); + if (params.run_report) + params.run_report->pause(false); + } } std::cout << "\rrunning iterations: " << n_iter << " (done)" << std::flush; std::cout << std::endl; + if (params.run_report) + params.run_report->cachePrepared(); params.m_g = worker_data[0].intermediate_trajectory[0]; return true; } void run_consistency(std::vector& worker_data, const LidarOdometryParams& params) { + RunReport::Scope timing(params.run_report.get(), RunReport::Stage::Consistency); std::cout << "Point cloud consistency and trajectory smoothness START" << std::endl; for (int i = 0; i < params.num_constistency_iter; i++) { @@ -908,10 +945,15 @@ void run_consistency(std::vector& worker_data, const LidarOdometryPa } } std::cout << "Point cloud consistency and trajectory smoothness FINISHED" << std::endl; + timing.finish(); + if (params.run_report) + params.run_report->finishOperation(); } -void save_result(std::vector& worker_data, LidarOdometryParams& params, fs::path outwd, double elapsed_time_s) +static bool write_result_files( + std::vector& worker_data, LidarOdometryParams& params, const fs::path& outwd, double elapsed_time_s) { + bool success = true; HDMAP_ZONE_SCOPE("save_result"); std::filesystem::create_directory(outwd); // concatenate data @@ -928,8 +970,11 @@ void save_result(std::vector& worker_data, LidarOdometryParams& para std::vector original_points; // = worker_data[i].load_points(worker_data[i].original_points_cache_file_name); if (!load_vector_data(worker_data[i].original_points_cache_file_name.string(), original_points)) { + if (params.run_report) + params.run_report->fail("Cannot read export cache"); std::cout << "problem with load_vector_data file '" << worker_data[i].original_points_cache_file_name.string() << "'" << std::endl; + return false; } if (i % 1000 == 0) @@ -979,11 +1024,12 @@ void save_result(std::vector& worker_data, LidarOdometryParams& para std::cout << "original_points_to_save_cache_file_name " << path.string() << std::endl; - if (!save_vector_data(wd.original_points_to_save_cache_file_name.string(), original_points_to_save)) + if (!save_cache_data(params, wd.original_points_to_save_cache_file_name.string(), original_points_to_save)) { std::cout << "problem with save_vector_data for file '" << wd.original_points_to_save_cache_file_name.string() << "'" << std::endl; std::cout << __FILE__ << " " << __LINE__ << std::endl; + return false; } original_points_to_save_counter++; @@ -1009,11 +1055,12 @@ void save_result(std::vector& worker_data, LidarOdometryParams& para std::cout << "original_points_to_save_cache_file_name " << path.string() << std::endl; - if (!save_vector_data(wd.original_points_to_save_cache_file_name.string(), original_points_to_save)) + if (!save_cache_data(params, wd.original_points_to_save_cache_file_name.string(), original_points_to_save)) { std::cout << "problem with save_vector_data for file '" << wd.original_points_to_save_cache_file_name.string() << "'" << std::endl; std::cout << __FILE__ << " " << __LINE__ << std::endl; + return false; } original_points_to_save_counter++; @@ -1026,12 +1073,14 @@ void save_result(std::vector& worker_data, LidarOdometryParams& para std::ofstream out_point_sizes(point_sizes_path); if (!out_point_sizes) { + success = false; std::cerr << "Failed to open " << point_sizes_path << " for writing point sizes per chunk.\n"; } else { out_point_sizes << j_point_sizes.dump(2); out_point_sizes.close(); + success = static_cast(out_point_sizes) && success; } std::vector m_poses; @@ -1054,9 +1103,12 @@ void save_result(std::vector& worker_data, LidarOdometryParams& para std::vector original_points_to_save; // = worker_data[i].load_points(worker_data[i].original_points_cache_file_name); if (!load_vector_data(worker_data_concatenated[i].original_points_to_save_cache_file_name.string(), original_points_to_save)) { + if (params.run_report) + params.run_report->fail("Cannot read export cache"); std::cout << "problem with load_vector_data file '" << worker_data_concatenated[i].original_points_to_save_cache_file_name.string() << "'" << std::endl; std::cout << __FILE__ << " " << __LINE__ << std::endl; + return false; } points_to_vector( @@ -1079,7 +1131,9 @@ void save_result(std::vector& worker_data, LidarOdometryParams& para { return c[0] != 0 || c[1] != 0 || c[2] != 0; }); - exportLaz(path.string(), global_pointcloud, intensity, timestamps, 0.0, 0.0, 0.0, nullptr, has_colors ? &colors : nullptr); + success = + exportLaz(path.string(), global_pointcloud, intensity, timestamps, 0.0, 0.0, 0.0, nullptr, has_colors ? &colors : nullptr) && + success; if (params.save_index_pose) { @@ -1101,7 +1155,7 @@ void save_result(std::vector& worker_data, LidarOdometryParams& para if (!outfile.good()) { std::cout << "can not save file: " << pathtrj << std::endl; - return; + return false; } outfile << "timestamp_nanoseconds pose00 pose01 pose02 pose03 pose10 pose11 pose12 pose13 pose20 pose21 pose22 pose23 " @@ -1121,14 +1175,15 @@ void save_result(std::vector& worker_data, LidarOdometryParams& para << worker_data_concatenated[i].imu_om_fi_ka[j].z() << " " << std::endl; } outfile.close(); + success = static_cast(outfile) && success; // } fs::path path(outwd); path /= "session_ini_poses.mri"; - save_poses(path.string(), m_poses, file_names); + success = save_poses(path.string(), m_poses, file_names) && success; fs::path path2(outwd); path2 /= "session_poses.mrp"; - save_poses(path2.string(), m_poses, file_names); + success = save_poses(path2.string(), m_poses, file_names) && success; fs::path index_poses_path = outwd / "index_poses.json"; if (params.save_index_pose) @@ -1137,12 +1192,14 @@ void save_result(std::vector& worker_data, LidarOdometryParams& para std::ofstream out_index(index_poses_path); if (!out_index) { + success = false; std::cerr << "Failed to open " << index_poses_path << " for writing index poses.\n"; } else { out_index << j_index_poses.dump(2); out_index.close(); + success = static_cast(out_index) && success; } } @@ -1195,12 +1252,41 @@ void save_result(std::vector& worker_data, LidarOdometryParams& para std::ofstream fs(path3.string()); fs << jj.dump(2); fs.close(); + success = static_cast(fs) && success; // Save parameters to TOML file (loadable parameters only) - save_parameters_toml(params, outwd, elapsed_time_s); + success = save_parameters_toml(params, outwd, elapsed_time_s) && success; // Save processing results and complex data to JSON file - save_processing_results_json(params, outwd, elapsed_time_s); + return success; +} + +bool save_result(std::vector& worker_data, LidarOdometryParams& params, fs::path outwd, double elapsed_time_s) +{ + RunReport::Scope timing(params.run_report.get(), RunReport::Stage::Export); + if (params.run_report) + { + params.run_report->addVolume(outwd.parent_path(), "output"); + elapsed_time_s = params.run_report->stageSeconds(RunReport::Stage::Odometry); + } + bool success = false; + try + { + success = write_result_files(worker_data, params, outwd, elapsed_time_s); + } catch (const std::exception& error) + { + if (params.run_report) + params.run_report->fail(error.what()); + std::cerr << "Result export failed: " << error.what() << '\n'; + } + timing.finish(); + if (params.run_report) + { + if (!success) + params.run_report->fail("One or more result writers failed"); + params.run_report->finishOperation(success ? "completed" : "failed"); + } + return save_processing_results_json(params, outwd, elapsed_time_s) && success; } void filter_reference_buckets(LidarOdometryParams& params) @@ -1311,6 +1397,8 @@ void remove_cache(const LidarOdometryParams& params) { if (params.working_directory_cache.empty()) return; + const auto previousStatus = params.run_report ? params.run_report->live().status : "completed"; + RunReport::Scope timing(params.run_report.get(), RunReport::Stage::Cleanup); std::cout << "remove cache: '" << params.working_directory_cache << "' START" << std::endl; std::error_code ec; fs::remove_all(params.working_directory_cache, ec); @@ -1318,6 +1406,14 @@ void remove_cache(const LidarOdometryParams& params) std::cerr << "remove cache: '" << params.working_directory_cache << "' FAILED: " << ec.message() << std::endl; else std::cout << "remove cache: '" << params.working_directory_cache << "' FINISHED" << std::endl; + timing.finish(); + if (params.run_report) + { + params.run_report->cacheRemoved(!ec, ec.message()); + params.run_report->finishOperation(previousStatus); + if (!params.run_report->updateReports()) + std::cerr << "Could not update results report after cache cleanup\n"; + } } std::vector run_lidar_odometry(const std::string& input_dir, LidarOdometryParams& params) @@ -1369,7 +1465,7 @@ std::vector run_lidar_odometry(const std::string& input_dir, LidarOd return worker_data; } -void save_parameters_toml(const LidarOdometryParams& _params, const fs::path& outwd, double elapsed_seconds) +bool save_parameters_toml(const LidarOdometryParams& _params, const fs::path& outwd, double elapsed_seconds) { // Get current date and time auto now = std::chrono::system_clock::now(); @@ -1400,13 +1496,15 @@ void save_parameters_toml(const LidarOdometryParams& _params, const fs::path& ou { std::cerr << "Failed to save parameters to TOML file: " << toml_path << std::endl; } + return success; } catch (const std::exception& e) { std::cerr << "Error saving parameters to TOML file: " << e.what() << std::endl; } + return false; } -void save_processing_results_json(const LidarOdometryParams& params, const fs::path& outwd, double elapsed_seconds) +bool save_processing_results_json(const LidarOdometryParams& params, const fs::path& outwd, double elapsed_seconds) { // Get current date and time auto now = std::chrono::system_clock::now(); @@ -1433,6 +1531,8 @@ void save_processing_results_json(const LidarOdometryParams& params, const fs::p results["processing_info"]["build_date"] = params.build_date; results["processing_info"]["processing_date"] = datetime_str; results["processing_info"]["elapsed_time_seconds"] = elapsed_seconds; + results["processing_info"]["elapsed_time_scope"] = + params.run_report ? "odometry_wall_seconds_including_pauses" : "legacy_caller_supplied"; results["processing_info"]["OS"] = system_info::getOSName(); results["processing_info"]["CPU"] = system_info::getCPUName(); results["processing_info"]["RAM"] = system_info::getTotalRAM(); @@ -1483,6 +1583,13 @@ void save_processing_results_json(const LidarOdometryParams& params, const fs::p } // Save JSON file + if (params.run_report) + { + const bool success = params.run_report->write(json_path, std::move(results)); + if (!success) + params.run_report->fail("Could not save results JSON: " + json_path.string()); + return success; + } std::ofstream file(json_path); if (file.is_open()) { @@ -1490,6 +1597,7 @@ void save_processing_results_json(const LidarOdometryParams& params, const fs::p file.close(); std::cout << "Processing results saved to JSON file: " << json_path << std::endl; std::cout << "Processing time: " << fixed << std::setprecision(2) << elapsed_seconds << " [s]" << std::endl; + return static_cast(file); } else { @@ -1499,4 +1607,24 @@ void save_processing_results_json(const LidarOdometryParams& params, const fs::p { std::cerr << "Error saving processing results to JSON file: " << e.what() << std::endl; } + return false; +} + +bool save_run_status_report(LidarOdometryParams& params, const fs::path& output, const std::string& status, const std::string& error) +{ + if (!params.run_report) + return false; + if (!error.empty()) + params.run_report->fail(error); + params.run_report->finishOperation(status); + std::error_code ec; + fs::create_directories(output, ec); + if (ec) + return false; + return save_processing_results_json(params, output, params.run_report->stageSeconds(RunReport::Stage::Odometry)); +} + +bool save_failed_run_report(LidarOdometryParams& params, const fs::path& output, const std::string& error) +{ + return save_run_status_report(params, output, "failed", error); } diff --git a/apps/lidar_odometry_step_1/lidar_odometry.h b/apps/lidar_odometry_step_1/lidar_odometry.h index 3b2fc1da8..f76757ec2 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry.h +++ b/apps/lidar_odometry_step_1/lidar_odometry.h @@ -4,6 +4,7 @@ #include #include "lidar_odometry_utils.h" +#include "run_report.h" #include "toml_io.h" #include #include @@ -36,12 +37,16 @@ void remove_cache(const LidarOdometryParams& params); void run_consistency(std::vector& worker_data, const LidarOdometryParams& params); void filter_reference_buckets(LidarOdometryParams& params); void load_reference_point_clouds(const std::vector& input_file_names, LidarOdometryParams& params); -void save_result(std::vector& worker_data, LidarOdometryParams& params, fs::path outwd, double elapsed_seconds); -void save_parameters_toml(const LidarOdometryParams& params, const fs::path& outwd, double elapsed_seconds); -void save_processing_results_json(const LidarOdometryParams& params, const fs::path& outwd, double elapsed_seconds); +bool save_result(std::vector& worker_data, LidarOdometryParams& params, fs::path outwd, double elapsed_seconds); +bool save_parameters_toml(const LidarOdometryParams& params, const fs::path& outwd, double elapsed_seconds); +bool save_processing_results_json(const LidarOdometryParams& params, const fs::path& outwd, double elapsed_seconds); void save_trajectory_to_ascii(std::vector& worker_data, std::string output_file_name); std::string save_results_automatic( LidarOdometryParams& params, std::vector& worker_data, const std::string& working_directory, double elapsed_seconds); std::vector run_lidar_odometry(const std::string& input_dir, LidarOdometryParams& params); // bool SaveParametersToTomlFile(const std::string &filepath, const LidarOdometryParams ¶ms); // bool LoadParametersFromTomlFile(const std::string &filepath, LidarOdometryParams ¶ms); + +bool save_failed_run_report(LidarOdometryParams& params, const fs::path& output, const std::string& error); + +bool save_run_status_report(LidarOdometryParams& params, const fs::path& output, const std::string& status, const std::string& error); diff --git a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp index c942e10ba..dbf8ff145 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp @@ -226,14 +226,78 @@ std::atomic loRunning{ false }; std::atomic loProgress{ 0.0 }; std::atomic loPause{ false }; std::atomic loParked{ false }; //!< step 2 is waiting on loPause and touches no file (see compute_step_2) -bool loQuitting = false; //!< quit confirmed mid-run: the run is paused, display() exits once it is parked or done -std::string pendingLoadFolder; //!< openData() picked it; display() loads it once the "Loading data" modal is on screen -int pendingLoadFrames = 0; //!< frames left before that load; 0 = none pending -std::chrono::time_point loStartTime; +std::atomic loQuitting{ false }; //!< quit confirmed mid-run: the run is paused, display() exits once it is parked or done +std::string pendingLoadFolder; // GUI-owned label; unchanged while the loading worker is running std::atomic loElapsedSeconds{ 0.0 }; std::atomic loEstimatedTimeRemaining{ 0.0 }; fs::path outwd; +std::atomic loLoading{ false }; +std::thread pipelineThread; +std::mutex completionMutex; +std::string completionMessage; +bool pipelinePending = false; +bool pendingCompute = true, pendingSave = true; +std::string pendingFolder; +void startPipeline(const std::string& folder, bool compute, bool save); + +static void resources_gui() +{ + if (!params.run_report || !ImGui::CollapsingHeader("Resources", ImGuiTreeNodeFlags_DefaultOpen)) + return; + // OS queries run in the sampler; the GUI copies only the small aggregate snapshot. + const auto live = params.run_report->live(); + ImGui::Text("Stage: %s | Total: %.1f s | Paused: %.1f s", live.label.c_str(), live.total, live.paused); + auto memoryRow = [&](const char* key, const char* label) + { + auto it = live.memory.find(key); + if (it == live.memory.end() || !it->second.current) + { + ImGui::Text("%s: N/A", label); + return; + } + ImGui::Text( + "%s: %.1f MiB | Peak sampled: %.1f MiB", + label, + *it->second.current / (1024 * 1024), + it->second.maximum.value_or(0) / (1024 * 1024)); + }; + memoryRow("process_resident_bytes", "Application resident RAM"); + memoryRow("process_private_commit_bytes", "Application private commit"); + memoryRow("gpu_dedicated_bytes", "GPU dedicated (adapter sum)"); + memoryRow("gpu_shared_bytes", "GPU shared (adapter sum)"); + if (ImGui::TreeNode("GPU adapter detail")) + { + for (const auto& [name, metric] : live.memory) + if (name.find("/luid_") != std::string::npos) + memoryRow(name.c_str(), name.c_str()); + ImGui::TreePop(); + } + memoryRow("system_available_ram_bytes", "System available RAM"); + memoryRow("system_commit_bytes", "System commit used"); + memoryRow("system_commit_limit_bytes", "System commit limit"); + for (const auto& volume : live.volumes) + { + std::string roles; + for (const auto& role : volume.roles) + roles += (roles.empty() ? "" : ", ") + role; + if (volume.free.current) + ImGui::Text( + "%s free: %.2f GiB | Min sampled: %.2f GiB", + volume.path.c_str(), + *volume.free.current / (1024 * 1024 * 1024), + volume.free.minimum.value_or(0) / (1024 * 1024 * 1024)); + else + ImGui::Text("%s free: N/A", volume.path.c_str()); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", roles.c_str()); + } + ImGui::Text( + "Disk cache: %.1f MiB | Peak: %.1f MiB", + static_cast(live.cacheBytes) / (1024 * 1024), + static_cast(live.cachePeak) / (1024 * 1024)); + ImGui::TextDisabled("Commit is not physical pagefile usage. Peaks are sampled within this run."); +} #if _WIN32 #define DEFAULT_PATH "C:\\" @@ -673,13 +737,12 @@ void step1(const std::string& input_folder_name, const std::atomic& loPaus if (fs::exists(input_folder_name)) { - std::string newTitle = winTitle + " - ..\\" + std::filesystem::path(input_folder_name).filename().string(); - SetWindowTitle(newTitle.c_str()); - + RunReport::Scope discovery(params.run_report.get(), RunReport::Stage::Loading); for (const auto& entry : fs::directory_iterator(input_folder_name)) if (entry.is_regular_file()) input_file_names.push_back(entry.path().string()); + discovery.finish(); if (load_data(input_file_names, params, pointsPerFile, imu_data, full_debug_messages)) { working_directory = fs::path(input_file_names[0]).parent_path().string(); @@ -698,10 +761,7 @@ void step1(const std::string& input_folder_name, const std::atomic& loPaus std::string message_info = "Problem with loading data from folder '" + input_folder_name + "' (Pease check if folder exists). Program will close once You click OK!!!"; std::cout << message_info << std::endl; - [[maybe_unused]] pfd::message message("Information", message_info.c_str(), pfd::choice::ok, pfd::icon::info); - message.result(); - - exit(1); + throw std::runtime_error("Input data loading failed: " + input_folder_name); } } } @@ -735,19 +795,6 @@ void step2(const std::atomic& loPause) } } -void save_results(bool info, double elapsed_seconds) -{ - outwd = get_next_result_path(working_directory); - save_result(worker_data, params, outwd, elapsed_seconds); - if (info) - { - std::string message_info = "Results saved to folder: '" + outwd.string() + "'"; - std::cout << message_info << std::endl; - [[maybe_unused]] pfd::message message("Information", message_info.c_str(), pfd::choice::ok, pfd::icon::info); - message.result(); - } -} - void settings_gui() { if (ImGui::Begin("Settings", &is_settings_gui)) @@ -1195,15 +1242,9 @@ void settings_gui() { if (ImGui::Button("Load data")) { - loStartTime = std::chrono::system_clock::now(); - - step1(mandeye::fd::SelectFolder("Select Mandeye data folder"), loPause); - std::cout << "Load data done please click 'Compute all' to continue calculations" << std::endl; - - std::chrono::duration elapsed = std::chrono::system_clock::now() - loStartTime; - double elapsedSeconds = elapsed.count(); - - std::cout << "Elapsed time: " << formatTime(elapsedSeconds).c_str() << std::endl; + const auto folder = mandeye::fd::SelectFolder("Select Mandeye data folder"); + if (!folder.empty()) + startPipeline(folder, false, false); } if (ImGui::IsItemHovered()) ImGui::SetTooltip( @@ -1212,7 +1253,7 @@ void settings_gui() if (step_1_done && !step_2_done) { if (ImGui::Button("Compute all")) - step2(loPause); + startPipeline("", true, false); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Press this button for automatic LiDAR odometry calculation -> it will produce trajectory"); @@ -1239,7 +1280,7 @@ void settings_gui() ImGui::SetTooltip("Multiple Gaussians suppose to work better in floor plan indoor scenarios (multiple neighbouring rooms)"); if (ImGui::Button("Save result")) - save_results(true, 0.0); + startPipeline("", false, true); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); @@ -1727,16 +1768,26 @@ void settings_gui() ImGui::End(); } +static void recording_span_gui() +{ + const auto seconds = params.run_report ? params.run_report->recordingSeconds() : std::nullopt; + if (seconds) + ImGui::Text("Raw recording span (IMU): %.3f s (%.2f min)", *seconds, *seconds / 60.0); + else + ImGui::TextDisabled("Raw recording span (IMU): awaiting timestamps"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Last minus first loaded raw IMU timestamp, including gaps. Separate from processing time."); +} + void progress_window() { ImGui::Begin("Progress", nullptr, ImGuiWindowFlags_AlwaysAutoResize); ImGui::Text(("Working directory:\n'" + working_directory + "'").c_str()); + recording_span_gui(); // Calculate elapsed time and ETA - auto currentTime = std::chrono::system_clock::now(); - std::chrono::duration elapsed = currentTime - loStartTime; - double elapsedSeconds = elapsed.count(); + double elapsedSeconds = params.run_report ? params.run_report->stageSeconds(RunReport::Stage::Odometry, true) : 0; loElapsedSeconds.store(elapsedSeconds); float progress = loProgress.load(); @@ -1760,7 +1811,7 @@ void progress_window() snprintf( timeInfo, sizeof(timeInfo), - "Elapsed: %s | Remaining: %s | Estimated finish: ~%s", + "Odometry (without pauses): %s | Remaining: %s | Estimated finish: ~%s", formatTime(elapsedSeconds).c_str(), formatTime(estimatedTimeRemaining).c_str(), completionTime.c_str()); @@ -1768,11 +1819,18 @@ void progress_window() else { snprintf(progressText, sizeof(progressText), "Processing: %.1f%%", progress * 100.0f); - snprintf(timeInfo, sizeof(timeInfo), "Elapsed: %s | Calculating completion time...", formatTime(elapsedSeconds).c_str()); + snprintf( + timeInfo, + sizeof(timeInfo), + "Odometry (without pauses): %s | Calculating completion time...", + formatTime(elapsedSeconds).c_str()); } + if (params.run_report && params.run_report->live().stage == "export") + snprintf(progressText, sizeof(progressText), "Writing results..."); ImGui::ProgressBar(progress, ImVec2(-1.0f, 0.0f), progressText); ImGui::Text("%s", timeInfo); + resources_gui(); #ifdef _WIN32 // Update Windows taskbar progress @@ -1790,6 +1848,8 @@ void progress_window() if (loQuitting) ImGui::TextColored(ImVec4(1.f, 0.6f, 0.2f, 1.f), "Quitting: waiting for the current worker to finish..."); + else if (params.run_report && params.run_report->live().stage != "odometry") + ImGui::Text("Finishing output..."); else if (!loPause) { if (ImGui::Button("Pause")) @@ -1829,67 +1889,117 @@ void progress_window() } //! folder: Mandeye data folder to process; empty asks for one with a folder dialog. -//! Loading (step 1) blocks the UI thread, so display() first presents a "Loading data" modal and only -//! then calls loadData(): one frame for the auto-resized modal to measure itself, one to show it. +//! Loading and processing share one owned worker; drawing is suspended only during initial preparation. void openData(const std::string& folder = "") { const std::string input_folder_name = folder.empty() ? mandeye::fd::SelectFolder("Select Mandeye data folder") : folder; - if (input_folder_name.empty()) + if (!input_folder_name.empty()) + startPipeline(input_folder_name, true, true); +} + +void startPipeline(const std::string& folder, bool compute, bool save) +{ + if (loRunning) return; - pendingLoadFolder = input_folder_name; - pendingLoadFrames = 3; + pendingFolder = folder; + pendingCompute = compute; + pendingSave = save; + pipelinePending = true; } -void loadData(const std::string& input_folder_name) +static void launchPipeline(const std::string& folder, bool compute, bool save) { + if (loRunning) + return; + if (pipelineThread.joinable()) + pipelineThread.join(); is_settings_gui = false; info_gui = false; - - loRunning.store(true); - loProgress.store(0.0f); - loElapsedSeconds.store(0.0); - loEstimatedTimeRemaining.store(0.0); - loStartTime = std::chrono::system_clock::now(); - - step1(input_folder_name, loPause); - - if (step_1_done) + loPause = false; + loParked = false; + loProgress = 0; + loQuitting = false; + if (!folder.empty()) { - std::thread loThread( - []() + // Dispose the previous run before changing the shared report/data pointers. + if (params.run_report && !params.working_directory_cache.empty()) + remove_cache(params); + params.run_report = std::make_shared(folder, params.points_global_spill_directory, "gui"); + step_1_done = step_2_done = false; + calculations_failed = false; + pendingLoadFolder = folder; + SetWindowTitle((winTitle + " - " + fs::path(folder).filename().string()).c_str()); + } + if (folder.empty()) + publish_trajectory_preview(worker_data, true); + loLoading = !folder.empty(); + loRunning = true; + pipelineThread = std::thread( + [folder, compute, save] + { + try { - std::chrono::time_point start, end; - start = std::chrono::system_clock::now(); - - step2(loPause); - if (!step_2_done) + if (!folder.empty()) + step1(folder, loPause); + if (!folder.empty() && !step_1_done) + throw std::runtime_error("Initial preparation failed"); + loLoading = false; // release publishes the completed initial geometry to display() + if (loQuitting) { - loRunning = false; - std::cerr << "Lidar odometry step 2 failed: no results saved" << std::endl; - return; + if (params.run_report) + params.run_report->finishOperation("cancelled"); } - - end = std::chrono::system_clock::now(); - std::chrono::duration elapsed_seconds = end - start; - - save_results(false, elapsed_seconds.count()); - - loRunning = false; - - std::ostringstream oss; - oss << "Data saved to folder:\n'" << outwd.string() << "'\n" - << "Calculated trajectory length: " << std::fixed << std::setprecision(1) - << params.total_length_of_calculated_trajectory << "[m]\n" - << "Elapsed time: " << formatTime(elapsed_seconds.count()).c_str(); - - [[maybe_unused]] pfd::message message("Information", oss.str(), pfd::choice::ok, pfd::icon::info); - message.result(); - }); - - loThread.detach(); - } - else // no data loaded - loRunning = false; + else + { + if (compute) + { + step2(loPause); + if (!step_2_done) + throw std::runtime_error("Odometry failed"); + } + if (loQuitting) + { + if (params.run_report) + params.run_report->finishOperation("cancelled"); + } + else if (save) + { + outwd = get_next_result_path(working_directory); + const bool success = save_result(worker_data, params, outwd, 0); + std::lock_guard lock(completionMutex); + completionMessage = std::string(success ? "Results saved to: " : "Export incomplete: ") + outwd.string() + "\n" + + "Calculated trajectory length: " + std::to_string(params.total_length_of_calculated_trajectory) + " m\n" + + params.run_report->summary() + "Report: HDMapping_results_*.json"; + } + else if (params.run_report) + params.run_report->finishOperation(compute ? "processed" : "prepared"); + } + } catch (const std::exception& error) + { + if (params.run_report) + { + params.run_report->fail(error.what()); + params.run_report->finishOperation("failed"); + } + std::lock_guard lock(completionMutex); + completionMessage = std::string("Operation failed: ") + error.what(); + try + { + const fs::path input = folder.empty() ? fs::path(working_directory) : fs::path(folder); + if (fs::is_directory(input)) + { + const auto output = get_next_result_path(input.string()); + if (save_failed_run_report(params, output, error.what())) + completionMessage += "\nFailure report: " + output.string(); + } + } catch (const std::exception&) + { + completionMessage += "\nCould not save failure report."; + } + } + loLoading = false; + loRunning = false; + }); } bool step1( @@ -1902,7 +2012,9 @@ bool step1( std::vector& worker_data, const std::atomic& loPause) { + params.run_report = std::make_shared(folder, params.points_global_spill_directory, "cli"); std::vector input_file_names; + RunReport::Scope discovery(params.run_report.get(), RunReport::Stage::Loading); for (const auto& entry : fs::directory_iterator(folder)) { @@ -1913,6 +2025,7 @@ bool step1( } } + discovery.finish(); if (load_data(input_file_names, params, pointsPerFile, imu_data, full_debug_messages)) { working_directory = fs::path(input_file_names[0]).parent_path().string(); @@ -1934,17 +2047,6 @@ bool step2(std::vector& worker_data, LidarOdometryParams& params, co return compute_step_2(worker_data, params, ts_failure, loProgress, loPause, full_debug_messages, parked); } -void save_results( - bool info, - double elapsed_seconds, - std::string& working_directory, - std::vector& worker_data, - LidarOdometryParams& params, - fs::path outwd) -{ - save_result(worker_data, params, outwd, elapsed_seconds); -} - //! Window close: while odometry runs, ask first. A confirmed quit pauses the run and keeps the //! window open until display() sees the run parked or finished (quit_abandoned_run()). bool confirm_close() @@ -1955,13 +2057,15 @@ bool confirm_close() return false; pfd::message message( "Lidar odometry is running", - "Quit anyway? The run is abandoned: nothing is saved and the cache is deleted.", + "Close after reaching a safe boundary? Unfinished processing is abandoned; an export already in progress finishes before cache " + "cleanup.", pfd::choice::yes_no, pfd::icon::warning); if (message.result() != pfd::button::yes) return false; loQuitting = true; - loPause.store(true); + if (!loLoading) + loPause.store(true); return false; } @@ -1969,15 +2073,60 @@ bool confirm_close() //! without destructors, after removing the cache the parked (or finished) run no longer reads. static void quit_abandoned_run() { + if (params.run_report && (loParked || params.run_report->live().status == "cancelled")) + { + params.run_report->finishOperation("cancelled"); + try + { + const fs::path input = working_directory.empty() ? fs::path(pendingLoadFolder) : fs::path(working_directory); + if (fs::is_directory(input)) + save_run_status_report(params, get_next_result_path(input.string()), "cancelled", ""); + } catch (const std::exception& error) + { + std::cerr << "Cancellation report: " << error.what() << '\n'; + } + } remove_cache(params); std::_Exit(0); } void display() { + if (pipelinePending) + { + pipelinePending = false; + launchPipeline(pendingFolder, pendingCompute, pendingSave); + } if (loQuitting && (loParked || !loRunning)) quit_abandoned_run(); + if (loLoading) + { + ClearBackground(LIGHTGRAY); + rlImGuiBegin(); + ImGui::Begin("Loading data", nullptr, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::Text("Loading and preparing: %s", pendingLoadFolder.c_str()); + recording_span_gui(); + resources_gui(); + ImGui::End(); + rlImGuiEnd(); + return; // initial_points, m_g and buckets are being initialized; never read them concurrently + } + if (!loRunning) + { + std::string message; + { + std::lock_guard lock(completionMutex); + message.swap(completionMessage); + } + if (!message.empty()) + { + if (pipelineThread.joinable()) + pipelineThread.join(); + pfd::message popup("Run report", message, pfd::choice::ok, pfd::icon::info); + popup.result(); + } + } const bool trajectory_running = loRunning.load(); const auto preview = [] // retain an immutable snapshot for this whole frame { @@ -2179,7 +2328,7 @@ void display() // Drag and drop: a Mandeye data folder, or any file in one, is processed like "Load & process scanning". const auto dropped = takeDroppedFiles(); - if (!dropped.empty() && !loRunning && pendingLoadFrames == 0) + if (!dropped.empty() && !loRunning && !pipelinePending) { fs::path folder(dropped[0]); if (!fs::is_directory(folder)) @@ -2187,28 +2336,7 @@ void display() openData(folder.string()); } - // The previous frame presented the "Loading data" modal, so it stays on screen while loading blocks. - if (pendingLoadFrames == 1) - { - pendingLoadFrames = 0; - loadData(pendingLoadFolder); - } - else if (pendingLoadFrames > 1) - --pendingLoadFrames; - - if (pendingLoadFrames > 0 && !ImGui::IsPopupOpen("Loading data")) - ImGui::OpenPopup("Loading data"); - ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); - if (ImGui::BeginPopupModal("Loading data", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) - { - ImGui::Text("Loading data and running step 1 from folder:\n'%s'", pendingLoadFolder.c_str()); - ImGui::TextDisabled("The window does not respond until this finishes, see console for progress."); - if (pendingLoadFrames == 0) - ImGui::CloseCurrentPopup(); - ImGui::EndPopup(); - } - - if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_O, false) && !loRunning && pendingLoadFrames == 0) + if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_O, false) && !loRunning && !pipelinePending) { openData(); @@ -2606,7 +2734,7 @@ void display() void on_exit() { - remove_cache(params); + remove_cache(params); // Persist final cleanup status without repeating the export notification. } void mouse(int glut_button, int state, int x, int y) @@ -2699,15 +2827,15 @@ int main(int argc, char* argv[]) if (!step1(path.string(), params, pointsPerFile, imu_data, working_directory, trajectory, worker_data, loPause) || !step2(worker_data, params, loPause)) { - std::cerr << "Lidar odometry failed: no results saved" << std::endl; + std::cerr << "Lidar odometry failed: no point-cloud results saved" << std::endl; + save_failed_run_report(params, get_next_result_path(path.string()), "Loading/preparation/odometry failed"); + remove_cache(params); return 1; } end = std::chrono::system_clock::now(); std::chrono::duration elapsed_seconds = end - start; - std::time_t end_time = std::chrono::system_clock::to_time_t(end); - std::cout << "calculations finished computation at " << std::ctime(&end_time) - << "Elapsed time: " << formatTime(elapsed_seconds.count()).c_str() << "s\n"; + std::cout << "Odometry finished; exporting results...\n"; // Only the input folder was given: store the session where the GUI would, // in the next free lio_result_N under the working directory. @@ -2717,9 +2845,12 @@ int main(int argc, char* argv[]) return 1; } const fs::path result_dir = get_next_result_path(working_directory); - save_results(false, elapsed_seconds.count(), working_directory, worker_data, params, result_dir); - std::cout << "Results saved to folder: '" << result_dir.string() << "'" << std::endl; + const bool success = save_result(worker_data, params, result_dir, elapsed_seconds.count()); remove_cache(params); + std::cout << params.run_report->summary(); + if (!success || params.run_report->live().status != "completed") + return 1; + std::cout << "Results and run report saved to: '" << result_dir.string() << "'\n"; } } else if (argc == 4) // runnning from command line with custom params @@ -2739,18 +2870,21 @@ int main(int argc, char* argv[]) if (!step1(argv[1], params, pointsPerFile, imu_data, working_directory, trajectory, worker_data, loPause) || !step2(worker_data, params, loPause)) { - std::cerr << "Lidar odometry failed: no results saved" << std::endl; + std::cerr << "Lidar odometry failed: no point-cloud results saved" << std::endl; + save_failed_run_report(params, argv[3], "Loading/preparation/odometry failed"); + remove_cache(params); return 1; } end = std::chrono::system_clock::now(); std::chrono::duration elapsed_seconds = end - start; - std::time_t end_time = std::chrono::system_clock::to_time_t(end); - std::cout << "calculations finished computation at " << std::ctime(&end_time) - << "Elapsed time: " << formatTime(elapsed_seconds.count()).c_str() << "s\n"; + std::cout << "Odometry finished; exporting results...\n"; - save_results(false, elapsed_seconds.count(), working_directory, worker_data, params, argv[3]); + const bool success = save_result(worker_data, params, argv[3], elapsed_seconds.count()); remove_cache(params); + std::cout << params.run_report->summary(); + if (!success || params.run_report->live().status != "completed") + return 1; } else // full GUI mode { @@ -2765,6 +2899,8 @@ int main(int argc, char* argv[]) #endif mainLoop(confirm_close); + if (pipelineThread.joinable()) + pipelineThread.join(); trajectory_cache.clear(trajectory_renderer); unloadPointVertices(initial_point_cache.parts); @@ -2779,12 +2915,24 @@ int main(int argc, char* argv[]) { std::cerr << "System is out of memory : " << e.what() << std::endl; mandeye::fd::OutOfMemMessage(); + loPause = false; + if (pipelineThread.joinable()) + pipelineThread.join(); + return 1; } catch (const std::exception& e) { std::cout << e.what(); + loPause = false; + if (pipelineThread.joinable()) + pipelineThread.join(); + return 1; } catch (...) { std::cerr << "Unknown fatal error occurred." << std::endl; + loPause = false; + if (pipelineThread.joinable()) + pipelineThread.join(); + return 1; } return 0; diff --git a/apps/lidar_odometry_step_1/lidar_odometry_utils.cpp b/apps/lidar_odometry_step_1/lidar_odometry_utils.cpp index 32c7cd6d6..bb69beea9 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_utils.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry_utils.cpp @@ -395,7 +395,7 @@ bool save_poses(const std::string& file_name, const std::vector } outfile.close(); - return true; + return static_cast(outfile); } std::vector, Eigen::Vector3f, Eigen::Vector3f>> load_imu(const std::string& imu_file, int imuToUse) diff --git a/apps/lidar_odometry_step_1/lidar_odometry_utils.h b/apps/lidar_odometry_step_1/lidar_odometry_utils.h index 9ac1dc0f0..59049a689 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_utils.h +++ b/apps/lidar_odometry_step_1/lidar_odometry_utils.h @@ -48,6 +48,7 @@ inline std::string get_software_version() } struct RawCloudLoader; // raw_cloud_loader.h: raw point clouds loaded per file during step 1 +class RunReport; class PointsGlobalSpill; // points_global_spill.h: step 2's map buffer kept in a file struct LidarOdometryParams @@ -72,6 +73,7 @@ struct LidarOdometryParams // runtime state of the two options above, not parameters (not saved to the parameter file) std::shared_ptr raw_cloud_loader; PointsGlobalSpill* points_global_spill = nullptr; + std::shared_ptr run_report; // runtime accounting, never a processing parameter // Optional GUI observer, called by the producer only at safe trajectory boundaries. std::function&, bool)> publish_trajectory; diff --git a/apps/lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp b/apps/lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp index 1fac18564..edcaf79ee 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp @@ -1,6 +1,7 @@ #include "hdmapping_profiler.hpp" #include "lidar_odometry_utils.h" #include "points_global_spill.h" +#include "run_report.h" #include #include #include @@ -2410,11 +2411,17 @@ bool compute_step_2( bool debugMsg, std::atomic& parked) { + RunReport::Scope timing(params.run_report.get(), RunReport::Stage::Odometry); try { - return compute_step_2_impl(worker_data, params, ts_failure, loProgress, pause, debugMsg, parked); + const bool success = compute_step_2_impl(worker_data, params, ts_failure, loProgress, pause, debugMsg, parked); + if (!success && params.run_report) + params.run_report->fail("Odometry failed"); + return success; } catch (const std::runtime_error& e) // a points_global spill I/O failure; its files are already removed { + if (params.run_report) + params.run_report->fail(e.what()); spdlog::error("{}", e.what()); return false; } @@ -2463,6 +2470,8 @@ static bool compute_step_2_impl( { if (params.publish_trajectory) params.publish_trajectory(worker_data, true); + if (params.run_report) + params.run_report->pause(true); parked.store(true); while (pause) { @@ -2470,6 +2479,8 @@ static bool compute_step_2_impl( std::this_thread::sleep_for(std::chrono::seconds(1)); } parked.store(false); + if (params.run_report) + params.run_report->pause(false); } spdlog::stopwatch stopwatch_worker_process_worker_step_1; diff --git a/apps/lidar_odometry_step_1/points_global_spill.cpp b/apps/lidar_odometry_step_1/points_global_spill.cpp index d38fd9ca6..d115a87f0 100644 --- a/apps/lidar_odometry_step_1/points_global_spill.cpp +++ b/apps/lidar_odometry_step_1/points_global_spill.cpp @@ -1,4 +1,5 @@ #include "points_global_spill.h" +#include "run_report.h" #include #include @@ -23,6 +24,8 @@ PointsGlobalSpill::PointsGlobalSpill(LidarOdometryParams& params) PointsGlobalSpill::~PointsGlobalSpill() { + if (params_.run_report) + params_.run_report->spillSize(n_ * sizeof(Point3Di)); if (params_.points_global_spill == this) params_.points_global_spill = nullptr; if (in_) @@ -31,9 +34,19 @@ PointsGlobalSpill::~PointsGlobalSpill() std::fclose(f_); std::error_code ec; if (!pending_remove_.empty()) // a reset that did not finish: the previous generation's file too + { std::filesystem::remove(pending_remove_, ec); + if (ec && params_.run_report) + params_.run_report->fail("Spill cleanup failed: " + pending_remove_.string() + ": " + ec.message()); + } if (!dir_.empty()) std::filesystem::remove(path(), ec); + if (params_.run_report) + { + if (ec) + params_.run_report->fail("Spill cleanup failed: " + ec.message()); + params_.run_report->spillSize(n_ * sizeof(Point3Di), !ec); + } } void PointsGlobalSpill::append(const Point3Di& p) @@ -45,6 +58,8 @@ void PointsGlobalSpill::append(const Point3Di& p) void PointsGlobalSpill::finish() { + if (params_.run_report) + params_.run_report->spillSize(n_ * sizeof(Point3Di)); if (f_ && std::fclose(f_) != 0) { f_ = nullptr; @@ -75,4 +90,4 @@ void PointsGlobalSpill::seek64(std::FILE* f, std::uint64_t offset) std::filesystem::path PointsGlobalSpill::path() const { return dir_ / ("points_global_" + tag_ + "_" + std::to_string(gen_) + ".bin"); -} \ No newline at end of file +} diff --git a/apps/lidar_odometry_step_1/points_global_spill.h b/apps/lidar_odometry_step_1/points_global_spill.h index 0f48458e1..c41f98a92 100644 --- a/apps/lidar_odometry_step_1/points_global_spill.h +++ b/apps/lidar_odometry_step_1/points_global_spill.h @@ -1,6 +1,7 @@ #pragma once #include "lidar_odometry_utils.h" +#include "run_report.h" #include @@ -77,13 +78,21 @@ void PointsGlobalSpill::reset(Update update) fail("reset read/write failed on '" + old_path.string() + "'"); update(chunk, ray_cast); done += m; + if (params_.run_report) + params_.run_report->spillSize((n_ + done) * sizeof(Point3Di)); } std::fclose(in_); in_ = nullptr; std::error_code ec; std::filesystem::remove(old_path, ec); if (ec) + { spdlog::warn("points_global spill: could not remove '{}': {}", old_path.string(), ec.message()); + if (params_.run_report) + params_.run_report->fail("Spill cleanup failed: " + old_path.string() + ": " + ec.message()); + } pending_remove_.clear(); n_ = keep; -} \ No newline at end of file + if (params_.run_report) + params_.run_report->spillSize(n_ * sizeof(Point3Di)); +} diff --git a/apps/lidar_odometry_step_1/run_report.cpp b/apps/lidar_odometry_step_1/run_report.cpp new file mode 100644 index 000000000..da2fb07f3 --- /dev/null +++ b/apps/lidar_odometry_step_1/run_report.cpp @@ -0,0 +1,765 @@ +#include "run_report.h" + +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#include +#include +#elif defined(__linux__) +#include +#elif defined(__APPLE__) +#include +#endif + +namespace +{ + std::string utcNow() + { + const auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + std::tm tm{}; +#ifdef _WIN32 + gmtime_s(&tm, &t); +#else + gmtime_r(&t, &tm); +#endif + std::ostringstream out; + out << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ"); + return out.str(); + } + + using Values = std::map>; + const std::array memoryNames = { "process_resident_bytes", "process_private_commit_bytes", "system_available_ram_bytes", + "system_commit_bytes", "system_commit_limit_bytes", "gpu_dedicated_bytes", + "gpu_shared_bytes" }; + + // PDH wildcard counters are collected in the sampling thread only, not per frame or per point. + // Keep adapter identities in the metric names; summing shared allocations across adapters could double count them. + class MemorySampler + { + std::mutex queryMutex_; +#ifdef _WIN32 + PDH_HQUERY query_ = nullptr; + PDH_HCOUNTER dedicated_ = nullptr, shared_ = nullptr; + bool initialized_ = false; + void gpuCounter(PDH_HCOUNTER counter, const std::string& name, Values& values) + { + DWORD bytes = 0, count = 0; + if (!counter || PdhGetFormattedCounterArrayW(counter, PDH_FMT_LARGE, &bytes, &count, nullptr) != PDH_MORE_DATA) + return; + std::vector buffer(bytes); + auto* items = reinterpret_cast(buffer.data()); + if (PdhGetFormattedCounterArrayW(counter, PDH_FMT_LARGE, &bytes, &count, items) != ERROR_SUCCESS) + return; + double total = 0; + bool valid = false; + for (DWORD i = 0; i < count; ++i) + { + const auto& value = items[i].FmtValue; + if (value.CStatus != PDH_CSTATUS_VALID_DATA && value.CStatus != PDH_CSTATUS_NEW_DATA) + continue; + std::wstring instance(items[i].szName); + const auto luid = instance.find(L"luid_"); + std::string adapter = "unknown"; + if (luid != std::wstring::npos) + { + adapter.clear(); + for (size_t j = luid; j < instance.size(); ++j) + adapter += static_cast(instance[j]); // PDH LUID/physical-index suffix is ASCII + } + values[name + "/" + adapter] = static_cast(value.largeValue); + total += static_cast(value.largeValue); + valid = true; + } + // Totals are convenient for a single GPU; adapter detail remains available in the report. + if (valid) + values[name] = total; + } +#endif + public: + ~MemorySampler() + { +#ifdef _WIN32 + if (query_) + PdhCloseQuery(query_); +#endif + } + Values read() + { + std::lock_guard lock(queryMutex_); + Values values; + for (const auto* name : memoryNames) + values[name] = std::nullopt; +#ifdef _WIN32 + PROCESS_MEMORY_COUNTERS_EX process{}; + process.cb = sizeof(process); + if (GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&process), sizeof(process))) + { + values["process_resident_bytes"] = static_cast(process.WorkingSetSize); + values["process_private_commit_bytes"] = static_cast(process.PrivateUsage); + } + MEMORYSTATUSEX memory{}; + memory.dwLength = sizeof(memory); + if (GlobalMemoryStatusEx(&memory)) + values["system_available_ram_bytes"] = static_cast(memory.ullAvailPhys); + PERFORMANCE_INFORMATION performance{}; + performance.cb = sizeof(performance); + if (GetPerformanceInfo(&performance, sizeof(performance))) + { + values["system_commit_bytes"] = static_cast(performance.CommitTotal) * performance.PageSize; + values["system_commit_limit_bytes"] = static_cast(performance.CommitLimit) * performance.PageSize; + } + if (!initialized_) + { + initialized_ = true; + if (PdhOpenQueryW(nullptr, 0, &query_) == ERROR_SUCCESS) + { + const std::wstring prefix = L"\\GPU Process Memory(pid_" + std::to_wstring(GetCurrentProcessId()) + L"_*)\\"; + PdhAddEnglishCounterW(query_, (prefix + L"Dedicated Usage").c_str(), 0, &dedicated_); + PdhAddEnglishCounterW(query_, (prefix + L"Shared Usage").c_str(), 0, &shared_); + } + } + if (query_ && PdhCollectQueryData(query_) == ERROR_SUCCESS) + { + gpuCounter(dedicated_, "gpu_dedicated_bytes", values); + gpuCounter(shared_, "gpu_shared_bytes", values); + } +#elif defined(__linux__) + std::ifstream stat("/proc/self/statm"); + std::uint64_t size = 0, resident = 0; + if (stat >> size >> resident) + values["process_resident_bytes"] = static_cast(resident) * sysconf(_SC_PAGESIZE); + std::ifstream info("/proc/meminfo"); + std::string key, rest; + std::uint64_t kb; + while (info >> key >> kb) + { + std::getline(info, rest); + if (key == "MemAvailable:") + values["system_available_ram_bytes"] = static_cast(kb) * 1024; + } +#elif defined(__APPLE__) + mach_task_basic_info_data_t info{}; + mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT; + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, reinterpret_cast(&info), &count) == KERN_SUCCESS) + values["process_resident_bytes"] = static_cast(info.resident_size); +#endif + return values; + } + }; + + std::shared_ptr memorySampler() + { + // Process-wide PDH handles: a second run must not repeatedly initialize the GPU performance provider. + // Each sampler thread retains ownership, so shutdown cannot destroy a backend still in use. + static auto sampler = std::make_shared(); + return sampler; + } + + std::optional threadCpuSeconds() + { +#ifdef _WIN32 + FILETIME created{}, exited{}, kernel{}, user{}; + if (GetThreadTimes(GetCurrentThread(), &created, &exited, &kernel, &user)) + { + ULARGE_INTEGER k{}, u{}; + k.LowPart = kernel.dwLowDateTime; + k.HighPart = kernel.dwHighDateTime; + u.LowPart = user.dwLowDateTime; + u.HighPart = user.dwHighDateTime; + return static_cast(k.QuadPart + u.QuadPart) / 1e7; + } +#elif defined(__linux__) + timespec time{}; + if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &time) == 0) + return time.tv_sec + time.tv_nsec / 1e9; +#endif + return std::nullopt; + } + + std::string volumePath(std::filesystem::path path) + { + if (path.empty()) + return {}; + std::error_code error; + while (!path.empty() && !std::filesystem::exists(path, error)) + { + const auto parent = path.parent_path(); + if (parent == path) + return {}; + path = parent; + } +#ifdef _WIN32 + wchar_t root[MAX_PATH + 1]{}; + if (GetVolumePathNameW(std::filesystem::absolute(path, error).c_str(), root, MAX_PATH)) + return std::filesystem::path(root).string(); + return {}; +#else + // Keep a valid path to the filesystem; space() queries the containing mount, not its directory contents. + return std::filesystem::absolute(path, error).string(); +#endif + } + +#ifdef _WIN32 + BOOL CALLBACK pagefileVolume(LPVOID context, PENUM_PAGE_FILE_INFORMATION, LPCWSTR name) + { + auto* report = static_cast(context); + std::wstring path(name); + if (path.rfind(L"\\??\\", 0) == 0) + path.erase(0, 4); + report->addVolume(std::filesystem::path(path).parent_path(), "pagefile"); + return TRUE; + } +#endif +} // namespace + +void RunReport::Metric::observe(std::optional value) +{ + current = value; + if (!value) + return; + if (!first) + first = value; + minimum = minimum ? std::min(*minimum, *value) : value; + maximum = maximum ? std::max(*maximum, *value) : value; + ++samples; +} + +void RunReport::Metric::integrate(double seconds) +{ + if (current) + { + integral += *current * seconds; + covered += seconds; + } +} + +nlohmann::json RunReport::Metric::json() const +{ + auto nullable = [](std::optional value) + { + return value ? nlohmann::json(*value) : nlohmann::json(nullptr); + }; + return { { "first_bytes", nullable(first) }, + { "last_bytes", nullable(current) }, + { "min_bytes", nullable(minimum) }, + { "max_sampled_bytes", nullable(maximum) }, + { "time_weighted_mean_bytes", covered > 0 ? nlohmann::json(integral / covered) : nlohmann::json(nullptr) }, + { "coverage_seconds", covered }, + { "sample_count", samples }, + { "availability", samples ? "observed" : "unsupported_or_query_failed" } }; +} + +const char* RunReport::stageName(Stage stage) +{ + static const char* names[] = { + "loading", "initialization", "cache_preparation", "odometry", "export", "cleanup", "consistency", "idle" + }; + return names[static_cast(stage)]; +} + +const char* RunReport::stageLabel(Stage stage) +{ + static const char* labels[] = { "Loading data", "Initial trajectory", "Preparing data and cache", "Odometry", + "Writing results", "Removing cache", "Trajectory consistency", "Ready" }; + return labels[static_cast(stage)]; +} + +RunReport::Scope::Scope(RunReport* report, Stage stage) + : report(report) + , exceptions(std::uncaught_exceptions()) +{ + if (report) + report->begin(stage); +} +RunReport::Scope::~Scope() +{ + if (report && std::uncaught_exceptions() > exceptions) + report->fail("Exception during measured stage"); + finish(); +} +void RunReport::Scope::finish() +{ + if (report) + report->end(); + report = nullptr; +} + +RunReport::RunReport(const std::filesystem::path& input, const std::filesystem::path& spill, const std::string& mode) + : mode_(mode) +{ + started_ = updated_ = operationStarted_ = utcNow(); + id_ = started_ + "-" + std::to_string(Clock::now().time_since_epoch().count()); + addVolume(input, "input/cache"); + addVolume(spill, "spill"); +#ifdef _WIN32 + EnumPageFilesW(pagefileVolume, this); +#endif + setupCost_ = std::chrono::duration(Clock::now() - last_).count(); + sampler_ = std::thread(&RunReport::sampleLoop, this); +} +RunReport::~RunReport() +{ + { + std::lock_guard lock(mutex_); + stopping_ = true; + } + wake_.notify_all(); + if (sampler_.joinable()) + sampler_.join(); +} + +void RunReport::account(Clock::time_point now) +{ + const double seconds = std::chrono::duration(now - last_).count(); + last_ = now; + if (!active_) + return; + total_ += seconds; + if (paused_) + pausedSeconds_ += seconds; + for (auto& [name, metric] : memory_) + metric.integrate(seconds); + for (auto& volume : volumes_) + volume.free.integrate(seconds); + if (stage_ != Stage::Count) + { + auto& stage = stages_[static_cast(stage_)]; + stage.seconds += seconds; + if (paused_) + stage.paused += seconds; + for (auto& [name, metric] : stage.memory) + metric.integrate(seconds); + for (auto& [path, metric] : stage.disk) + metric.integrate(seconds); + } +} + +void RunReport::begin(Stage stage) +{ + std::lock_guard lock(mutex_); + account(Clock::now()); + if (!active_) + { + operationStarted_ = utcNow(); + operationStartTotal_ = total_; + operationStartPaused_ = pausedSeconds_; + // Never extrapolate the last reading across an unmeasured interactive interval. + for (auto& [name, metric] : memory_) + metric.current.reset(); + for (auto& volume : volumes_) + volume.free.current.reset(); + } + active_ = true; + status_ = "running"; + stage_ = stage; + auto& data = stages_[static_cast(stage)]; + ++data.calls; + for (auto& [name, metric] : memory_) + data.memory[name].observe(metric.current); + for (const auto& volume : volumes_) + data.disk[volume.path].observe(volume.free.current); + sampleRequested_ = true; + wake_.notify_one(); +} +void RunReport::end() +{ + std::lock_guard lock(mutex_); + account(Clock::now()); + stage_ = Stage::Count; + sampleRequested_ = true; + wake_.notify_one(); +} +void RunReport::pause(bool paused) +{ + std::lock_guard lock(mutex_); + account(Clock::now()); + paused_ = paused; +} +void RunReport::finishOperation(const std::string& status) +{ + std::lock_guard lock(mutex_); + account(Clock::now()); + if (status == "failed" || status == "cancelled") + outcome_ = status; + else if (outcome_ != "failed" && outcome_ != "cancelled") + outcome_ = errors_.empty() ? status : "partial_failure"; + if (active_) + operations_.push_back( + { { "started_utc", operationStarted_ }, + { "finished_utc", utcNow() }, + { "wall_seconds", total_ - operationStartTotal_ }, + { "paused_seconds", pausedSeconds_ - operationStartPaused_ }, + { "status", outcome_ } }); + active_ = false; + stage_ = Stage::Count; + paused_ = false; + status_ = outcome_; + updated_ = utcNow(); + wake_.notify_one(); +} +void RunReport::fail(const std::string& error) +{ + std::lock_guard lock(mutex_); + errors_.push_back(error); + status_ = "partial_failure"; +} + +void RunReport::addVolume(const std::filesystem::path& path, const std::string& role) +{ + const auto root = volumePath(path); + if (root.empty()) + return; + std::lock_guard lock(mutex_); + auto it = std::find_if( + volumes_.begin(), + volumes_.end(), + [&](const Volume& v) + { + return v.path == root; + }); + if (it == volumes_.end()) + { + volumes_.push_back({ root, { role }, {} }); + } + else if (std::find(it->roles.begin(), it->roles.end(), role) == it->roles.end()) + it->roles.push_back(role); +} + +bool RunReport::cacheFile( + const std::filesystem::path& path, double writeSeconds, const std::string& kind, std::optional expectedBytes) +{ + const auto start = Clock::now(); + std::error_code error; + const auto bytes = std::filesystem::file_size(path, error); // once per completed file; no directory traversal + std::lock_guard lock(mutex_); + cacheWriteSeconds_ += writeSeconds; + cacheWriteByKind_[kind] += writeSeconds; + if (error || (expectedBytes && bytes != *expectedBytes)) + { + errors_.push_back("Missing or incomplete cache file: " + path.string()); + cacheAccountingCost_ += std::chrono::duration(Clock::now() - start).count(); + return false; + } + auto& entry = cacheFiles_[path.string()]; + cacheBytes_ -= entry.first; + entry = { bytes, kind }; + cacheBytes_ += bytes; + cachePeak_ = std::max(cachePeak_, cacheBytes_); + cachePeakFiles_ = std::max(cachePeakFiles_, static_cast(cacheFiles_.size())); + cacheStatus_ = "retained"; + cacheAccountingCost_ += std::chrono::duration(Clock::now() - start).count(); + return true; +} +void RunReport::cachePrepared() +{ + std::lock_guard lock(mutex_); + preparedBytes_ = cacheBytes_; + preparedFiles_ = cacheFiles_.size(); +} +void RunReport::cacheRemoved(bool success, const std::string& error) +{ + std::lock_guard lock(mutex_); + cacheStatus_ = success ? "removed" : "cleanup_failed"; + if (success) + { + cacheBytes_ = 0; + cacheFiles_.clear(); + } + else + errors_.push_back("Cache cleanup: " + error); +} +void RunReport::spillSize(std::uint64_t bytes, bool removed) +{ + std::lock_guard lock(mutex_); + spillBytes_ = removed ? 0 : bytes; + spillPeak_ = std::max(spillPeak_, bytes); +} + +void RunReport::sampleLoop() +{ + const auto sampler = memorySampler(); + const auto cpuStart = threadCpuSeconds(); + auto nextDisk = Clock::time_point{}; + std::unique_lock lock(mutex_); + while (!stopping_) + { + if (!active_) + { + wake_.wait( + lock, + [&] + { + return stopping_ || active_; + }); + continue; + } + sampleRequested_ = false; + std::vector paths; + const bool disk = Clock::now() >= nextDisk; + if (disk) + for (const auto& volume : volumes_) + paths.push_back(volume.path); + lock.unlock(); + const auto start = Clock::now(); + Values values; + try + { + values = sampler->read(); + } catch (const std::exception&) + { + } // telemetry must not terminate a processing run + std::map> free; + for (const auto& path : paths) + { + std::error_code error; + auto space = std::filesystem::space(path, error); + free[path] = error ? std::nullopt : std::optional(static_cast(space.available)); + } + const auto now = Clock::now(); + const double cost = std::chrono::duration(now - start).count(); + const auto cpuNow = threadCpuSeconds(); + lock.lock(); + account(Clock::now()); // another stage transition may have accounted time while the OS query was in flight + if (!active_) + continue; // final snapshots remain immutable until the next explicit operation + sampleCost_ += cost; + if (!sampleCount_) + firstSampleCost_ = cost; + if (cpuStart && cpuNow) + samplerCpuSeconds_ = *cpuNow - *cpuStart; + maxSampleCost_ = std::max(maxSampleCost_, cost); + ++sampleCount_; + for (auto& [name, metric] : memory_) + if (!values.count(name)) + metric.observe(std::nullopt); + for (const auto& [name, value] : values) + { + memory_[name].observe(value); + if (active_ && stage_ != Stage::Count) + stages_[static_cast(stage_)].memory[name].observe(value); + } + for (auto& volume : volumes_) + if (free.count(volume.path)) + { + volume.free.observe(free[volume.path]); + if (stage_ != Stage::Count) + stages_[static_cast(stage_)].disk[volume.path].observe(free[volume.path]); + } + if (disk) + nextDisk = now + std::chrono::seconds(5); + // Bound even stage-boundary bursts; OS calls never run under the report mutex. + wake_.wait_until( + lock, + now + std::chrono::milliseconds(100), + [&] + { + return stopping_; + }); + wake_.wait_until( + lock, + now + std::chrono::seconds(1), + [&] + { + return stopping_ || !active_ || sampleRequested_; + }); + } +} + +double RunReport::stageSeconds(Stage stage, bool excludePauses) const +{ + std::lock_guard lock(mutex_); + const auto& data = stages_[static_cast(stage)]; + const double pending = active_ && stage_ == stage ? std::chrono::duration(Clock::now() - last_).count() : 0; + return data.seconds - (excludePauses ? data.paused : 0) + (excludePauses && paused_ ? 0 : pending); +} +void RunReport::setRecordingSpan(double firstTimestamp, double lastTimestamp) +{ + std::lock_guard lock(mutex_); + recordingFirst_.reset(); + recordingLast_.reset(); + if (std::isfinite(firstTimestamp) && std::isfinite(lastTimestamp) && lastTimestamp >= firstTimestamp && + std::isfinite(lastTimestamp - firstTimestamp)) + { + recordingFirst_ = firstTimestamp; + recordingLast_ = lastTimestamp; + } +} + +std::optional RunReport::recordingSeconds() const +{ + std::lock_guard lock(mutex_); + return recordingFirst_ && recordingLast_ ? std::optional(*recordingLast_ - *recordingFirst_) : std::nullopt; +} + +RunReport::Live RunReport::live() const +{ + std::lock_guard lock(mutex_); + const double pending = active_ ? std::chrono::duration(Clock::now() - last_).count() : 0; + return { stageName(stage_), stageLabel(stage_), status_, total_ + pending, pausedSeconds_ + (paused_ ? pending : 0), + memory_, volumes_, cacheBytes_, cachePeak_ }; +} + +nlohmann::json RunReport::jsonLocked() const +{ + nlohmann::json stages = nlohmann::json::object(), resources = nlohmann::json::object(); + double stageTotal = 0; + for (size_t i = 0; i < count; ++i) + { + const auto& data = stages_[i]; + stageTotal += data.seconds; + auto& stage = stages[stageName(static_cast(i))]; + stage = { { "wall_seconds", data.seconds }, + { "paused_seconds", data.paused }, + { "excluding_pauses_seconds", data.seconds - data.paused }, + { "invocations", data.calls } }; + for (const auto& [name, metric] : data.memory) + stage["memory"][name] = metric.json(); + for (const auto& [path, metric] : data.disk) + stage["available_disk_space"][path] = metric.json(); + } + for (const auto& [name, metric] : memory_) + resources[name] = metric.json(); + nlohmann::json volumes = nlohmann::json::array(); + for (const auto& volume : volumes_) + volumes.push_back({ { "path", volume.path }, { "roles", volume.roles }, { "available_space", volume.free.json() } }); + return { + { "schema_version", 1 }, + { "run_id", id_ }, + { "started_utc", started_ }, + { "updated_utc", updated_ }, + { "status", status_ }, + { "mode", mode_ }, + { "errors", errors_ }, + { "operations", operations_ }, + { "input_recording", + { { "source", "loaded_raw_imu_timestamps" }, + { "start_timestamp_seconds", recordingFirst_ ? nlohmann::json(*recordingFirst_) : nlohmann::json(nullptr) }, + { "end_timestamp_seconds", recordingLast_ ? nlohmann::json(*recordingLast_) : nlohmann::json(nullptr) }, + { "span_seconds", + recordingFirst_ && recordingLast_ ? nlohmann::json(*recordingLast_ - *recordingFirst_) : nlohmann::json(nullptr) }, + { "includes_gaps", true } } }, + { "timing", + { { "total_operation_wall_seconds", total_ }, + { "paused_seconds", pausedSeconds_ }, + { "excluding_pauses_seconds", total_ - pausedSeconds_ }, + { "between_stages_seconds", std::max(0.0, total_ - stageTotal) }, + { "scope", + "Cumulative operation intervals; includes pauses, excludes interactive idle between operations and final report " + "serialization" }, + { "stages", stages }, + { "cache_write_seconds_nested", cacheWriteSeconds_ }, + { "cache_write_seconds_by_kind_nested", cacheWriteByKind_ } } }, + { "memory", resources }, + { "volumes", volumes }, + { "disk_cache", + { { "status", cacheStatus_ }, + { "scope", "Completed cache-file writes tracked for this run; unmodified pre-existing files are excluded" }, + { "prepared_bytes", preparedBytes_ }, + { "prepared_file_count", preparedFiles_ }, + { "current_bytes", cacheStatus_ == "cleanup_failed" ? nlohmann::json(nullptr) : nlohmann::json(cacheBytes_) }, + { "peak_bytes", cachePeak_ }, + { "current_file_count", cacheStatus_ == "cleanup_failed" ? nlohmann::json(nullptr) : nlohmann::json(cacheFiles_.size()) }, + { "peak_file_count", cachePeakFiles_ }, + { "spill_current_bytes", spillBytes_ }, + { "spill_scope", + "Current stream; peak includes observed generation overlap. Cleanup failures may leave other files; see errors" }, + { "spill_peak_bytes", spillPeak_ } } }, + { "sampling", + { { "interval_seconds", 1 }, + { "disk_interval_seconds", 5 }, + { "sample_count", sampleCount_ }, + { "query_wall_seconds", sampleCost_ }, + { "max_query_wall_seconds", maxSampleCost_ }, + { "first_query_wall_seconds", firstSampleCost_ }, + { "subsequent_query_wall_seconds", sampleCost_ - firstSampleCost_ }, + { "sampler_thread_cpu_seconds", samplerCpuSeconds_ ? nlohmann::json(*samplerCpuSeconds_) : nlohmann::json(nullptr) }, + { "setup_wall_seconds", setupCost_ }, + { "cache_accounting_wall_seconds", cacheAccountingCost_ }, + { "query_wall_fraction", total_ > 0 ? sampleCost_ / total_ : 0 }, + { "average_method", "Time-weighted last observation, over valid coverage including pauses" }, + { "stage_boundaries", "Carry the most recent available sample within an operation; refresh asynchronously" }, + { "peak_method", "Sampled within this run; short spikes may be missed" }, + { "source", "Native OS process/system memory APIs; Windows GPU Process Memory PDH counters (driver/OS limitations apply)" }, + { "commit_definition", "Private committed memory, not physical pagefile occupancy" } } } + }; +} +nlohmann::json RunReport::json() const +{ + std::lock_guard lock(mutex_); + return jsonLocked(); +} +std::string RunReport::summary() const +{ + const auto report = json(); + std::ostringstream out; + out << std::fixed << std::setprecision(2) << "\nTotal operations: " << report["timing"]["total_operation_wall_seconds"].get() + << " s (paused: " << report["timing"]["paused_seconds"].get() << " s)\n"; + for (size_t i = 0; i < count; ++i) + { + const char* name = stageName(static_cast(i)); + const auto& stage = report["timing"]["stages"][name]; + if (stage["invocations"].get()) + out << stageLabel(static_cast(i)) << ": " << stage["wall_seconds"].get() << " s\n"; + } + out << "Cache writes (included above): " << report["timing"]["cache_write_seconds_nested"].get() << " s\n"; + for (const auto& [name, label] : + std::array, 4>{ { { "process_resident_bytes", "Application resident RAM" }, + { "process_private_commit_bytes", "Application private commit" }, + { "gpu_dedicated_bytes", "GPU dedicated (adapter sum)" }, + { "gpu_shared_bytes", "GPU shared (adapter sum)" } } }) + { + out << label << " peak sampled: "; + if (report["memory"].contains(name) && !report["memory"][name]["max_sampled_bytes"].is_null()) + out << report["memory"][name]["max_sampled_bytes"].get() / (1024 * 1024) << " MiB\n"; + else + out << "N/A\n"; + } + out << "Cache: " << report["disk_cache"]["status"].get() << "; peak " + << static_cast(report["disk_cache"]["peak_bytes"].get()) / (1024 * 1024) << " MiB\n" + << "Status: " << report["status"].get() << "\n"; + return out.str(); +} + +bool RunReport::persist(const std::filesystem::path& path, nlohmann::json metadata) +{ + metadata["run_analysis"] = json(); + const auto temporary = std::filesystem::path(path.string() + ".tmp"); + { + std::ofstream out(temporary, std::ios::binary | std::ios::trunc); + out << metadata.dump(4) << '\n'; + out.close(); + if (!out) + return false; + } +#ifdef _WIN32 + return MoveFileExW(temporary.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING) != 0; +#else + std::error_code error; + std::filesystem::rename(temporary, path, error); + return !error; +#endif +} +bool RunReport::write(const std::filesystem::path& path, nlohmann::json metadata) +{ + std::lock_guard lock(filesMutex_); + reports_[path] = metadata; + return persist(path, std::move(metadata)); +} +bool RunReport::updateReports() +{ + std::lock_guard lock(filesMutex_); + bool success = true; + for (const auto& [path, metadata] : reports_) + success = persist(path, metadata) && success; + return success; +} diff --git a/apps/lidar_odometry_step_1/run_report.h b/apps/lidar_odometry_step_1/run_report.h new file mode 100644 index 000000000..763a2aad4 --- /dev/null +++ b/apps/lidar_odometry_step_1/run_report.h @@ -0,0 +1,135 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Wall-clock accounting only: stage durations include I/O and rendering contention, not summed CPU time. +// One pipeline producer changes stages; the sampler never reads pipeline data or scans cache directories. +class RunReport +{ +public: + using Clock = std::chrono::steady_clock; + enum class Stage + { + Loading, + Initialization, + Cache, + Odometry, + Export, + Cleanup, + Consistency, + Count + }; + static const char* stageName(Stage stage); + static const char* stageLabel(Stage stage); + struct Metric + { + std::optional current, minimum, maximum, first; + double integral = 0, covered = 0; + std::uint64_t samples = 0; + void observe(std::optional value); + void integrate(double seconds); + nlohmann::json json() const; + }; + struct Volume + { + std::string path; + std::vector roles; + Metric free; + }; + struct Live + { + std::string stage, label, status; + double total = 0, paused = 0; + std::map memory; + std::vector volumes; + std::uint64_t cacheBytes = 0, cachePeak = 0; + }; + struct Scope + { + RunReport* report; + int exceptions; + explicit Scope(RunReport* report, Stage stage); + ~Scope(); + Scope(const Scope&) = delete; + Scope& operator=(const Scope&) = delete; + void finish(); + }; + + explicit RunReport(const std::filesystem::path& input, const std::filesystem::path& spill = {}, const std::string& mode = "library"); + ~RunReport(); + RunReport(const RunReport&) = delete; + RunReport& operator=(const RunReport&) = delete; + void begin(Stage stage); + void end(); + void pause(bool paused); + void finishOperation(const std::string& status = "completed"); + void fail(const std::string& error); + bool cacheFile( + const std::filesystem::path& path, double writeSeconds, const std::string& kind, std::optional expectedBytes = {}); + void cachePrepared(); + void cacheRemoved(bool success, const std::string& error); + void spillSize(std::uint64_t bytes, bool removed = false); + void addVolume(const std::filesystem::path& path, const std::string& role); + double stageSeconds(Stage stage, bool excludePauses = false) const; + void setRecordingSpan(double firstTimestamp, double lastTimestamp); + std::optional recordingSeconds() const; + Live live() const; + nlohmann::json json() const; + std::string summary() const; + // The final report's serialization/replace is explicitly outside measured operation totals. + bool write(const std::filesystem::path& path, nlohmann::json metadata); + bool updateReports(); + +private: + static constexpr size_t count = static_cast(Stage::Count); + struct StageData + { + double seconds = 0, paused = 0; + std::uint64_t calls = 0; + std::map memory; + std::map disk; + }; + void account(Clock::time_point now); + void sampleLoop(); + nlohmann::json jsonLocked() const; + bool persist(const std::filesystem::path& path, nlohmann::json metadata); + mutable std::mutex mutex_; + std::mutex filesMutex_; + std::condition_variable wake_; + std::thread sampler_; + bool stopping_ = false, active_ = true, paused_ = false, sampleRequested_ = true; + Stage stage_ = Stage::Count; + Clock::time_point last_ = Clock::now(); + double total_ = 0, pausedSeconds_ = 0, sampleCost_ = 0, maxSampleCost_ = 0, setupCost_ = 0, cacheAccountingCost_ = 0; + double firstSampleCost_ = 0; + std::optional samplerCpuSeconds_; + double operationStartTotal_ = 0, operationStartPaused_ = 0; + std::uint64_t sampleCount_ = 0; + std::string id_, started_, updated_, status_ = "running", cacheStatus_ = "not_created"; + std::string operationStarted_, outcome_ = "completed"; + std::string mode_; + std::optional recordingFirst_, recordingLast_; + nlohmann::json operations_ = nlohmann::json::array(); + std::vector errors_; + std::array stages_; + std::map memory_; + std::vector volumes_; + std::map> cacheFiles_; + std::uint64_t cacheBytes_ = 0, cachePeak_ = 0, cachePeakFiles_ = 0, preparedBytes_ = 0, preparedFiles_ = 0; + std::uint64_t spillBytes_ = 0, spillPeak_ = 0; + double cacheWriteSeconds_ = 0; + std::map cacheWriteByKind_; + std::map reports_; +}; diff --git a/apps/lidar_odometry_step_1/toml_io.cpp b/apps/lidar_odometry_step_1/toml_io.cpp index cff1a502e..cab3fa52b 100644 --- a/apps/lidar_odometry_step_1/toml_io.cpp +++ b/apps/lidar_odometry_step_1/toml_io.cpp @@ -99,7 +99,8 @@ bool TomlIO::SaveParametersToTomlFile(const std::string& filepath, const LidarOd tbl.erase("version_info"); out << tbl; - return true; + out.close(); + return static_cast(out); } template diff --git a/apps/lidar_odometry_step_1_legacy/CMakeLists.txt b/apps/lidar_odometry_step_1_legacy/CMakeLists.txt index 7d2210d4c..373979a8e 100644 --- a/apps/lidar_odometry_step_1_legacy/CMakeLists.txt +++ b/apps/lidar_odometry_step_1_legacy/CMakeLists.txt @@ -55,6 +55,7 @@ target_include_directories( target_link_libraries( lidar_odometry_step_1_legacy PRIVATE + step1_run_report vqf Fusion unordered_dense::unordered_dense diff --git a/apps/livox_mid_360_intrinsic_calibration/CMakeLists.txt b/apps/livox_mid_360_intrinsic_calibration/CMakeLists.txt index e2f719b4e..456fc1018 100644 --- a/apps/livox_mid_360_intrinsic_calibration/CMakeLists.txt +++ b/apps/livox_mid_360_intrinsic_calibration/CMakeLists.txt @@ -31,7 +31,7 @@ target_include_directories( target_link_libraries( livox_mid_360_intrinsic_calibration - PRIVATE vqf + PRIVATE step1_run_report vqf unordered_dense::unordered_dense spdlog::spdlog UTL::include diff --git a/apps/mandeye_mission_recorder_calibration/CMakeLists.txt b/apps/mandeye_mission_recorder_calibration/CMakeLists.txt index d308cd1e2..9463505df 100644 --- a/apps/mandeye_mission_recorder_calibration/CMakeLists.txt +++ b/apps/mandeye_mission_recorder_calibration/CMakeLists.txt @@ -41,7 +41,7 @@ target_include_directories( target_link_libraries( mandeye_mission_recorder_calibration - PRIVATE vqf + PRIVATE step1_run_report vqf unordered_dense::unordered_dense spdlog::spdlog UTL::include diff --git a/apps/mandeye_raw_data_viewer/CMakeLists.txt b/apps/mandeye_raw_data_viewer/CMakeLists.txt index 4363923db..f87435a42 100644 --- a/apps/mandeye_raw_data_viewer/CMakeLists.txt +++ b/apps/mandeye_raw_data_viewer/CMakeLists.txt @@ -43,6 +43,7 @@ target_include_directories( target_link_libraries( mandeye_raw_data_viewer PRIVATE + step1_run_report # core_raylib_utils brings in core_raylib (core, raylib), raylib_widgets and rlImGui. core_raylib_utils imgui_raylib diff --git a/apps/mandeye_raw_data_viewer_legacy/CMakeLists.txt b/apps/mandeye_raw_data_viewer_legacy/CMakeLists.txt index 106335e4f..403e4c7c5 100644 --- a/apps/mandeye_raw_data_viewer_legacy/CMakeLists.txt +++ b/apps/mandeye_raw_data_viewer_legacy/CMakeLists.txt @@ -49,7 +49,7 @@ target_include_directories( target_link_libraries( mandeye_raw_data_viewer_legacy - PRIVATE vqf Fusion + PRIVATE step1_run_report vqf Fusion unordered_dense::unordered_dense spdlog::spdlog UTL::include diff --git a/cmake/step1_run_report.cmake b/cmake/step1_run_report.cmake new file mode 100644 index 000000000..612f45453 --- /dev/null +++ b/cmake/step1_run_report.cmake @@ -0,0 +1,16 @@ +# Shared by the odometry applications, viewers/calibration tools and Python bindings. +add_library(step1_run_report STATIC + ${REPOSITORY_DIRECTORY}/apps/lidar_odometry_step_1/run_report.cpp + ${REPOSITORY_DIRECTORY}/apps/lidar_odometry_step_1/run_report.h +) +target_include_directories(step1_run_report PUBLIC + ${REPOSITORY_DIRECTORY}/apps/lidar_odometry_step_1 + ${THIRDPARTY_DIRECTORY}/json/include +) +target_compile_features(step1_run_report PUBLIC cxx_std_20) +target_link_libraries(step1_run_report PUBLIC Threads::Threads) +# This static library is also linked into the Python extension module on Linux/macOS. +set_target_properties(step1_run_report PROPERTIES POSITION_INDEPENDENT_CODE ON) +if(WIN32) + target_link_libraries(step1_run_report PRIVATE psapi pdh) +endif() diff --git a/doc/processing_report.md b/doc/processing_report.md new file mode 100644 index 000000000..5f2050ca2 --- /dev/null +++ b/doc/processing_report.md @@ -0,0 +1,116 @@ +# Step 1 run analysis + +The raylib Step 1 GUI and CLI add `run_analysis` (schema version 1) to +`HDMapping_results_*.json`. The completion dialog and console use the same +accounting object. Existing result metadata is retained. + +## Timing boundaries + +Durations use `std::chrono::steady_clock`. UTC timestamps identify events; +changing the system clock does not change measured durations. + +- `loading`: input discovery/loading pass, including the initial lazy-loader range pass. +- `initialization`: IMU-based initial trajectory. +- `cache_preparation`: worker/chunk preparation, decimation, cache writes, and + any deferred raw-cloud reads performed by lazy loading. +- `odometry`: the complete odometry call, including its cache reads, spill work, + final bookkeeping and spill destruction. +- `export`: preparing, writing and closing point clouds, trajectories, poses, + session metadata and parameters. A writer failure makes the export unsuccessful. +- `cleanup`: the actual cache removal attempt. +- `consistency`: optional post-processing, when invoked. + +Stage wall times include actual pauses. `paused_seconds` measures waiting at +the processing pause boundary, not time since clicking Pause. The separate +`excluding_pauses_seconds` is wall time with those waits subtracted, not CPU time. +The progress ETA uses odometry time excluding pauses; it does not predict export. + +Progress also shows `Raw recording span (IMU)`: the last minus first loaded raw +IMU timestamp, in seconds and minutes, including acquisition gaps. It uses the +already sorted input IMU vector, not the shorter optimized trajectory or file +modification times, and requires no additional data reads/scans. The same range +and source are saved under `run_analysis.input_recording`. These sensor +timestamps are not UTC/`timestampUnix`; missing/invalid ranges remain null. + +`total_operation_wall_seconds` sums measured operation intervals. For the +automatic GUI flow this begins before input discovery and ends after export. +For CLI it also includes immediate cache cleanup. Gaps between stages inside +an operation appear as `between_stages_seconds`. Later interactive idle is +excluded. Re-export, consistency and deferred cleanup resume accounting as +additional operations of the same run; their intervals are recorded in +`operations`. They do not reset the odometry duration. + +Cache write durations are **nested** within preparation/export. They are +reported separately by kind (`initial`, `export`) and must not be added to totals. +The final report's own serialization and replacement are outside measured +operation intervals; completion is shown only after that write returns. +Closing a stream does not imply an explicit physical-media flush. + +The legacy `processing_info.elapsed_time_seconds` is odometry wall time, +including pauses, when run analysis is present. Its scope is labeled explicitly. +Historical files generated before this change have different boundaries. + +## Resource statistics and cost + +The sampler queries native process/system memory approximately once a second, +and available disk space every five seconds, independently of frame rate. +Stage transitions request an asynchronous refresh, with a minimum 100 ms +between samples to bound bursts. A stage boundary can carry the most recent +available sample of the same operation. Interactive idle is never extrapolated. + +Each metric records first/last observations, time-weighted mean over valid +coverage, minimum, sampled maximum, observation count and coverage duration. +Missing values are null, not zero. Short peaks can fall between samples. +Per-stage statistics use the same definitions. No unbounded sample history or +periodic cache-directory traversal is retained. + +Windows uses process working set for resident RAM, private commit for process +committed memory, and system commit/limit for context. Commit is **not actual +pagefile disk occupancy**; subtracting resident RAM from commit does not produce +that quantity. Active pagefile volumes are discovered at run start, alongside +input/cache, optional spill and output locations. Available disk space is not +a promise of additional commit capacity. Hover a volume in the GUI to see its roles. + +GPU metrics use Windows GPU Process Memory PDH counters, with dedicated and +shared memory recorded per adapter LUID/physical index. Adapter sums may count +shared allocations more than once; they are not unique physical residency. +OS/driver limitations apply. The PDH query is reused between runs in the process. +Unsupported platforms/counters report unavailable values. Linux and macOS +provide resident RAM; Linux also provides available system RAM. Windows-specific +commit/GPU counters are not replaced with differently defined quantities. + +`sampling` reports first/subsequent query wall cost, maximum query cost, +sampler-thread CPU time when supported, setup cost and cache-accounting cost. +A cold GPU performance-provider initialization can cost much more than later +queries. Queries run outside the report mutex on the sampling thread; their +wall duration is not equivalent to time blocked in the processing worker. +GUI snapshots only copy small aggregates and make no OS resource queries. + +Cache accounting performs one size lookup per completed file, including export +chunks; overwrites replace the previous size. It records logical bytes/file +counts after preparation, historical peak and cleanup status. Spill sizes are +updated at reset/finish/destruction boundaries, never for each appended point. +Spill peak includes the overlapping old/new generation during reset. Disk-free +minima are sampled; cache peaks are derived from the application's file events. +Cache-file accounting covers this run's completed writes, not an inventory of +unmodified files left by an earlier crashed run. That scope is saved in the JSON. +After a failed cache removal, remaining bytes/file count are unknown (null). +Spill cleanup errors identify files that may remain outside the current stream. + +## Completion and later updates + +The GUI retains cache for consistency/editing/re-export and reports it as +`retained`. Closing the application removes it and updates all reports registered +for that run without repeating the export completion popup. Automatic processing +and manual re-export share a single completion-notification path. CLI removes +cache immediately and updates its report before the +final console summary. No result file is written by the sampler itself. + +Reports are written through a temporary file and replaced only after the stream +has closed successfully. Error/cancellation status is retained during later +cleanup. Failed or cancelled runs write a diagnostic report when an output +directory is available; an unwritable destination cannot retain its own failure +report. Fatal process termination cannot guarantee finalization. + +This change covers the raylib Step 1 workflow. Shared processing sources also +build for the older GLUT entry points, whose legacy UI is not redesigned here. diff --git a/pybind/CMakeLists.txt b/pybind/CMakeLists.txt index 243de8011..180da5746 100644 --- a/pybind/CMakeLists.txt +++ b/pybind/CMakeLists.txt @@ -192,7 +192,8 @@ target_link_libraries( ${PLATFORM_MISCELLANEOUS_LIBS} ) target_link_libraries(lidar_odometry_py - PRIVATE pybind11::module + PRIVATE step1_run_report + pybind11::module core_no_gui unordered_dense::unordered_dense spdlog::spdlog