diff --git a/minco_ws/docs/diagnostics/ivox_knn_regression/README.md b/minco_ws/docs/diagnostics/ivox_knn_regression/README.md new file mode 100644 index 0000000..3cc1c52 --- /dev/null +++ b/minco_ws/docs/diagnostics/ivox_knn_regression/README.md @@ -0,0 +1,42 @@ +# IVox 近邻与 Point-LIO 观测模型回归 + +用于验证近邻候选压缩和逐点匹配并行化,直接编译生产头文件、调用实际构建的 +`point_lio_component`;不启动雷达、ROS 节点或底盘。需要先完成实车 Point-LIO 构建。 + +```bash +cd /home/xie/RC2027_BR_code +source /opt/ros/humble/setup.bash +source minco_ws/install/mission/setup.bash +bash minco_ws/docs/diagnostics/ivox_knn_regression/build_and_run.sh \ + minco_ws/log/ivox_knn_regression_01 +``` + +脚本从 `minco_ws/build/mission/point_lio/compile_commands.json` 复用生产编译选项, +并链接该构建目录中的 `libpoint_lio_component.so`。不同构建目录可通过 +`BR_KNN_COMPILE_COMMANDS=/absolute/path/compile_commands.json` 指定。 +输出目录保存实际编译命令、测试程序和 `matching_order.json`。 + +两个测试分别覆盖: + +- `test_ivox_knn.cpp`:646 个随机、空集、少量点、边界及等距用例;与穷举最近距离 + 以及旧版完整 DistPoint 的 `nth_element` 选择顺序对照。还验证已有候选前缀、点身份, + 并报告 10000 次稠密查询耗时和顺序摘要。耗时只作观察,不作为跨机器通过门槛。 +- `test_matching_order.cpp`:调用生产 `h_model_input/output`,覆盖两种外参估计开关、 + 6 种点数及每组 8 次重复,共每种线程模式 192 次观测模型调用。 + 两个独立进程分别用 `OMP_THREAD_LIMIT=1/4`,比较 Jacobian、残差、掩码及有序近邻的 + 完整摘要;共 384 次调用。地图每组重建,重复调用也覆盖线程局部候选缓冲的复用。 + +只对照冻结的旧版头文件时,可设置 `BR_KNN_ONLY=1` 与 +`BR_KNN_HEADER_ROOT=/absolute/path/include`,该根目录应包含 `ivox/ivox3d_node.hpp`。 +此模式不运行链接组件的观测模型测试,避免旧头文件与新组件混用。 + +本机最终结果:646 个近邻用例通过;有序近邻摘要 `90192090487253394` 与旧版一致; +单线程/四线程观测模型摘要均为 `1776722514077682147`。 +测试限定于本机编译工具链和这些输入,不能据此承诺所有平台、场景的位级一致。 + +硬件及相同数据回放是独立验证,记录见 [RAIN_NET_005](../../RAIN_NET_005_2026-11-19.md)。 +本次证据位于 `minco_ws/log/rain-net-005/`: +`compact_parallel_regression_final.txt`、`compact_parallel/regression_final/`、 +`comparison_contract.json`、`compact_parallel/replay_comparison.json`、 +`compact_parallel/live_01/summary.json`。回放用原始时间、完整接收并处理至最后一帧, +比较全部里程计和完整点云;该静止记录通过不代表动态或完整任务验收通过。 diff --git a/minco_ws/docs/diagnostics/ivox_knn_regression/build_and_run.sh b/minco_ws/docs/diagnostics/ivox_knn_regression/build_and_run.sh new file mode 100644 index 0000000..9ba4147 --- /dev/null +++ b/minco_ws/docs/diagnostics/ivox_knn_regression/build_and_run.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Directly exercise the production voxel node, without ROS or sensor hardware. +set -euo pipefail +BR_KNN_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +BR_KNN_WS=$(cd -- "$BR_KNN_DIR/../../.." && pwd) +BR_KNN_OUT=${1:-"$BR_KNN_WS/log/ivox_knn_regression"} +mkdir -p -- "$BR_KNN_OUT" +BR_KNN_COMPDB=${BR_KNN_COMPILE_COMMANDS:-"$BR_KNN_WS/build/mission/point_lio/compile_commands.json"} +/usr/bin/python3 - "$BR_KNN_COMPDB" "$BR_KNN_DIR/test_ivox_knn.cpp" "$BR_KNN_OUT" "${BR_KNN_HEADER_ROOT:-}" <<'PY' +import json, os, shlex, subprocess, sys +from pathlib import Path +database, source, output = map(Path, sys.argv[1:4]) +if sys.argv[4] and os.environ.get('BR_KNN_ONLY') != '1': + raise SystemExit('BR_KNN_HEADER_ROOT requires BR_KNN_ONLY=1; model tests use the built component') +entry = next(e for e in json.loads(database.read_text()) if e['file'].endswith('laserMapping.cpp')) +args = entry.get('arguments') or shlex.split(entry['command']) +command = [args[0]] +if sys.argv[4]: + command.append('-I' + str(Path(sys.argv[4]).resolve())) +i = 1 +while i < len(args): + if args[i] == '-o': + i += 2 + continue + if args[i] == '-c' or args[i] == entry['file']: + i += 1 + continue + command.append(args[i]) + i += 1 +base_command = list(command) +command += [str(source.resolve()), '-o', str(output.resolve() / 'test_ivox_knn')] +(output / 'compile_command.json').write_text(json.dumps(command, indent=2) + '\n') +subprocess.run(command, cwd=entry['directory'], check=True) +if os.environ.get('BR_KNN_ONLY') != '1': + component = Path(entry['directory']) / 'libpoint_lio_component.so' + model_binary = output.resolve() / 'test_matching_order' + model_command = base_command + ['-I' + str(Path(entry['file']).parent), + str(source.with_name('test_matching_order.cpp').resolve()), + str(component), '-Wl,-rpath,' + str(component.parent), + '-o', str(model_binary)] + (output / 'model_compile_command.json').write_text(json.dumps(model_command, indent=2) + '\n') + subprocess.run(model_command, cwd=entry['directory'], check=True) + results = [] + for limit in ('1', '4'): + result = subprocess.run([str(model_binary)], check=True, text=True, capture_output=True, + env=dict(os.environ, OMP_THREAD_LIMIT=limit)) + record = json.loads(result.stdout.strip().splitlines()[-1]) + results.append(record) + assert results[0]['matching_digest'] == results[1]['matching_digest'], results + (output / 'matching_order.json').write_text(json.dumps(results, indent=2) + '\n') + print(json.dumps({'serial_parallel_matching': 'PASS', 'cases_per_mode': results[0]['model_cases'], + 'digest': results[0]['matching_digest']})) +PY +"$BR_KNN_OUT/test_ivox_knn" diff --git a/minco_ws/docs/diagnostics/ivox_knn_regression/test_ivox_knn.cpp b/minco_ws/docs/diagnostics/ivox_knn_regression/test_ivox_knn.cpp new file mode 100644 index 0000000..0ac6d66 --- /dev/null +++ b/minco_ws/docs/diagnostics/ivox_knn_regression/test_ivox_knn.cpp @@ -0,0 +1,126 @@ +#include +#include "ivox/ivox3d_node.hpp" +#include +#include +#include +#include +#include +#include +#include + +using Point = pcl::PointXYZINormal; +using Node = faster_lio::IVoxNode; +using Candidate = Node::DistPoint; +std::uint64_t ordered_digest = 1469598103934665603ULL; + +void require(bool value, const char * message) +{ + if (!value) throw std::runtime_error(message); +} + +Point point(float x, float y, float z, int id) +{ + Point p{}; p.x=x; p.y=y; p.z=z; p.intensity=id; return p; +} + +void check(const std::vector & points, const Point & query, int k, double range) +{ + Node node; + for (const auto & p : points) node.InsertPoint(p); + std::vector selected{Candidate(-7.0, nullptr, -123)}; + node.KNNPointByCondition(selected, query, k, range); + require(selected.front().node==nullptr && selected.front().idx==-123 && + selected.front().dist==-7.0, "earlier voxel candidates changed"); + std::vector reference; + std::vector legacy_order; + for (std::size_t index=0;index(index)); + } + } + // Compatibility oracle: the old implementation partitioned full DistPoints. + // Separately compare against exhaustive distances below, so retaining the old + // permutation cannot hide an incorrect nearest-neighbor result. + if (legacy_order.size()>static_cast(k)) { + std::nth_element(legacy_order.begin(),legacy_order.begin()+k-1,legacy_order.end()); + legacy_order.resize(k); + } + std::sort(reference.begin(),reference.end()); + reference.resize(std::min(reference.size(),static_cast(k))); + require(selected.size()==reference.size()+1, "incorrect candidate count"); + std::vector actual; + std::unordered_set ids; + for (std::size_t i=1;i=0 && c.idx(points.size()), + "invalid candidate identity"); + require(c.idx==legacy_order[i-1].idx, "legacy candidate order changed"); + require(ids.insert(c.idx).second, "candidate duplicated"); + require(c.dist==faster_lio::distance2(points[c.idx],query), "candidate distance changed"); + ordered_digest^=static_cast(c.idx); + ordered_digest*=1099511628211ULL; + actual.push_back(c.dist); + } + std::sort(actual.begin(),actual.end()); + require(actual==reference, "nearest distances differ from exhaustive reference"); +} + +int main() +{ + try { + std::mt19937 random(20261119); + std::uniform_real_distribution coordinate(-2.0F,2.0F); + std::size_t cases=0; + for (int count : {0,1,4,5,6,35,500,2000}) { + std::vector points; + for (int i=0;i tied; + for (int i=0;i<100;++i) tied.push_back(point((i%2) ? 1.F : -1.F,0.F,0.F,i)); + tied.push_back(point(0.F,0.F,0.F,100)); + for (int k : {1,5,32}) for (double range : {1.0,1.01}) { + check(tied,point(0.F,0.F,0.F,-1),k,range); ++cases; + } + // When fewer than K qualify, preserve the original insertion order. + Node small; + small.InsertPoint(point(3,0,0,0));small.InsertPoint(point(1,0,0,1)); + std::vector limited; + small.KNNPointByCondition(limited,point(0,0,0,-1),5,5.0); + require(limited.size()==2 && limited[0].idx==0 && limited[1].idx==1, + "small candidate sequence changed"); + + // Dense-voxel workload with an order-independent identity digest. + Node dense; + for (int i=0;i<1000;++i) dense.InsertPoint(point(coordinate(random),coordinate(random),coordinate(random),i)); + std::vector queries; + for (int i=0;i<2000;++i) queries.push_back(point(coordinate(random),coordinate(random),coordinate(random),-1)); + std::uint64_t digest=1469598103934665603ULL; + auto start=std::chrono::steady_clock::now(); + for (int repeat=0;repeat<5;++repeat) for (const auto & q : queries) { + std::vector candidates; + candidates.reserve(35); + dense.KNNPointByCondition(candidates,q,5,5.0); + std::vector ids; + for (const auto & c : candidates) ids.push_back(c.idx); + std::sort(ids.begin(),ids.end()); + for (int id : ids) {digest^=static_cast(id);digest*=1099511628211ULL;} + } + double ms=std::chrono::duration(std::chrono::steady_clock::now()-start).count(); + std::cout<<"{\"status\":\"PASS\",\"reference_cases\":"< +#include +#include +#include +#include + +std::uint64_t digest = 1469598103934665603ULL; +template void hash_value(const T & value) +{ + unsigned char bytes[sizeof(T)];std::memcpy(bytes,&value,sizeof(T)); + for (auto byte : bytes) {digest^=byte;digest*=1099511628211ULL;} +} + +int main() +{ + try { + std::size_t cases=0; + for (bool input : {false,true}) for (bool extrinsic : {false,true}) { + use_imu_as_input=input;extrinsic_est_en=extrinsic; + Lidar_R_wrt_IMU.setIdentity();Lidar_T_wrt_IMU<<.01,.02,.03; + kf_input.x_.rot=M3D::Identity();kf_output.x_.rot=M3D::Identity(); + kf_input.x_.pos=V3D::Zero();kf_output.x_.pos=V3D::Zero(); + kf_input.x_.offset_R_L_I=M3D::Identity();kf_output.x_.offset_R_L_I=M3D::Identity(); + kf_input.x_.offset_T_L_I=Lidar_T_wrt_IMU;kf_output.x_.offset_T_L_I=Lidar_T_wrt_IMU; + IVoxType::Options options;options.resolution_=2.F;options.point_resolution_=.1F; + ivox_=std::make_shared(options); + PointVector map; + for (int x=-25;x<=25;++x) for (int y=-25;y<=25;++y) { + PointType body{};body.x=x*.12F;body.y=y*.12F;body.z=1.5F;body.intensity=map.size(); + PointType world{};pointBodyToWorld(&body,&world);map.push_back(world); + } + ivox_->AddPoints(map);laser_point_cov=.01;plane_thr=.1;match_s=81.; + for (int count : {1,5,29,30,200,1000}) { + k=0;idx=-1;time_seq={count};feats_down_body->resize(count);feats_down_world->resize(count); + pbody_list.resize(count);crossmat_list.resize(count);Nearest_Points.resize(count); + for (int j=0;jpoints[j];p.x=-2.F+.013F*(j%307);p.y=-2.F+.017F*((j*17)%233);p.z=1.5F+.001F*(j%3); + pbody_list[j]=V3D(p.x,p.y,p.z); + crossmat_list[j]<<0.,-p.z,p.y,p.z,0.,-p.x,-p.y,p.x,0.; + } + // Repeat to exercise reusable per-worker scratch buffers. + for (int repeat=0;repeat<8;++repeat) { + esekfom::dyn_share_modified model;model.valid=true; + if (input) h_model_input(kf_input.x_,M3D::Identity(),M3D::Identity(),model); + else h_model_output(kf_output.x_,M3D::Identity(),M3D::Identity(),model); + if (!model.valid || !model.h_x.allFinite() || !model.z.allFinite()) + throw std::runtime_error("invalid observation model"); + hash_value(model.h_x.rows());hash_value(model.h_x.cols()); + for (Eigen::Index i=0;i(startup_frame_cnt_+1)};', 1), + (' /*** downsample the feature points in a scan ***/', + ' rain_profile.next(rain_latency::ImuProcess);\n /*** downsample the feature points in a scan ***/', 1), + (' enqueueFullCloud(feats_undistort, Measures.lidar_beg_time);', + ' rain_profile.next(rain_latency::Enqueue);\n enqueueFullCloud(feats_undistort, Measures.lidar_beg_time);', 1), + (' if (space_down_sample) {', + ' rain_profile.next(rain_latency::VoxelSort);\n if (space_down_sample) {', 1), + (' if (!p_imu->after_imu_init_)', + ' rain_profile.next(rain_latency::InitMap);\n if (!p_imu->after_imu_init_)', 1), + (' /*** ICP and Kalman filter update ***/', + ' rain_profile.next(rain_latency::ModelPrep);\n /*** ICP and Kalman filter update ***/', 1), + (' time_current = point_body.curvature / 1000.0 + pcl_beg_time;', + ' rain_profile.next(rain_latency::Predict);\n time_current = point_body.curvature / 1000.0 + pcl_beg_time;', 2), + (' const auto update_start = statistics_enabled', + ' rain_profile.next(rain_latency::LidarUpdate);\n const auto update_start = statistics_enabled', 2), + (' processFullCloudSegmentWithSnapshot(makeStateSnapshot(time_current));', + ' rain_profile.next(rain_latency::FullSegment);\n processFullCloudSegmentWithSnapshot(makeStateSnapshot(time_current));', 2), + (' if (publish_odometry_without_downsample) {', + ' rain_profile.next(rain_latency::OdomPublish);\n if (publish_odometry_without_downsample) {', 2), + (' for (int j = 0; j < time_seq[k]; j++) {', + ' rain_profile.next(rain_latency::PointTransform);\n for (int j = 0; j < time_seq[k]; j++) {', 2), + (' /******* Publish odometry downsample *******/', + ' rain_profile.next(rain_latency::FinishScan);\n /******* Publish odometry downsample *******/', 1), + (' if (feats_down_size > 4) {', + ' rain_profile.next(rain_latency::MapUpdate);\n if (feats_down_size > 4) {', 1), + (' /******* Publish points *******/', + ' rain_profile.next(rain_latency::EndPublish);\n /******* Publish points *******/', 1), + (' const StateLogRecord state_log = makeStateLogRecord();', + ' rain_profile.next(rain_latency::Statistics);\n const StateLogRecord state_log = makeStateLogRecord();', 1), + ] + original = text + for before, after, count in markers: + if text.count(before) != count: + raise ValueError('unexpected source layout at ' + before.strip()) + text = text.replace(before, after) + # No original algorithm statement may change or move. + reverse = text + for before, after, _ in reversed(markers): + reverse = reverse.replace(after, before) + if reverse != original: + raise ValueError('instrumentation did not preserve original statements') + return '#include "latency_profile.hpp"\n' + text + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, required=True) + ws = Path(__file__).resolve().parents[3] + parser.add_argument('--compile-commands', type=Path, + default=ws / 'build/mission/point_lio/compile_commands.json') + args = parser.parse_args() + database = json.loads(args.compile_commands.read_text()) + entry = next(e for e in database if e['file'].endswith('/laserMapping.cpp') and + any('POINT_LIO_BUILD_MAIN' in x for x in + (e.get('arguments') or shlex.split(e['command'])))) + source = Path(entry['file']) + instrumented = instrument(source.read_text()) + build = Path(entry['directory']) + output = args.out.resolve() + output.mkdir(parents=True, exist_ok=False) + shutil.copyfile(Path(__file__).with_name('latency_profile.hpp'), output / 'latency_profile.hpp') + (output / 'laserMapping.cpp').write_text(instrumented) + command = list(entry.get('arguments') or shlex.split(entry['command'])) + command[command.index('-o') + 1] = str(output / 'laserMapping.cpp.o') + command[command.index('-c') + 1] = str(output / 'laserMapping.cpp') + command.insert(1, '-I' + str(source.parent)) + link = shlex.split((build / 'CMakeFiles/pointlio_mapping.dir/link.txt').read_text()) + original_object = 'CMakeFiles/pointlio_mapping.dir/src/laserMapping.cpp.o' + if link.count(original_object) != 1: + raise ValueError('unexpected native link layout') + link[link.index('-o') + 1] = str(output / 'pointlio_mapping') + link[link.index(original_object)] = str(output / 'laserMapping.cpp.o') + metadata = {'source': str(source), 'source_sha256': hashlib.sha256(source.read_bytes()).hexdigest(), + 'compile': command, 'link': link, 'phases': PHASES, + 'scope': 'Independent profiling executable; original source/build/install not written'} + (output / 'build.json').write_text(json.dumps(metadata, indent=2) + '\n') + subprocess.run(command, cwd=build, check=True) + subprocess.run(link, cwd=build, check=True) + print(output / 'pointlio_mapping') + + +if __name__ == '__main__': + main() diff --git a/minco_ws/docs/diagnostics/profile_pointlio_latency/latency_profile.hpp b/minco_ws/docs/diagnostics/profile_pointlio_latency/latency_profile.hpp new file mode 100644 index 0000000..33e4087 --- /dev/null +++ b/minco_ws/docs/diagnostics/profile_pointlio_latency/latency_profile.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace rain_latency { + +enum Phase { + Startup, ImuProcess, Enqueue, VoxelSort, InitMap, ModelPrep, Predict, + LidarUpdate, FullSegment, OdomPublish, PointTransform, FinishScan, MapUpdate, + EndPublish, Statistics, Count +}; + +inline long long wall_ns() +{ + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +inline long long cpu_ns() +{ + timespec t{}; + clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t); + return t.tv_sec * 1000000000LL + t.tv_nsec; +} + +struct TraceOutput { + FILE * file = nullptr; + TraceOutput() + { + const char * path = std::getenv("RAIN_LATENCY_TRACE_PATH"); + if (path) { + // A diagnostic must never overwrite a previous run. + file = std::fopen(path, "wx"); + } + if (!file) { + std::fputs("[latency profile] Set RAIN_LATENCY_TRACE_PATH to a new writable file; trace disabled\n", stderr); + return; + } + std::fputs("frame,monotonic_ns,phase,wall_ms,thread_cpu_ms\n", file); + } + ~TraceOutput() { if (file) std::fclose(file); } +}; + +struct Frame { + unsigned long long id; + Phase phase = Startup; + long long wall = wall_ns(), cpu = cpu_ns(); + std::array walls{}, cpus{}; + + void next(Phase p) + { + const auto w = wall_ns(), c = cpu_ns(); + walls[phase] += w - wall; + cpus[phase] += c - cpu; + wall = w; + cpu = c; + phase = p; + } + + ~Frame() + { + next(Statistics); + static TraceOutput output; + if (!output.file) return; + for (int i = 0; i < Count; ++i) { + std::fprintf(output.file, "%llu,%lld,%d,%.12g,%.12g\n", + id, wall, i, walls[i] * 1e-6, cpus[i] * 1e-6); + } + if (id % 20 == 0) std::fflush(output.file); + } +}; + +} // namespace rain_latency diff --git a/minco_ws/src/perception/Point-LIO/include/ivox/ivox3d_node.hpp b/minco_ws/src/perception/Point-LIO/include/ivox/ivox3d_node.hpp index a03bb06..eda7194 100644 --- a/minco_ws/src/perception/Point-LIO/include/ivox/ivox3d_node.hpp +++ b/minco_ws/src/perception/Point-LIO/include/ivox/ivox3d_node.hpp @@ -216,69 +216,40 @@ template int IVoxNode::KNNPointByCondition( std::vector & dis_points, const PointT & point, const int & K, const double & max_range) { - std::size_t old_size = dis_points.size(); -// #define INNER_TIMER -#ifdef INNER_TIMER - static std::unordered_map> stats; - if (stats.empty()) { - stats["dis"] = std::vector(); - stats["put"] = std::vector(); - stats["nth"] = std::vector(); + const std::size_t old_size = dis_points.size(); + if (K <= 0) { + return static_cast(old_size); } -#endif - - for (const auto & pt : points_) { -#ifdef INNER_TIMER - auto t0 = std::chrono::high_resolution_clock::now(); -#endif - double d = distance2(pt, point); -#ifdef INNER_TIMER - auto t1 = std::chrono::high_resolution_clock::now(); -#endif - if (d < max_range * max_range) { - dis_points.template emplace_back(DistPoint(d, this, &pt - points_.data())); - } -#ifdef INNER_TIMER - auto t2 = std::chrono::high_resolution_clock::now(); - - auto dis = std::chrono::duration_cast(t1 - t0).count(); - stats["dis"].emplace_back(dis); - auto put = std::chrono::duration_cast(t2 - t1).count(); - stats["put"].emplace_back(put); -#endif - } - -#ifdef INNER_TIMER - auto t1 = std::chrono::high_resolution_clock::now(); -#endif - // sort by distance - if (old_size + K >= dis_points.size()) { - } else { - std::nth_element( - dis_points.begin() + old_size, dis_points.begin() + old_size + K - 1, dis_points.end()); - dis_points.resize(old_size + K); - } - -#ifdef INNER_TIMER - auto t2 = std::chrono::high_resolution_clock::now(); - auto nth = std::chrono::duration_cast(t2 - t1).count(); - stats["nth"].emplace_back(nth); - - constexpr int STAT_PERIOD = 100000; - if (!stats["nth"].empty() && stats["nth"].size() % STAT_PERIOD == 0) { - for (auto & it : stats) { - const std::string & key = it.first; - std::vector & stat = it.second; - int64_t sum_ = std::accumulate(stat.begin(), stat.end(), 0); - int64_t num_ = stat.size(); - stat.clear(); - std::cout << "inner_" << key << "(ns): sum=" << sum_ << " num=" << num_ - << " ave=" << 1.0 * sum_ / num_ << " ave*n=" << 1.0 * sum_ / STAT_PERIOD << '\n'; + // distance2 computes a float squared norm before returning double. Keeping + // that exact value plus its point index avoids materializing a node pointer + // for every candidate. Preserve the legacy partition/comparison order, + // including ties: plane fitting consumes the returned point sequence. + struct LocalCandidate + { + float dist; + int index; + bool operator<(const LocalCandidate & other) const { return dist < other.dist; } + }; + thread_local std::vector local_candidates; + local_candidates.clear(); + const double range_squared = max_range * max_range; + for (std::size_t index = 0; index < points_.size(); ++index) { + const double d = distance2(points_[index], point); + if (d < range_squared) { + local_candidates.push_back({static_cast(d), static_cast(index)}); } } -#endif - - return dis_points.size(); + const std::size_t selected = + std::min(local_candidates.size(), static_cast(K)); + if (local_candidates.size() > selected) { + std::nth_element(local_candidates.begin(), local_candidates.begin() + K - 1, + local_candidates.end()); + } + for (std::size_t i = 0; i < selected; ++i) { + const auto & candidate = local_candidates[i]; + dis_points.emplace_back(candidate.dist, this, candidate.index); + } + return static_cast(dis_points.size()); } template struct IVoxNodePhc::DistPoint diff --git a/minco_ws/src/perception/Point-LIO/src/Estimator.cpp b/minco_ws/src/perception/Point-LIO/src/Estimator.cpp index 81b74de..776b36f 100644 --- a/minco_ws/src/perception/Point-LIO/src/Estimator.cpp +++ b/minco_ws/src/perception/Point-LIO/src/Estimator.cpp @@ -369,11 +369,17 @@ void h_model_input(state_input & s, esekfom::dyn_share_modified & ekfom_data) { bool match_in_map = false; - VF(4) pabcd; - pabcd.setZero(); normvec->resize(time_seq[k]); int effect_num_k = 0; + // Each point owns its world point, neighbor vector, mask and plane row. + // The map/state are read-only until this region joins; only the integer + // count is reduced. Assemble Jacobian rows below in the original order. +#ifdef MP_EN +#pragma omp parallel for num_threads(MP_PROC_NUM) reduction(+:effect_num_k) schedule(static) +#endif for (int j = 0; j < time_seq[k]; j++) { + VF(4) pabcd; + pabcd.setZero(); PointType & point_body_j = feats_down_body->points[idx + j + 1]; PointType & point_world_j = feats_down_world->points[idx + j + 1]; pointBodyToWorld(&point_body_j, &point_world_j); @@ -475,11 +481,17 @@ void h_model_output(state_output & s, esekfom::dyn_share_modified & ekfom_data) { bool match_in_map = false; - VF(4) pabcd; - pabcd.setZero(); normvec->resize(time_seq[k]); int effect_num_k = 0; + // Each point owns its world point, neighbor vector, mask and plane row. + // The map/state are read-only until this region joins; only the integer + // count is reduced. Assemble Jacobian rows below in the original order. +#ifdef MP_EN +#pragma omp parallel for num_threads(MP_PROC_NUM) reduction(+:effect_num_k) schedule(static) +#endif for (int j = 0; j < time_seq[k]; j++) { + VF(4) pabcd; + pabcd.setZero(); PointType & point_body_j = feats_down_body->points[idx + j + 1]; PointType & point_world_j = feats_down_world->points[idx + j + 1]; pointBodyToWorld(&point_body_j, &point_world_j);