sar3d: port the Multi_antenna_3D_clean_v1 notebook algorithm
The old sar3d core was a port of the superseded Horns_3D notebook and produced wrong volumes. The compute core now follows the reference notebook exactly: - segmented_interleaved frame timing rebuilt from per-trace capture stamps (uniform tx_per_segment split as the no-stamps fallback), with the coarse inter-segment dtau and the intra-sweep dtau applied as one phase ramp before the IFFT; - ground scene coordinates with the ground_depth_m lift (scene Y=0 is the ground), full-region grid instead of a window around a center depth, geo_ref compensation anchored on the ground plane, power 0.3; - notebook finalization in C++: |acc/cnt|, depth mask, normalization without the Y-edge planes, separable Gaussian over (Z, X), level; - CUDA kernel computes geometry in double: float32 loses ~3e-4 of an A-scan sample in tau and drifts ~1e-4 from the float64 reference. Live-config keys follow: the center_depth/half_width/grid_n window knobs are replaced by ground/voxel/y-range/margin/sigma/power/tx_per_segment. Parity against the notebook npz exports (frames 0034-0036 of the 20260922_mine_fast_true dataset): max|diff| <= 1.6e-6 off the depth-mask knife edge, identical argmax, level rel diff <= 7e-7. Verified via make sar3d_parity --dump-dir + scripts/sar3d_volume_compare.py; the executable spec lives in scripts/sar3d_reference_check.py (bit-tight against the npz, including the animation shifted-grid arithmetic). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,23 +1,24 @@
|
||||
# gpr_cpp — C++/CUDA счёт-ядро MIMO GPR 3D SAR
|
||||
|
||||
> Вендорено из репозитория VNA_AlGo (`gpr_cpp/`, коммит `544dc59`); python-биндинги
|
||||
> (`bindings/`, pybind11) при переносе не взяты — сборка здесь только C++
|
||||
> (`GPR_BUILD_PYTHON=OFF`). Собирается из корневого Makefile radar_system
|
||||
> Инфраструктура (сборка, NVRTC, PocketFFT, npy) вендорена из репозитория
|
||||
> VNA_AlGo (`gpr_cpp/`, коммит `544dc59`) без python-биндингов
|
||||
> (`GPR_BUILD_PYTHON=OFF`). АЛГОРИТМ с сентября 2026 переписан: это порт
|
||||
> эталонного ноутбука `Multi_antenna_3D_clean_v1.ipynb` (ячейки 0 и 4), а не
|
||||
> старого `gpr_core`/Horns_3D. Паритет с ноутбуком проверяется инструментом
|
||||
> `sar3d_parity` + `python_app/scripts/sar3d_volume_compare.py` по
|
||||
> референсным `*_volume.npz`. Собирается из корневого Makefile radar_system
|
||||
> (цель `$(GPR_CPP_LIB)` вызывает `build_cmake.sh`).
|
||||
|
||||
Порт вычислительного ядра из Python/CuPy (`gpr_core`) в самостоятельную
|
||||
C++/CUDA библиотеку для интеграции в C++ проект.
|
||||
Алгоритм — см. `ALGORITHM.md` в репозитории VNA_AlGo.
|
||||
## Что внутри
|
||||
|
||||
## Что внутри (граница C++ ↔ Python)
|
||||
|
||||
**В C++ (`libgpr_core_cpp`):** геометрия, препроцессинг A-сканов (bg-subtract,
|
||||
фазовая коррекция движения, k0-вставка + Ханн + IFFT через PocketFFT, нормировка),
|
||||
3D SAR апертурный объём (одно CUDA-ядро на всю апертуру). Возвращает **сырые**
|
||||
`acc`(complex64)/`cnt`(float32).
|
||||
|
||||
**Остаётся в Python:** загрузка `.npy`, финализация объёма (abs+gate+gaussian+
|
||||
нормировка), CLEAN-детекция, трек, оценка скорости, plotly.
|
||||
**В C++ (`libgpr_core_cpp`):** сегментированный тайминг кадра по per-trace
|
||||
меткам захвата (`compute_pair_timestamps`), препроцессинг A-сканов (bg-subtract,
|
||||
полная фазовая коррекция движения intra+pair до IFFT, k0-вставка + Ханн + IFFT
|
||||
через PocketFFT, нормировка пар), полнообластная ground-сетка
|
||||
(`build_full_region_grid`), 3D SAR апертурный объём (одно CUDA-ядро на всю
|
||||
апертуру; геометрия в double, A-сканы float32) и финализация
|
||||
(`finish_volume`: |acc/cnt| → маска глубины → нормировка без Y-краёв → гаусс
|
||||
по (Z,X) → нормировка; возвращает объём [0,1] + level).
|
||||
|
||||
## Ключевое решение: CUDA без nvcc (NVRTC + Driver API)
|
||||
|
||||
@@ -42,14 +43,14 @@ libnvrtc прописан — бинарники/модуль грузятся
|
||||
## Публичный C++ API ([include/gpr/](include/gpr/))
|
||||
|
||||
```cpp
|
||||
#include "gpr/config.hpp" // GeometryConfig/BPConfig/MotionConfig/SARConfig (дефолты = config.py)
|
||||
#include "gpr/ascan.hpp" // preprocess_snapshot(...) -> AScanSet
|
||||
#include "gpr/sar3d.hpp" // SarEngine::aperture_volume(frames, grid) -> VolumeRaw{acc,cnt}
|
||||
#include "gpr/geometry.hpp" // frame_offsets, frame_weights, build_grid_scene, point_to_scene
|
||||
#include "gpr/config.hpp" // GeometryConfig/BPConfig/MotionConfig/SARConfig (дефолты = ноутбук)
|
||||
#include "gpr/ascan.hpp" // compute_pair_timestamps, preprocess_snapshot(...) -> AScanSet
|
||||
#include "gpr/sar3d.hpp" // SarEngine::aperture_volume -> VolumeRaw; finish_volume -> FinishedVolume
|
||||
#include "gpr/geometry.hpp" // frame_offsets, frame_weights, build_full_region_grid
|
||||
|
||||
gpr::SarEngine engine(geom, bp, mot, sar); // компилит ядро под устройство
|
||||
auto vol = engine.aperture_volume(frames, grid); // один запуск ядра на апертуру
|
||||
// vol.acc / vol.cnt — сырые; финализацию (gaussian/normalize) делает вызывающий
|
||||
auto raw = engine.aperture_volume(frames, grid); // один запуск ядра на апертуру
|
||||
auto fin = gpr::finish_volume(raw, grid, mot.pitch_deg, bp, sar); // объём [0,1] + level
|
||||
```
|
||||
Пример без Python: [examples/standalone_bp.cpp](examples/standalone_bp.cpp) — грузит
|
||||
S21 из `.npy`, строит объём, печатает максимум.
|
||||
@@ -67,16 +68,13 @@ a = _gpr_cpp.preprocess_snapshot(s21, freq, background, mot, geom, bp, True) #
|
||||
acc, cnt = eng.aperture_volume([(a, dx, dy, dz, w), ...], gx, gy, gz) # numpy
|
||||
```
|
||||
|
||||
## Паритет (проверено на x86 T600)
|
||||
## Паритет с ноутбуком (проверено на x86 T600, датасет 20260922_mine_fast_true)
|
||||
|
||||
| Этап | Порог | Факт |
|
||||
|---|---|---|
|
||||
| config дефолты vs dataclass | точно | OK |
|
||||
| A-сканы raw H vs numpy (float64) | <1e-9 | 1.7e-12 |
|
||||
| A-сканы норм. H (FFT-ULP через медиану) | <1e-4 | 2.5e-6 |
|
||||
| **3D объём C++ ядро vs cupy** (float32) | <5e-3 | **3e-7, argmax идентичен** |
|
||||
|
||||
Тесты: [../tests/test_parity_cpp.py](../tests/test_parity_cpp.py) (C++ vs cupy).
|
||||
Кадры 0034/0035/0036 против референсных `*_volume.npz` ноутбука
|
||||
(`make sar3d_parity` + `python_app/scripts/sar3d_volume_compare.py`):
|
||||
max|Δ| ≤ 1.6e-6 вне ножевой границы маски глубины, argmax и level совпадают
|
||||
(level rel ≤ 7e-7). Python-эталон той же цепочки:
|
||||
`python_app/scripts/sar3d_reference_check.py`.
|
||||
|
||||
## Статус
|
||||
|
||||
|
||||
@@ -95,7 +95,20 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
};
|
||||
|
||||
auto ts = compute_pair_timestamps(mot, geom);
|
||||
// Демо без чтения meta.json: равномерные сегменты по интервалу между
|
||||
// соседними снапшотами (реальные per-trace окна читает sar3d_parity).
|
||||
double acq_s = 0.0;
|
||||
{
|
||||
std::vector<double> stamps;
|
||||
for (auto& s : snaps) {
|
||||
auto pos = s.rfind("_ns");
|
||||
if (pos != std::string::npos) stamps.push_back(std::stod(s.substr(pos + 3)) * 1e-9);
|
||||
}
|
||||
std::sort(stamps.begin(), stamps.end());
|
||||
if (stamps.size() >= 2) acq_s = stamps[1] - stamps[0];
|
||||
}
|
||||
auto windows = uniform_tx_windows(geom.output_idx, acq_s, mot.tx_per_segment);
|
||||
auto ts = compute_pair_timestamps(windows, acq_s, geom.output_idx, geom, mot);
|
||||
SarEngine engine(geom, bp, mot, sar);
|
||||
|
||||
// держим AScanSet живыми
|
||||
@@ -122,22 +135,20 @@ int main(int argc, char** argv) {
|
||||
frames.push_back(ApertureFrame{a.get(), offs[f], wts[f]});
|
||||
}
|
||||
|
||||
// центр сетки: под центральным снапшотом на глубине 5.6 м (сцена)
|
||||
auto center_scene = point_to_scene(0.0, 0.0, 5.6, mot, sar);
|
||||
Grid grid = build_grid_scene(center_scene, sar);
|
||||
// полнообластная ground-сетка (как одиночный 3D в ноутбуке)
|
||||
Grid grid = build_full_region_grid(geom, bp, sar, mot.pitch_deg);
|
||||
printf("сетка %dx%dx%d, счёт объёма...\n", grid.NX(), grid.NY(), grid.NZ());
|
||||
|
||||
VolumeRaw vol = engine.aperture_volume(frames, grid);
|
||||
FinishedVolume fin = finish_volume(vol, grid, mot.pitch_deg, bp, sar);
|
||||
|
||||
// финализация: |acc/cnt|, максимум
|
||||
double vmax = 0; size_t amax = 0;
|
||||
for (size_t i = 0; i < vol.acc.size(); ++i) {
|
||||
double v = std::abs(vol.acc[i]) / (vol.cnt[i] + 1e-12);
|
||||
if (v > vmax) { vmax = v; amax = i; }
|
||||
}
|
||||
for (size_t i = 0; i < fin.volume.size(); ++i)
|
||||
if (fin.volume[i] > vmax) { vmax = fin.volume[i]; amax = i; }
|
||||
int NX = vol.NX, NZ = vol.NZ;
|
||||
int ix = amax % NX, iz = (amax / NX) % NZ, iy = amax / ((size_t)NX * NZ);
|
||||
printf("МАКСИМУМ объёма: |acc/cnt|=%.4e в вокселе (ix=%d,iy=%d,iz=%d)\n", vmax, ix, iy, iz);
|
||||
printf("МАКСИМУМ объёма: %.4f (level %.4e) в вокселе (ix=%d,iy=%d,iz=%d)\n",
|
||||
vmax, fin.level, ix, iy, iz);
|
||||
printf(" X=%.1f см, Y=%.1f см, Z=%.1f см\n",
|
||||
grid.x[ix] * 100, grid.y[iy] * 100, grid.z[iz] * 100);
|
||||
printf("OK: автономный C++ путь отработал без Python.\n");
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
// Препроцессинг S21 → комплексные A-сканы (host, float64). Порт preprocess.py.
|
||||
// Препроцессинг S21 → комплексные A-сканы (host, float64).
|
||||
// Порт ячейки 0 Multi_antenna_3D_clean_v1.ipynb (segmented_interleaved тайминг,
|
||||
// frequency-domain коррекция движения, k0-IFFT, нормировка пар).
|
||||
#pragma once
|
||||
#include <map>
|
||||
#include <string>
|
||||
@@ -12,15 +14,34 @@ namespace gpr {
|
||||
|
||||
using PairKey = std::pair<int, int>;
|
||||
|
||||
// Тайминги пары (нужны slot/n_slots/t_center для фазовой коррекции).
|
||||
// Тайминг пары в модели segmented_interleaved: пара живёт в сегменте своего Tx
|
||||
// (окно [segment_start, segment_start+segment_time] от начала акквизиции),
|
||||
// внутри сегмента передатчики чередуются по частоте (slot из n_slots).
|
||||
struct PairTiming {
|
||||
int tx_interleave_slot = 0;
|
||||
int tx_interleave_slots = 1;
|
||||
double t_center_s = 0.0;
|
||||
double segment_start_s = 0.0;
|
||||
double segment_time_s = 0.0;
|
||||
double t_center_s = 0.0; // центр окна сегмента
|
||||
// Грубый межсегментный сдвиг: dtau центра сегмента относительно центра
|
||||
// акквизиции кадра (2*dz/v, dz = dir*speed*dt*cos(look)).
|
||||
double dtau_pair_s = 0.0;
|
||||
};
|
||||
using PairTimestamps = std::map<PairKey, PairTiming>;
|
||||
|
||||
PairTimestamps compute_pair_timestamps(const MotionConfig&, const GeometryConfig&);
|
||||
// Окна захвата по Tx (output_pos → [start,end] сек от начала акквизиции).
|
||||
using TxWindows = std::map<int, std::pair<double, double>>;
|
||||
|
||||
// Fallback без per-trace меток: сегменты по tx_per_segment штук делят кадр
|
||||
// [0, acq_s] поровну (медианная модель ноутбука compute_pair_timestamps).
|
||||
TxWindows uniform_tx_windows(const std::vector<int>& tx_order, double acq_s, int tx_per_segment);
|
||||
|
||||
// Порт compute_pair_timestamps_for_snapshot: Tx с одинаковым окном — один
|
||||
// сегмент (сегменты по возрастанию окна), слот — порядок в tx_order (полный
|
||||
// аппаратный порядок из run.combos; выбранные каналы его не меняют).
|
||||
PairTimestamps compute_pair_timestamps(const TxWindows& tx_windows_s, double acq_s,
|
||||
const std::vector<int>& tx_order,
|
||||
const GeometryConfig&, const MotionConfig&);
|
||||
|
||||
// A-сканы одного снапшота, общая ось времени у всех пар (assert).
|
||||
struct AScanSet {
|
||||
@@ -32,7 +53,7 @@ struct AScanSet {
|
||||
const c128* pair_ptr(int p) const { return H.data() + (size_t)p * n_fft; }
|
||||
};
|
||||
|
||||
// Порт compute_pair_ascans: bg-subtract → phase correction → k0-IFFT → норма.
|
||||
// Порт sar_pair_ascans: bg-subtract → phase correction → k0-IFFT → норма.
|
||||
// s21/freq/background — по ключам (i_tx,i_rx); background может быть nullptr.
|
||||
AScanSet preprocess_snapshot(
|
||||
const std::map<PairKey, std::vector<c128>>& s21,
|
||||
@@ -42,10 +63,12 @@ AScanSet preprocess_snapshot(
|
||||
const PairTimestamps&, bool normalize = true);
|
||||
|
||||
// Отдельные шаги (для тестов/переиспользования):
|
||||
// Полная фазовая модель движения до IFFT: dtau_intra(f) + dtau_pair одной
|
||||
// фазой exp(sign*j*2*pi*f*dtau_total) (порт apply_intra_sweep_phase_correction).
|
||||
std::vector<c128> apply_intra_sweep_phase_correction(
|
||||
const std::vector<c128>& s21, const std::vector<double>& freq_full,
|
||||
const PairTiming&, const MotionConfig&, double wave_speed,
|
||||
double f_start, double f_stop, int n_slots_default);
|
||||
double f_start, double f_stop);
|
||||
|
||||
// Возвращает t (ось), h (комплексный A-скан). n_fft через out-параметр.
|
||||
void compute_ascan_bp(const std::vector<c128>& s21, const std::vector<double>& freq,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Конфигурация счёт-ядра. Дефолты 1:1 повторяют gpr_core/config.py.
|
||||
// Конфигурация счёт-ядра. Дефолты 1:1 повторяют Multi_antenna_3D_clean_v1.ipynb
|
||||
// (ячейки 0 и 4) — эталонный ноутбук 3D SAR.
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -11,13 +12,13 @@ namespace gpr {
|
||||
|
||||
struct GeometryConfig {
|
||||
std::vector<int> input_idx{0, 1, 2, 3};
|
||||
std::vector<int> output_idx{0, 1};
|
||||
// (x,y,z) метры; порядок по физическим индексам как в config.py
|
||||
std::vector<std::array<double, 3>> tx_positions{{0.785, 0.0, 0.0}, {-0.785, 0.0, 0.0}};
|
||||
std::vector<int> output_idx{0, 1, 2, 3};
|
||||
// (x,y,z) метры; порядок соответствует input_idx/output_idx
|
||||
std::vector<std::array<double, 3>> tx_positions{
|
||||
{-0.88, 0.0, 0.0}, {0.89, 0.0, 0.0}, {-0.33, 0.445, 0.0}, {0.33, 0.445, 0.0}};
|
||||
std::vector<std::array<double, 3>> rx_positions{
|
||||
{-0.42, 0.0, 0.0}, {0.48, 0.0, 0.0}, {0.18, 0.0, 0.0}, {-0.12, 0.0, 0.0}};
|
||||
{0.23, 0.0, 0.0}, {0.54, 0.15, 0.0}, {-0.55, 0.3, 0.0}, {-0.23, 0.0, 0.0}};
|
||||
double eps_r = 1.0;
|
||||
double bp_plane_y = 0.0;
|
||||
|
||||
// --- производные (заполняются finalize) ---
|
||||
std::vector<double> x_tx, y_tx, z_tx; // отсортированы по phys-индексу
|
||||
@@ -50,53 +51,61 @@ struct GeometryConfig {
|
||||
};
|
||||
|
||||
struct BPConfig {
|
||||
double f_start = 20 * 1e8; // 2 ГГц
|
||||
double f_start = 2.0e9;
|
||||
double f_stop = 6.0e9;
|
||||
double min_depth = 3.2;
|
||||
double max_depth = 10.0;
|
||||
double grid_x_pad = 2.0;
|
||||
double z_min = 0.1;
|
||||
int nx = 300;
|
||||
int nz = 300;
|
||||
double min_depth = 2.5;
|
||||
double max_depth = 8.0;
|
||||
int oversample = 8;
|
||||
bool window = true;
|
||||
bool window = true; // окно Ханна на полосе
|
||||
bool pair_normalize = true;
|
||||
double pair_norm_percentile = 50.0;
|
||||
double pair_norm_depth_min = 3.2;
|
||||
double pair_norm_depth_max = 10.0;
|
||||
double pair_norm_depth_min = 2.5;
|
||||
double pair_norm_depth_max = 8.0;
|
||||
double pair_norm_eps = 1e-15;
|
||||
double comp_range_power = 0.25;
|
||||
// Компенсация геометрического расхождения 1/(Rtx*Rrx), нормированная на
|
||||
// точку под виртуальным центром пары на глубине comp_ref_depth НА ПЛОСКОСТИ
|
||||
// ЗЕМЛИ (высота (-ground_depth + d*sin p)/cos p).
|
||||
double comp_range_power = 0.3;
|
||||
double comp_weight_max = 5.0;
|
||||
double comp_ref_depth = 5.0;
|
||||
double smooth_sigma = 1.5;
|
||||
bool bg_subtract = true;
|
||||
double cf_eps = 1e-12;
|
||||
};
|
||||
|
||||
struct MotionConfig {
|
||||
double speed_m_s = 0.854;
|
||||
double look_angle_deg = 6.0;
|
||||
double pitch_deg = 6.0;
|
||||
double tx_sweep_time_s = 0.079;
|
||||
double tx_switch_time_s = 1e-5;
|
||||
// frequency_timing_mode всегда interleaved_tx_by_frequency
|
||||
double speed_m_s = 1.45;
|
||||
double look_angle_deg = 17.5;
|
||||
// Наклон рамы для ground-координат и смещений кадров; в ноутбуке
|
||||
// BP_GROUND_PITCH_DEG=None означает «равен look_angle».
|
||||
double pitch_deg = 17.5;
|
||||
double direction_sign = +1.0;
|
||||
// Внутрисвиповая (по частоте) фазовая коррекция движения.
|
||||
bool apply_freq_phase_correction = true;
|
||||
// Грубая межсегментная коррекция (dtau сегмента относительно центра кадра),
|
||||
// вносится той же фазовой моделью до IFFT (режим 'frequency_domain').
|
||||
bool apply_pair_motion_correction = true;
|
||||
double motion_phase_sign = -1.0;
|
||||
|
||||
double frame_time_s(int n_tx) const {
|
||||
return n_tx * tx_sweep_time_s + std::max(0, n_tx - 1) * tx_switch_time_s;
|
||||
}
|
||||
// Fallback-разбиение кадра на сегменты, когда per-trace меток захвата нет.
|
||||
int tx_per_segment = 2;
|
||||
};
|
||||
|
||||
struct SARConfig {
|
||||
int frame_radius = 6;
|
||||
double edge_frame_weight = 0.75;
|
||||
std::array<double, 3> half_width_m{1.8, 1.0, 1.8};
|
||||
std::array<int, 3> grid{150, 120, 160}; // NX, NY, NZ
|
||||
bool coord_mode_ground = true; // 'ground' vs 'radar_local'
|
||||
int frame_radius = 0; // 0 = один снимок (физическая вертикальная база)
|
||||
double edge_frame_weight = 0.8; // вес крайнего кадра апертуры
|
||||
bool coord_mode_ground = true; // 'ground' vs 'radar_local'
|
||||
bool use_compensation = true;
|
||||
bool normalize_each_frame = true;
|
||||
// Высота НИЖНЕГО ряда антенн над землёй; Y=0 сцены — поверхность земли.
|
||||
double ground_depth_m = 1.25;
|
||||
// Полнообластная сетка: X — размах антенн ±x_margin_m, Y — высота над
|
||||
// землёй, Z — полоса, покрывающая радарные глубины [min,max]_depth на всех
|
||||
// высотах Y (см. build_full_region_grid).
|
||||
double x_margin_m = 2.0;
|
||||
double y_min_m = -0.5;
|
||||
double y_max_m = 2.0;
|
||||
std::array<double, 3> voxel_m{0.025, 0.02, 0.02}; // шаг (X, Y, Z)
|
||||
// Финализация объёма: нормировка без верхних/нижних norm_edge_margin_m по Y
|
||||
// (там ложный гребень постоянной дальности), сглаживание по (Z,X) в каждом
|
||||
// Y-плане.
|
||||
double norm_edge_margin_m = 0.3;
|
||||
double smooth_sigma = 1.5;
|
||||
};
|
||||
|
||||
} // namespace gpr
|
||||
|
||||
@@ -18,10 +18,18 @@ std::vector<FrameOffset> frame_offsets(const std::vector<double>& frame_times, d
|
||||
// Косинусные веса апертуры (порт sar_frame_weights); dt берётся относительно центра.
|
||||
std::vector<double> frame_weights(const std::vector<FrameOffset>& offsets, double edge_weight);
|
||||
|
||||
// Сетка вокруг точки сцены (порт sar_build_grid_scene).
|
||||
Grid build_grid_scene(const std::array<double, 3>& center_scene, const SARConfig&);
|
||||
// Высота плоскости земли (радарные оси) на радарной глубине depth:
|
||||
// y = (-ground_depth + depth*sin(pitch)) / cos(pitch) (порт bp_plane_y).
|
||||
double ground_plane_y(double depth, double ground_depth_m, double pitch_rad);
|
||||
|
||||
// point_to_scene: оси радара → сцена (поворот на pitch, если ground).
|
||||
// Полнообластная сетка сцены (порт sar_build_full_region_grid):
|
||||
// X — размах антенн ±x_margin, Y — [y_min, y_max] над землёй, Z — полоса,
|
||||
// покрывающая радарные глубины [min_depth, max_depth] на всех высотах Y.
|
||||
Grid build_full_region_grid(const GeometryConfig&, const BPConfig&, const SARConfig&,
|
||||
double pitch_deg);
|
||||
|
||||
// point_to_scene: оси радара → сцена (поворот на pitch + подъём на ground_depth,
|
||||
// если ground; Y=0 сцены — земля).
|
||||
std::array<double, 3> point_to_scene(double x, double y, double z, const MotionConfig&,
|
||||
const SARConfig&);
|
||||
|
||||
|
||||
@@ -19,13 +19,24 @@ struct ApertureFrame {
|
||||
double weight;
|
||||
};
|
||||
|
||||
// Сырой результат объёма (Python делает finish: abs+gate+gaussian+normalize).
|
||||
// Сырой результат объёма (до finish_volume).
|
||||
struct VolumeRaw {
|
||||
std::vector<c64> acc; // [NY*NZ*NX]
|
||||
std::vector<float> cnt; // [NY*NZ*NX]
|
||||
int NX = 0, NY = 0, NZ = 0;
|
||||
};
|
||||
|
||||
// Финальный объём (порт sar_finish_volume): |acc/cnt| → маска глубины →
|
||||
// нормировка по Y-планам без краёв → гаусс по (Z,X) → нормировка → clip.
|
||||
struct FinishedVolume {
|
||||
std::vector<float> volume; // [NY*NZ*NX], нормирован на ~[0,1]
|
||||
double level = 0.0; // масштаб, на который поделён объём
|
||||
int NX = 0, NY = 0, NZ = 0;
|
||||
};
|
||||
|
||||
FinishedVolume finish_volume(const VolumeRaw&, const Grid&, double pitch_deg,
|
||||
const BPConfig&, const SARConfig&);
|
||||
|
||||
class SarEngine {
|
||||
public:
|
||||
SarEngine(const GeometryConfig&, const BPConfig&, const MotionConfig&, const SARConfig&);
|
||||
|
||||
@@ -9,19 +9,69 @@
|
||||
|
||||
namespace gpr {
|
||||
|
||||
PairTimestamps compute_pair_timestamps(const MotionConfig& mot, const GeometryConfig& geom) {
|
||||
// interleaved_tx_by_frequency: слот Tx = порядок в отсортированном output_idx.
|
||||
std::vector<int> tx = geom.output_idx, rx = geom.input_idx;
|
||||
std::sort(tx.begin(), tx.end());
|
||||
std::sort(rx.begin(), rx.end());
|
||||
int n_slots = (int)tx.size();
|
||||
double frame_center = 0.5 * n_slots * mot.tx_sweep_time_s;
|
||||
TxWindows uniform_tx_windows(const std::vector<int>& tx_order, double acq_s, int tx_per_segment) {
|
||||
TxWindows windows;
|
||||
if (tx_order.empty()) return windows;
|
||||
int per_seg = std::max(1, tx_per_segment);
|
||||
int n_seg = std::max(1, (int)((tx_order.size() + per_seg - 1) / per_seg));
|
||||
double t_seg = acq_s / n_seg;
|
||||
for (size_t k = 0; k < tx_order.size(); ++k) {
|
||||
int seg = (int)k / per_seg;
|
||||
windows[tx_order[k]] = {seg * t_seg, seg * t_seg + t_seg};
|
||||
}
|
||||
return windows;
|
||||
}
|
||||
|
||||
PairTimestamps compute_pair_timestamps(const TxWindows& tx_windows_s, double acq_s,
|
||||
const std::vector<int>& tx_order,
|
||||
const GeometryConfig& geom, const MotionConfig& mot) {
|
||||
// Аппаратный порядок: сперва tx_order (run.combos), затем прочие ключи окон.
|
||||
std::vector<int> hw_order;
|
||||
for (int tx : tx_order)
|
||||
if (tx_windows_s.count(tx) && std::find(hw_order.begin(), hw_order.end(), tx) == hw_order.end())
|
||||
hw_order.push_back(tx);
|
||||
for (auto& [tx, _] : tx_windows_s)
|
||||
if (std::find(hw_order.begin(), hw_order.end(), tx) == hw_order.end())
|
||||
hw_order.push_back(tx);
|
||||
|
||||
// Tx с одинаковым окном — один сегмент; сегменты по возрастанию окна,
|
||||
// слот — порядок появления в hw_order (порт группировки ноутбука).
|
||||
std::vector<std::pair<std::pair<double, double>, std::vector<int>>> groups;
|
||||
for (int tx : hw_order) {
|
||||
auto win = tx_windows_s.at(tx);
|
||||
auto found = std::find_if(groups.begin(), groups.end(),
|
||||
[&](const auto& g) { return g.first == win; });
|
||||
if (found == groups.end())
|
||||
groups.push_back({win, {tx}});
|
||||
else
|
||||
found->second.push_back(tx);
|
||||
}
|
||||
std::sort(groups.begin(), groups.end(),
|
||||
[](const auto& a, const auto& b) { return a.first < b.first; });
|
||||
|
||||
struct SegSlot { double t0, t1; int slot, n_slots; };
|
||||
std::map<int, SegSlot> seg_of;
|
||||
for (auto& [win, txs] : groups)
|
||||
for (size_t slot = 0; slot < txs.size(); ++slot)
|
||||
seg_of[txs[slot]] = {win.first, win.second, (int)slot, (int)txs.size()};
|
||||
|
||||
double cos_theta = std::cos(mot.look_angle_deg * M_PI / 180.0);
|
||||
double t_ref = 0.5 * acq_s;
|
||||
PairTimestamps ts;
|
||||
for (int slot = 0; slot < (int)tx.size(); ++slot) {
|
||||
int i_tx = slot; // индекс в отсортированном == логический
|
||||
for (int j = 0; j < (int)rx.size(); ++j) {
|
||||
ts[{i_tx, j}] = PairTiming{slot, n_slots, frame_center};
|
||||
}
|
||||
for (int i = 0; i < geom.n_tx; ++i) {
|
||||
auto it = seg_of.find(geom.output_idx[i]);
|
||||
if (it == seg_of.end())
|
||||
throw std::runtime_error("pair timestamps: нет окна для Tx");
|
||||
const SegSlot& s = it->second;
|
||||
PairTiming timing;
|
||||
timing.tx_interleave_slot = s.slot;
|
||||
timing.tx_interleave_slots = s.n_slots;
|
||||
timing.segment_start_s = s.t0;
|
||||
timing.segment_time_s = s.t1 - s.t0;
|
||||
timing.t_center_s = 0.5 * (s.t0 + s.t1);
|
||||
double dz = mot.direction_sign * mot.speed_m_s * (timing.t_center_s - t_ref) * cos_theta;
|
||||
timing.dtau_pair_s = 2.0 * dz / geom.v;
|
||||
for (int j = 0; j < geom.n_rx; ++j) ts[{i, j}] = timing;
|
||||
}
|
||||
return ts;
|
||||
}
|
||||
@@ -37,7 +87,7 @@ static double median_of_diff(const std::vector<double>& f) {
|
||||
std::vector<c128> apply_intra_sweep_phase_correction(
|
||||
const std::vector<c128>& s21, const std::vector<double>& freq_full,
|
||||
const PairTiming& info, const MotionConfig& cfg, double wave_speed,
|
||||
double f_start, double f_stop, int n_slots_default) {
|
||||
double f_start, double f_stop) {
|
||||
std::vector<c128> out = s21;
|
||||
int n_full = (int)freq_full.size();
|
||||
// индексы в полосе
|
||||
@@ -47,21 +97,23 @@ std::vector<c128> apply_intra_sweep_phase_correction(
|
||||
if (idx.empty()) throw std::runtime_error("phase corr: пустая полоса");
|
||||
if (n_full < 2) return out;
|
||||
|
||||
int n_slots = info.tx_interleave_slots ? info.tx_interleave_slots : n_slots_default;
|
||||
// Сегмент проходит все n_full частот за своё окно; на каждой частоте по
|
||||
// очереди работают его n_slots передатчиков, поэтому событие частоты i для
|
||||
// слота slot имеет номер (n_slots*i + slot) из (n_slots*n_full).
|
||||
int n_slots = std::max(1, info.tx_interleave_slots);
|
||||
int slot = info.tx_interleave_slot;
|
||||
double dt_base = cfg.tx_sweep_time_s / (n_full - 1);
|
||||
// t_all по всему свипу; t_center — середина ПОЛНОГО свипа (как в preprocess.py)
|
||||
double t_first = (double)(n_slots * 0 + slot) * dt_base;
|
||||
double t_last = (double)(n_slots * (n_full - 1) + slot) * dt_base;
|
||||
double t_center = 0.5 * (t_first + t_last);
|
||||
double theta = cfg.look_angle_deg * M_PI / 180.0;
|
||||
if (!cfg.apply_freq_phase_correction) return out;
|
||||
double dt_event = info.segment_time_s / ((double)n_slots * n_full);
|
||||
double cos_theta = std::cos(cfg.look_angle_deg * M_PI / 180.0);
|
||||
double pair_dtau = cfg.apply_pair_motion_correction ? info.dtau_pair_s : 0.0;
|
||||
if (!cfg.apply_freq_phase_correction && pair_dtau == 0.0) return out;
|
||||
for (int i : idx) {
|
||||
double t_abs = (double)(n_slots * i + slot) * dt_base;
|
||||
double dt_intra = t_abs - t_center;
|
||||
double delta_range = cfg.direction_sign * cfg.speed_m_s * std::cos(theta) * dt_intra;
|
||||
double dtau = 2.0 * delta_range / wave_speed;
|
||||
double phi = 2.0 * M_PI * freq_full[i] * dtau;
|
||||
double dtau_intra = 0.0;
|
||||
if (cfg.apply_freq_phase_correction) {
|
||||
double t_abs = info.segment_start_s + (double)(n_slots * i + slot) * dt_event;
|
||||
double dt_intra = t_abs - info.t_center_s;
|
||||
dtau_intra = 2.0 * cfg.direction_sign * cfg.speed_m_s * cos_theta * dt_intra / wave_speed;
|
||||
}
|
||||
double phi = 2.0 * M_PI * freq_full[i] * (dtau_intra + pair_dtau);
|
||||
double ang = cfg.motion_phase_sign * phi;
|
||||
out[i] *= c128(std::cos(ang), std::sin(ang));
|
||||
}
|
||||
@@ -163,7 +215,7 @@ AScanSet preprocess_snapshot(
|
||||
auto itt = ts.find(key);
|
||||
if (itt != ts.end())
|
||||
s = apply_intra_sweep_phase_correction(s, fr, itt->second, mot, geom.v,
|
||||
bp.f_start, bp.f_stop, geom.n_tx);
|
||||
bp.f_start, bp.f_stop);
|
||||
std::vector<double> t;
|
||||
std::vector<c128> h;
|
||||
compute_ascan_bp(s, fr, bp.f_start, bp.f_stop, bp.window, bp.oversample, t, h);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "gpr/geometry.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace gpr {
|
||||
@@ -48,20 +49,53 @@ std::array<double, 3> point_to_scene(double x, double y, double z, const MotionC
|
||||
const SARConfig& sar) {
|
||||
if (!sar.coord_mode_ground) return {x, y, z};
|
||||
double p = mot.pitch_deg * M_PI / 180.0;
|
||||
double ys = y * std::cos(p) - z * std::sin(p);
|
||||
double ys = y * std::cos(p) - z * std::sin(p) + sar.ground_depth_m;
|
||||
double zs = y * std::sin(p) + z * std::cos(p);
|
||||
return {x, ys, zs};
|
||||
}
|
||||
|
||||
Grid build_grid_scene(const std::array<double, 3>& c, const SARConfig& sar) {
|
||||
Grid g;
|
||||
auto lin = [](double a, double b, int n, std::vector<double>& out) {
|
||||
double ground_plane_y(double depth, double ground_depth_m, double pitch_rad) {
|
||||
return (-ground_depth_m + depth * std::sin(pitch_rad)) / std::cos(pitch_rad);
|
||||
}
|
||||
|
||||
Grid build_full_region_grid(const GeometryConfig& geom, const BPConfig& bp, const SARConfig& sar,
|
||||
double pitch_deg) {
|
||||
// numpy: linspace(lo, hi, max(round(span/step)+1, 2)); nearbyint = банковское
|
||||
// округление python round()
|
||||
auto axis = [](double lo, double hi, double step, std::vector<double>& out) {
|
||||
int n = std::max((int)std::nearbyint((hi - lo) / step) + 1, 2);
|
||||
out.resize(n);
|
||||
for (int i = 0; i < n; ++i) out[i] = a + (b - a) * i / (double)(n - 1);
|
||||
for (int i = 0; i < n; ++i) out[i] = lo + (hi - lo) * i / (double)(n - 1);
|
||||
};
|
||||
lin(c[0] - sar.half_width_m[0], c[0] + sar.half_width_m[0], sar.grid[0], g.x);
|
||||
lin(c[1] - sar.half_width_m[1], c[1] + sar.half_width_m[1], sar.grid[1], g.y);
|
||||
lin(c[2] - sar.half_width_m[2], c[2] + sar.half_width_m[2], sar.grid[2], g.z);
|
||||
double x_lo = geom.x_tx[0], x_hi = geom.x_tx[0];
|
||||
for (double x : geom.x_tx) { x_lo = std::min(x_lo, x); x_hi = std::max(x_hi, x); }
|
||||
for (double x : geom.x_rx) { x_lo = std::min(x_lo, x); x_hi = std::max(x_hi, x); }
|
||||
x_lo -= sar.x_margin_m;
|
||||
x_hi += sar.x_margin_m;
|
||||
|
||||
Grid g;
|
||||
axis(x_lo, x_hi, sar.voxel_m[0], g.x);
|
||||
axis(sar.y_min_m, sar.y_max_m, sar.voxel_m[1], g.y);
|
||||
if (sar.coord_mode_ground) {
|
||||
// Радарная z линейна по Z сцены при фиксированной высоте:
|
||||
// z_rad(Y, Z=0) = -(Y - ground_depth)*sin(p), z = (depth - z_rad)/cos(p).
|
||||
double p = pitch_deg * M_PI / 180.0;
|
||||
double cos_p = std::cos(p), sin_p = std::sin(p);
|
||||
double z_lo = 0.0, z_hi = 0.0;
|
||||
bool first = true;
|
||||
for (double y : {sar.y_min_m, sar.y_max_m}) {
|
||||
for (double depth : {bp.min_depth, bp.max_depth}) {
|
||||
double z_rad0 = -(y - sar.ground_depth_m) * sin_p;
|
||||
double z = (depth - z_rad0) / cos_p;
|
||||
if (first) { z_lo = z_hi = z; first = false; }
|
||||
z_lo = std::min(z_lo, z);
|
||||
z_hi = std::max(z_hi, z);
|
||||
}
|
||||
}
|
||||
axis(z_lo, z_hi, sar.voxel_m[2], g.z);
|
||||
} else {
|
||||
axis(bp.min_depth, bp.max_depth, sar.voxel_m[2], g.z);
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,28 +1,30 @@
|
||||
// Исходник CUDA-ядра для NVRTC (порт bp_aperture_contribution из gpr_core/kernels.py).
|
||||
// Self-contained complex<float> (без cupy-заголовков).
|
||||
// Исходник CUDA-ядра для NVRTC (порт sar_frame_contribution из
|
||||
// Multi_antenna_3D_clean_v1.ipynb). Self-contained complex<float>.
|
||||
//
|
||||
// Геометрия (координаты, дальности, tau, вес компенсации) считается в double:
|
||||
// эталон ноутбука — float64, а в float32 позиция выборки A-скана (тысячи
|
||||
// отсчётов) теряет ~3e-4 отсчёта и расходится с эталоном на ~1e-4. A-сканы
|
||||
// остаются float32 — их значения O(1) и линейная интерполяция не теряет.
|
||||
#pragma once
|
||||
|
||||
namespace gpr {
|
||||
|
||||
inline const char* APERTURE_KERNEL_SRC = R"CUDA(
|
||||
struct cf { float x, y; };
|
||||
__device__ __forceinline__ cf operator+(cf a, cf b){ return {a.x+b.x, a.y+b.y}; }
|
||||
__device__ __forceinline__ cf operator-(cf a, cf b){ return {a.x-b.x, a.y-b.y}; }
|
||||
__device__ __forceinline__ cf operator*(float s, cf a){ return {s*a.x, s*a.y}; }
|
||||
|
||||
// Весь взвешенный объём апертуры за один запуск: один поток на воксель,
|
||||
// внутренний цикл по n_contrib = n_frames*n_pairs. acc/cnt пишутся один раз.
|
||||
extern "C" __global__ void bp_aperture_contribution(
|
||||
const cf* __restrict__ H,
|
||||
const float t0, const float inv_dt, const int n_fft, const float inv_v,
|
||||
const float* __restrict__ xt, const float* __restrict__ yt, const float* __restrict__ zt,
|
||||
const float* __restrict__ xr, const float* __restrict__ yr, const float* __restrict__ zr,
|
||||
const float* __restrict__ inv_geo_ref, const float* __restrict__ wgt,
|
||||
const float* __restrict__ gx, const float* __restrict__ gy, const float* __restrict__ gz,
|
||||
const double t0, const double inv_dt, const int n_fft, const double inv_v,
|
||||
const double* __restrict__ xt, const double* __restrict__ yt, const double* __restrict__ zt,
|
||||
const double* __restrict__ xr, const double* __restrict__ yr, const double* __restrict__ zr,
|
||||
const double* __restrict__ inv_geo_ref, const float* __restrict__ wgt,
|
||||
const double* __restrict__ gx, const double* __restrict__ gy, const double* __restrict__ gz,
|
||||
const int NX, const int NY, const int NZ, const int n_contrib,
|
||||
const float cos_p, const float sin_p,
|
||||
const float min_depth, const float max_depth,
|
||||
const float comp_pow, const float w_max, const int use_comp,
|
||||
const double cos_p, const double sin_p, const double ground_depth,
|
||||
const double min_depth, const double max_depth,
|
||||
const double comp_pow, const double w_max, const int use_comp,
|
||||
cf* __restrict__ acc, float* __restrict__ cnt)
|
||||
{
|
||||
const long total = (long)NX * NY * NZ;
|
||||
@@ -31,39 +33,45 @@ extern "C" __global__ void bp_aperture_contribution(
|
||||
int ix = gid % NX;
|
||||
int iz = (gid / NX) % NZ;
|
||||
int iy = gid / ((long)NX * NZ);
|
||||
float x = gx[ix];
|
||||
float ys = gy[iy], zs = gz[iz];
|
||||
float y_rad = ys * cos_p + zs * sin_p;
|
||||
float z_rad = -ys * sin_p + zs * cos_p;
|
||||
double x = gx[ix];
|
||||
double zs = gz[iz];
|
||||
// Сцена → оси радара: Y=0 сцены — земля, ground_depth ниже нижнего ряда
|
||||
// антенн (порт sar_scene_to_radar_yz).
|
||||
double y0 = gy[iy] - ground_depth;
|
||||
double y_rad = y0 * cos_p + zs * sin_p;
|
||||
double z_rad = -y0 * sin_p + zs * cos_p;
|
||||
bool depth_ok = (z_rad >= min_depth) && (z_rad <= max_depth);
|
||||
|
||||
cf a = {0.f, 0.f};
|
||||
double ax = 0.0, ay = 0.0;
|
||||
float c = 0.f;
|
||||
for (int i = 0; i < n_contrib; ++i) {
|
||||
float w = wgt[i];
|
||||
float dxt = x - xt[i], dyt = y_rad - yt[i], dzt = z_rad - zt[i];
|
||||
float dxr = x - xr[i], dyr = y_rad - yr[i], dzr = z_rad - zr[i];
|
||||
float Rt = sqrtf(dxt*dxt + dyt*dyt + dzt*dzt);
|
||||
float Rr = sqrtf(dxr*dxr + dyr*dyr + dzr*dzr);
|
||||
float pos = ((Rt + Rr) * inv_v - t0) * inv_dt;
|
||||
bool inside = (pos >= 0.f) && (pos <= (float)(n_fft - 1));
|
||||
if (!inside) continue;
|
||||
int k = (int)floorf(pos);
|
||||
double dxt = x - xt[i], dyt = y_rad - yt[i], dzt = z_rad - zt[i];
|
||||
double dxr = x - xr[i], dyr = y_rad - yr[i], dzr = z_rad - zr[i];
|
||||
double Rt = sqrt(dxt*dxt + dyt*dyt + dzt*dzt);
|
||||
double Rr = sqrt(dxr*dxr + dyr*dyr + dzr*dzr);
|
||||
double pos = ((Rt + Rr) * inv_v - t0) * inv_dt;
|
||||
bool inside = (pos >= 0.0) && (pos <= (double)(n_fft - 1));
|
||||
if (!inside || !depth_ok) continue;
|
||||
int k = (int)floor(pos);
|
||||
if (k < 0) k = 0;
|
||||
if (k > n_fft - 2) k = n_fft - 2;
|
||||
float f = pos - (float)k;
|
||||
float f = (float)(pos - (double)k);
|
||||
const cf* h = H + (long)i * n_fft;
|
||||
cf hv = h[k] + f * (h[k+1] - h[k]);
|
||||
float hx = h[k].x + f * (h[k+1].x - h[k].x);
|
||||
float hy = h[k].y + f * (h[k+1].y - h[k].y);
|
||||
double w = (double)wgt[i];
|
||||
if (use_comp) {
|
||||
float ratio = (1.f/(Rt*Rr + 1e-12f) + 1e-30f) * inv_geo_ref[i];
|
||||
float denom = (comp_pow == 0.25f) ? sqrtf(sqrtf(ratio)) : powf(ratio, comp_pow);
|
||||
float ww = 1.f/(denom + 1e-12f);
|
||||
ww = fminf(fmaxf(ww, 0.f), w_max);
|
||||
hv = ww * hv;
|
||||
double ratio = (1.0/(Rt*Rr + 1e-12) + 1e-30) * inv_geo_ref[i];
|
||||
double ww = 1.0/(pow(ratio, comp_pow) + 1e-12);
|
||||
ww = fmin(fmax(ww, 0.0), w_max);
|
||||
w *= ww;
|
||||
}
|
||||
if (depth_ok) { a = a + (w * hv); c += w; }
|
||||
ax += w * (double)hx;
|
||||
ay += w * (double)hy;
|
||||
c += wgt[i];
|
||||
}
|
||||
acc[gid] = a;
|
||||
acc[gid].x = (float)ax;
|
||||
acc[gid].y = (float)ay;
|
||||
cnt[gid] = c;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,11 +31,18 @@ VolumeRaw SarEngine::aperture_volume(const std::vector<ApertureFrame>& frames, c
|
||||
int NX = grid.NX(), NY = grid.NY(), NZ = grid.NZ();
|
||||
size_t nvox = (size_t)NX * NY * NZ;
|
||||
|
||||
double pitch = mot_.pitch_deg * M_PI / 180.0;
|
||||
// Опорное расхождение пары — на плоскости земли на глубине comp_ref_depth.
|
||||
double geo_ref_y = sar_.coord_mode_ground
|
||||
? ground_plane_y(bp_.comp_ref_depth, sar_.ground_depth_m, pitch)
|
||||
: 0.0;
|
||||
|
||||
// Плоские массивы по (кадр, пара)
|
||||
std::vector<c64> H_stack((size_t)n_contrib * n_fft);
|
||||
std::vector<float> xt(n_contrib), yt(n_contrib), zt(n_contrib);
|
||||
std::vector<float> xr(n_contrib), yr(n_contrib), zr(n_contrib);
|
||||
std::vector<float> igr(n_contrib), wgt(n_contrib);
|
||||
std::vector<double> xt(n_contrib), yt(n_contrib), zt(n_contrib);
|
||||
std::vector<double> xr(n_contrib), yr(n_contrib), zr(n_contrib);
|
||||
std::vector<double> igr(n_contrib);
|
||||
std::vector<float> wgt(n_contrib);
|
||||
int idx = 0;
|
||||
for (int f = 0; f < n_frames; ++f) {
|
||||
const AScanSet& a = *frames[f].ascans;
|
||||
@@ -49,49 +56,47 @@ VolumeRaw SarEngine::aperture_volume(const std::vector<ApertureFrame>& frames, c
|
||||
const c128* src = a.pair_ptr(p);
|
||||
c64* dst = H_stack.data() + (size_t)idx * n_fft;
|
||||
for (int k = 0; k < n_fft; ++k) dst[k] = c64((float)src[k].real(), (float)src[k].imag());
|
||||
xt[idx] = (float)(geom_.x_tx[i] + dx); yt[idx] = (float)(geom_.y_tx[i] + dy);
|
||||
zt[idx] = (float)(geom_.z_tx[i] + dz);
|
||||
xr[idx] = (float)(geom_.x_rx[j] + dx); yr[idx] = (float)(geom_.y_rx[j] + dy);
|
||||
zr[idx] = (float)(geom_.z_rx[j] + dz);
|
||||
igr[idx] = (float)(1.0 / pair_geo_ref(geom_, bp_, i, j, geom_.bp_plane_y));
|
||||
xt[idx] = geom_.x_tx[i] + dx; yt[idx] = geom_.y_tx[i] + dy;
|
||||
zt[idx] = geom_.z_tx[i] + dz;
|
||||
xr[idx] = geom_.x_rx[j] + dx; yr[idx] = geom_.y_rx[j] + dy;
|
||||
zr[idx] = geom_.z_rx[j] + dz;
|
||||
igr[idx] = 1.0 / pair_geo_ref(geom_, bp_, i, j, geo_ref_y);
|
||||
wgt[idx] = w;
|
||||
++idx;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<float> gx(grid.x.begin(), grid.x.end());
|
||||
std::vector<float> gy(grid.y.begin(), grid.y.end());
|
||||
std::vector<float> gz(grid.z.begin(), grid.z.end());
|
||||
|
||||
float cos_p = 1.f, sin_p = 0.f;
|
||||
double cos_p = 1.0, sin_p = 0.0, ground_depth = 0.0;
|
||||
if (sar_.coord_mode_ground) {
|
||||
double p = mot_.pitch_deg * M_PI / 180.0;
|
||||
cos_p = (float)std::cos(p); sin_p = (float)std::sin(p);
|
||||
cos_p = std::cos(pitch);
|
||||
sin_p = std::sin(pitch);
|
||||
ground_depth = sar_.ground_depth_m;
|
||||
}
|
||||
|
||||
// Заливка на устройство
|
||||
DeviceBuffer<c64> dH(H_stack.size()); dH.upload(H_stack.data(), H_stack.size());
|
||||
DeviceBuffer<float> dxt(n_contrib), dyt(n_contrib), dzt(n_contrib);
|
||||
DeviceBuffer<float> dxr(n_contrib), dyr(n_contrib), dzr(n_contrib);
|
||||
DeviceBuffer<float> digr(n_contrib), dwgt(n_contrib);
|
||||
DeviceBuffer<double> dxt(n_contrib), dyt(n_contrib), dzt(n_contrib);
|
||||
DeviceBuffer<double> dxr(n_contrib), dyr(n_contrib), dzr(n_contrib);
|
||||
DeviceBuffer<double> digr(n_contrib);
|
||||
DeviceBuffer<float> dwgt(n_contrib);
|
||||
dxt.upload(xt.data(), n_contrib); dyt.upload(yt.data(), n_contrib); dzt.upload(zt.data(), n_contrib);
|
||||
dxr.upload(xr.data(), n_contrib); dyr.upload(yr.data(), n_contrib); dzr.upload(zr.data(), n_contrib);
|
||||
digr.upload(igr.data(), n_contrib); dwgt.upload(wgt.data(), n_contrib);
|
||||
DeviceBuffer<float> dgx(NX), dgy(NY), dgz(NZ);
|
||||
dgx.upload(gx.data(), NX); dgy.upload(gy.data(), NY); dgz.upload(gz.data(), NZ);
|
||||
DeviceBuffer<double> dgx(NX), dgy(NY), dgz(NZ);
|
||||
dgx.upload(grid.x.data(), NX); dgy.upload(grid.y.data(), NY); dgz.upload(grid.z.data(), NZ);
|
||||
DeviceBuffer<c64> dacc(nvox);
|
||||
DeviceBuffer<float> dcnt(nvox);
|
||||
|
||||
float f_t0 = (float)t0, f_inv_dt = (float)(1.0 / dt), f_inv_v = (float)(1.0 / geom_.v);
|
||||
float min_d = (float)bp_.min_depth, max_d = (float)bp_.max_depth;
|
||||
float comp_pow = (float)bp_.comp_range_power, w_max = (float)bp_.comp_weight_max;
|
||||
double inv_dt = 1.0 / dt, inv_v = 1.0 / geom_.v;
|
||||
double min_d = bp_.min_depth, max_d = bp_.max_depth;
|
||||
double comp_pow = bp_.comp_range_power, w_max = bp_.comp_weight_max;
|
||||
int use_comp = sar_.use_compensation ? 1 : 0;
|
||||
|
||||
void* args[] = {
|
||||
dH.addr(), &f_t0, &f_inv_dt, &n_fft, &f_inv_v,
|
||||
dH.addr(), &t0, &inv_dt, &n_fft, &inv_v,
|
||||
dxt.addr(), dyt.addr(), dzt.addr(), dxr.addr(), dyr.addr(), dzr.addr(),
|
||||
digr.addr(), dwgt.addr(), dgx.addr(), dgy.addr(), dgz.addr(),
|
||||
&NX, &NY, &NZ, &n_contrib, &cos_p, &sin_p, &min_d, &max_d,
|
||||
&NX, &NY, &NZ, &n_contrib, &cos_p, &sin_p, &ground_depth, &min_d, &max_d,
|
||||
&comp_pow, &w_max, &use_comp, dacc.addr(), dcnt.addr()};
|
||||
|
||||
int block = 256;
|
||||
@@ -108,4 +113,113 @@ VolumeRaw SarEngine::aperture_volume(const std::vector<ApertureFrame>& frames, c
|
||||
return out;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// scipy.ndimage.gaussian_filter: ядро радиуса int(truncate*sigma+0.5), reflect.
|
||||
std::vector<double> gaussian_kernel_1d(double sigma, int radius) {
|
||||
std::vector<double> w(2 * radius + 1);
|
||||
double sum = 0.0;
|
||||
for (int i = -radius; i <= radius; ++i) {
|
||||
w[i + radius] = std::exp(-0.5 * i * i / (sigma * sigma));
|
||||
sum += w[i + radius];
|
||||
}
|
||||
for (auto& v : w) v /= sum;
|
||||
return w;
|
||||
}
|
||||
|
||||
// Корреляция вдоль оси с reflect-границами ('d c b a | a b c d').
|
||||
inline int reflect_index(int i, int n) {
|
||||
while (i < 0 || i >= n) {
|
||||
if (i < 0) i = -i - 1;
|
||||
if (i >= n) i = 2 * n - i - 1;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
FinishedVolume finish_volume(const VolumeRaw& raw, const Grid& grid, double pitch_deg,
|
||||
const BPConfig& bp, const SARConfig& sar) {
|
||||
int NX = raw.NX, NY = raw.NY, NZ = raw.NZ;
|
||||
size_t nvox = (size_t)NX * NY * NZ;
|
||||
FinishedVolume out;
|
||||
out.NX = NX; out.NY = NY; out.NZ = NZ;
|
||||
|
||||
std::vector<double> vol(nvox);
|
||||
for (size_t i = 0; i < nvox; ++i)
|
||||
vol[i] = std::abs(c128(raw.acc[i].real(), raw.acc[i].imag())) / ((double)raw.cnt[i] + 1e-12);
|
||||
|
||||
// Маска глубины в радарных осях (в ядре невалидные вкладов не получали,
|
||||
// но |0/(0+eps)| уже 0; обнуление здесь повторяет ноутбук буквально).
|
||||
if (sar.coord_mode_ground) {
|
||||
double p = pitch_deg * M_PI / 180.0;
|
||||
double cos_p = std::cos(p), sin_p = std::sin(p);
|
||||
for (int iy = 0; iy < NY; ++iy) {
|
||||
double y0 = grid.y[iy] - sar.ground_depth_m;
|
||||
for (int iz = 0; iz < NZ; ++iz) {
|
||||
double z_rad = -y0 * sin_p + grid.z[iz] * cos_p;
|
||||
if (z_rad >= bp.min_depth && z_rad <= bp.max_depth) continue;
|
||||
double* row = vol.data() + ((size_t)iy * NZ + iz) * NX;
|
||||
std::fill(row, row + NX, 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Плоскости Y для нормировки: без верхних/нижних norm_edge_margin_m.
|
||||
std::vector<bool> ref_plane(NY, true);
|
||||
double margin = sar.norm_edge_margin_m;
|
||||
double y_span = grid.y.back() - grid.y.front();
|
||||
if (margin > 0.0 && y_span > 2.5 * margin) {
|
||||
for (int iy = 0; iy < NY; ++iy)
|
||||
ref_plane[iy] = grid.y[iy] >= grid.y.front() + margin &&
|
||||
grid.y[iy] <= grid.y.back() - margin;
|
||||
}
|
||||
auto ref_max = [&](const std::vector<double>& v) {
|
||||
double m = 0.0;
|
||||
for (int iy = 0; iy < NY; ++iy) {
|
||||
if (!ref_plane[iy]) continue;
|
||||
const double* plane = v.data() + (size_t)iy * NZ * NX;
|
||||
for (size_t i = 0; i < (size_t)NZ * NX; ++i) m = std::max(m, plane[i]);
|
||||
}
|
||||
return m + 1e-12;
|
||||
};
|
||||
|
||||
double level_raw = ref_max(vol);
|
||||
for (auto& v : vol) v /= level_raw;
|
||||
|
||||
// Гаусс sigma=(0, s, s): сглаживание по Z и X внутри каждого Y-плана
|
||||
// (порядок осей как у scipy: сначала ось 1, затем ось 2).
|
||||
if (sar.smooth_sigma > 0.0) {
|
||||
int radius = (int)(4.0 * sar.smooth_sigma + 0.5);
|
||||
const auto kernel = gaussian_kernel_1d(sar.smooth_sigma, radius);
|
||||
std::vector<double> tmp((size_t)NZ * NX);
|
||||
for (int iy = 0; iy < NY; ++iy) {
|
||||
double* plane = vol.data() + (size_t)iy * NZ * NX;
|
||||
// вдоль Z (ось 1)
|
||||
for (int iz = 0; iz < NZ; ++iz)
|
||||
for (int ix = 0; ix < NX; ++ix) {
|
||||
double s = 0.0;
|
||||
for (int k = -radius; k <= radius; ++k)
|
||||
s += kernel[k + radius] * plane[(size_t)reflect_index(iz + k, NZ) * NX + ix];
|
||||
tmp[(size_t)iz * NX + ix] = s;
|
||||
}
|
||||
// вдоль X (ось 2)
|
||||
for (int iz = 0; iz < NZ; ++iz)
|
||||
for (int ix = 0; ix < NX; ++ix) {
|
||||
double s = 0.0;
|
||||
for (int k = -radius; k <= radius; ++k)
|
||||
s += kernel[k + radius] * tmp[(size_t)iz * NX + reflect_index(ix + k, NX)];
|
||||
plane[(size_t)iz * NX + ix] = s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double level_smooth = ref_max(vol);
|
||||
out.volume.resize(nvox);
|
||||
for (size_t i = 0; i < nvox; ++i)
|
||||
out.volume[i] = (float)std::max(vol[i] / level_smooth, 0.0);
|
||||
out.level = level_raw * level_smooth;
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace gpr
|
||||
|
||||
Reference in New Issue
Block a user