From 64c813bf02a018f54170d331ff40243d6c0d3376 Mon Sep 17 00:00:00 2001 From: Theodor Chikin Date: Tue, 10 Feb 2026 21:55:12 +0300 Subject: [PATCH 01/13] implemented new normalisator mode: projector. It takes upper and lower evenlopes of ref signal and projects raw data from evenlopes scope to +-1000 --- RFG_ADC_dataplotter.py | 137 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 121 insertions(+), 16 deletions(-) diff --git a/RFG_ADC_dataplotter.py b/RFG_ADC_dataplotter.py index b3ab06d..80fbf32 100755 --- a/RFG_ADC_dataplotter.py +++ b/RFG_ADC_dataplotter.py @@ -85,6 +85,116 @@ def _parse_spec_clip(spec: Optional[str]) -> Optional[Tuple[float, float]]: return None +def _normalize_sweep_simple(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: + """Простая нормировка: поэлементное деление raw/calib.""" + w = min(raw.size, calib.size) + if w <= 0: + return raw + out = np.full_like(raw, np.nan, dtype=np.float32) + with np.errstate(divide="ignore", invalid="ignore"): + out[:w] = raw[:w] / calib[:w] + out = np.nan_to_num(out, nan=np.nan, posinf=np.nan, neginf=np.nan) + return out + + +def _build_calib_envelopes(calib: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """Оценить нижнюю/верхнюю огибающие калибровочной кривой.""" + n = int(calib.size) + if n <= 0: + empty = np.zeros((0,), dtype=np.float32) + return empty, empty + + y = np.asarray(calib, dtype=np.float32) + finite = np.isfinite(y) + if not np.any(finite): + zeros = np.zeros_like(y, dtype=np.float32) + return zeros, zeros + + if not np.all(finite): + x = np.arange(n, dtype=np.float32) + y = y.copy() + y[~finite] = np.interp(x[~finite], x[finite], y[finite]).astype(np.float32) + + if n < 3: + return y.copy(), y.copy() + + dy = np.diff(y) + s = np.sign(dy).astype(np.int8, copy=False) + + if np.any(s == 0): + for i in range(1, s.size): + if s[i] == 0: + s[i] = s[i - 1] + for i in range(s.size - 2, -1, -1): + if s[i] == 0: + s[i] = s[i + 1] + s[s == 0] = 1 + + max_idx = np.where((s[:-1] > 0) & (s[1:] < 0))[0] + 1 + min_idx = np.where((s[:-1] < 0) & (s[1:] > 0))[0] + 1 + + x = np.arange(n, dtype=np.float32) + + def _interp_nodes(nodes: np.ndarray) -> np.ndarray: + if nodes.size == 0: + idx = np.array([0, n - 1], dtype=np.int64) + else: + idx = np.unique(np.concatenate(([0], nodes, [n - 1]))).astype(np.int64) + return np.interp(x, idx.astype(np.float32), y[idx]).astype(np.float32) + + upper = _interp_nodes(max_idx) + lower = _interp_nodes(min_idx) + + swap = lower > upper + if np.any(swap): + tmp = upper[swap].copy() + upper[swap] = lower[swap] + lower[swap] = tmp + + return lower, upper + + +def _normalize_sweep_projector(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: + """Нормировка через проекцию между огибающими калибровки в диапазон [-1, +1].""" + w = min(raw.size, calib.size) + if w <= 0: + return raw + + out = np.full_like(raw, np.nan, dtype=np.float32) + raw_seg = np.asarray(raw[:w], dtype=np.float32) + lower, upper = _build_calib_envelopes(np.asarray(calib[:w], dtype=np.float32)) + span = upper - lower + + finite_span = span[np.isfinite(span) & (span > 0)] + if finite_span.size > 0: + eps = max(float(np.median(finite_span)) * 1e-6, 1e-9) + else: + eps = 1e-9 + + valid = ( + np.isfinite(raw_seg) + & np.isfinite(lower) + & np.isfinite(upper) + & (span > eps) + ) + if np.any(valid): + proj = np.empty_like(raw_seg, dtype=np.float32) + proj[valid] = ((2.0 * (raw_seg[valid] - lower[valid]) / span[valid]) - 1.0) * 1000.0 + proj[valid] = np.clip(proj[valid], -1000.0, 1000.0) + proj[~valid] = np.nan + out[:w] = proj + + return out + + +def _normalize_by_calib(raw: np.ndarray, calib: np.ndarray, norm_type: str) -> np.ndarray: + """Нормировка свипа по выбранному алгоритму.""" + nt = str(norm_type).strip().lower() + if nt == "simple": + return _normalize_sweep_simple(raw, calib) + return _normalize_sweep_projector(raw, calib) + + def try_open_pyserial(path: str, baud: int, timeout: float): try: import serial # type: ignore @@ -532,6 +642,12 @@ def main(): default="auto", help="Графический бэкенд: pyqtgraph (pg) — быстрее; matplotlib (mpl) — совместимый. По умолчанию auto", ) + parser.add_argument( + "--norm-type", + choices=["projector", "simple"], + default="projector", + help="Тип нормировки: projector (по огибающим в [-1,+1]) или simple (raw/calib)", + ) args = parser.parse_args() @@ -592,6 +708,7 @@ def main(): ymax_slider = None contrast_slider = None calib_enabled = False + norm_type = str(getattr(args, "norm_type", "projector")).strip().lower() cb = None # Статусная строка (внизу окна) @@ -674,15 +791,9 @@ def main(): ax_spec.tick_params(axis="x", labelbottom=False) except Exception: pass + def _normalize_sweep(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: - w = min(raw.size, calib.size) - if w <= 0: - return raw - out = np.full_like(raw, np.nan, dtype=np.float32) - with np.errstate(divide="ignore", invalid="ignore"): - out[:w] = raw[:w] / calib[:w] - out = np.nan_to_num(out, nan=np.nan, posinf=np.nan, neginf=np.nan) - return out + return _normalize_by_calib(raw, calib, norm_type=norm_type) def _set_calib_enabled(): nonlocal calib_enabled, current_sweep_norm @@ -1146,6 +1257,7 @@ def run_pyqtgraph(args): spec_clip = _parse_spec_clip(getattr(args, "spec_clip", None)) spec_mean_sec = float(getattr(args, "spec_mean_sec", 0.0)) calib_enabled = False + norm_type = str(getattr(args, "norm_type", "projector")).strip().lower() # Диапазон по Y: авто по умолчанию (поддерживает отрицательные значения) fixed_ylim: Optional[Tuple[float, float]] = None if args.ylim: @@ -1158,14 +1270,7 @@ def run_pyqtgraph(args): p_line.setYRange(fixed_ylim[0], fixed_ylim[1], padding=0) def _normalize_sweep(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: - w = min(raw.size, calib.size) - if w <= 0: - return raw - out = np.full_like(raw, np.nan, dtype=np.float32) - with np.errstate(divide="ignore", invalid="ignore"): - out[:w] = raw[:w] / calib[:w] - out = np.nan_to_num(out, nan=np.nan, posinf=np.nan, neginf=np.nan) - return out + return _normalize_by_calib(raw, calib, norm_type=norm_type) def _set_calib_enabled(): nonlocal calib_enabled, current_sweep_norm -- 2.49.0 From 0eaa07c03aa2684971a9aecdc11b442b3e549511 Mon Sep 17 00:00:00 2001 From: awe Date: Wed, 11 Feb 2026 16:32:04 +0300 Subject: [PATCH 02/13] gitignore upd --- .gitignore | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..11817c6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +my_picocom_logfile.txt +*pyc +__pycache__/ +*.log +*.tmp +*.bak +*.swp +*.swo \ No newline at end of file -- 2.49.0 From c3acd0c19391381e6985d5729369a49bfde430c8 Mon Sep 17 00:00:00 2001 From: awe Date: Wed, 11 Feb 2026 16:32:21 +0300 Subject: [PATCH 03/13] new project structure --- replay_pty.py | 102 ++++++++ rfg_adc_plotter/__init__.py | 0 rfg_adc_plotter/constants.py | 5 + rfg_adc_plotter/gui/__init__.py | 0 rfg_adc_plotter/gui/matplotlib_backend.py | 284 ++++++++++++++++++++++ rfg_adc_plotter/gui/pyqtgraph_backend.py | 272 +++++++++++++++++++++ rfg_adc_plotter/io/__init__.py | 0 rfg_adc_plotter/io/serial_source.py | 181 ++++++++++++++ rfg_adc_plotter/io/sweep_reader.py | 217 +++++++++++++++++ rfg_adc_plotter/main.py | 108 ++++++++ rfg_adc_plotter/processing/__init__.py | 0 rfg_adc_plotter/processing/normalizer.py | 115 +++++++++ rfg_adc_plotter/state/__init__.py | 0 rfg_adc_plotter/state/app_state.py | 119 +++++++++ rfg_adc_plotter/state/ring_buffer.py | 166 +++++++++++++ rfg_adc_plotter/types.py | 7 + 16 files changed, 1576 insertions(+) create mode 100644 replay_pty.py create mode 100644 rfg_adc_plotter/__init__.py create mode 100644 rfg_adc_plotter/constants.py create mode 100644 rfg_adc_plotter/gui/__init__.py create mode 100644 rfg_adc_plotter/gui/matplotlib_backend.py create mode 100644 rfg_adc_plotter/gui/pyqtgraph_backend.py create mode 100644 rfg_adc_plotter/io/__init__.py create mode 100644 rfg_adc_plotter/io/serial_source.py create mode 100644 rfg_adc_plotter/io/sweep_reader.py create mode 100644 rfg_adc_plotter/main.py create mode 100644 rfg_adc_plotter/processing/__init__.py create mode 100644 rfg_adc_plotter/processing/normalizer.py create mode 100644 rfg_adc_plotter/state/__init__.py create mode 100644 rfg_adc_plotter/state/app_state.py create mode 100644 rfg_adc_plotter/state/ring_buffer.py create mode 100644 rfg_adc_plotter/types.py diff --git a/replay_pty.py b/replay_pty.py new file mode 100644 index 0000000..00a0798 --- /dev/null +++ b/replay_pty.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +""" +Эмулятор серийного порта: воспроизводит лог-файл в цикле через PTY. + +Использование: + python3 replay_pty.py my_picocom_logfile.txt + python3 replay_pty.py my_picocom_logfile.txt --pty /tmp/ttyVIRT0 + python3 replay_pty.py my_picocom_logfile.txt --speed 2.0 # в 2 раза быстрее реального + python3 replay_pty.py my_picocom_logfile.txt --speed 0 # максимально быстро + +Затем в другом терминале: + python -m rfg_adc_plotter.main /tmp/ttyVIRT0 +""" + +import argparse +import os +import sys +import time + + +def main(): + parser = argparse.ArgumentParser( + description="Воспроизводит лог-файл через PTY как виртуальный серийный порт." + ) + parser.add_argument("file", help="Путь к лог-файлу (например my_picocom_logfile.txt)") + parser.add_argument( + "--pty", + default="/tmp/ttyVIRT0", + help="Путь симлинка PTY (по умолчанию /tmp/ttyVIRT0)", + ) + parser.add_argument( + "--speed", + type=float, + default=1.0, + help=( + "Множитель скорости воспроизведения: " + "1.0 = реальное время при --baud, " + "2.0 = вдвое быстрее, " + "0 = максимально быстро" + ), + ) + parser.add_argument( + "--baud", + type=int, + default=115200, + help="Скорость (бод) для расчёта задержек (по умолчанию 115200)", + ) + args = parser.parse_args() + + if not os.path.isfile(args.file): + sys.stderr.write(f"[error] Файл не найден: {args.file}\n") + sys.exit(1) + + # Открываем PTY-пару: master (мы пишем) / slave (GUI читает) + master_fd, slave_fd = os.openpty() + slave_path = os.ttyname(slave_fd) + os.close(slave_fd) # GUI откроет slave сам по симлинку + + # Симлинк с удобным именем + try: + os.unlink(args.pty) + except FileNotFoundError: + pass + os.symlink(slave_path, args.pty) + + print(f"PTY slave : {slave_path}") + print(f"Симлинк : {args.pty} → {slave_path}") + print(f"Запустите : python -m rfg_adc_plotter.main {args.pty}") + print("Ctrl+C для остановки.\n") + + # Задержка на байт: 10 бит (8N1) / скорость / множитель + if args.speed > 0: + bytes_per_sec = args.baud / 10.0 * args.speed + delay_per_byte = 1.0 / bytes_per_sec + else: + delay_per_byte = 0.0 + + loop = 0 + try: + while True: + loop += 1 + print(f"[loop {loop}] {args.file}") + with open(args.file, "rb") as f: + for line in f: + os.write(master_fd, line) + if delay_per_byte > 0: + time.sleep(delay_per_byte * len(line)) + except KeyboardInterrupt: + print("\nОстановлено.") + finally: + try: + os.unlink(args.pty) + except Exception: + pass + try: + os.close(master_fd) + except Exception: + pass + + +if __name__ == "__main__": + main() diff --git a/rfg_adc_plotter/__init__.py b/rfg_adc_plotter/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/rfg_adc_plotter/constants.py b/rfg_adc_plotter/constants.py new file mode 100644 index 0000000..47ca55c --- /dev/null +++ b/rfg_adc_plotter/constants.py @@ -0,0 +1,5 @@ +WF_WIDTH = 1000 # максимальное число точек в ряду водопада +FFT_LEN = 1024 # длина БПФ для спектра/водопада спектров +# Порог для инверсии сырых данных: если среднее значение свипа ниже порога — +# считаем, что сигнал «меньше нуля» и домножаем свип на -1 +DATA_INVERSION_THRESHOLD = 10.0 diff --git a/rfg_adc_plotter/gui/__init__.py b/rfg_adc_plotter/gui/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/rfg_adc_plotter/gui/matplotlib_backend.py b/rfg_adc_plotter/gui/matplotlib_backend.py new file mode 100644 index 0000000..c6664b0 --- /dev/null +++ b/rfg_adc_plotter/gui/matplotlib_backend.py @@ -0,0 +1,284 @@ +"""Matplotlib-бэкенд реалтайм-плоттера свипов.""" + +import sys +import threading +from queue import Queue +from typing import Optional, Tuple + +import numpy as np + +from rfg_adc_plotter.constants import FFT_LEN +from rfg_adc_plotter.io.sweep_reader import SweepReader +from rfg_adc_plotter.state.app_state import AppState, format_status +from rfg_adc_plotter.state.ring_buffer import RingBuffer +from rfg_adc_plotter.types import SweepPacket + + +def _parse_ylim(ylim_str: Optional[str]) -> Optional[Tuple[float, float]]: + if not ylim_str: + return None + try: + y0, y1 = ylim_str.split(",") + return (float(y0), float(y1)) + except Exception: + sys.stderr.write("[warn] Некорректный формат --ylim, игнорирую. Ожидалось min,max\n") + return None + + +def _parse_spec_clip(spec: Optional[str]) -> Optional[Tuple[float, float]]: + if not spec: + return None + s = str(spec).strip().lower() + if s in ("off", "none", "no"): + return None + try: + p0, p1 = s.replace(";", ",").split(",") + low, high = float(p0), float(p1) + if not (0.0 <= low < high <= 100.0): + return None + return (low, high) + except Exception: + return None + + +def _visible_levels(data: np.ndarray, axis) -> Optional[Tuple[float, float]]: + """(vmin, vmax) по текущей видимой области imshow.""" + if data.size == 0: + return None + ny, nx = data.shape[0], data.shape[1] + try: + x0, x1 = axis.get_xlim() + y0, y1 = axis.get_ylim() + except Exception: + x0, x1 = 0.0, float(nx - 1) + y0, y1 = 0.0, float(ny - 1) + xmin, xmax = sorted((float(x0), float(x1))) + ymin, ymax = sorted((float(y0), float(y1))) + ix0 = max(0, min(nx - 1, int(np.floor(xmin)))) + ix1 = max(0, min(nx - 1, int(np.ceil(xmax)))) + iy0 = max(0, min(ny - 1, int(np.floor(ymin)))) + iy1 = max(0, min(ny - 1, int(np.ceil(ymax)))) + if ix1 < ix0: + ix1 = ix0 + if iy1 < iy0: + iy1 = iy0 + sub = data[iy0 : iy1 + 1, ix0 : ix1 + 1] + finite = np.isfinite(sub) + if not finite.any(): + return None + vals = sub[finite] + vmin = float(np.min(vals)) + vmax = float(np.max(vals)) + if not (np.isfinite(vmin) and np.isfinite(vmax)) or vmin == vmax: + return None + return (vmin, vmax) + + +def run_matplotlib(args): + try: + import matplotlib + import matplotlib.pyplot as plt + from matplotlib.animation import FuncAnimation + from matplotlib.widgets import CheckButtons, Slider + except Exception as e: + sys.stderr.write(f"[error] Нужны matplotlib и её зависимости: {e}\n") + sys.exit(1) + + q: Queue[SweepPacket] = Queue(maxsize=1000) + stop_event = threading.Event() + reader = SweepReader(args.port, args.baud, q, stop_event, fancy=bool(args.fancy)) + reader.start() + + max_sweeps = int(max(10, args.max_sweeps)) + max_fps = max(1.0, float(args.max_fps)) + interval_ms = int(1000.0 / max_fps) + spec_clip = _parse_spec_clip(getattr(args, "spec_clip", None)) + spec_mean_sec = float(getattr(args, "spec_mean_sec", 0.0)) + fixed_ylim = _parse_ylim(getattr(args, "ylim", None)) + norm_type = str(getattr(args, "norm_type", "projector")).strip().lower() + + state = AppState(norm_type=norm_type) + ring = RingBuffer(max_sweeps) + + # --- Создание фигуры --- + fig, axs = plt.subplots(2, 2, figsize=(12, 8)) + (ax_line, ax_img), (ax_fft, ax_spec) = axs + if hasattr(fig.canvas.manager, "set_window_title"): + fig.canvas.manager.set_window_title(args.title) + fig.subplots_adjust(wspace=0.25, hspace=0.35, left=0.07, right=0.90, top=0.92, bottom=0.08) + + # Статусная строка + status_text = fig.text(0.01, 0.01, "", ha="left", va="bottom", fontsize=8, family="monospace") + + # График последнего свипа + line_obj, = ax_line.plot([], [], lw=1, color="tab:blue") + line_calib_obj, = ax_line.plot([], [], lw=1, color="tab:red") + line_norm_obj, = ax_line.plot([], [], lw=1, color="tab:green") + ax_line.set_title("Сырые данные", pad=1) + ax_line.set_xlabel("F") + channel_text = ax_line.text( + 0.98, 0.98, "", transform=ax_line.transAxes, + ha="right", va="top", fontsize=9, family="monospace", + ) + if fixed_ylim is not None: + ax_line.set_ylim(fixed_ylim) + + # График спектра + fft_line_obj, = ax_fft.plot([], [], lw=1) + ax_fft.set_title("FFT", pad=1) + ax_fft.set_xlabel("X") + ax_fft.set_ylabel("Амплитуда, дБ") + + # Водопад сырых данных + img_obj = ax_img.imshow( + np.zeros((1, 1), dtype=np.float32), + aspect="auto", interpolation="nearest", origin="lower", cmap=args.cmap, + ) + ax_img.set_title("Сырые данные", pad=12) + ax_img.set_ylabel("частота") + try: + ax_img.tick_params(axis="x", labelbottom=False) + except Exception: + pass + + # Водопад спектров + img_fft_obj = ax_spec.imshow( + np.zeros((1, 1), dtype=np.float32), + aspect="auto", interpolation="nearest", origin="lower", cmap=args.cmap, + ) + ax_spec.set_title("B-scan (дБ)", pad=12) + ax_spec.set_ylabel("расстояние") + try: + ax_spec.tick_params(axis="x", labelbottom=False) + except Exception: + pass + + # Слайдеры и чекбокс + contrast_slider = None + try: + fft_bins = ring.fft_bins + ax_smin = fig.add_axes([0.92, 0.55, 0.02, 0.35]) + ax_smax = fig.add_axes([0.95, 0.55, 0.02, 0.35]) + ax_sctr = fig.add_axes([0.98, 0.55, 0.02, 0.35]) + ax_cb = fig.add_axes([0.92, 0.45, 0.08, 0.08]) + ymin_slider = Slider(ax_smin, "Y min", 0, max(1, fft_bins - 1), valinit=0, valstep=1, orientation="vertical") + ymax_slider = Slider(ax_smax, "Y max", 0, max(1, fft_bins - 1), valinit=max(1, fft_bins - 1), valstep=1, orientation="vertical") + contrast_slider = Slider(ax_sctr, "Int max", 0, 100, valinit=100, valstep=1, orientation="vertical") + calib_cb = CheckButtons(ax_cb, ["калибровка"], [False]) + + def _on_ylim_change(_val): + try: + y0 = int(min(ymin_slider.val, ymax_slider.val)) + y1 = int(max(ymin_slider.val, ymax_slider.val)) + ax_spec.set_ylim(y0, y1) + fig.canvas.draw_idle() + except Exception: + pass + + ymin_slider.on_changed(_on_ylim_change) + ymax_slider.on_changed(_on_ylim_change) + contrast_slider.on_changed(lambda _v: fig.canvas.draw_idle()) + calib_cb.on_clicked(lambda _v: state.set_calib_enabled( + bool(calib_cb.get_status()[0]) + )) + except Exception: + calib_cb = None + + # --- Инициализация imshow при первом свипе --- + def _init_imshow_extents(): + w = ring.width + ms = ring.max_sweeps + fb = ring.fft_bins + img_obj.set_data(np.zeros((w, ms), dtype=np.float32)) + img_obj.set_extent((0, ms - 1, 0, w - 1 if w > 0 else 1)) + ax_img.set_xlim(0, ms - 1) + ax_img.set_ylim(0, max(1, w - 1)) + img_fft_obj.set_data(np.zeros((fb, ms), dtype=np.float32)) + img_fft_obj.set_extent((0, ms - 1, 0, fb - 1)) + ax_spec.set_xlim(0, ms - 1) + ax_spec.set_ylim(0, max(1, fb - 1)) + + _imshow_initialized = [False] + + def update(_frame): + changed = state.drain_queue(q, ring) > 0 + + if changed and not _imshow_initialized[0] and ring.is_ready: + _init_imshow_extents() + _imshow_initialized[0] = True + + # Линейный график свипа + if state.current_sweep_raw is not None: + raw = state.current_sweep_raw + if ring.x_shared is not None and raw.size <= ring.x_shared.size: + xs = ring.x_shared[: raw.size] + else: + xs = np.arange(raw.size, dtype=np.int32) + line_obj.set_data(xs, raw) + if state.last_calib_sweep is not None: + line_calib_obj.set_data(xs[: state.last_calib_sweep.size], state.last_calib_sweep) + else: + line_calib_obj.set_data([], []) + if state.current_sweep_norm is not None: + line_norm_obj.set_data(xs[: state.current_sweep_norm.size], state.current_sweep_norm) + else: + line_norm_obj.set_data([], []) + ax_line.set_xlim(0, max(1, raw.size - 1)) + if fixed_ylim is None: + y0 = float(np.nanmin(raw)) + y1 = float(np.nanmax(raw)) + if np.isfinite(y0) and np.isfinite(y1): + if y0 == y1: + pad = max(1.0, abs(y0) * 0.05) + y0 -= pad + y1 += pad + else: + pad = 0.05 * (y1 - y0) + y0 -= pad + y1 += pad + ax_line.set_ylim(y0, y1) + + # Спектр — используем уже вычисленный в ring FFT + if ring.last_fft_vals is not None and ring.freq_shared is not None: + fft_vals = ring.last_fft_vals + xs_fft = ring.freq_shared + if fft_vals.size > xs_fft.size: + fft_vals = fft_vals[: xs_fft.size] + fft_line_obj.set_data(xs_fft[: fft_vals.size], fft_vals) + if np.isfinite(np.nanmin(fft_vals)) and np.isfinite(np.nanmax(fft_vals)): + ax_fft.set_xlim(0, max(1, xs_fft.size - 1)) + ax_fft.set_ylim(float(np.nanmin(fft_vals)), float(np.nanmax(fft_vals))) + + # Водопад сырых данных + if changed and ring.is_ready: + disp = ring.get_display_ring() + img_obj.set_data(disp) + levels = _visible_levels(disp, ax_img) + if levels is not None: + img_obj.set_clim(vmin=levels[0], vmax=levels[1]) + + # Водопад спектров + if changed and ring.is_ready: + disp_fft = ring.get_display_ring_fft() + disp_fft = ring.subtract_recent_mean_fft(disp_fft, spec_mean_sec) + img_fft_obj.set_data(disp_fft) + levels = ring.compute_fft_levels(disp_fft, spec_clip) + if levels is not None: + try: + c = float(contrast_slider.val) / 100.0 if contrast_slider is not None else 1.0 + except Exception: + c = 1.0 + vmax_eff = levels[0] + c * (levels[1] - levels[0]) + img_fft_obj.set_clim(vmin=levels[0], vmax=vmax_eff) + + # Статус и подпись канала + if changed and state.current_info: + status_text.set_text(format_status(state.current_info)) + channel_text.set_text(state.format_channel_label()) + + return (line_obj, line_calib_obj, line_norm_obj, img_obj, fft_line_obj, img_fft_obj, status_text, channel_text) + + ani = FuncAnimation(fig, update, interval=interval_ms, blit=False) + plt.show() + stop_event.set() + reader.join(timeout=1.0) diff --git a/rfg_adc_plotter/gui/pyqtgraph_backend.py b/rfg_adc_plotter/gui/pyqtgraph_backend.py new file mode 100644 index 0000000..afe01eb --- /dev/null +++ b/rfg_adc_plotter/gui/pyqtgraph_backend.py @@ -0,0 +1,272 @@ +"""PyQtGraph-бэкенд реалтайм-плоттера свипов.""" + +import sys +import threading +from queue import Queue +from typing import Optional, Tuple + +import numpy as np + +from rfg_adc_plotter.io.sweep_reader import SweepReader +from rfg_adc_plotter.state.app_state import AppState, format_status +from rfg_adc_plotter.state.ring_buffer import RingBuffer +from rfg_adc_plotter.types import SweepPacket + + +def _parse_ylim(ylim_str: Optional[str]) -> Optional[Tuple[float, float]]: + if not ylim_str: + return None + try: + y0, y1 = ylim_str.split(",") + return (float(y0), float(y1)) + except Exception: + return None + + +def _parse_spec_clip(spec: Optional[str]) -> Optional[Tuple[float, float]]: + if not spec: + return None + s = str(spec).strip().lower() + if s in ("off", "none", "no"): + return None + try: + p0, p1 = s.replace(";", ",").split(",") + low, high = float(p0), float(p1) + if not (0.0 <= low < high <= 100.0): + return None + return (low, high) + except Exception: + return None + + +def _visible_levels(data: np.ndarray, plot_item) -> Optional[Tuple[float, float]]: + """(vmin, vmax) по текущей видимой области ImageItem.""" + if data.size == 0: + return None + ny, nx = data.shape[0], data.shape[1] + try: + (x0, x1), (y0, y1) = plot_item.viewRange() + except Exception: + x0, x1 = 0.0, float(nx - 1) + y0, y1 = 0.0, float(ny - 1) + xmin, xmax = sorted((float(x0), float(x1))) + ymin, ymax = sorted((float(y0), float(y1))) + ix0 = max(0, min(nx - 1, int(np.floor(xmin)))) + ix1 = max(0, min(nx - 1, int(np.ceil(xmax)))) + iy0 = max(0, min(ny - 1, int(np.floor(ymin)))) + iy1 = max(0, min(ny - 1, int(np.ceil(ymax)))) + if ix1 < ix0: + ix1 = ix0 + if iy1 < iy0: + iy1 = iy0 + sub = data[iy0 : iy1 + 1, ix0 : ix1 + 1] + finite = np.isfinite(sub) + if not finite.any(): + return None + vals = sub[finite] + vmin = float(np.min(vals)) + vmax = float(np.max(vals)) + if not (np.isfinite(vmin) and np.isfinite(vmax)) or vmin == vmax: + return None + return (vmin, vmax) + + +def run_pyqtgraph(args): + """Быстрый GUI на PyQtGraph. Требует pyqtgraph и PyQt5/PySide6.""" + try: + import pyqtgraph as pg + from PyQt5 import QtCore, QtWidgets # noqa: F401 + except Exception: + try: + import pyqtgraph as pg + from PySide6 import QtCore, QtWidgets # noqa: F401 + except Exception as e: + raise RuntimeError( + "pyqtgraph/PyQt5(PySide6) не найдены. Установите: pip install pyqtgraph PyQt5" + ) from e + + q: Queue[SweepPacket] = Queue(maxsize=1000) + stop_event = threading.Event() + reader = SweepReader(args.port, args.baud, q, stop_event, fancy=bool(args.fancy)) + reader.start() + + max_sweeps = int(max(10, args.max_sweeps)) + max_fps = max(1.0, float(args.max_fps)) + interval_ms = int(1000.0 / max_fps) + spec_clip = _parse_spec_clip(getattr(args, "spec_clip", None)) + spec_mean_sec = float(getattr(args, "spec_mean_sec", 0.0)) + fixed_ylim = _parse_ylim(getattr(args, "ylim", None)) + norm_type = str(getattr(args, "norm_type", "projector")).strip().lower() + + state = AppState(norm_type=norm_type) + ring = RingBuffer(max_sweeps) + + # --- Создание окна --- + pg.setConfigOptions(useOpenGL=True, antialias=False) + app = pg.mkQApp(args.title) + win = pg.GraphicsLayoutWidget(show=True, title=args.title) + win.resize(1200, 600) + + # График последнего свипа (слева-сверху) + p_line = win.addPlot(row=0, col=0, title="Сырые данные") + p_line.showGrid(x=True, y=True, alpha=0.3) + curve = p_line.plot(pen=pg.mkPen((80, 120, 255), width=1)) + curve_calib = p_line.plot(pen=pg.mkPen((220, 60, 60), width=1)) + curve_norm = p_line.plot(pen=pg.mkPen((60, 180, 90), width=1)) + p_line.setLabel("bottom", "X") + p_line.setLabel("left", "Y") + ch_text = pg.TextItem("", anchor=(1, 1)) + ch_text.setZValue(10) + p_line.addItem(ch_text) + if fixed_ylim is not None: + p_line.setYRange(fixed_ylim[0], fixed_ylim[1], padding=0) + + # Водопад (справа-сверху) + p_img = win.addPlot(row=0, col=1, title="Сырые данные водопад") + p_img.invertY(False) + p_img.showGrid(x=False, y=False) + p_img.setLabel("bottom", "Время (новое справа)") + try: + p_img.getAxis("bottom").setStyle(showValues=False) + except Exception: + pass + p_img.setLabel("left", "X (0 снизу)") + img = pg.ImageItem() + p_img.addItem(img) + + # Применяем LUT из цветовой карты + try: + cm = pg.colormap.get(args.cmap) + img.setLookupTable(cm.getLookupTable(0.0, 1.0, 256)) + except Exception: + pass + + # FFT (слева-снизу) + p_fft = win.addPlot(row=1, col=0, title="FFT") + p_fft.showGrid(x=True, y=True, alpha=0.3) + curve_fft = p_fft.plot(pen=pg.mkPen((255, 120, 80), width=1)) + p_fft.setLabel("bottom", "Бин") + p_fft.setLabel("left", "Амплитуда, дБ") + + # Водопад спектров (справа-снизу) + p_spec = win.addPlot(row=1, col=1, title="B-scan (дБ)") + p_spec.invertY(True) + p_spec.showGrid(x=False, y=False) + p_spec.setLabel("bottom", "Время (новое справа)") + try: + p_spec.getAxis("bottom").setStyle(showValues=False) + except Exception: + pass + p_spec.setLabel("left", "Бин (0 снизу)") + img_fft = pg.ImageItem() + p_spec.addItem(img_fft) + + # Чекбокс калибровки + calib_cb = QtWidgets.QCheckBox("калибровка") + cb_proxy = QtWidgets.QGraphicsProxyWidget() + cb_proxy.setWidget(calib_cb) + win.addItem(cb_proxy, row=2, col=1) + calib_cb.stateChanged.connect(lambda _v: state.set_calib_enabled(calib_cb.isChecked())) + + # Статусная строка + status = pg.LabelItem(justify="left") + win.addItem(status, row=3, col=0, colspan=2) + + _imshow_initialized = [False] + + def _init_imshow_extents(): + w = ring.width + ms = ring.max_sweeps + fb = ring.fft_bins + img.setImage(ring.ring.T, autoLevels=False) + p_img.setRange(xRange=(0, ms - 1), yRange=(0, max(1, w - 1)), padding=0) + p_line.setXRange(0, max(1, w - 1), padding=0) + img_fft.setImage(ring.ring_fft.T, autoLevels=False) + p_spec.setRange(xRange=(0, ms - 1), yRange=(0, max(1, fb - 1)), padding=0) + p_fft.setXRange(0, max(1, fb - 1), padding=0) + + def update(): + changed = state.drain_queue(q, ring) > 0 + + if changed and not _imshow_initialized[0] and ring.is_ready: + _init_imshow_extents() + _imshow_initialized[0] = True + + # Линейный график свипа + if state.current_sweep_raw is not None and ring.x_shared is not None: + raw = state.current_sweep_raw + xs = ring.x_shared[: raw.size] if raw.size <= ring.x_shared.size else np.arange(raw.size) + curve.setData(xs, raw, autoDownsample=True) + if state.last_calib_sweep is not None: + curve_calib.setData(xs[: state.last_calib_sweep.size], state.last_calib_sweep, autoDownsample=True) + else: + curve_calib.setData([], []) + if state.current_sweep_norm is not None: + curve_norm.setData(xs[: state.current_sweep_norm.size], state.current_sweep_norm, autoDownsample=True) + else: + curve_norm.setData([], []) + if fixed_ylim is None: + y0 = float(np.nanmin(raw)) + y1 = float(np.nanmax(raw)) + if np.isfinite(y0) and np.isfinite(y1): + margin = 0.05 * max(1.0, (y1 - y0)) + p_line.setYRange(y0 - margin, y1 + margin, padding=0) + + # Спектр — используем уже вычисленный в ring FFT + if ring.last_fft_vals is not None and ring.freq_shared is not None: + fft_vals = ring.last_fft_vals + xs_fft = ring.freq_shared + if fft_vals.size > xs_fft.size: + fft_vals = fft_vals[: xs_fft.size] + curve_fft.setData(xs_fft[: fft_vals.size], fft_vals) + p_fft.setYRange(float(np.nanmin(fft_vals)), float(np.nanmax(fft_vals)), padding=0) + + # Позиция подписи канала + try: + (x0, x1), (y0, y1) = p_line.viewRange() + dx = 0.01 * max(1.0, float(x1 - x0)) + dy = 0.01 * max(1.0, float(y1 - y0)) + ch_text.setPos(float(x1 - dx), float(y1 - dy)) + except Exception: + pass + + # Водопад сырых данных — новые данные справа (без реверса) + if changed and ring.is_ready: + disp = ring.get_display_ring() # (width, time), новые справа + levels = _visible_levels(disp, p_img) + if levels is not None: + img.setImage(disp, autoLevels=False, levels=levels) + else: + img.setImage(disp, autoLevels=False) + + # Статус и подпись канала + if changed and state.current_info: + try: + status.setText(format_status(state.current_info)) + except Exception: + pass + ch_text.setText(state.format_channel_label()) + + # Водопад спектров — новые данные справа (без реверса) + if changed and ring.is_ready: + disp_fft = ring.get_display_ring_fft() # (bins, time), новые справа + disp_fft = ring.subtract_recent_mean_fft(disp_fft, spec_mean_sec) + levels = ring.compute_fft_levels(disp_fft, spec_clip) + if levels is not None: + img_fft.setImage(disp_fft, autoLevels=False, levels=levels) + else: + img_fft.setImage(disp_fft, autoLevels=False) + + timer = pg.QtCore.QTimer() + timer.timeout.connect(update) + timer.start(interval_ms) + + def on_quit(): + stop_event.set() + reader.join(timeout=1.0) + + app.aboutToQuit.connect(on_quit) + win.show() + exec_fn = getattr(app, "exec_", None) or getattr(app, "exec", None) + exec_fn() + on_quit() diff --git a/rfg_adc_plotter/io/__init__.py b/rfg_adc_plotter/io/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/rfg_adc_plotter/io/serial_source.py b/rfg_adc_plotter/io/serial_source.py new file mode 100644 index 0000000..31a2ba4 --- /dev/null +++ b/rfg_adc_plotter/io/serial_source.py @@ -0,0 +1,181 @@ +"""Источники последовательного ввода: обёртки над pyserial и raw TTY.""" + +import io +import os +import sys +from typing import Optional + + +def try_open_pyserial(path: str, baud: int, timeout: float): + try: + import serial # type: ignore + except Exception: + return None + try: + ser = serial.Serial(path, baudrate=baud, timeout=timeout) + return ser + except Exception: + return None + + +class FDReader: + """Простой враппер чтения строк из файлового дескриптора TTY.""" + + def __init__(self, fd: int): + self._fd = fd + raw = os.fdopen(fd, "rb", closefd=False) + self._file = raw + self._buf = io.BufferedReader(raw, buffer_size=65536) + + def fileno(self) -> int: + return self._fd + + def readline(self) -> bytes: + return self._buf.readline() + + def close(self): + try: + self._buf.close() + except Exception: + pass + + +def open_raw_tty(path: str, baud: int) -> Optional[FDReader]: + """Открыть TTY без pyserial и настроить порт через termios. + + Возвращает FDReader или None при ошибке. + """ + try: + import termios + import tty + except Exception: + return None + + try: + fd = os.open(path, os.O_RDONLY | os.O_NOCTTY) + except Exception: + return None + + try: + attrs = termios.tcgetattr(fd) + tty.setraw(fd) + + baud_map = { + 9600: termios.B9600, + 19200: termios.B19200, + 38400: termios.B38400, + 57600: termios.B57600, + 115200: termios.B115200, + 230400: getattr(termios, "B230400", None), + 460800: getattr(termios, "B460800", None), + } + b = baud_map.get(baud) or termios.B115200 + + attrs[4] = b # ispeed + attrs[5] = b # ospeed + + # VMIN=1, VTIME=0 — блокирующее чтение по байту + cc = attrs[6] + cc[termios.VMIN] = 1 + cc[termios.VTIME] = 0 + attrs[6] = cc + + termios.tcsetattr(fd, termios.TCSANOW, attrs) + except Exception: + try: + os.close(fd) + except Exception: + pass + return None + + return FDReader(fd) + + +class SerialLineSource: + """Единый интерфейс для чтения строк из порта (pyserial или raw TTY).""" + + def __init__(self, path: str, baud: int, timeout: float = 1.0): + self._pyserial = try_open_pyserial(path, baud, timeout) + self._fdreader = None + self._using = "pyserial" if self._pyserial is not None else "raw" + if self._pyserial is None: + self._fdreader = open_raw_tty(path, baud) + if self._fdreader is None: + msg = f"Не удалось открыть порт '{path}' (pyserial и raw TTY не сработали)" + if sys.platform.startswith("win"): + msg += ". На Windows нужен pyserial: pip install pyserial" + raise RuntimeError(msg) + + def readline(self) -> bytes: + if self._pyserial is not None: + try: + return self._pyserial.readline() + except Exception: + return b"" + else: + try: + return self._fdreader.readline() # type: ignore[union-attr] + except Exception: + return b"" + + def close(self): + try: + if self._pyserial is not None: + self._pyserial.close() + elif self._fdreader is not None: + self._fdreader.close() + except Exception: + pass + + +class SerialChunkReader: + """Быстрое неблокирующее чтение чанков из serial/raw TTY для максимального дренажа буфера.""" + + def __init__(self, src: SerialLineSource): + self._src = src + self._ser = src._pyserial + self._fd: Optional[int] = None + if self._ser is not None: + try: + self._ser.timeout = 0 + except Exception: + pass + else: + try: + self._fd = src._fdreader.fileno() # type: ignore[union-attr] + try: + os.set_blocking(self._fd, False) + except Exception: + pass + except Exception: + self._fd = None + + def read_available(self) -> bytes: + """Вернёт доступные байты (b"" если данных нет).""" + if self._ser is not None: + try: + n = int(getattr(self._ser, "in_waiting", 0)) + except Exception: + n = 0 + if n > 0: + try: + return self._ser.read(n) + except Exception: + return b"" + return b"" + if self._fd is None: + return b"" + out = bytearray() + while True: + try: + chunk = os.read(self._fd, 65536) + if not chunk: + break + out += chunk + if len(chunk) < 65536: + break + except BlockingIOError: + break + except Exception: + break + return bytes(out) diff --git a/rfg_adc_plotter/io/sweep_reader.py b/rfg_adc_plotter/io/sweep_reader.py new file mode 100644 index 0000000..31768a6 --- /dev/null +++ b/rfg_adc_plotter/io/sweep_reader.py @@ -0,0 +1,217 @@ +"""Фоновый поток чтения и парсинга свипов из последовательного порта.""" + +import sys +import threading +import time +from collections import deque +from queue import Full, Queue +from typing import Optional + +import numpy as np + +from rfg_adc_plotter.constants import DATA_INVERSION_THRESHOLD +from rfg_adc_plotter.io.serial_source import SerialChunkReader, SerialLineSource +from rfg_adc_plotter.types import SweepInfo, SweepPacket + + +class SweepReader(threading.Thread): + """Фоновый поток: читает строки, формирует завершённые свипы и кладёт в очередь.""" + + def __init__( + self, + port_path: str, + baud: int, + out_queue: "Queue[SweepPacket]", + stop_event: threading.Event, + fancy: bool = False, + ): + super().__init__(daemon=True) + self._port_path = port_path + self._baud = baud + self._q = out_queue + self._stop = stop_event + self._src: Optional[SerialLineSource] = None + self._fancy = bool(fancy) + self._max_width: int = 0 + self._sweep_idx: int = 0 + self._last_sweep_ts: Optional[float] = None + self._n_valid_hist = deque() + + def _finalize_current(self, xs, ys, channels: Optional[set]): + if not xs: + return + ch_list = sorted(channels) if channels else [0] + ch_primary = ch_list[0] if ch_list else 0 + max_x = max(xs) + width = max_x + 1 + self._max_width = max(self._max_width, width) + target_width = self._max_width if self._fancy else width + + sweep = np.full((target_width,), np.nan, dtype=np.float32) + try: + idx = np.asarray(xs, dtype=np.int64) + vals = np.asarray(ys, dtype=np.float32) + sweep[idx] = vals + except Exception: + for x, y in zip(xs, ys): + if 0 <= x < target_width: + sweep[x] = float(y) + + finite_pre = np.isfinite(sweep) + n_valid_cur = int(np.count_nonzero(finite_pre)) + + if self._fancy: + try: + known = ~np.isnan(sweep) + if np.any(known): + known_idx = np.nonzero(known)[0] + for i0, i1 in zip(known_idx[:-1], known_idx[1:]): + if i1 - i0 > 1: + avg = (sweep[i0] + sweep[i1]) * 0.5 + sweep[i0 + 1 : i1] = avg + first_idx = int(known_idx[0]) + last_idx = int(known_idx[-1]) + if first_idx > 0: + sweep[:first_idx] = sweep[first_idx] + if last_idx < sweep.size - 1: + sweep[last_idx + 1 :] = sweep[last_idx] + except Exception: + pass + + try: + m = float(np.nanmean(sweep)) + if np.isfinite(m) and m < DATA_INVERSION_THRESHOLD: + sweep *= -1.0 + except Exception: + pass + + self._sweep_idx += 1 + if len(ch_list) > 1: + sys.stderr.write( + f"[warn] Sweep {self._sweep_idx}: изменялся номер канала: {ch_list}\n" + ) + now = time.time() + if self._last_sweep_ts is None: + dt_ms = float("nan") + else: + dt_ms = (now - self._last_sweep_ts) * 1000.0 + self._last_sweep_ts = now + self._n_valid_hist.append((now, n_valid_cur)) + while self._n_valid_hist and (now - self._n_valid_hist[0][0]) > 1.0: + self._n_valid_hist.popleft() + if self._n_valid_hist: + n_valid = float(sum(v for _t, v in self._n_valid_hist) / len(self._n_valid_hist)) + else: + n_valid = float(n_valid_cur) + + if n_valid_cur > 0: + vmin = float(np.nanmin(sweep)) + vmax = float(np.nanmax(sweep)) + mean = float(np.nanmean(sweep)) + std = float(np.nanstd(sweep)) + else: + vmin = vmax = mean = std = float("nan") + info: SweepInfo = { + "sweep": self._sweep_idx, + "ch": ch_primary, + "chs": ch_list, + "n_valid": n_valid, + "min": vmin, + "max": vmax, + "mean": mean, + "std": std, + "dt_ms": dt_ms, + } + + try: + self._q.put_nowait((sweep, info)) + except Full: + try: + _ = self._q.get_nowait() + except Exception: + pass + try: + self._q.put_nowait((sweep, info)) + except Exception: + pass + + def run(self): + xs: list = [] + ys: list = [] + cur_channel: Optional[int] = None + cur_channels: set = set() + + try: + self._src = SerialLineSource(self._port_path, self._baud, timeout=1.0) + sys.stderr.write(f"[info] Открыл порт {self._port_path} ({self._src._using})\n") + except Exception as e: + sys.stderr.write(f"[error] {e}\n") + return + + try: + chunk_reader = SerialChunkReader(self._src) + buf = bytearray() + while not self._stop.is_set(): + data = chunk_reader.read_available() + if data: + buf += data + else: + time.sleep(0.0005) + continue + + while True: + nl = buf.find(b"\n") + if nl == -1: + break + line = bytes(buf[:nl]) + del buf[: nl + 1] + if line.endswith(b"\r"): + line = line[:-1] + if not line: + continue + + if line.startswith(b"Sweep_start"): + self._finalize_current(xs, ys, cur_channels) + xs.clear() + ys.clear() + cur_channel = None + cur_channels.clear() + continue + + if len(line) >= 3: + parts = line.split() + if len(parts) >= 3 and (parts[0].lower() == b"s" or parts[0].lower().startswith(b"s")): + try: + if parts[0].lower() == b"s": + if len(parts) >= 4: + ch = int(parts[1], 10) + x = int(parts[2], 10) + y = int(parts[3], 10) + else: + ch = 0 + x = int(parts[1], 10) + y = int(parts[2], 10) + else: + ch = int(parts[0][1:], 10) + x = int(parts[1], 10) + y = int(parts[2], 10) + except Exception: + continue + if cur_channel is None: + cur_channel = ch + cur_channels.add(ch) + xs.append(x) + ys.append(y) + + if len(buf) > 1_000_000: + del buf[:-262144] + finally: + try: + self._finalize_current(xs, ys, cur_channels) + except Exception: + pass + try: + if self._src is not None: + self._src.close() + except Exception: + pass diff --git a/rfg_adc_plotter/main.py b/rfg_adc_plotter/main.py new file mode 100644 index 0000000..78e4e02 --- /dev/null +++ b/rfg_adc_plotter/main.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +""" +Реалтайм-плоттер для свипов из виртуального COM-порта. + +Формат строк: + - "Sweep_start" — начало нового свипа (предыдущий считается завершённым) + - "s CH X Y" — точка (номер канала, индекс X, значение Y), все целые со знаком + +Отрисовываются четыре графика: + - Сырые данные: последний полученный свип (Y vs X) + - Водопад сырых данных: последние N свипов + - FFT текущего свипа + - B-scan: водопад FFT-строк + +Зависимости: numpy. PySerial опционален — при его отсутствии +используется сырой доступ к TTY через termios. +GUI: matplotlib (совместимый) или pyqtgraph (быстрый). +""" + +import argparse +import sys + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Читает свипы из виртуального COM-порта и рисует: " + "последний свип и водопад (реалтайм)." + ) + ) + parser.add_argument( + "port", + help="Путь к порту, например /dev/ttyACM1 или COM3 (COM10+: \\\\.\\COM10)", + ) + parser.add_argument("--baud", type=int, default=115200, help="Скорость (по умолчанию 115200)") + parser.add_argument("--max-sweeps", type=int, default=200, help="Количество видимых свипов в водопаде") + parser.add_argument("--max-fps", type=float, default=30.0, help="Лимит частоты отрисовки, кадров/с") + parser.add_argument("--cmap", default="viridis", help="Цветовая карта водопада") + parser.add_argument( + "--spec-clip", + default="2,98", + help=( + "Процентильная обрезка уровней водопада спектров, %% (min,max). " + "Напр. 2,98. 'off' — отключить" + ), + ) + parser.add_argument( + "--spec-mean-sec", + type=float, + default=0.0, + help=( + "Вычитание среднего по каждой частоте за последние N секунд " + "в водопаде спектров (0 — отключить)" + ), + ) + parser.add_argument("--title", default="ADC Sweeps", help="Заголовок окна") + parser.add_argument( + "--fancy", + action="store_true", + help="Заполнять выпавшие точки средними значениями между соседними", + ) + parser.add_argument( + "--ylim", + type=str, + default=None, + help="Фиксированные Y-пределы для кривой формата min,max (например -1000,1000). По умолчанию авто", + ) + parser.add_argument( + "--backend", + choices=["auto", "pg", "mpl"], + default="auto", + help="Графический бэкенд: pyqtgraph (pg) — быстрее; matplotlib (mpl) — совместимый. По умолчанию auto", + ) + parser.add_argument( + "--norm-type", + choices=["projector", "simple"], + default="projector", + help="Тип нормировки: projector (по огибающим в [-1000,+1000]) или simple (raw/calib)", + ) + return parser + + +def main(): + args = build_parser().parse_args() + + if args.backend == "pg": + from rfg_adc_plotter.gui.pyqtgraph_backend import run_pyqtgraph + try: + run_pyqtgraph(args) + except Exception as e: + sys.stderr.write(f"[error] PyQtGraph бэкенд недоступен: {e}\n") + sys.exit(1) + return + + if args.backend == "auto": + try: + from rfg_adc_plotter.gui.pyqtgraph_backend import run_pyqtgraph + run_pyqtgraph(args) + return + except Exception: + pass # Откатываемся на matplotlib + + from rfg_adc_plotter.gui.matplotlib_backend import run_matplotlib + run_matplotlib(args) + + +if __name__ == "__main__": + main() diff --git a/rfg_adc_plotter/processing/__init__.py b/rfg_adc_plotter/processing/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/rfg_adc_plotter/processing/normalizer.py b/rfg_adc_plotter/processing/normalizer.py new file mode 100644 index 0000000..10780d5 --- /dev/null +++ b/rfg_adc_plotter/processing/normalizer.py @@ -0,0 +1,115 @@ +"""Алгоритмы нормировки свипов по калибровочной кривой.""" + +from typing import Tuple + +import numpy as np + + +def normalize_simple(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: + """Простая нормировка: поэлементное деление raw/calib.""" + w = min(raw.size, calib.size) + if w <= 0: + return raw + out = np.full_like(raw, np.nan, dtype=np.float32) + with np.errstate(divide="ignore", invalid="ignore"): + out[:w] = raw[:w] / calib[:w] + out = np.nan_to_num(out, nan=np.nan, posinf=np.nan, neginf=np.nan) + return out + + +def build_calib_envelopes(calib: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """Оценить нижнюю/верхнюю огибающие калибровочной кривой.""" + n = int(calib.size) + if n <= 0: + empty = np.zeros((0,), dtype=np.float32) + return empty, empty + + y = np.asarray(calib, dtype=np.float32) + finite = np.isfinite(y) + if not np.any(finite): + zeros = np.zeros_like(y, dtype=np.float32) + return zeros, zeros + + if not np.all(finite): + x = np.arange(n, dtype=np.float32) + y = y.copy() + y[~finite] = np.interp(x[~finite], x[finite], y[finite]).astype(np.float32) + + if n < 3: + return y.copy(), y.copy() + + dy = np.diff(y) + s = np.sign(dy).astype(np.int8, copy=False) + + if np.any(s == 0): + for i in range(1, s.size): + if s[i] == 0: + s[i] = s[i - 1] + for i in range(s.size - 2, -1, -1): + if s[i] == 0: + s[i] = s[i + 1] + s[s == 0] = 1 + + max_idx = np.where((s[:-1] > 0) & (s[1:] < 0))[0] + 1 + min_idx = np.where((s[:-1] < 0) & (s[1:] > 0))[0] + 1 + + x = np.arange(n, dtype=np.float32) + + def _interp_nodes(nodes: np.ndarray) -> np.ndarray: + if nodes.size == 0: + idx = np.array([0, n - 1], dtype=np.int64) + else: + idx = np.unique(np.concatenate(([0], nodes, [n - 1]))).astype(np.int64) + return np.interp(x, idx.astype(np.float32), y[idx]).astype(np.float32) + + upper = _interp_nodes(max_idx) + lower = _interp_nodes(min_idx) + + swap = lower > upper + if np.any(swap): + tmp = upper[swap].copy() + upper[swap] = lower[swap] + lower[swap] = tmp + + return lower, upper + + +def normalize_projector(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: + """Нормировка через проекцию между огибающими калибровки в диапазон [-1000, +1000].""" + w = min(raw.size, calib.size) + if w <= 0: + return raw + + out = np.full_like(raw, np.nan, dtype=np.float32) + raw_seg = np.asarray(raw[:w], dtype=np.float32) + lower, upper = build_calib_envelopes(np.asarray(calib[:w], dtype=np.float32)) + span = upper - lower + + finite_span = span[np.isfinite(span) & (span > 0)] + if finite_span.size > 0: + eps = max(float(np.median(finite_span)) * 1e-6, 1e-9) + else: + eps = 1e-9 + + valid = ( + np.isfinite(raw_seg) + & np.isfinite(lower) + & np.isfinite(upper) + & (span > eps) + ) + if np.any(valid): + proj = np.empty_like(raw_seg, dtype=np.float32) + proj[valid] = ((2.0 * (raw_seg[valid] - lower[valid]) / span[valid]) - 1.0) * 1000.0 + proj[valid] = np.clip(proj[valid], -1000.0, 1000.0) + proj[~valid] = np.nan + out[:w] = proj + + return out + + +def normalize_by_calib(raw: np.ndarray, calib: np.ndarray, norm_type: str) -> np.ndarray: + """Нормировка свипа по выбранному алгоритму.""" + nt = str(norm_type).strip().lower() + if nt == "simple": + return normalize_simple(raw, calib) + return normalize_projector(raw, calib) diff --git a/rfg_adc_plotter/state/__init__.py b/rfg_adc_plotter/state/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/rfg_adc_plotter/state/app_state.py b/rfg_adc_plotter/state/app_state.py new file mode 100644 index 0000000..1ad5682 --- /dev/null +++ b/rfg_adc_plotter/state/app_state.py @@ -0,0 +1,119 @@ +"""Состояние приложения: текущие свипы и настройки калибровки/нормировки.""" + +from queue import Empty, Queue +from typing import Any, Dict, Mapping, Optional + +import numpy as np + +from rfg_adc_plotter.processing.normalizer import normalize_by_calib +from rfg_adc_plotter.state.ring_buffer import RingBuffer +from rfg_adc_plotter.types import SweepInfo, SweepPacket + + +def format_status(data: Mapping[str, Any]) -> str: + """Преобразовать словарь метрик в одну строку 'k:v'.""" + + def _fmt(v: Any) -> str: + if v is None: + return "NA" + try: + fv = float(v) + except Exception: + return str(v) + if not np.isfinite(fv): + return "nan" + if abs(fv) >= 1000 or (0 < abs(fv) < 0.01): + return f"{fv:.3g}" + return f"{fv:.3f}".rstrip("0").rstrip(".") + + parts = [f"{k}:{_fmt(v)}" for k, v in data.items()] + return " ".join(parts) + + +class AppState: + """Весь изменяемый GUI-state: текущие данные, калибровка, настройки. + + Методы drain_queue и set_calib_enabled заменяют одноимённые closures + с nonlocal из оригинального кода. + """ + + def __init__(self, norm_type: str = "projector"): + self.current_sweep_raw: Optional[np.ndarray] = None + self.current_sweep_norm: Optional[np.ndarray] = None + self.last_calib_sweep: Optional[np.ndarray] = None + self.current_info: Optional[SweepInfo] = None + self.calib_enabled: bool = False + self.norm_type: str = norm_type + + def _normalize(self, raw: np.ndarray, calib: np.ndarray) -> np.ndarray: + return normalize_by_calib(raw, calib, self.norm_type) + + def set_calib_enabled(self, enabled: bool): + """Включить/выключить режим калибровки, пересчитать norm-свип.""" + self.calib_enabled = enabled + if ( + self.calib_enabled + and self.current_sweep_raw is not None + and self.last_calib_sweep is not None + ): + self.current_sweep_norm = self._normalize( + self.current_sweep_raw, self.last_calib_sweep + ) + else: + self.current_sweep_norm = None + + def drain_queue(self, q: "Queue[SweepPacket]", ring: RingBuffer) -> int: + """Вытащить все ожидающие свипы из очереди, обновить state и ring. + + Возвращает количество обработанных свипов. + """ + drained = 0 + while True: + try: + s, info = q.get_nowait() + except Empty: + break + drained += 1 + self.current_sweep_raw = s + self.current_info = info + + ch = 0 + try: + ch = int(info.get("ch", 0)) if isinstance(info, dict) else 0 + except Exception: + ch = 0 + + # Канал 0 — опорный (калибровочный) свип + if ch == 0: + self.last_calib_sweep = s + self.current_sweep_norm = None + sweep_for_ring = s + else: + if self.calib_enabled and self.last_calib_sweep is not None: + self.current_sweep_norm = self._normalize(s, self.last_calib_sweep) + sweep_for_ring = self.current_sweep_norm + else: + self.current_sweep_norm = None + sweep_for_ring = s + + ring.ensure_init(s.size) + ring.push(sweep_for_ring) + return drained + + def format_channel_label(self) -> str: + """Строка с номерами каналов для подписи на графике.""" + if self.current_info is None: + return "" + info = self.current_info + chs = info.get("chs") if isinstance(info, dict) else None + if chs is None: + chs = info.get("ch") if isinstance(info, dict) else None + if chs is None: + return "" + try: + if isinstance(chs, (list, tuple, set)): + ch_list = sorted(int(v) for v in chs) + return "chs " + ", ".join(str(v) for v in ch_list) + return f"chs {int(chs)}" + except Exception: + return f"chs {chs}" diff --git a/rfg_adc_plotter/state/ring_buffer.py b/rfg_adc_plotter/state/ring_buffer.py new file mode 100644 index 0000000..56d3334 --- /dev/null +++ b/rfg_adc_plotter/state/ring_buffer.py @@ -0,0 +1,166 @@ +"""Кольцевой буфер свипов и FFT-строк для водопадного отображения.""" + +import time +from typing import Optional, Tuple + +import numpy as np + +from rfg_adc_plotter.constants import FFT_LEN, WF_WIDTH + + +class RingBuffer: + """Хранит последние N свипов и соответствующие FFT-строки. + + Все мутабельные поля водопада инкапсулированы здесь, + что устраняет необходимость nonlocal в GUI-коде. + """ + + def __init__(self, max_sweeps: int): + self.max_sweeps = max_sweeps + self.fft_bins = FFT_LEN // 2 + 1 + + # Инициализируются при первом свипе (ensure_init) + self.ring: Optional[np.ndarray] = None # (max_sweeps, WF_WIDTH) + self.ring_fft: Optional[np.ndarray] = None # (max_sweeps, fft_bins) + self.ring_time: Optional[np.ndarray] = None # (max_sweeps,) + self.head: int = 0 + self.width: Optional[int] = None + self.x_shared: Optional[np.ndarray] = None + self.freq_shared: Optional[np.ndarray] = None + self.y_min_fft: Optional[float] = None + self.y_max_fft: Optional[float] = None + # FFT последнего свипа (для отображения без повторного вычисления) + self.last_fft_vals: Optional[np.ndarray] = None + + @property + def is_ready(self) -> bool: + return self.ring is not None + + def ensure_init(self, sweep_width: int): + """Инициализировать буферы при первом свипе. Повторные вызовы — no-op.""" + if self.ring is not None: + return + self.width = WF_WIDTH + self.x_shared = np.arange(self.width, dtype=np.int32) + self.ring = np.full((self.max_sweeps, self.width), np.nan, dtype=np.float32) + self.ring_time = np.full((self.max_sweeps,), np.nan, dtype=np.float64) + self.ring_fft = np.full((self.max_sweeps, self.fft_bins), np.nan, dtype=np.float32) + self.freq_shared = np.arange(self.fft_bins, dtype=np.int32) + self.head = 0 + + def push(self, s: np.ndarray): + """Добавить строку свипа в кольцевой буфер, вычислить FFT-строку.""" + if s is None or s.size == 0 or self.ring is None: + return + w = self.ring.shape[1] + row = np.full((w,), np.nan, dtype=np.float32) + take = min(w, s.size) + row[:take] = s[:take] + self.ring[self.head, :] = row + self.ring_time[self.head] = time.time() + self.head = (self.head + 1) % self.ring.shape[0] + + self._push_fft(s) + + def _push_fft(self, s: np.ndarray): + bins = self.ring_fft.shape[1] + take_fft = min(int(s.size), FFT_LEN) + if take_fft <= 0: + fft_row = np.full((bins,), np.nan, dtype=np.float32) + else: + fft_in = np.zeros((FFT_LEN,), dtype=np.float32) + seg = np.nan_to_num(s[:take_fft], nan=0.0).astype(np.float32, copy=False) + win = np.hanning(take_fft).astype(np.float32) + fft_in[:take_fft] = seg * win + spec = np.fft.rfft(fft_in) + mag = np.abs(spec).astype(np.float32) + fft_row = (20.0 * np.log10(mag + 1e-9)).astype(np.float32) + if fft_row.shape[0] != bins: + fft_row = fft_row[:bins] + + prev_head = (self.head - 1) % self.ring_fft.shape[0] + self.ring_fft[prev_head, :] = fft_row + self.last_fft_vals = fft_row + + fr_min = np.nanmin(fft_row) + fr_max = float(np.nanpercentile(fft_row, 90)) + if self.y_min_fft is None or (not np.isnan(fr_min) and fr_min < self.y_min_fft): + self.y_min_fft = float(fr_min) + if self.y_max_fft is None or (not np.isnan(fr_max) and fr_max > self.y_max_fft): + self.y_max_fft = float(fr_max) + + def get_display_ring(self) -> np.ndarray: + """Кольцо в порядке от старого к новому, ось времени по X. Форма: (width, time).""" + if self.ring is None: + return np.zeros((1, 1), dtype=np.float32) + base = self.ring if self.head == 0 else np.roll(self.ring, -self.head, axis=0) + return base.T # (width, time) + + def get_display_ring_fft(self) -> np.ndarray: + """FFT-кольцо в порядке от старого к новому. Форма: (bins, time).""" + if self.ring_fft is None: + return np.zeros((1, 1), dtype=np.float32) + base = self.ring_fft if self.head == 0 else np.roll(self.ring_fft, -self.head, axis=0) + return base.T # (bins, time) + + def get_display_times(self) -> Optional[np.ndarray]: + """Временные метки строк в порядке от старого к новому.""" + if self.ring_time is None: + return None + return self.ring_time if self.head == 0 else np.roll(self.ring_time, -self.head) + + def subtract_recent_mean_fft( + self, disp_fft: np.ndarray, spec_mean_sec: float + ) -> np.ndarray: + """Вычесть среднее по каждой частоте за последние spec_mean_sec секунд.""" + if spec_mean_sec <= 0.0: + return disp_fft + disp_times = self.get_display_times() + if disp_times is None: + return disp_fft + now_t = time.time() + mask = np.isfinite(disp_times) & (disp_times >= (now_t - spec_mean_sec)) + if not np.any(mask): + return disp_fft + try: + mean_spec = np.nanmean(disp_fft[:, mask], axis=1) + except Exception: + return disp_fft + mean_spec = np.nan_to_num(mean_spec, nan=0.0) + return disp_fft - mean_spec[:, None] + + def compute_fft_levels( + self, disp_fft: np.ndarray, spec_clip: Optional[Tuple[float, float]] + ) -> Optional[Tuple[float, float]]: + """Вычислить (vmin, vmax) для отображения водопада спектров.""" + # 1. По среднему спектру за видимое время + try: + mean_spec = np.nanmean(disp_fft, axis=1) + vmin_v = float(np.nanmin(mean_spec)) + vmax_v = float(np.nanmax(mean_spec)) + if np.isfinite(vmin_v) and np.isfinite(vmax_v) and vmin_v != vmax_v: + return (vmin_v, vmax_v) + except Exception: + pass + + # 2. Процентильная обрезка + if spec_clip is not None: + try: + vmin_v = float(np.nanpercentile(disp_fft, spec_clip[0])) + vmax_v = float(np.nanpercentile(disp_fft, spec_clip[1])) + if np.isfinite(vmin_v) and np.isfinite(vmax_v) and vmin_v != vmax_v: + return (vmin_v, vmax_v) + except Exception: + pass + + # 3. Глобальные накопленные мин/макс + if ( + self.y_min_fft is not None + and self.y_max_fft is not None + and np.isfinite(self.y_min_fft) + and np.isfinite(self.y_max_fft) + and self.y_min_fft != self.y_max_fft + ): + return (self.y_min_fft, self.y_max_fft) + + return None diff --git a/rfg_adc_plotter/types.py b/rfg_adc_plotter/types.py new file mode 100644 index 0000000..7b53fb3 --- /dev/null +++ b/rfg_adc_plotter/types.py @@ -0,0 +1,7 @@ +from typing import Any, Dict, Tuple, Union + +import numpy as np + +Number = Union[int, float] +SweepInfo = Dict[str, Any] +SweepPacket = Tuple[np.ndarray, SweepInfo] -- 2.49.0 From ea57f879200faf3de5e8aad74f5aa26f6a54e2c1 Mon Sep 17 00:00:00 2001 From: awe Date: Wed, 11 Feb 2026 18:27:12 +0300 Subject: [PATCH 04/13] new graph style --- RFG_ADC_dataplotter.py | 41 ++++++------- rfg_adc_plotter/gui/matplotlib_backend.py | 54 ++++++++++------- rfg_adc_plotter/gui/pyqtgraph_backend.py | 72 +++++++++++++++++------ rfg_adc_plotter/processing/normalizer.py | 40 ++++++------- rfg_adc_plotter/state/ring_buffer.py | 21 +++---- 5 files changed, 131 insertions(+), 97 deletions(-) diff --git a/RFG_ADC_dataplotter.py b/RFG_ADC_dataplotter.py index 80fbf32..d4cade9 100755 --- a/RFG_ADC_dataplotter.py +++ b/RFG_ADC_dataplotter.py @@ -1019,31 +1019,24 @@ def main(): xs = x_shared[: current_sweep_raw.size] else: xs = np.arange(current_sweep_raw.size, dtype=np.int32) - line_obj.set_data(xs, current_sweep_raw) + def _norm_to_max(data): + m = float(np.nanmax(np.abs(data))) + return data / m if m > 0.0 else data + line_obj.set_data(xs, _norm_to_max(current_sweep_raw)) if last_calib_sweep is not None: - line_calib_obj.set_data(xs[: last_calib_sweep.size], last_calib_sweep) + line_calib_obj.set_data(xs[: last_calib_sweep.size], _norm_to_max(last_calib_sweep)) else: line_calib_obj.set_data([], []) if current_sweep_norm is not None: - line_norm_obj.set_data(xs[: current_sweep_norm.size], current_sweep_norm) + line_norm_obj.set_data(xs[: current_sweep_norm.size], _norm_to_max(current_sweep_norm)) else: line_norm_obj.set_data([], []) # Лимиты по X постоянные под текущую ширину ax_line.set_xlim(0, max(1, current_sweep_raw.size - 1)) - # Адаптивные Y-лимиты (если не задан --ylim) + # Фиксированные Y-лимиты после нормировки на максимум if fixed_ylim is None: - y0 = float(np.nanmin(current_sweep_raw)) - y1 = float(np.nanmax(current_sweep_raw)) - if np.isfinite(y0) and np.isfinite(y1): - if y0 == y1: - pad = max(1.0, abs(y0) * 0.05) - y0 -= pad - y1 += pad - else: - pad = 0.05 * (y1 - y0) - y0 -= pad - y1 += pad - ax_line.set_ylim(y0, y1) + ax_line.set_ylim(-1.05, 1.05) + ax_line.set_ylabel("/ max") # Обновление спектра текущего свипа sweep_for_fft = current_sweep_norm if current_sweep_norm is not None else current_sweep_raw @@ -1422,21 +1415,21 @@ def run_pyqtgraph(args): xs = x_shared[: current_sweep_raw.size] else: xs = np.arange(current_sweep_raw.size) - curve.setData(xs, current_sweep_raw, autoDownsample=True) + def _norm_to_max(data): + m = float(np.nanmax(np.abs(data))) + return data / m if m > 0.0 else data + curve.setData(xs, _norm_to_max(current_sweep_raw), autoDownsample=True) if last_calib_sweep is not None: - curve_calib.setData(xs[: last_calib_sweep.size], last_calib_sweep, autoDownsample=True) + curve_calib.setData(xs[: last_calib_sweep.size], _norm_to_max(last_calib_sweep), autoDownsample=True) else: curve_calib.setData([], []) if current_sweep_norm is not None: - curve_norm.setData(xs[: current_sweep_norm.size], current_sweep_norm, autoDownsample=True) + curve_norm.setData(xs[: current_sweep_norm.size], _norm_to_max(current_sweep_norm), autoDownsample=True) else: curve_norm.setData([], []) if fixed_ylim is None: - y0 = float(np.nanmin(current_sweep_raw)) - y1 = float(np.nanmax(current_sweep_raw)) - if np.isfinite(y0) and np.isfinite(y1): - margin = 0.05 * max(1.0, (y1 - y0)) - p_line.setYRange(y0 - margin, y1 + margin, padding=0) + p_line.setYRange(-1.05, 1.05, padding=0) + p_line.setLabel("left", "/ max") # Обновим спектр sweep_for_fft = current_sweep_norm if current_sweep_norm is not None else current_sweep_raw diff --git a/rfg_adc_plotter/gui/matplotlib_backend.py b/rfg_adc_plotter/gui/matplotlib_backend.py index c6664b0..1f80a8a 100644 --- a/rfg_adc_plotter/gui/matplotlib_backend.py +++ b/rfg_adc_plotter/gui/matplotlib_backend.py @@ -9,6 +9,7 @@ import numpy as np from rfg_adc_plotter.constants import FFT_LEN from rfg_adc_plotter.io.sweep_reader import SweepReader +from rfg_adc_plotter.processing.normalizer import build_calib_envelopes from rfg_adc_plotter.state.app_state import AppState, format_status from rfg_adc_plotter.state.ring_buffer import RingBuffer from rfg_adc_plotter.types import SweepPacket @@ -112,10 +113,11 @@ def run_matplotlib(args): # График последнего свипа line_obj, = ax_line.plot([], [], lw=1, color="tab:blue") - line_calib_obj, = ax_line.plot([], [], lw=1, color="tab:red") line_norm_obj, = ax_line.plot([], [], lw=1, color="tab:green") + line_env_lo, = ax_line.plot([], [], lw=1, color="tab:orange", linestyle="--", alpha=0.7) + line_env_hi, = ax_line.plot([], [], lw=1, color="tab:orange", linestyle="--", alpha=0.7) ax_line.set_title("Сырые данные", pad=1) - ax_line.set_xlabel("F") + ax_line.set_xlabel("Частота, ГГц") channel_text = ax_line.text( 0.98, 0.98, "", transform=ax_line.transAxes, ha="right", va="top", fontsize=9, family="monospace", @@ -184,15 +186,18 @@ def run_matplotlib(args): except Exception: calib_cb = None + FREQ_MIN = 3.323 + FREQ_MAX = 14.323 + # --- Инициализация imshow при первом свипе --- def _init_imshow_extents(): w = ring.width ms = ring.max_sweeps fb = ring.fft_bins img_obj.set_data(np.zeros((w, ms), dtype=np.float32)) - img_obj.set_extent((0, ms - 1, 0, w - 1 if w > 0 else 1)) + img_obj.set_extent((0, ms - 1, FREQ_MIN, FREQ_MAX)) ax_img.set_xlim(0, ms - 1) - ax_img.set_ylim(0, max(1, w - 1)) + ax_img.set_ylim(FREQ_MIN, FREQ_MAX) img_fft_obj.set_data(np.zeros((fb, ms), dtype=np.float32)) img_fft_obj.set_extent((0, ms - 1, 0, fb - 1)) ax_spec.set_xlim(0, ms - 1) @@ -214,29 +219,29 @@ def run_matplotlib(args): xs = ring.x_shared[: raw.size] else: xs = np.arange(raw.size, dtype=np.int32) - line_obj.set_data(xs, raw) + def _norm_to_max(data): + m = float(np.nanmax(np.abs(data))) + return data / m if m > 0.0 else data + line_obj.set_data(xs, _norm_to_max(raw)) if state.last_calib_sweep is not None: - line_calib_obj.set_data(xs[: state.last_calib_sweep.size], state.last_calib_sweep) + calib = state.last_calib_sweep + m_calib = float(np.nanmax(np.abs(calib))) + if m_calib <= 0.0: + m_calib = 1.0 + lower, upper = build_calib_envelopes(calib) + line_env_lo.set_data(xs[: calib.size], lower / m_calib) + line_env_hi.set_data(xs[: calib.size], upper / m_calib) else: - line_calib_obj.set_data([], []) + line_env_lo.set_data([], []) + line_env_hi.set_data([], []) if state.current_sweep_norm is not None: - line_norm_obj.set_data(xs[: state.current_sweep_norm.size], state.current_sweep_norm) + line_norm_obj.set_data(xs[: state.current_sweep_norm.size], _norm_to_max(state.current_sweep_norm)) else: line_norm_obj.set_data([], []) - ax_line.set_xlim(0, max(1, raw.size - 1)) + ax_line.set_xlim(FREQ_MIN, FREQ_MAX) if fixed_ylim is None: - y0 = float(np.nanmin(raw)) - y1 = float(np.nanmax(raw)) - if np.isfinite(y0) and np.isfinite(y1): - if y0 == y1: - pad = max(1.0, abs(y0) * 0.05) - y0 -= pad - y1 += pad - else: - pad = 0.05 * (y1 - y0) - y0 -= pad - y1 += pad - ax_line.set_ylim(y0, y1) + ax_line.set_ylim(-1.05, 1.05) + ax_line.set_ylabel("/ max") # Спектр — используем уже вычисленный в ring FFT if ring.last_fft_vals is not None and ring.freq_shared is not None: @@ -252,7 +257,12 @@ def run_matplotlib(args): # Водопад сырых данных if changed and ring.is_ready: disp = ring.get_display_ring() + if ring.x_shared is not None: + n = ring.x_shared.size + disp = disp[:n, :] img_obj.set_data(disp) + img_obj.set_extent((0, ring.max_sweeps - 1, FREQ_MIN, FREQ_MAX)) + ax_img.set_ylim(FREQ_MIN, FREQ_MAX) levels = _visible_levels(disp, ax_img) if levels is not None: img_obj.set_clim(vmin=levels[0], vmax=levels[1]) @@ -276,7 +286,7 @@ def run_matplotlib(args): status_text.set_text(format_status(state.current_info)) channel_text.set_text(state.format_channel_label()) - return (line_obj, line_calib_obj, line_norm_obj, img_obj, fft_line_obj, img_fft_obj, status_text, channel_text) + return (line_obj, line_norm_obj, line_env_lo, line_env_hi, img_obj, fft_line_obj, img_fft_obj, status_text, channel_text) ani = FuncAnimation(fig, update, interval=interval_ms, blit=False) plt.show() diff --git a/rfg_adc_plotter/gui/pyqtgraph_backend.py b/rfg_adc_plotter/gui/pyqtgraph_backend.py index afe01eb..54136be 100644 --- a/rfg_adc_plotter/gui/pyqtgraph_backend.py +++ b/rfg_adc_plotter/gui/pyqtgraph_backend.py @@ -8,6 +8,7 @@ from typing import Optional, Tuple import numpy as np from rfg_adc_plotter.io.sweep_reader import SweepReader +from rfg_adc_plotter.processing.normalizer import build_calib_envelopes from rfg_adc_plotter.state.app_state import AppState, format_status from rfg_adc_plotter.state.ring_buffer import RingBuffer from rfg_adc_plotter.types import SweepPacket @@ -39,8 +40,17 @@ def _parse_spec_clip(spec: Optional[str]) -> Optional[Tuple[float, float]]: return None -def _visible_levels(data: np.ndarray, plot_item) -> Optional[Tuple[float, float]]: - """(vmin, vmax) по текущей видимой области ImageItem.""" +def _visible_levels( + data: np.ndarray, + plot_item, + freq_min: Optional[float] = None, + freq_max: Optional[float] = None, +) -> Optional[Tuple[float, float]]: + """(vmin, vmax) по текущей видимой области ImageItem. + + Если freq_min/freq_max заданы, ось Y трактуется как частота [freq_min..freq_max] + и пересчитывается в индексы строк данных. + """ if data.size == 0: return None ny, nx = data.shape[0], data.shape[1] @@ -53,8 +63,13 @@ def _visible_levels(data: np.ndarray, plot_item) -> Optional[Tuple[float, float] ymin, ymax = sorted((float(y0), float(y1))) ix0 = max(0, min(nx - 1, int(np.floor(xmin)))) ix1 = max(0, min(nx - 1, int(np.ceil(xmax)))) - iy0 = max(0, min(ny - 1, int(np.floor(ymin)))) - iy1 = max(0, min(ny - 1, int(np.ceil(ymax)))) + if freq_min is not None and freq_max is not None and freq_max > freq_min: + span = freq_max - freq_min + iy0 = max(0, min(ny - 1, int(np.floor((ymin - freq_min) / span * ny)))) + iy1 = max(0, min(ny - 1, int(np.ceil((ymax - freq_min) / span * ny)))) + else: + iy0 = max(0, min(ny - 1, int(np.floor(ymin)))) + iy1 = max(0, min(ny - 1, int(np.ceil(ymax)))) if ix1 < ix0: ix1 = ix0 if iy1 < iy0: @@ -111,10 +126,13 @@ def run_pyqtgraph(args): p_line = win.addPlot(row=0, col=0, title="Сырые данные") p_line.showGrid(x=True, y=True, alpha=0.3) curve = p_line.plot(pen=pg.mkPen((80, 120, 255), width=1)) - curve_calib = p_line.plot(pen=pg.mkPen((220, 60, 60), width=1)) curve_norm = p_line.plot(pen=pg.mkPen((60, 180, 90), width=1)) - p_line.setLabel("bottom", "X") + curve_env_lo = p_line.plot(pen=pg.mkPen((255, 165, 0), width=1, style=QtCore.Qt.DashLine)) + curve_env_hi = p_line.plot(pen=pg.mkPen((255, 165, 0), width=1, style=QtCore.Qt.DashLine)) + p_line.setLabel("bottom", "Частота, ГГц") p_line.setLabel("left", "Y") + p_line.setXRange(3.323, 14.323, padding=0) + p_line.enableAutoRange(axis="x", enable=False) ch_text = pg.TextItem("", anchor=(1, 1)) ch_text.setZValue(10) p_line.addItem(ch_text) @@ -130,7 +148,8 @@ def run_pyqtgraph(args): p_img.getAxis("bottom").setStyle(showValues=False) except Exception: pass - p_img.setLabel("left", "X (0 снизу)") + p_img.setLabel("left", "Частота, ГГц") + p_img.enableAutoRange(enable=False) img = pg.ImageItem() p_img.addItem(img) @@ -174,17 +193,24 @@ def run_pyqtgraph(args): _imshow_initialized = [False] + FREQ_MIN = 3.323 + FREQ_MAX = 14.323 + def _init_imshow_extents(): w = ring.width ms = ring.max_sweeps fb = ring.fft_bins img.setImage(ring.ring.T, autoLevels=False) - p_img.setRange(xRange=(0, ms - 1), yRange=(0, max(1, w - 1)), padding=0) - p_line.setXRange(0, max(1, w - 1), padding=0) + img.setRect(pg.QtCore.QRectF(0.0, FREQ_MIN, float(ms), FREQ_MAX - FREQ_MIN)) + p_img.setRange(xRange=(0, ms - 1), yRange=(FREQ_MIN, FREQ_MAX), padding=0) + p_line.setXRange(FREQ_MIN, FREQ_MAX, padding=0) img_fft.setImage(ring.ring_fft.T, autoLevels=False) p_spec.setRange(xRange=(0, ms - 1), yRange=(0, max(1, fb - 1)), padding=0) p_fft.setXRange(0, max(1, fb - 1), padding=0) + def _img_rect(ms: int) -> "pg.QtCore.QRectF": + return pg.QtCore.QRectF(0.0, FREQ_MIN, float(ms), FREQ_MAX - FREQ_MIN) + def update(): changed = state.drain_queue(q, ring) > 0 @@ -196,21 +222,28 @@ def run_pyqtgraph(args): if state.current_sweep_raw is not None and ring.x_shared is not None: raw = state.current_sweep_raw xs = ring.x_shared[: raw.size] if raw.size <= ring.x_shared.size else np.arange(raw.size) - curve.setData(xs, raw, autoDownsample=True) + def _norm_to_max(data): + m = float(np.nanmax(np.abs(data))) + return data / m if m > 0.0 else data + curve.setData(xs, _norm_to_max(raw), autoDownsample=True) if state.last_calib_sweep is not None: - curve_calib.setData(xs[: state.last_calib_sweep.size], state.last_calib_sweep, autoDownsample=True) + calib = state.last_calib_sweep + m_calib = float(np.nanmax(np.abs(calib))) + if m_calib <= 0.0: + m_calib = 1.0 + lower, upper = build_calib_envelopes(calib) + curve_env_lo.setData(xs[: calib.size], lower / m_calib, autoDownsample=True) + curve_env_hi.setData(xs[: calib.size], upper / m_calib, autoDownsample=True) else: - curve_calib.setData([], []) + curve_env_lo.setData([], []) + curve_env_hi.setData([], []) if state.current_sweep_norm is not None: - curve_norm.setData(xs[: state.current_sweep_norm.size], state.current_sweep_norm, autoDownsample=True) + curve_norm.setData(xs[: state.current_sweep_norm.size], _norm_to_max(state.current_sweep_norm), autoDownsample=True) else: curve_norm.setData([], []) if fixed_ylim is None: - y0 = float(np.nanmin(raw)) - y1 = float(np.nanmax(raw)) - if np.isfinite(y0) and np.isfinite(y1): - margin = 0.05 * max(1.0, (y1 - y0)) - p_line.setYRange(y0 - margin, y1 + margin, padding=0) + p_line.setYRange(-1.05, 1.05, padding=0) + p_line.setLabel("left", "/ max") # Спектр — используем уже вычисленный в ring FFT if ring.last_fft_vals is not None and ring.freq_shared is not None: @@ -233,11 +266,12 @@ def run_pyqtgraph(args): # Водопад сырых данных — новые данные справа (без реверса) if changed and ring.is_ready: disp = ring.get_display_ring() # (width, time), новые справа - levels = _visible_levels(disp, p_img) + levels = _visible_levels(disp, p_img, FREQ_MIN, FREQ_MAX) if levels is not None: img.setImage(disp, autoLevels=False, levels=levels) else: img.setImage(disp, autoLevels=False) + img.setRect(_img_rect(ring.max_sweeps)) # Статус и подпись канала if changed and state.current_info: diff --git a/rfg_adc_plotter/processing/normalizer.py b/rfg_adc_plotter/processing/normalizer.py index 10780d5..5d9c675 100644 --- a/rfg_adc_plotter/processing/normalizer.py +++ b/rfg_adc_plotter/processing/normalizer.py @@ -18,7 +18,11 @@ def normalize_simple(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: def build_calib_envelopes(calib: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: - """Оценить нижнюю/верхнюю огибающие калибровочной кривой.""" + """Оценить огибающую по модулю сигнала. + + Возвращает (lower, upper) = (-envelope, +envelope), где envelope — + интерполяция через локальные максимумы |calib|. + """ n = int(calib.size) if n <= 0: empty = np.zeros((0,), dtype=np.float32) @@ -35,11 +39,14 @@ def build_calib_envelopes(calib: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: y = y.copy() y[~finite] = np.interp(x[~finite], x[finite], y[finite]).astype(np.float32) - if n < 3: - return y.copy(), y.copy() + a = np.abs(y) - dy = np.diff(y) - s = np.sign(dy).astype(np.int8, copy=False) + if n < 3: + env = a.copy() + return -env, env + + da = np.diff(a) + s = np.sign(da).astype(np.int8, copy=False) if np.any(s == 0): for i in range(1, s.size): @@ -51,27 +58,16 @@ def build_calib_envelopes(calib: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: s[s == 0] = 1 max_idx = np.where((s[:-1] > 0) & (s[1:] < 0))[0] + 1 - min_idx = np.where((s[:-1] < 0) & (s[1:] > 0))[0] + 1 x = np.arange(n, dtype=np.float32) - def _interp_nodes(nodes: np.ndarray) -> np.ndarray: - if nodes.size == 0: - idx = np.array([0, n - 1], dtype=np.int64) - else: - idx = np.unique(np.concatenate(([0], nodes, [n - 1]))).astype(np.int64) - return np.interp(x, idx.astype(np.float32), y[idx]).astype(np.float32) + if max_idx.size == 0: + idx = np.array([0, n - 1], dtype=np.int64) + else: + idx = np.unique(np.concatenate(([0], max_idx, [n - 1]))).astype(np.int64) + env = np.interp(x, idx.astype(np.float32), a[idx]).astype(np.float32) - upper = _interp_nodes(max_idx) - lower = _interp_nodes(min_idx) - - swap = lower > upper - if np.any(swap): - tmp = upper[swap].copy() - upper[swap] = lower[swap] - lower[swap] = tmp - - return lower, upper + return -env, env def normalize_projector(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: diff --git a/rfg_adc_plotter/state/ring_buffer.py b/rfg_adc_plotter/state/ring_buffer.py index 56d3334..1b9ecd5 100644 --- a/rfg_adc_plotter/state/ring_buffer.py +++ b/rfg_adc_plotter/state/ring_buffer.py @@ -37,16 +37,17 @@ class RingBuffer: return self.ring is not None def ensure_init(self, sweep_width: int): - """Инициализировать буферы при первом свипе. Повторные вызовы — no-op.""" - if self.ring is not None: - return - self.width = WF_WIDTH - self.x_shared = np.arange(self.width, dtype=np.int32) - self.ring = np.full((self.max_sweeps, self.width), np.nan, dtype=np.float32) - self.ring_time = np.full((self.max_sweeps,), np.nan, dtype=np.float64) - self.ring_fft = np.full((self.max_sweeps, self.fft_bins), np.nan, dtype=np.float32) - self.freq_shared = np.arange(self.fft_bins, dtype=np.int32) - self.head = 0 + """Инициализировать буферы при первом свипе. Повторные вызовы — no-op (кроме x_shared).""" + if self.ring is None: + self.width = WF_WIDTH + self.ring = np.full((self.max_sweeps, self.width), np.nan, dtype=np.float32) + self.ring_time = np.full((self.max_sweeps,), np.nan, dtype=np.float64) + self.ring_fft = np.full((self.max_sweeps, self.fft_bins), np.nan, dtype=np.float32) + self.freq_shared = np.arange(self.fft_bins, dtype=np.int32) + self.head = 0 + # Обновляем x_shared если пришёл свип большего размера + if self.x_shared is None or sweep_width > self.x_shared.size: + self.x_shared = np.linspace(3.323, 14.323, sweep_width, dtype=np.float32) def push(self, s: np.ndarray): """Добавить строку свипа в кольцевой буфер, вычислить FFT-строку.""" -- 2.49.0 From 66b9eee230948f230a3cb1775ae7a850d08caa58 Mon Sep 17 00:00:00 2001 From: awe Date: Wed, 11 Feb 2026 18:43:43 +0300 Subject: [PATCH 05/13] right ifft implementation --- RFG_ADC_dataplotter.py | 1544 --------------------- rfg_adc_plotter/constants.py | 10 +- rfg_adc_plotter/gui/matplotlib_backend.py | 13 +- rfg_adc_plotter/gui/pyqtgraph_backend.py | 28 +- rfg_adc_plotter/state/ring_buffer.py | 50 +- 5 files changed, 66 insertions(+), 1579 deletions(-) delete mode 100755 RFG_ADC_dataplotter.py diff --git a/RFG_ADC_dataplotter.py b/RFG_ADC_dataplotter.py deleted file mode 100755 index d4cade9..0000000 --- a/RFG_ADC_dataplotter.py +++ /dev/null @@ -1,1544 +0,0 @@ -#!/usr/bin/env python3 -""" -Реалтайм-плоттер для свипов из виртуального COM-порта. - -Формат строк: - - "Sweep_start" — начало нового свипа (предыдущий считается завершённым) - - "s CH X Y" — точка (номер канала, индекс X, значение Y), все целые со знаком - -Отрисовываются два графика: - - Левый: последний полученный свип (Y vs X) - - Правый: водопад (последние N свипов во времени) - -Оптимизации для скорости: - - Парсинг и чтение в фоновой нити - - Анимация с обновлением только данных (без лишнего пересоздания фигур) - - Кольцевой буфер под водопад с фиксированным числом свипов - -Зависимости: matplotlib, numpy. PySerial опционален — при его отсутствии -используется сырой доступ к TTY через termios. -""" - -import argparse -import io -import os -import sys -import threading -import time -from collections import deque -from queue import Queue, Empty, Full -from typing import Any, Dict, Mapping, Optional, Tuple, Union - -import numpy as np - -WF_WIDTH = 1000 # максимальное число точек в ряду водопада -FFT_LEN = 1024 # длина БПФ для спектра/водопада спектров -# Порог для инверсии сырых данных: если среднее значение свипа ниже порога — -# считаем, что сигнал «меньше нуля» и домножаем свип на -1 -DATA_INVERSION_THRASHOLD = 10.0 - -Number = Union[int, float] -SweepInfo = Dict[str, Any] -SweepPacket = Tuple[np.ndarray, SweepInfo] - - -def _format_status_kv(data: Mapping[str, Any]) -> str: - """Преобразовать словарь метрик в одну строку 'k:v'.""" - - def _fmt(v: Any) -> str: - if v is None: - return "NA" - try: - fv = float(v) - except Exception: - return str(v) - if not np.isfinite(fv): - return "nan" - # Достаточно компактно для статус-строки. - if abs(fv) >= 1000 or (0 < abs(fv) < 0.01): - return f"{fv:.3g}" - return f"{fv:.3f}".rstrip("0").rstrip(".") - - parts = [f"{k}:{_fmt(v)}" for k, v in data.items()] - return " ".join(parts) - - -def _parse_spec_clip(spec: Optional[str]) -> Optional[Tuple[float, float]]: - """Разобрать строку вида "low,high" процентов для контрастного отображения водопада спектров. - - Возвращает пару (low, high) или None для отключения. Допустимы значения 0..100, low < high. - Ключевые слова отключения: "off", "none", "no". - """ - if not spec: - return None - s = str(spec).strip().lower() - if s in ("off", "none", "no"): - return None - try: - p0, p1 = s.replace(";", ",").split(",") - low = float(p0) - high = float(p1) - if not (0.0 <= low < high <= 100.0): - return None - return (low, high) - except Exception: - return None - - -def _normalize_sweep_simple(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: - """Простая нормировка: поэлементное деление raw/calib.""" - w = min(raw.size, calib.size) - if w <= 0: - return raw - out = np.full_like(raw, np.nan, dtype=np.float32) - with np.errstate(divide="ignore", invalid="ignore"): - out[:w] = raw[:w] / calib[:w] - out = np.nan_to_num(out, nan=np.nan, posinf=np.nan, neginf=np.nan) - return out - - -def _build_calib_envelopes(calib: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: - """Оценить нижнюю/верхнюю огибающие калибровочной кривой.""" - n = int(calib.size) - if n <= 0: - empty = np.zeros((0,), dtype=np.float32) - return empty, empty - - y = np.asarray(calib, dtype=np.float32) - finite = np.isfinite(y) - if not np.any(finite): - zeros = np.zeros_like(y, dtype=np.float32) - return zeros, zeros - - if not np.all(finite): - x = np.arange(n, dtype=np.float32) - y = y.copy() - y[~finite] = np.interp(x[~finite], x[finite], y[finite]).astype(np.float32) - - if n < 3: - return y.copy(), y.copy() - - dy = np.diff(y) - s = np.sign(dy).astype(np.int8, copy=False) - - if np.any(s == 0): - for i in range(1, s.size): - if s[i] == 0: - s[i] = s[i - 1] - for i in range(s.size - 2, -1, -1): - if s[i] == 0: - s[i] = s[i + 1] - s[s == 0] = 1 - - max_idx = np.where((s[:-1] > 0) & (s[1:] < 0))[0] + 1 - min_idx = np.where((s[:-1] < 0) & (s[1:] > 0))[0] + 1 - - x = np.arange(n, dtype=np.float32) - - def _interp_nodes(nodes: np.ndarray) -> np.ndarray: - if nodes.size == 0: - idx = np.array([0, n - 1], dtype=np.int64) - else: - idx = np.unique(np.concatenate(([0], nodes, [n - 1]))).astype(np.int64) - return np.interp(x, idx.astype(np.float32), y[idx]).astype(np.float32) - - upper = _interp_nodes(max_idx) - lower = _interp_nodes(min_idx) - - swap = lower > upper - if np.any(swap): - tmp = upper[swap].copy() - upper[swap] = lower[swap] - lower[swap] = tmp - - return lower, upper - - -def _normalize_sweep_projector(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: - """Нормировка через проекцию между огибающими калибровки в диапазон [-1, +1].""" - w = min(raw.size, calib.size) - if w <= 0: - return raw - - out = np.full_like(raw, np.nan, dtype=np.float32) - raw_seg = np.asarray(raw[:w], dtype=np.float32) - lower, upper = _build_calib_envelopes(np.asarray(calib[:w], dtype=np.float32)) - span = upper - lower - - finite_span = span[np.isfinite(span) & (span > 0)] - if finite_span.size > 0: - eps = max(float(np.median(finite_span)) * 1e-6, 1e-9) - else: - eps = 1e-9 - - valid = ( - np.isfinite(raw_seg) - & np.isfinite(lower) - & np.isfinite(upper) - & (span > eps) - ) - if np.any(valid): - proj = np.empty_like(raw_seg, dtype=np.float32) - proj[valid] = ((2.0 * (raw_seg[valid] - lower[valid]) / span[valid]) - 1.0) * 1000.0 - proj[valid] = np.clip(proj[valid], -1000.0, 1000.0) - proj[~valid] = np.nan - out[:w] = proj - - return out - - -def _normalize_by_calib(raw: np.ndarray, calib: np.ndarray, norm_type: str) -> np.ndarray: - """Нормировка свипа по выбранному алгоритму.""" - nt = str(norm_type).strip().lower() - if nt == "simple": - return _normalize_sweep_simple(raw, calib) - return _normalize_sweep_projector(raw, calib) - - -def try_open_pyserial(path: str, baud: int, timeout: float): - try: - import serial # type: ignore - except Exception: - return None - try: - ser = serial.Serial(path, baudrate=baud, timeout=timeout) - return ser - except Exception: - return None - - -class FDReader: - """Простой враппер чтения строк из файлового дескриптора TTY.""" - - def __init__(self, fd: int): - # Отдельно буферизуем для корректной readline() - self._fd = fd - raw = os.fdopen(fd, "rb", closefd=False) - self._file = raw - self._buf = io.BufferedReader(raw, buffer_size=65536) - - def fileno(self) -> int: - return self._fd - - def readline(self) -> bytes: - return self._buf.readline() - - def close(self): - try: - self._buf.close() - except Exception: - pass - - -def open_raw_tty(path: str, baud: int) -> Optional[FDReader]: - """Открыть TTY без pyserial и настроить порт через termios. - - Возвращает FDReader или None при ошибке. - """ - try: - import termios - import tty - except Exception: - return None - - try: - fd = os.open(path, os.O_RDONLY | os.O_NOCTTY) - except Exception: - return None - - try: - attrs = termios.tcgetattr(fd) - # Установим «сырое» состояние - tty.setraw(fd) - - # Скорость - baud_map = { - 9600: termios.B9600, - 19200: termios.B19200, - 38400: termios.B38400, - 57600: termios.B57600, - 115200: termios.B115200, - 230400: getattr(termios, "B230400", None), - 460800: getattr(termios, "B460800", None), - } - b = baud_map.get(baud) or termios.B115200 - - attrs[4] = b # ispeed - attrs[5] = b # ospeed - - # VMIN=1, VTIME=0 — блокирующее чтение по байту - cc = attrs[6] - cc[termios.VMIN] = 1 - cc[termios.VTIME] = 0 - attrs[6] = cc - - termios.tcsetattr(fd, termios.TCSANOW, attrs) - except Exception: - try: - os.close(fd) - except Exception: - pass - return None - - return FDReader(fd) - - -class SerialLineSource: - """Единый интерфейс для чтения строк из порта (pyserial или raw TTY).""" - - def __init__(self, path: str, baud: int, timeout: float = 1.0): - self._pyserial = try_open_pyserial(path, baud, timeout) - self._fdreader = None - self._using = "pyserial" if self._pyserial is not None else "raw" - if self._pyserial is None: - self._fdreader = open_raw_tty(path, baud) - if self._fdreader is None: - msg = f"Не удалось открыть порт '{path}' (pyserial и raw TTY не сработали)" - if sys.platform.startswith("win"): - msg += ". На Windows нужен pyserial: pip install pyserial" - raise RuntimeError(msg) - - def readline(self) -> bytes: - if self._pyserial is not None: - try: - return self._pyserial.readline() - except Exception: - return b"" - else: - try: - return self._fdreader.readline() # type: ignore[union-attr] - except Exception: - return b"" - - def close(self): - try: - if self._pyserial is not None: - self._pyserial.close() - elif self._fdreader is not None: - self._fdreader.close() - except Exception: - pass - - -class SerialChunkReader: - """Быстрое неблокирующее чтение чанков из serial/raw TTY для максимального дренажа буфера.""" - - def __init__(self, src: SerialLineSource): - self._src = src - self._ser = src._pyserial - self._fd: Optional[int] = None - if self._ser is not None: - # Неблокирующий режим для быстрой откачки - try: - self._ser.timeout = 0 - except Exception: - pass - else: - try: - self._fd = src._fdreader.fileno() # type: ignore[union-attr] - try: - os.set_blocking(self._fd, False) - except Exception: - pass - except Exception: - self._fd = None - - def read_available(self) -> bytes: - """Вернёт доступные байты (b"" если данных нет).""" - if self._ser is not None: - try: - n = int(getattr(self._ser, "in_waiting", 0)) - except Exception: - n = 0 - if n > 0: - try: - return self._ser.read(n) - except Exception: - return b"" - return b"" - if self._fd is None: - return b"" - out = bytearray() - while True: - try: - chunk = os.read(self._fd, 65536) - if not chunk: - break - out += chunk - if len(chunk) < 65536: - break - except BlockingIOError: - break - except Exception: - break - return bytes(out) - - -class SweepReader(threading.Thread): - """Фоновый поток: читает строки, формирует завершённые свипы и кладёт в очередь.""" - - def __init__( - self, - port_path: str, - baud: int, - out_queue: Queue[SweepPacket], - stop_event: threading.Event, - fancy: bool = False, - ): - super().__init__(daemon=True) - self._port_path = port_path - self._baud = baud - self._q = out_queue - self._stop = stop_event - self._src: Optional[SerialLineSource] = None - self._fancy = bool(fancy) - self._max_width: int = 0 - self._sweep_idx: int = 0 - self._last_sweep_ts: Optional[float] = None - self._n_valid_hist = deque() - - def _finalize_current(self, xs, ys, channels: Optional[set[int]]): - if not xs: - return - ch_list = sorted(channels) if channels else [0] - ch_primary = ch_list[0] if ch_list else 0 - max_x = max(xs) - width = max_x + 1 - self._max_width = max(self._max_width, width) - target_width = self._max_width if self._fancy else width - # Быстрый векторизованный путь - sweep = np.full((target_width,), np.nan, dtype=np.float32) - try: - idx = np.asarray(xs, dtype=np.int64) - vals = np.asarray(ys, dtype=np.float32) - sweep[idx] = vals - except Exception: - # Запасной путь - for x, y in zip(xs, ys): - if 0 <= x < target_width: - sweep[x] = float(y) - # Метрики валидных точек до заполнения пропусков - finite_pre = np.isfinite(sweep) - n_valid_cur = int(np.count_nonzero(finite_pre)) - - # Дополнительная обработка пропусков: при --fancy заполняем внутренние разрывы, края и дотягиваем до максимальной длины - if self._fancy: - try: - known = ~np.isnan(sweep) - if np.any(known): - known_idx = np.nonzero(known)[0] - # Для каждой пары соседних известных индексов заполним промежуток средним значением - for i0, i1 in zip(known_idx[:-1], known_idx[1:]): - if i1 - i0 > 1: - avg = (sweep[i0] + sweep[i1]) * 0.5 - sweep[i0 + 1 : i1] = avg - first_idx = int(known_idx[0]) - last_idx = int(known_idx[-1]) - if first_idx > 0: - sweep[:first_idx] = sweep[first_idx] - if last_idx < sweep.size - 1: - sweep[last_idx + 1 :] = sweep[last_idx] - except Exception: - # В случае ошибки просто оставляем как есть - pass - # Инверсия данных при «отрицательном» уровне (среднее ниже порога) - try: - m = float(np.nanmean(sweep)) - if np.isfinite(m) and m < DATA_INVERSION_THRASHOLD: - sweep *= -1.0 - except Exception: - pass - #sweep -= float(np.nanmean(sweep)) - - # Метрики для статусной строки (вид словаря: переменная -> значение) - self._sweep_idx += 1 - if len(ch_list) > 1: - sys.stderr.write( - f"[warn] Sweep {self._sweep_idx}: изменялся номер канала: {ch_list}\n" - ) - now = time.time() - if self._last_sweep_ts is None: - dt_ms = float("nan") - else: - dt_ms = (now - self._last_sweep_ts) * 1000.0 - self._last_sweep_ts = now - self._n_valid_hist.append((now, n_valid_cur)) - while self._n_valid_hist and (now - self._n_valid_hist[0][0]) > 1.0: - self._n_valid_hist.popleft() - if self._n_valid_hist: - n_valid = float(sum(v for _t, v in self._n_valid_hist) / len(self._n_valid_hist)) - else: - n_valid = float(n_valid_cur) - - if n_valid_cur > 0: - vmin = float(np.nanmin(sweep)) - vmax = float(np.nanmax(sweep)) - mean = float(np.nanmean(sweep)) - std = float(np.nanstd(sweep)) - else: - vmin = vmax = mean = std = float("nan") - info: SweepInfo = { - "sweep": self._sweep_idx, - "ch": ch_primary, - "chs": ch_list, - "n_valid": n_valid, - "min": vmin, - "max": vmax, - "mean": mean, - "std": std, - "dt_ms": dt_ms, - } - - # Кладём готовый свип (если очередь полна — выбрасываем самый старый) - try: - self._q.put_nowait((sweep, info)) - except Full: - try: - _ = self._q.get_nowait() - except Exception: - pass - try: - self._q.put_nowait((sweep, info)) - except Exception: - pass - - def run(self): - # Состояние текущего свипа - xs: list[int] = [] - ys: list[int] = [] - cur_channel: Optional[int] = None - cur_channels: set[int] = set() - - try: - self._src = SerialLineSource(self._port_path, self._baud, timeout=1.0) - sys.stderr.write(f"[info] Открыл порт {self._port_path} ({self._src._using})\n") - except Exception as e: - sys.stderr.write(f"[error] {e}\n") - return - - try: - # Быстрый неблокирующий дренаж порта с разбором по байтам - chunk_reader = SerialChunkReader(self._src) - buf = bytearray() - while not self._stop.is_set(): - data = chunk_reader.read_available() - if data: - buf += data - else: - # Короткая уступка CPU, если нет новых данных - time.sleep(0.0005) - continue - - # Обрабатываем все полные строки - while True: - nl = buf.find(b"\n") - if nl == -1: - break - line = bytes(buf[:nl]) - del buf[: nl + 1] - if line.endswith(b"\r"): - line = line[:-1] - if not line: - continue - - if line.startswith(b"Sweep_start"): - self._finalize_current(xs, ys, cur_channels) - xs.clear() - ys.clear() - cur_channel = None - cur_channels.clear() - continue - - # sCH X Y или s CH X Y (все целые со знаком). Разделяем по любым пробелам/табам. - if len(line) >= 3: - parts = line.split() - if len(parts) >= 3 and (parts[0].lower() == b"s" or parts[0].lower().startswith(b"s")): - try: - if parts[0].lower() == b"s": - if len(parts) >= 4: - ch = int(parts[1], 10) - x = int(parts[2], 10) - y = int(parts[3], 10) # поддержка знака: "+…" и "-…" - else: - ch = 0 - x = int(parts[1], 10) - y = int(parts[2], 10) # поддержка знака: "+…" и "-…" - else: - # формат вида "s0" - ch = int(parts[0][1:], 10) - x = int(parts[1], 10) - y = int(parts[2], 10) # поддержка знака: "+…" и "-…" - except Exception: - continue - if cur_channel is None: - cur_channel = ch - cur_channels.add(ch) - xs.append(x) - ys.append(y) - - # Защита от переполнения буфера при отсутствии переводов строки - if len(buf) > 1_000_000: - del buf[:-262144] - finally: - try: - # Завершаем оставшийся свип - self._finalize_current(xs, ys, cur_channels) - except Exception: - pass - try: - if self._src is not None: - self._src.close() - except Exception: - pass - - -def main(): - parser = argparse.ArgumentParser( - description=( - "Читает свипы из виртуального COM-порта и рисует: " - "последний свип и водопад (реалтайм)." - ) - ) - parser.add_argument( - "port", - help="Путь к порту, например /dev/ttyACM1 или COM3 (COM10+: \\\\.\\COM10)", - ) - parser.add_argument("--baud", type=int, default=115200, help="Скорость (по умолчанию 115200)") - parser.add_argument("--max-sweeps", type=int, default=200, help="Количество видимых свипов в водопаде") - parser.add_argument("--max-fps", type=float, default=30.0, help="Лимит частоты отрисовки, кадров/с") - parser.add_argument("--cmap", default="viridis", help="Цветовая карта водопада") - parser.add_argument( - "--spec-clip", - default="2,98", - help=( - "Процентильная обрезка уровней водопада спектров, % (min,max). " - "Напр. 2,98. 'off' — отключить" - ), - ) - parser.add_argument( - "--spec-mean-sec", - type=float, - default=0.0, - help=( - "Вычитание среднего по каждой частоте за последние N секунд " - "в водопаде спектров (0 — отключить)" - ), - ) - parser.add_argument("--title", default="ADC Sweeps", help="Заголовок окна") - parser.add_argument( - "--fancy", - action="store_true", - help="Заполнять выпавшие точки средними значениями между соседними", - ) - parser.add_argument( - "--ylim", - type=str, - default=None, - help="Фиксированные Y-пределы для кривой формата min,max (например -1000,1000). По умолчанию авто", - ) - parser.add_argument( - "--backend", - choices=["auto", "pg", "mpl"], - default="auto", - help="Графический бэкенд: pyqtgraph (pg) — быстрее; matplotlib (mpl) — совместимый. По умолчанию auto", - ) - parser.add_argument( - "--norm-type", - choices=["projector", "simple"], - default="projector", - help="Тип нормировки: projector (по огибающим в [-1,+1]) или simple (raw/calib)", - ) - - args = parser.parse_args() - - # Попробуем быстрый бэкенд (pyqtgraph) при auto/pg - if args.backend in ("pg"): - try: - return run_pyqtgraph(args) - except Exception as e: - if args.backend == "pg": - sys.stderr.write(f"[error] PyQtGraph бэкенд недоступен: {e}\n") - sys.exit(1) - # При auto — тихо откатываемся на matplotlib - - try: - import matplotlib - import matplotlib.pyplot as plt - from matplotlib.animation import FuncAnimation - from matplotlib.widgets import Slider, CheckButtons - except Exception as e: - sys.stderr.write(f"[error] Нужны matplotlib и ее зависимости: {e}\n") - sys.exit(1) - - # Очередь завершённых свипов и поток чтения - q: Queue[SweepPacket] = Queue(maxsize=1000) - stop_event = threading.Event() - reader = SweepReader(args.port, args.baud, q, stop_event, fancy=bool(args.fancy)) - reader.start() - - # Графика - fig, axs = plt.subplots(2, 2, figsize=(12, 8)) - (ax_line, ax_img), (ax_fft, ax_spec) = axs - fig.canvas.manager.set_window_title(args.title) if hasattr(fig.canvas.manager, "set_window_title") else None - # Увеличим расстояния и оставим место справа под ползунки оси Y B-scan - fig.subplots_adjust(wspace=0.25, hspace=0.35, left=0.07, right=0.90, top=0.92, bottom=0.08) - - # Состояние для отображения - current_sweep_raw: Optional[np.ndarray] = None - current_sweep_norm: Optional[np.ndarray] = None - last_calib_sweep: Optional[np.ndarray] = None - current_info: Optional[SweepInfo] = None - x_shared: Optional[np.ndarray] = None - width: Optional[int] = None - max_sweeps = int(max(10, args.max_sweeps)) - ring = None # type: Optional[np.ndarray] - ring_time = None # type: Optional[np.ndarray] - head = 0 - # Авто-уровни цветовой шкалы водопада сырых данных пересчитываются по видимой области. - # FFT состояние - fft_bins = FFT_LEN // 2 + 1 - ring_fft = None # type: Optional[np.ndarray] - y_min_fft, y_max_fft = None, None - freq_shared: Optional[np.ndarray] = None - # Параметры контраста водопада спектров - spec_clip = _parse_spec_clip(getattr(args, "spec_clip", None)) - spec_mean_sec = float(getattr(args, "spec_mean_sec", 0.0)) - # Ползунки управления Y для B-scan и контрастом - ymin_slider = None - ymax_slider = None - contrast_slider = None - calib_enabled = False - norm_type = str(getattr(args, "norm_type", "projector")).strip().lower() - cb = None - - # Статусная строка (внизу окна) - status_text = fig.text( - 0.01, - 0.01, - "", - ha="left", - va="bottom", - fontsize=8, - family="monospace", - ) - - # Линейный график последнего свипа - line_obj, = ax_line.plot([], [], lw=1, color="tab:blue") - line_calib_obj, = ax_line.plot([], [], lw=1, color="tab:red") - line_norm_obj, = ax_line.plot([], [], lw=1, color="tab:green") - ax_line.set_title("Сырые данные", pad=1) - ax_line.set_xlabel("F") - ax_line.set_ylabel("") - channel_text = ax_line.text( - 0.98, - 0.98, - "", - transform=ax_line.transAxes, - ha="right", - va="top", - fontsize=9, - family="monospace", - ) - - # Линейный график спектра текущего свипа - fft_line_obj, = ax_fft.plot([], [], lw=1) - ax_fft.set_title("FFT", pad=1) - ax_fft.set_xlabel("X") - ax_fft.set_ylabel("Амплитуда, дБ") - - # Диапазон по Y для последнего свипа: авто по умолчанию (поддерживает отрицательные значения) - fixed_ylim: Optional[Tuple[float, float]] = None - # CLI переопределение при необходимости - if args.ylim: - try: - y0, y1 = args.ylim.split(",") - fixed_ylim = (float(y0), float(y1)) - except Exception: - sys.stderr.write("[warn] Некорректный формат --ylim, игнорирую. Ожидалось min,max\n") - if fixed_ylim is not None: - ax_line.set_ylim(fixed_ylim) - - # Водопад (будет инициализирован при первом свипе) - img_obj = ax_img.imshow( - np.zeros((1, 1), dtype=np.float32), - aspect="auto", - interpolation="nearest", - origin="lower", - cmap=args.cmap, - ) - ax_img.set_title("Сырые данные", pad=12) - ax_img.set_xlabel("") - ax_img.set_ylabel("частота") - # Не показываем численные значения по времени на водопаде сырых данных - try: - ax_img.tick_params(axis="x", labelbottom=False) - except Exception: - pass - - # Водопад спектров - img_fft_obj = ax_spec.imshow( - np.zeros((1, 1), dtype=np.float32), - aspect="auto", - interpolation="nearest", - origin="lower", - cmap=args.cmap, - ) - ax_spec.set_title("B-scan (дБ)", pad=12) - ax_spec.set_xlabel("") - ax_spec.set_ylabel("расстояние") - # Не показываем численные значения по времени на B-scan - try: - ax_spec.tick_params(axis="x", labelbottom=False) - except Exception: - pass - - def _normalize_sweep(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: - return _normalize_by_calib(raw, calib, norm_type=norm_type) - - def _set_calib_enabled(): - nonlocal calib_enabled, current_sweep_norm - try: - calib_enabled = bool(cb.get_status()[0]) if cb is not None else False - except Exception: - calib_enabled = False - if calib_enabled and current_sweep_raw is not None and last_calib_sweep is not None: - current_sweep_norm = _normalize_sweep(current_sweep_raw, last_calib_sweep) - else: - current_sweep_norm = None - - # Слайдеры для управления осью Y B-scan (мин/макс) и контрастом - try: - ax_smin = fig.add_axes([0.92, 0.55, 0.02, 0.35]) - ax_smax = fig.add_axes([0.95, 0.55, 0.02, 0.35]) - ax_sctr = fig.add_axes([0.98, 0.55, 0.02, 0.35]) - ax_cb = fig.add_axes([0.92, 0.45, 0.08, 0.08]) - ymin_slider = Slider(ax_smin, "Y min", 0, max(1, fft_bins - 1), valinit=0, valstep=1, orientation="vertical") - ymax_slider = Slider(ax_smax, "Y max", 0, max(1, fft_bins - 1), valinit=max(1, fft_bins - 1), valstep=1, orientation="vertical") - contrast_slider = Slider(ax_sctr, "Int max", 0, 100, valinit=100, valstep=1, orientation="vertical") - cb = CheckButtons(ax_cb, ["калибровка"], [False]) - - def _on_ylim_change(_val): - try: - y0 = int(min(ymin_slider.val, ymax_slider.val)) - y1 = int(max(ymin_slider.val, ymax_slider.val)) - ax_spec.set_ylim(y0, y1) - fig.canvas.draw_idle() - except Exception: - pass - - ymin_slider.on_changed(_on_ylim_change) - ymax_slider.on_changed(_on_ylim_change) - # Контраст влияет на верхнюю границу цветовой шкалы (процент от авто-диапазона) - contrast_slider.on_changed(lambda _v: fig.canvas.draw_idle()) - cb.on_clicked(lambda _v: _set_calib_enabled()) - except Exception: - pass - - # Для контроля частоты обновления - max_fps = max(1.0, float(args.max_fps)) - interval_ms = int(1000.0 / max_fps) - frames_since_ylim_update = 0 - - - def ensure_buffer(_w: int): - nonlocal ring, width, head, x_shared, ring_fft, freq_shared, ring_time - if ring is not None: - return - width = WF_WIDTH - x_shared = np.arange(width, dtype=np.int32) - ring = np.full((max_sweeps, width), np.nan, dtype=np.float32) - ring_time = np.full((max_sweeps,), np.nan, dtype=np.float64) - head = 0 - # Обновляем изображение под новые размеры: время по X (горизонталь), X по Y - img_obj.set_data(np.zeros((width, max_sweeps), dtype=np.float32)) - img_obj.set_extent((0, max_sweeps - 1, 0, width - 1 if width > 0 else 1)) - ax_img.set_xlim(0, max_sweeps - 1) - ax_img.set_ylim(0, max(1, width - 1)) - # FFT буферы: время по X, бин по Y - ring_fft = np.full((max_sweeps, fft_bins), np.nan, dtype=np.float32) - img_fft_obj.set_data(np.zeros((fft_bins, max_sweeps), dtype=np.float32)) - img_fft_obj.set_extent((0, max_sweeps - 1, 0, fft_bins - 1)) - ax_spec.set_xlim(0, max_sweeps - 1) - ax_spec.set_ylim(0, max(1, fft_bins - 1)) - freq_shared = np.arange(fft_bins, dtype=np.int32) - - def _visible_levels_matplotlib(data: np.ndarray, axis) -> Optional[Tuple[float, float]]: - """(vmin, vmax) по текущей видимой области imshow (без накопления по времени).""" - if data.size == 0: - return None - ny, nx = data.shape[0], data.shape[1] - try: - x0, x1 = axis.get_xlim() - y0, y1 = axis.get_ylim() - except Exception: - x0, x1 = 0.0, float(nx - 1) - y0, y1 = 0.0, float(ny - 1) - xmin, xmax = sorted((float(x0), float(x1))) - ymin, ymax = sorted((float(y0), float(y1))) - ix0 = max(0, min(nx - 1, int(np.floor(xmin)))) - ix1 = max(0, min(nx - 1, int(np.ceil(xmax)))) - iy0 = max(0, min(ny - 1, int(np.floor(ymin)))) - iy1 = max(0, min(ny - 1, int(np.ceil(ymax)))) - if ix1 < ix0: - ix1 = ix0 - if iy1 < iy0: - iy1 = iy0 - sub = data[iy0 : iy1 + 1, ix0 : ix1 + 1] - finite = np.isfinite(sub) - if not finite.any(): - return None - vals = sub[finite] - vmin = float(np.min(vals)) - vmax = float(np.max(vals)) - if not (np.isfinite(vmin) and np.isfinite(vmax)) or vmin == vmax: - return None - return (vmin, vmax) - - def push_sweep(s: np.ndarray): - nonlocal ring, head, ring_fft, y_min_fft, y_max_fft, ring_time - if s is None or s.size == 0 or ring is None: - return - # Нормализуем длину до фиксированной ширины - w = ring.shape[1] - row = np.full((w,), np.nan, dtype=np.float32) - take = min(w, s.size) - row[:take] = s[:take] - ring[head, :] = row - if ring_time is not None: - ring_time[head] = time.time() - head = (head + 1) % ring.shape[0] - # FFT строка (дБ) - if ring_fft is not None: - bins = ring_fft.shape[1] - # Подготовка входа FFT_LEN, замена NaN на 0 - take_fft = min(int(s.size), FFT_LEN) - if take_fft <= 0: - fft_row = np.full((bins,), np.nan, dtype=np.float32) - else: - fft_in = np.zeros((FFT_LEN,), dtype=np.float32) - seg = s[:take_fft] - if isinstance(seg, np.ndarray): - seg = np.nan_to_num(seg, nan=0.0).astype(np.float32, copy=False) - else: - seg = np.asarray(seg, dtype=np.float32) - seg = np.nan_to_num(seg, nan=0.0) - # Окно Хэннинга - win = np.hanning(take_fft).astype(np.float32) - fft_in[:take_fft] = seg * win - spec = np.fft.rfft(fft_in) - mag = np.abs(spec).astype(np.float32) - fft_row = 20.0 * np.log10(mag + 1e-9) - if fft_row.shape[0] != bins: - # rfft длиной FFT_LEN даёт bins == FFT_LEN//2+1 - fft_row = fft_row[:bins] - ring_fft[(head - 1) % ring_fft.shape[0], :] = fft_row - # Экстремумы для цветовой шкалы - fr_min = np.nanmin(fft_row) - fr_max = np.nanmax(fft_row) - fr_max = np.nanpercentile(fft_row, 90) - if y_min_fft is None or (not np.isnan(fr_min) and fr_min < y_min_fft): - y_min_fft = float(fr_min) - if y_max_fft is None or (not np.isnan(fr_max) and fr_max > y_max_fft): - y_max_fft = float(fr_max) - - def drain_queue(): - nonlocal current_sweep_raw, current_sweep_norm, current_info, last_calib_sweep - drained = 0 - while True: - try: - s, info = q.get_nowait() - except Empty: - break - drained += 1 - current_sweep_raw = s - current_info = info - ch = 0 - try: - ch = int(info.get("ch", 0)) if isinstance(info, dict) else 0 - except Exception: - ch = 0 - if ch == 0: - last_calib_sweep = s - current_sweep_norm = None - sweep_for_proc = s - else: - if calib_enabled and last_calib_sweep is not None: - current_sweep_norm = _normalize_sweep(s, last_calib_sweep) - sweep_for_proc = current_sweep_norm - else: - current_sweep_norm = None - sweep_for_proc = s - ensure_buffer(s.size) - push_sweep(sweep_for_proc) - return drained - - def make_display_ring(): - # Возвращаем буфер с правильным порядком по времени (старые→новые) и осью времени по X - if ring is None: - return np.zeros((1, 1), dtype=np.float32) - base = ring if head == 0 else np.roll(ring, -head, axis=0) - return base.T # (width, time) - - def make_display_times(): - if ring_time is None: - return None - base_t = ring_time if head == 0 else np.roll(ring_time, -head) - return base_t - - def _subtract_recent_mean_fft(disp_fft: np.ndarray) -> np.ndarray: - """Вычесть среднее по каждой частоте за последние spec_mean_sec секунд.""" - if spec_mean_sec <= 0.0: - return disp_fft - disp_times = make_display_times() - if disp_times is None: - return disp_fft - now_t = time.time() - mask = np.isfinite(disp_times) & (disp_times >= (now_t - spec_mean_sec)) - if not np.any(mask): - return disp_fft - try: - mean_spec = np.nanmean(disp_fft[:, mask], axis=1) - except Exception: - return disp_fft - mean_spec = np.nan_to_num(mean_spec, nan=0.0) - return disp_fft - mean_spec[:, None] - - def make_display_ring_fft(): - if ring_fft is None: - return np.zeros((1, 1), dtype=np.float32) - base = ring_fft if head == 0 else np.roll(ring_fft, -head, axis=0) - return base.T # (bins, time) - - def update(_frame): - nonlocal frames_since_ylim_update - changed = drain_queue() > 0 - - # Обновление линии последнего свипа - if current_sweep_raw is not None: - if x_shared is not None and current_sweep_raw.size <= x_shared.size: - xs = x_shared[: current_sweep_raw.size] - else: - xs = np.arange(current_sweep_raw.size, dtype=np.int32) - def _norm_to_max(data): - m = float(np.nanmax(np.abs(data))) - return data / m if m > 0.0 else data - line_obj.set_data(xs, _norm_to_max(current_sweep_raw)) - if last_calib_sweep is not None: - line_calib_obj.set_data(xs[: last_calib_sweep.size], _norm_to_max(last_calib_sweep)) - else: - line_calib_obj.set_data([], []) - if current_sweep_norm is not None: - line_norm_obj.set_data(xs[: current_sweep_norm.size], _norm_to_max(current_sweep_norm)) - else: - line_norm_obj.set_data([], []) - # Лимиты по X постоянные под текущую ширину - ax_line.set_xlim(0, max(1, current_sweep_raw.size - 1)) - # Фиксированные Y-лимиты после нормировки на максимум - if fixed_ylim is None: - ax_line.set_ylim(-1.05, 1.05) - ax_line.set_ylabel("/ max") - - # Обновление спектра текущего свипа - sweep_for_fft = current_sweep_norm if current_sweep_norm is not None else current_sweep_raw - take_fft = min(int(sweep_for_fft.size), FFT_LEN) - if take_fft > 0 and freq_shared is not None: - fft_in = np.zeros((FFT_LEN,), dtype=np.float32) - seg = np.nan_to_num(sweep_for_fft[:take_fft], nan=0.0).astype(np.float32, copy=False) - win = np.hanning(take_fft).astype(np.float32) - fft_in[:take_fft] = seg * win - spec = np.fft.rfft(fft_in) - mag = np.abs(spec).astype(np.float32) - fft_vals = 20.0 * np.log10(mag + 1e-9) - xs_fft = freq_shared - if fft_vals.size > xs_fft.size: - fft_vals = fft_vals[: xs_fft.size] - fft_line_obj.set_data(xs_fft[: fft_vals.size], fft_vals) - # Авто-диапазон по Y для спектра - if np.isfinite(np.nanmin(fft_vals)) and np.isfinite(np.nanmax(fft_vals)): - ax_fft.set_xlim(0, max(1, xs_fft.size - 1)) - ax_fft.set_ylim(float(np.nanmin(fft_vals)), float(np.nanmax(fft_vals))) - - # Обновление водопада - if changed and ring is not None: - disp = make_display_ring() - # Новые данные справа: без реверса - img_obj.set_data(disp) - # Подписи времени не обновляем динамически (оставляем авто-тики) - # Авто-уровни: по видимой области (не накапливаем за всё время) - levels = _visible_levels_matplotlib(disp, ax_img) - if levels is not None: - img_obj.set_clim(vmin=levels[0], vmax=levels[1]) - - # Обновление водопада спектров - if changed and ring_fft is not None: - disp_fft = make_display_ring_fft() - disp_fft = _subtract_recent_mean_fft(disp_fft) - # Новые данные справа: без реверса - img_fft_obj.set_data(disp_fft) - # Подписи времени не обновляем динамически (оставляем авто-тики) - # Автодиапазон по среднему спектру за видимый интервал (как в хорошей версии) - try: - # disp_fft имеет форму (bins, time); берём среднее по времени - mean_spec = np.nanmean(disp_fft, axis=1) - vmin_v = float(np.nanmin(mean_spec)) - vmax_v = float(np.nanmax(mean_spec)) - except Exception: - vmin_v = vmax_v = None - # Если средние не дают валидный диапазон — используем процентильную обрезку (если задана) - if (vmin_v is None or not np.isfinite(vmin_v)) or (vmax_v is None or not np.isfinite(vmax_v)) or vmin_v == vmax_v: - if spec_clip is not None: - try: - vmin_v = float(np.nanpercentile(disp_fft, spec_clip[0])) - vmax_v = float(np.nanpercentile(disp_fft, spec_clip[1])) - except Exception: - vmin_v = vmax_v = None - # Фолбэк к отслеживаемым минимум/максимумам - if (vmin_v is None or not np.isfinite(vmin_v)) or (vmax_v is None or not np.isfinite(vmax_v)) or vmin_v == vmax_v: - if y_min_fft is not None and y_max_fft is not None and np.isfinite(y_min_fft) and np.isfinite(y_max_fft) and y_min_fft != y_max_fft: - vmin_v, vmax_v = y_min_fft, y_max_fft - if vmin_v is not None and vmax_v is not None and vmin_v != vmax_v: - # Применим скалирование контрастом (верхняя граница) - try: - c = float(contrast_slider.val) / 100.0 if contrast_slider is not None else 1.0 - except Exception: - c = 1.0 - vmax_eff = vmin_v + c * (vmax_v - vmin_v) - img_fft_obj.set_clim(vmin=vmin_v, vmax=vmax_eff) - - if changed and current_info: - status_text.set_text(_format_status_kv(current_info)) - chs = current_info.get("chs") if isinstance(current_info, dict) else None - if chs is None: - chs = current_info.get("ch") if isinstance(current_info, dict) else None - if chs is None: - channel_text.set_text("") - else: - try: - if isinstance(chs, (list, tuple, set)): - ch_list = sorted(int(v) for v in chs) - ch_text_val = ", ".join(str(v) for v in ch_list) - else: - ch_text_val = str(int(chs)) - channel_text.set_text(f"chs {ch_text_val}") - except Exception: - channel_text.set_text(f"chs {chs}") - - # Возвращаем обновлённые артисты - return ( - line_obj, - line_calib_obj, - line_norm_obj, - img_obj, - fft_line_obj, - img_fft_obj, - status_text, - channel_text, - ) - - ani = FuncAnimation(fig, update, interval=interval_ms, blit=False) - - plt.show() - # Нормальное завершение при закрытии окна - stop_event.set() - reader.join(timeout=1.0) - - -def run_pyqtgraph(args): - """Быстрый GUI на PyQtGraph. Требует pyqtgraph и PyQt5/PySide6.""" - try: - import pyqtgraph as pg - from PyQt5 import QtCore, QtWidgets # noqa: F401 - except Exception: - # Возможно установлена PySide6 - try: - import pyqtgraph as pg - from PySide6 import QtCore, QtWidgets # noqa: F401 - except Exception as e: - raise RuntimeError( - "pyqtgraph/PyQt5(Pyside6) не найдены. Установите: pip install pyqtgraph PyQt5" - ) from e - - # Очередь завершённых свипов и поток чтения - q: Queue[SweepPacket] = Queue(maxsize=1000) - stop_event = threading.Event() - reader = SweepReader(args.port, args.baud, q, stop_event, fancy=bool(args.fancy)) - reader.start() - - # Настройки скорости - max_sweeps = int(max(10, args.max_sweeps)) - max_fps = max(1.0, float(args.max_fps)) - interval_ms = int(1000.0 / max_fps) - - # PyQtGraph настройки - pg.setConfigOptions(useOpenGL=True, antialias=False) - app = pg.mkQApp(args.title) - win = pg.GraphicsLayoutWidget(show=True, title=args.title) - win.resize(1200, 600) - - # Плот последнего свипа (слева-сверху) - p_line = win.addPlot(row=0, col=0, title="Сырые данные") - p_line.showGrid(x=True, y=True, alpha=0.3) - curve = p_line.plot(pen=pg.mkPen((80, 120, 255), width=1)) - curve_calib = p_line.plot(pen=pg.mkPen((220, 60, 60), width=1)) - curve_norm = p_line.plot(pen=pg.mkPen((60, 180, 90), width=1)) - p_line.setLabel("bottom", "X") - p_line.setLabel("left", "Y") - ch_text = pg.TextItem("", anchor=(1, 1)) - ch_text.setZValue(10) - p_line.addItem(ch_text) - - # Водопад (справа-сверху) - p_img = win.addPlot(row=0, col=1, title="Сырые данные водопад") - p_img.invertY(False) - p_img.showGrid(x=False, y=False) - p_img.setLabel("bottom", "Время, с (новое справа)") - try: - p_img.getAxis("bottom").setStyle(showValues=False) - except Exception: - pass - p_img.setLabel("left", "X (0 снизу)") - img = pg.ImageItem() - p_img.addItem(img) - - # FFT (слева-снизу) - p_fft = win.addPlot(row=1, col=0, title="FFT") - p_fft.showGrid(x=True, y=True, alpha=0.3) - curve_fft = p_fft.plot(pen=pg.mkPen((255, 120, 80), width=1)) - p_fft.setLabel("bottom", "Бин") - p_fft.setLabel("left", "Амплитуда, дБ") - - # Водопад спектров (справа-снизу) - p_spec = win.addPlot(row=1, col=1, title="B-scan (дБ)") - p_spec.invertY(True) - p_spec.showGrid(x=False, y=False) - p_spec.setLabel("bottom", "Время, с (новое справа)") - try: - p_spec.getAxis("bottom").setStyle(showValues=False) - except Exception: - pass - p_spec.setLabel("left", "Бин (0 снизу)") - img_fft = pg.ImageItem() - p_spec.addItem(img_fft) - - # Чекбокс калибровки - calib_cb = QtWidgets.QCheckBox("калибровка") - cb_proxy = QtWidgets.QGraphicsProxyWidget() - cb_proxy.setWidget(calib_cb) - win.addItem(cb_proxy, row=2, col=1) - - # Статусная строка (внизу окна) - status = pg.LabelItem(justify="left") - win.addItem(status, row=3, col=0, colspan=2) - - # Состояние - ring: Optional[np.ndarray] = None - ring_time: Optional[np.ndarray] = None - head = 0 - width: Optional[int] = None - x_shared: Optional[np.ndarray] = None - current_sweep_raw: Optional[np.ndarray] = None - current_sweep_norm: Optional[np.ndarray] = None - last_calib_sweep: Optional[np.ndarray] = None - current_info: Optional[SweepInfo] = None - # Авто-уровни цветовой шкалы водопада сырых данных пересчитываются по видимой области. - # Для спектров - fft_bins = FFT_LEN // 2 + 1 - ring_fft: Optional[np.ndarray] = None - freq_shared: Optional[np.ndarray] = None - y_min_fft, y_max_fft = None, None - # Параметры контраста водопада спектров (процентильная обрезка) - spec_clip = _parse_spec_clip(getattr(args, "spec_clip", None)) - spec_mean_sec = float(getattr(args, "spec_mean_sec", 0.0)) - calib_enabled = False - norm_type = str(getattr(args, "norm_type", "projector")).strip().lower() - # Диапазон по Y: авто по умолчанию (поддерживает отрицательные значения) - fixed_ylim: Optional[Tuple[float, float]] = None - if args.ylim: - try: - y0, y1 = args.ylim.split(",") - fixed_ylim = (float(y0), float(y1)) - except Exception: - pass - if fixed_ylim is not None: - p_line.setYRange(fixed_ylim[0], fixed_ylim[1], padding=0) - - def _normalize_sweep(raw: np.ndarray, calib: np.ndarray) -> np.ndarray: - return _normalize_by_calib(raw, calib, norm_type=norm_type) - - def _set_calib_enabled(): - nonlocal calib_enabled, current_sweep_norm - try: - calib_enabled = bool(calib_cb.isChecked()) - except Exception: - calib_enabled = False - if calib_enabled and current_sweep_raw is not None and last_calib_sweep is not None: - current_sweep_norm = _normalize_sweep(current_sweep_raw, last_calib_sweep) - else: - current_sweep_norm = None - - try: - calib_cb.stateChanged.connect(lambda _v: _set_calib_enabled()) - except Exception: - pass - - def ensure_buffer(_w: int): - nonlocal ring, ring_time, head, width, x_shared, ring_fft, freq_shared - if ring is not None: - return - width = WF_WIDTH - x_shared = np.arange(width, dtype=np.int32) - ring = np.full((max_sweeps, width), np.nan, dtype=np.float32) - ring_time = np.full((max_sweeps,), np.nan, dtype=np.float64) - head = 0 - # Водопад: время по оси X, X по оси Y - img.setImage(ring.T, autoLevels=False) - p_img.setRange(xRange=(0, max_sweeps - 1), yRange=(0, max(1, width - 1)), padding=0) - p_line.setXRange(0, max(1, width - 1), padding=0) - # FFT: время по оси X, бин по оси Y - ring_fft = np.full((max_sweeps, fft_bins), np.nan, dtype=np.float32) - img_fft.setImage(ring_fft.T, autoLevels=False) - p_spec.setRange(xRange=(0, max_sweeps - 1), yRange=(0, max(1, fft_bins - 1)), padding=0) - p_fft.setXRange(0, max(1, fft_bins - 1), padding=0) - freq_shared = np.arange(fft_bins, dtype=np.int32) - - def _visible_levels_pyqtgraph(data: np.ndarray) -> Optional[Tuple[float, float]]: - """(vmin, vmax) по текущей видимой области ImageItem (без накопления по времени).""" - if data.size == 0: - return None - ny, nx = data.shape[0], data.shape[1] - try: - (x0, x1), (y0, y1) = p_img.viewRange() - except Exception: - x0, x1 = 0.0, float(nx - 1) - y0, y1 = 0.0, float(ny - 1) - xmin, xmax = sorted((float(x0), float(x1))) - ymin, ymax = sorted((float(y0), float(y1))) - ix0 = max(0, min(nx - 1, int(np.floor(xmin)))) - ix1 = max(0, min(nx - 1, int(np.ceil(xmax)))) - iy0 = max(0, min(ny - 1, int(np.floor(ymin)))) - iy1 = max(0, min(ny - 1, int(np.ceil(ymax)))) - if ix1 < ix0: - ix1 = ix0 - if iy1 < iy0: - iy1 = iy0 - sub = data[iy0 : iy1 + 1, ix0 : ix1 + 1] - finite = np.isfinite(sub) - if not finite.any(): - return None - vals = sub[finite] - vmin = float(np.min(vals)) - vmax = float(np.max(vals)) - if not (np.isfinite(vmin) and np.isfinite(vmax)) or vmin == vmax: - return None - return (vmin, vmax) - - def push_sweep(s: np.ndarray): - nonlocal ring, ring_time, head, ring_fft, y_min_fft, y_max_fft - if s is None or s.size == 0 or ring is None: - return - w = ring.shape[1] - row = np.full((w,), np.nan, dtype=np.float32) - take = min(w, s.size) - row[:take] = s[:take] - ring[head, :] = row - if ring_time is not None: - ring_time[head] = time.time() - head = (head + 1) % ring.shape[0] - # FFT строка (дБ) - if ring_fft is not None: - bins = ring_fft.shape[1] - take_fft = min(int(s.size), FFT_LEN) - if take_fft > 0: - fft_in = np.zeros((FFT_LEN,), dtype=np.float32) - seg = np.nan_to_num(s[:take_fft], nan=0.0).astype(np.float32, copy=False) - win = np.hanning(take_fft).astype(np.float32) - fft_in[:take_fft] = seg * win - spec = np.fft.rfft(fft_in) - mag = np.abs(spec).astype(np.float32) - fft_row = 20.0 * np.log10(mag + 1e-9) - if fft_row.shape[0] != bins: - fft_row = fft_row[:bins] - else: - fft_row = np.full((bins,), np.nan, dtype=np.float32) - ring_fft[(head - 1) % ring_fft.shape[0], :] = fft_row - fr_min = np.nanmin(fft_row) - fr_max = np.nanmax(fft_row) - if y_min_fft is None or (not np.isnan(fr_min) and fr_min < y_min_fft): - y_min_fft = float(fr_min) - if y_max_fft is None or (not np.isnan(fr_max) and fr_max > y_max_fft): - y_max_fft = float(fr_max) - - def drain_queue(): - nonlocal current_sweep_raw, current_sweep_norm, current_info, last_calib_sweep - drained = 0 - while True: - try: - s, info = q.get_nowait() - except Empty: - break - drained += 1 - current_sweep_raw = s - current_info = info - ch = 0 - try: - ch = int(info.get("ch", 0)) if isinstance(info, dict) else 0 - except Exception: - ch = 0 - if ch == 0: - last_calib_sweep = s - current_sweep_norm = None - sweep_for_proc = s - else: - if calib_enabled and last_calib_sweep is not None: - current_sweep_norm = _normalize_sweep(s, last_calib_sweep) - sweep_for_proc = current_sweep_norm - else: - current_sweep_norm = None - sweep_for_proc = s - ensure_buffer(s.size) - push_sweep(sweep_for_proc) - return drained - - # Попытка применить LUT из колормэпа (если доступен) - try: - cm_mod = getattr(pg, "colormap", None) - if cm_mod is not None: - cm = cm_mod.get(args.cmap) - img.setLookupTable(cm.getLookupTable(0.0, 1.0, 256)) - except Exception: - pass - - def update(): - changed = drain_queue() > 0 - if current_sweep_raw is not None and x_shared is not None: - if current_sweep_raw.size <= x_shared.size: - xs = x_shared[: current_sweep_raw.size] - else: - xs = np.arange(current_sweep_raw.size) - def _norm_to_max(data): - m = float(np.nanmax(np.abs(data))) - return data / m if m > 0.0 else data - curve.setData(xs, _norm_to_max(current_sweep_raw), autoDownsample=True) - if last_calib_sweep is not None: - curve_calib.setData(xs[: last_calib_sweep.size], _norm_to_max(last_calib_sweep), autoDownsample=True) - else: - curve_calib.setData([], []) - if current_sweep_norm is not None: - curve_norm.setData(xs[: current_sweep_norm.size], _norm_to_max(current_sweep_norm), autoDownsample=True) - else: - curve_norm.setData([], []) - if fixed_ylim is None: - p_line.setYRange(-1.05, 1.05, padding=0) - p_line.setLabel("left", "/ max") - - # Обновим спектр - sweep_for_fft = current_sweep_norm if current_sweep_norm is not None else current_sweep_raw - take_fft = min(int(sweep_for_fft.size), FFT_LEN) - if take_fft > 0 and freq_shared is not None: - fft_in = np.zeros((FFT_LEN,), dtype=np.float32) - seg = np.nan_to_num(sweep_for_fft[:take_fft], nan=0.0).astype(np.float32, copy=False) - win = np.hanning(take_fft).astype(np.float32) - fft_in[:take_fft] = seg * win - spec = np.fft.rfft(fft_in) - mag = np.abs(spec).astype(np.float32) - fft_vals = 20.0 * np.log10(mag + 1e-9) - xs_fft = freq_shared - if fft_vals.size > xs_fft.size: - fft_vals = fft_vals[: xs_fft.size] - curve_fft.setData(xs_fft[: fft_vals.size], fft_vals) - p_fft.setYRange(float(np.nanmin(fft_vals)), float(np.nanmax(fft_vals)), padding=0) - - if changed and ring is not None: - disp = ring if head == 0 else np.roll(ring, -head, axis=0) - disp = disp.T[:, ::-1] # (width, time with newest at left) - levels = _visible_levels_pyqtgraph(disp) - if levels is not None: - img.setImage(disp, autoLevels=False, levels=levels) - else: - img.setImage(disp, autoLevels=False) - - if changed and current_info: - try: - status.setText(_format_status_kv(current_info)) - except Exception: - pass - try: - chs = current_info.get("chs") if isinstance(current_info, dict) else None - if chs is None: - chs = current_info.get("ch") if isinstance(current_info, dict) else None - if chs is None: - ch_text.setText("") - else: - if isinstance(chs, (list, tuple, set)): - ch_list = sorted(int(v) for v in chs) - ch_text_val = ", ".join(str(v) for v in ch_list) - else: - ch_text_val = str(int(chs)) - ch_text.setText(f"chs {ch_text_val}") - (x0, x1), (y0, y1) = p_line.viewRange() - dx = 0.01 * max(1.0, float(x1 - x0)) - dy = 0.01 * max(1.0, float(y1 - y0)) - ch_text.setPos(float(x1 - dx), float(y1 - dy)) - except Exception: - pass - - if changed and ring_fft is not None: - disp_fft = ring_fft if head == 0 else np.roll(ring_fft, -head, axis=0) - disp_fft = disp_fft.T[:, ::-1] - if spec_mean_sec > 0.0 and ring_time is not None: - disp_times = ring_time if head == 0 else np.roll(ring_time, -head) - disp_times = disp_times[::-1] - now_t = time.time() - mask = np.isfinite(disp_times) & (disp_times >= (now_t - spec_mean_sec)) - if np.any(mask): - try: - mean_spec = np.nanmean(disp_fft[:, mask], axis=1) - mean_spec = np.nan_to_num(mean_spec, nan=0.0) - disp_fft = disp_fft - mean_spec[:, None] - except Exception: - pass - # Автодиапазон по среднему спектру за видимый интервал (как в хорошей версии) - levels = None - try: - mean_spec = np.nanmean(disp_fft, axis=1) - vmin_v = float(np.nanmin(mean_spec)) - vmax_v = float(np.nanmax(mean_spec)) - if np.isfinite(vmin_v) and np.isfinite(vmax_v) and vmin_v != vmax_v: - levels = (vmin_v, vmax_v) - except Exception: - levels = None - # Процентильная обрезка как запасной вариант - if levels is None and spec_clip is not None: - try: - vmin_v = float(np.nanpercentile(disp_fft, spec_clip[0])) - vmax_v = float(np.nanpercentile(disp_fft, spec_clip[1])) - if np.isfinite(vmin_v) and np.isfinite(vmax_v) and vmin_v != vmax_v: - levels = (vmin_v, vmax_v) - except Exception: - levels = None - # Ещё один фолбэк — глобальные накопленные мин/макс - if levels is None and y_min_fft is not None and y_max_fft is not None and np.isfinite(y_min_fft) and np.isfinite(y_max_fft) and y_min_fft != y_max_fft: - levels = (y_min_fft, y_max_fft) - if levels is not None: - img_fft.setImage(disp_fft, autoLevels=False, levels=levels) - else: - img_fft.setImage(disp_fft, autoLevels=False) - - timer = pg.QtCore.QTimer() - timer.timeout.connect(update) - timer.start(interval_ms) - - def on_quit(): - stop_event.set() - reader.join(timeout=1.0) - - app.aboutToQuit.connect(on_quit) - win.show() - exec_fn = getattr(app, "exec_", None) or getattr(app, "exec", None) - exec_fn() - # На случай если aboutToQuit не сработал - on_quit() - - -if __name__ == "__main__": - main() diff --git a/rfg_adc_plotter/constants.py b/rfg_adc_plotter/constants.py index 47ca55c..1ccfef8 100644 --- a/rfg_adc_plotter/constants.py +++ b/rfg_adc_plotter/constants.py @@ -1,5 +1,13 @@ WF_WIDTH = 1000 # максимальное число точек в ряду водопада -FFT_LEN = 1024 # длина БПФ для спектра/водопада спектров +FFT_LEN = 2048 # длина БПФ для спектра/водопада спектров # Порог для инверсии сырых данных: если среднее значение свипа ниже порога — # считаем, что сигнал «меньше нуля» и домножаем свип на -1 DATA_INVERSION_THRESHOLD = 10.0 + +# Параметры IFFT-спектра (временной профиль из спектра 3.2..14.3 ГГц) +# Двусторонний спектр формируется как: [нули -14.3..-3.2 | нули -3.2..+3.2 | данные +3.2..+14.3] +ZEROS_LOW = 758 # нули от -14.3 до -3.2 ГГц +ZEROS_MID = 437 # нули от -3.2 до +3.2 ГГц +SWEEP_LEN = 758 # ожидаемая длина свипа (3.2 → 14.3 ГГц) +FREQ_SPAN_GHZ = 28.6 # полная двусторонняя полоса (-14.3 .. +14.3 ГГц) +IFFT_LEN = ZEROS_LOW + ZEROS_MID + SWEEP_LEN # = 1953 diff --git a/rfg_adc_plotter/gui/matplotlib_backend.py b/rfg_adc_plotter/gui/matplotlib_backend.py index 1f80a8a..93eb0a4 100644 --- a/rfg_adc_plotter/gui/matplotlib_backend.py +++ b/rfg_adc_plotter/gui/matplotlib_backend.py @@ -243,15 +243,14 @@ def run_matplotlib(args): ax_line.set_ylim(-1.05, 1.05) ax_line.set_ylabel("/ max") - # Спектр — используем уже вычисленный в ring FFT - if ring.last_fft_vals is not None and ring.freq_shared is not None: + # Спектр — используем уже вычисленный в ring IFFT (временной профиль) + if ring.last_fft_vals is not None and ring.fft_time_axis is not None: fft_vals = ring.last_fft_vals - xs_fft = ring.freq_shared - if fft_vals.size > xs_fft.size: - fft_vals = fft_vals[: xs_fft.size] - fft_line_obj.set_data(xs_fft[: fft_vals.size], fft_vals) + xs_fft = ring.fft_time_axis + n = min(fft_vals.size, xs_fft.size) + fft_line_obj.set_data(xs_fft[:n], fft_vals[:n]) if np.isfinite(np.nanmin(fft_vals)) and np.isfinite(np.nanmax(fft_vals)): - ax_fft.set_xlim(0, max(1, xs_fft.size - 1)) + ax_fft.set_xlim(0, float(xs_fft[n - 1])) ax_fft.set_ylim(float(np.nanmin(fft_vals)), float(np.nanmax(fft_vals))) # Водопад сырых данных diff --git a/rfg_adc_plotter/gui/pyqtgraph_backend.py b/rfg_adc_plotter/gui/pyqtgraph_backend.py index 54136be..d2a9ac1 100644 --- a/rfg_adc_plotter/gui/pyqtgraph_backend.py +++ b/rfg_adc_plotter/gui/pyqtgraph_backend.py @@ -7,12 +7,16 @@ from typing import Optional, Tuple import numpy as np +from rfg_adc_plotter.constants import FREQ_SPAN_GHZ, IFFT_LEN from rfg_adc_plotter.io.sweep_reader import SweepReader from rfg_adc_plotter.processing.normalizer import build_calib_envelopes from rfg_adc_plotter.state.app_state import AppState, format_status from rfg_adc_plotter.state.ring_buffer import RingBuffer from rfg_adc_plotter.types import SweepPacket +# Максимальное значение временной оси IFFT в нс +_IFFT_T_MAX_NS = float((IFFT_LEN - 1) / (FREQ_SPAN_GHZ * 1e9) * 1e9) + def _parse_ylim(ylim_str: Optional[str]) -> Optional[Tuple[float, float]]: if not ylim_str: @@ -164,8 +168,8 @@ def run_pyqtgraph(args): p_fft = win.addPlot(row=1, col=0, title="FFT") p_fft.showGrid(x=True, y=True, alpha=0.3) curve_fft = p_fft.plot(pen=pg.mkPen((255, 120, 80), width=1)) - p_fft.setLabel("bottom", "Бин") - p_fft.setLabel("left", "Амплитуда, дБ") + p_fft.setLabel("bottom", "Время, нс") + p_fft.setLabel("left", "Мощность, дБ") # Водопад спектров (справа-снизу) p_spec = win.addPlot(row=1, col=1, title="B-scan (дБ)") @@ -176,7 +180,7 @@ def run_pyqtgraph(args): p_spec.getAxis("bottom").setStyle(showValues=False) except Exception: pass - p_spec.setLabel("left", "Бин (0 снизу)") + p_spec.setLabel("left", "Время, нс") img_fft = pg.ImageItem() p_spec.addItem(img_fft) @@ -197,7 +201,6 @@ def run_pyqtgraph(args): FREQ_MAX = 14.323 def _init_imshow_extents(): - w = ring.width ms = ring.max_sweeps fb = ring.fft_bins img.setImage(ring.ring.T, autoLevels=False) @@ -205,8 +208,9 @@ def run_pyqtgraph(args): p_img.setRange(xRange=(0, ms - 1), yRange=(FREQ_MIN, FREQ_MAX), padding=0) p_line.setXRange(FREQ_MIN, FREQ_MAX, padding=0) img_fft.setImage(ring.ring_fft.T, autoLevels=False) - p_spec.setRange(xRange=(0, ms - 1), yRange=(0, max(1, fb - 1)), padding=0) - p_fft.setXRange(0, max(1, fb - 1), padding=0) + img_fft.setRect(pg.QtCore.QRectF(0.0, 0.0, float(ms), _IFFT_T_MAX_NS)) + p_spec.setRange(xRange=(0, ms - 1), yRange=(0.0, _IFFT_T_MAX_NS), padding=0) + p_fft.setXRange(0.0, _IFFT_T_MAX_NS, padding=0) def _img_rect(ms: int) -> "pg.QtCore.QRectF": return pg.QtCore.QRectF(0.0, FREQ_MIN, float(ms), FREQ_MAX - FREQ_MIN) @@ -245,13 +249,12 @@ def run_pyqtgraph(args): p_line.setYRange(-1.05, 1.05, padding=0) p_line.setLabel("left", "/ max") - # Спектр — используем уже вычисленный в ring FFT - if ring.last_fft_vals is not None and ring.freq_shared is not None: + # Спектр — используем уже вычисленный в ring IFFT (временной профиль) + if ring.last_fft_vals is not None and ring.fft_time_axis is not None: fft_vals = ring.last_fft_vals - xs_fft = ring.freq_shared - if fft_vals.size > xs_fft.size: - fft_vals = fft_vals[: xs_fft.size] - curve_fft.setData(xs_fft[: fft_vals.size], fft_vals) + xs_fft = ring.fft_time_axis + n = min(fft_vals.size, xs_fft.size) + curve_fft.setData(xs_fft[:n], fft_vals[:n]) p_fft.setYRange(float(np.nanmin(fft_vals)), float(np.nanmax(fft_vals)), padding=0) # Позиция подписи канала @@ -290,6 +293,7 @@ def run_pyqtgraph(args): img_fft.setImage(disp_fft, autoLevels=False, levels=levels) else: img_fft.setImage(disp_fft, autoLevels=False) + img_fft.setRect(pg.QtCore.QRectF(0.0, 0.0, float(ring.max_sweeps), _IFFT_T_MAX_NS)) timer = pg.QtCore.QTimer() timer.timeout.connect(update) diff --git a/rfg_adc_plotter/state/ring_buffer.py b/rfg_adc_plotter/state/ring_buffer.py index 1b9ecd5..11f9f09 100644 --- a/rfg_adc_plotter/state/ring_buffer.py +++ b/rfg_adc_plotter/state/ring_buffer.py @@ -5,7 +5,15 @@ from typing import Optional, Tuple import numpy as np -from rfg_adc_plotter.constants import FFT_LEN, WF_WIDTH +from rfg_adc_plotter.constants import ( + FFT_LEN, + FREQ_SPAN_GHZ, + IFFT_LEN, + SWEEP_LEN, + WF_WIDTH, + ZEROS_LOW, + ZEROS_MID, +) class RingBuffer: @@ -17,7 +25,7 @@ class RingBuffer: def __init__(self, max_sweeps: int): self.max_sweeps = max_sweeps - self.fft_bins = FFT_LEN // 2 + 1 + self.fft_bins = IFFT_LEN # = 1953 (полная длина IFFT-результата) # Инициализируются при первом свипе (ensure_init) self.ring: Optional[np.ndarray] = None # (max_sweeps, WF_WIDTH) @@ -26,7 +34,7 @@ class RingBuffer: self.head: int = 0 self.width: Optional[int] = None self.x_shared: Optional[np.ndarray] = None - self.freq_shared: Optional[np.ndarray] = None + self.fft_time_axis: Optional[np.ndarray] = None # временная ось IFFT в нс self.y_min_fft: Optional[float] = None self.y_max_fft: Optional[float] = None # FFT последнего свипа (для отображения без повторного вычисления) @@ -43,7 +51,10 @@ class RingBuffer: self.ring = np.full((self.max_sweeps, self.width), np.nan, dtype=np.float32) self.ring_time = np.full((self.max_sweeps,), np.nan, dtype=np.float64) self.ring_fft = np.full((self.max_sweeps, self.fft_bins), np.nan, dtype=np.float32) - self.freq_shared = np.arange(self.fft_bins, dtype=np.int32) + # Временная ось IFFT: шаг dt = 1/(FREQ_SPAN_GHZ*1e9), переведём в нс + self.fft_time_axis = ( + np.arange(IFFT_LEN, dtype=np.float64) / (FREQ_SPAN_GHZ * 1e9) * 1e9 + ).astype(np.float32) self.head = 0 # Обновляем x_shared если пришёл свип большего размера if self.x_shared is None or sweep_width > self.x_shared.size: @@ -64,20 +75,29 @@ class RingBuffer: self._push_fft(s) def _push_fft(self, s: np.ndarray): - bins = self.ring_fft.shape[1] - take_fft = min(int(s.size), FFT_LEN) - if take_fft <= 0: + bins = self.ring_fft.shape[1] # = IFFT_LEN = 1953 + if s is None or s.size == 0: fft_row = np.full((bins,), np.nan, dtype=np.float32) else: - fft_in = np.zeros((FFT_LEN,), dtype=np.float32) - seg = np.nan_to_num(s[:take_fft], nan=0.0).astype(np.float32, copy=False) - win = np.hanning(take_fft).astype(np.float32) - fft_in[:take_fft] = seg * win - spec = np.fft.rfft(fft_in) - mag = np.abs(spec).astype(np.float32) + # 1. Взять первые SWEEP_LEN отсчётов (остаток — нули если свип короче) + sig = np.zeros(SWEEP_LEN, dtype=np.float32) + take = min(int(s.size), SWEEP_LEN) + seg = np.nan_to_num(s[:take], nan=0.0).astype(np.float32, copy=False) + sig[:take] = seg + + # 2. Собрать двусторонний спектр: + # [ZEROS_LOW нулей | ZEROS_MID нулей | SWEEP_LEN данных] + # = [-14.3..-3.2 ГГц | -3.2..+3.2 ГГц | +3.2..+14.3 ГГц] + data = np.zeros(IFFT_LEN, dtype=np.complex64) + data[ZEROS_LOW + ZEROS_MID:] = sig + + # 3. ifftshift + ifft → временной профиль + spec = np.fft.ifftshift(data) + result = np.fft.ifft(spec) + + # 4. Амплитуда в дБ + mag = np.abs(result).astype(np.float32) fft_row = (20.0 * np.log10(mag + 1e-9)).astype(np.float32) - if fft_row.shape[0] != bins: - fft_row = fft_row[:bins] prev_head = (self.head - 1) % self.ring_fft.shape[0] self.ring_fft[prev_head, :] = fft_row -- 2.49.0 From d2d504f5b895e2259100b706b3a7a33882bd1905 Mon Sep 17 00:00:00 2001 From: awe Date: Wed, 11 Feb 2026 19:26:00 +0300 Subject: [PATCH 06/13] fix axis --- rfg_adc_plotter/gui/matplotlib_backend.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/rfg_adc_plotter/gui/matplotlib_backend.py b/rfg_adc_plotter/gui/matplotlib_backend.py index 93eb0a4..304660d 100644 --- a/rfg_adc_plotter/gui/matplotlib_backend.py +++ b/rfg_adc_plotter/gui/matplotlib_backend.py @@ -7,7 +7,9 @@ from typing import Optional, Tuple import numpy as np -from rfg_adc_plotter.constants import FFT_LEN +from rfg_adc_plotter.constants import FFT_LEN, FREQ_SPAN_GHZ, IFFT_LEN + +_IFFT_T_MAX_NS = float((IFFT_LEN - 1) / (FREQ_SPAN_GHZ * 1e9) * 1e9) from rfg_adc_plotter.io.sweep_reader import SweepReader from rfg_adc_plotter.processing.normalizer import build_calib_envelopes from rfg_adc_plotter.state.app_state import AppState, format_status @@ -128,8 +130,8 @@ def run_matplotlib(args): # График спектра fft_line_obj, = ax_fft.plot([], [], lw=1) ax_fft.set_title("FFT", pad=1) - ax_fft.set_xlabel("X") - ax_fft.set_ylabel("Амплитуда, дБ") + ax_fft.set_xlabel("Время, нс") + ax_fft.set_ylabel("Мощность, дБ") # Водопад сырых данных img_obj = ax_img.imshow( @@ -149,7 +151,7 @@ def run_matplotlib(args): aspect="auto", interpolation="nearest", origin="lower", cmap=args.cmap, ) ax_spec.set_title("B-scan (дБ)", pad=12) - ax_spec.set_ylabel("расстояние") + ax_spec.set_ylabel("Время, нс") try: ax_spec.tick_params(axis="x", labelbottom=False) except Exception: @@ -199,9 +201,10 @@ def run_matplotlib(args): ax_img.set_xlim(0, ms - 1) ax_img.set_ylim(FREQ_MIN, FREQ_MAX) img_fft_obj.set_data(np.zeros((fb, ms), dtype=np.float32)) - img_fft_obj.set_extent((0, ms - 1, 0, fb - 1)) + img_fft_obj.set_extent((0, ms - 1, 0.0, _IFFT_T_MAX_NS)) ax_spec.set_xlim(0, ms - 1) - ax_spec.set_ylim(0, max(1, fb - 1)) + ax_spec.set_ylim(0.0, _IFFT_T_MAX_NS) + ax_fft.set_xlim(0.0, _IFFT_T_MAX_NS) _imshow_initialized = [False] -- 2.49.0 From 66a318fff8e232e70b5833e6cb7d701918f58429 Mon Sep 17 00:00:00 2001 From: awe Date: Fri, 13 Feb 2026 17:32:04 +0300 Subject: [PATCH 07/13] add calibration file --- calib_envelope.npy | Bin 0 -> 3164 bytes rfg_adc_plotter/gui/matplotlib_backend.py | 32 +++++++-- rfg_adc_plotter/gui/pyqtgraph_backend.py | 46 +++++++++++-- rfg_adc_plotter/processing/normalizer.py | 38 +++++++++++ rfg_adc_plotter/state/app_state.py | 79 +++++++++++++++++++--- 5 files changed, 174 insertions(+), 21 deletions(-) create mode 100644 calib_envelope.npy diff --git a/calib_envelope.npy b/calib_envelope.npy new file mode 100644 index 0000000000000000000000000000000000000000..9053d4f604ebba00a6d93003e6ac2ff91ef38a58 GIT binary patch literal 3164 zcmbW3e~4676vwYW(Zy=}y@=Id+HT951J7TH)SLIPRQj=mFH(YL$sI&YhusP>ilI_A zu^L^CouOce%w$cvHx{nud3AC5`QbB%e@HKi@E!!?nNYf}4N6Yphw$u;)l z*zZApldOW+fC3;DIKH@q7CqwpZy4~thfF63KT{~U6T7+aASB3IF`4Pz?C3DEwOBOS|T zcEv2KH#S(=6H6rCLf6N-cS8SubSJQ##%}_(H&R~&F5;)X?|~Hlo%pXpj{5V!rkcn0 ztUane)tQDq$bn+WwgnoY1#FlD(_qBL4_-yCLKz0gl_%#uycR z1CGI2m_Z#iM#Yrh0Vw)$3;Es1TJtg}_jc&1BgwoSq99o{$u|y5pb>`Hdy4+=usv^Y zSc~crC8&Z4eIw+aOKq*pqoF+0wHlwbB5}sHtgphgT0e$jM8Y_d6}Mz(GauuB z&>pNDVD0Pur~0Ozfc{<--Bgc!0(*Dm%z8?+k$VWevFgN ztmJIDoS$W!qea-FumIGbWnfe92H1g|gDmJw={u?4tDy;s$^kkLTC4BU&${FE>3if$ za1!(l^{s4J2l^g5)BP|2MJR#3c^b5zdfL$?iM7{$UjVe-3Q|Y`f6y`d>TxIOXx0#KAKPF?VHFOI04x(PG_#SZx-AJ zx5FKvx8hc~7N&sWOk!++>!FEtGg+@S@|_7cf&7(wDoh6DH25~)do%KtzS>VA|9iOi zU&H-se_B7zVC6FB_-FcjhJK&IPd!vGRQIUg3(xxrSv?vJ^|H%PeH^Ed|CavASG`hy zRNqCY`TC%*iXokRRFB@BYd|$#2YORgtL)0Def$;aWRs72r#$CDd;O6-I{(_=4{#dv zEo-4|7`cqBd-4f#5spIzbUu{lJJ5Qa3)Lu}9Q1(h;U3Vv)LW}}_b_q^4naS>4LZkr zu?K$j_gMEx_bIp^$+~ep^EkAF4N-`|5|B>z`rnuqbn&EzeCDsSKk|83P9YFXXrY>0z=lqVOy zuiJflHnRqueEutnlYm~1`84!xpk7BndE}>aq5o-gr$>+npa*P_kEz3Eo`T#}(QlA`W7M}Ed0VeU* z&EP)XLR{tlXSn~=(tw{~JWCIT$yWlci$fapwra0>Yg3?}B*Rhju{T(<^jg;rHbnmw z&znc?R{UD%zkai4BS*q@`c2ch(f?l2P+pF#_$xp;mOzyE=T5)wY-YOu+Zyz>MlA-r gzDpxWuA;k=p#EQcf5ot@8|mdNV&26X)nQ_P0u2rk9smFU literal 0 HcmV?d00001 diff --git a/rfg_adc_plotter/gui/matplotlib_backend.py b/rfg_adc_plotter/gui/matplotlib_backend.py index 304660d..e7f737f 100644 --- a/rfg_adc_plotter/gui/matplotlib_backend.py +++ b/rfg_adc_plotter/gui/matplotlib_backend.py @@ -12,7 +12,7 @@ from rfg_adc_plotter.constants import FFT_LEN, FREQ_SPAN_GHZ, IFFT_LEN _IFFT_T_MAX_NS = float((IFFT_LEN - 1) / (FREQ_SPAN_GHZ * 1e9) * 1e9) from rfg_adc_plotter.io.sweep_reader import SweepReader from rfg_adc_plotter.processing.normalizer import build_calib_envelopes -from rfg_adc_plotter.state.app_state import AppState, format_status +from rfg_adc_plotter.state.app_state import CALIB_ENVELOPE_PATH, AppState, format_status from rfg_adc_plotter.state.ring_buffer import RingBuffer from rfg_adc_plotter.types import SweepPacket @@ -165,10 +165,16 @@ def run_matplotlib(args): ax_smax = fig.add_axes([0.95, 0.55, 0.02, 0.35]) ax_sctr = fig.add_axes([0.98, 0.55, 0.02, 0.35]) ax_cb = fig.add_axes([0.92, 0.45, 0.08, 0.08]) + ax_cb_file = fig.add_axes([0.92, 0.36, 0.08, 0.08]) ymin_slider = Slider(ax_smin, "Y min", 0, max(1, fft_bins - 1), valinit=0, valstep=1, orientation="vertical") ymax_slider = Slider(ax_smax, "Y max", 0, max(1, fft_bins - 1), valinit=max(1, fft_bins - 1), valstep=1, orientation="vertical") contrast_slider = Slider(ax_sctr, "Int max", 0, 100, valinit=100, valstep=1, orientation="vertical") calib_cb = CheckButtons(ax_cb, ["калибровка"], [False]) + calib_file_cb = CheckButtons(ax_cb_file, ["из файла"], [False]) + + import os as _os + if not _os.path.isfile(CALIB_ENVELOPE_PATH): + ax_cb_file.set_visible(False) def _on_ylim_change(_val): try: @@ -179,12 +185,30 @@ def run_matplotlib(args): except Exception: pass + def _on_calib_file_clicked(_v): + use_file = bool(calib_file_cb.get_status()[0]) + if use_file: + ok = state.load_calib_envelope(CALIB_ENVELOPE_PATH) + if ok: + state.set_calib_mode("file") + else: + calib_file_cb.set_active(0) # снять галочку + else: + state.set_calib_mode("live") + state.set_calib_enabled(bool(calib_cb.get_status()[0])) + + def _on_calib_clicked(_v): + import os as _os2 + if _os2.path.isfile(CALIB_ENVELOPE_PATH): + ax_cb_file.set_visible(True) + state.set_calib_enabled(bool(calib_cb.get_status()[0])) + fig.canvas.draw_idle() + ymin_slider.on_changed(_on_ylim_change) ymax_slider.on_changed(_on_ylim_change) contrast_slider.on_changed(lambda _v: fig.canvas.draw_idle()) - calib_cb.on_clicked(lambda _v: state.set_calib_enabled( - bool(calib_cb.get_status()[0]) - )) + calib_cb.on_clicked(_on_calib_clicked) + calib_file_cb.on_clicked(_on_calib_file_clicked) except Exception: calib_cb = None diff --git a/rfg_adc_plotter/gui/pyqtgraph_backend.py b/rfg_adc_plotter/gui/pyqtgraph_backend.py index d2a9ac1..ed76229 100644 --- a/rfg_adc_plotter/gui/pyqtgraph_backend.py +++ b/rfg_adc_plotter/gui/pyqtgraph_backend.py @@ -10,7 +10,7 @@ import numpy as np from rfg_adc_plotter.constants import FREQ_SPAN_GHZ, IFFT_LEN from rfg_adc_plotter.io.sweep_reader import SweepReader from rfg_adc_plotter.processing.normalizer import build_calib_envelopes -from rfg_adc_plotter.state.app_state import AppState, format_status +from rfg_adc_plotter.state.app_state import CALIB_ENVELOPE_PATH, AppState, format_status from rfg_adc_plotter.state.ring_buffer import RingBuffer from rfg_adc_plotter.types import SweepPacket @@ -184,12 +184,46 @@ def run_pyqtgraph(args): img_fft = pg.ImageItem() p_spec.addItem(img_fft) - # Чекбокс калибровки + # Чекбоксы калибровки — в одном контейнере + calib_widget = QtWidgets.QWidget() + calib_layout = QtWidgets.QHBoxLayout(calib_widget) + calib_layout.setContentsMargins(2, 2, 2, 2) + calib_layout.setSpacing(8) + calib_cb = QtWidgets.QCheckBox("калибровка") - cb_proxy = QtWidgets.QGraphicsProxyWidget() - cb_proxy.setWidget(calib_cb) - win.addItem(cb_proxy, row=2, col=1) - calib_cb.stateChanged.connect(lambda _v: state.set_calib_enabled(calib_cb.isChecked())) + calib_file_cb = QtWidgets.QCheckBox("из файла") + calib_file_cb.setEnabled(False) # активируется только если файл существует + + calib_layout.addWidget(calib_cb) + calib_layout.addWidget(calib_file_cb) + + cb_container_proxy = QtWidgets.QGraphicsProxyWidget() + cb_container_proxy.setWidget(calib_widget) + win.addItem(cb_container_proxy, row=2, col=1) + + def _check_file_cb_available(): + import os + calib_file_cb.setEnabled(os.path.isfile(CALIB_ENVELOPE_PATH)) + + _check_file_cb_available() + + def _on_calib_file_toggled(checked): + if checked: + ok = state.load_calib_envelope(CALIB_ENVELOPE_PATH) + if ok: + state.set_calib_mode("file") + else: + calib_file_cb.setChecked(False) + else: + state.set_calib_mode("live") + state.set_calib_enabled(calib_cb.isChecked()) + + def _on_calib_toggled(_v): + _check_file_cb_available() + state.set_calib_enabled(calib_cb.isChecked()) + + calib_cb.stateChanged.connect(_on_calib_toggled) + calib_file_cb.stateChanged.connect(lambda _v: _on_calib_file_toggled(calib_file_cb.isChecked())) # Статусная строка status = pg.LabelItem(justify="left") diff --git a/rfg_adc_plotter/processing/normalizer.py b/rfg_adc_plotter/processing/normalizer.py index 5d9c675..0b68760 100644 --- a/rfg_adc_plotter/processing/normalizer.py +++ b/rfg_adc_plotter/processing/normalizer.py @@ -109,3 +109,41 @@ def normalize_by_calib(raw: np.ndarray, calib: np.ndarray, norm_type: str) -> np if nt == "simple": return normalize_simple(raw, calib) return normalize_projector(raw, calib) + + +def normalize_by_envelope(raw: np.ndarray, envelope: np.ndarray) -> np.ndarray: + """Нормировка свипа через проекцию на огибающую из файла. + + Воспроизводит логику normalize_projector: проецирует raw в [-1000, +1000] + используя готовую верхнюю огибающую (upper = envelope, lower = -envelope). + """ + w = min(raw.size, envelope.size) + if w <= 0: + return raw + + out = np.full_like(raw, np.nan, dtype=np.float32) + raw_seg = np.asarray(raw[:w], dtype=np.float32) + upper = np.asarray(envelope[:w], dtype=np.float32) + lower = -upper + span = upper - lower # = 2 * upper + + finite_span = span[np.isfinite(span) & (span > 0)] + if finite_span.size > 0: + eps = max(float(np.median(finite_span)) * 1e-6, 1e-9) + else: + eps = 1e-9 + + valid = ( + np.isfinite(raw_seg) + & np.isfinite(lower) + & np.isfinite(upper) + & (span > eps) + ) + if np.any(valid): + proj = np.empty_like(raw_seg, dtype=np.float32) + proj[valid] = ((2.0 * (raw_seg[valid] - lower[valid]) / span[valid]) - 1.0) * 1000.0 + proj[valid] = np.clip(proj[valid], -1000.0, 1000.0) + proj[~valid] = np.nan + out[:w] = proj + + return out diff --git a/rfg_adc_plotter/state/app_state.py b/rfg_adc_plotter/state/app_state.py index 1ad5682..229b273 100644 --- a/rfg_adc_plotter/state/app_state.py +++ b/rfg_adc_plotter/state/app_state.py @@ -1,14 +1,21 @@ """Состояние приложения: текущие свипы и настройки калибровки/нормировки.""" +import os from queue import Empty, Queue from typing import Any, Dict, Mapping, Optional import numpy as np -from rfg_adc_plotter.processing.normalizer import normalize_by_calib +from rfg_adc_plotter.processing.normalizer import ( + build_calib_envelopes, + normalize_by_calib, + normalize_by_envelope, +) from rfg_adc_plotter.state.ring_buffer import RingBuffer from rfg_adc_plotter.types import SweepInfo, SweepPacket +CALIB_ENVELOPE_PATH = "calib_envelope.npy" + def format_status(data: Mapping[str, Any]) -> str: """Преобразовать словарь метрик в одну строку 'k:v'.""" @@ -44,21 +51,65 @@ class AppState: self.current_info: Optional[SweepInfo] = None self.calib_enabled: bool = False self.norm_type: str = norm_type + # "live" — нормировка по текущему ch0-свипу; "file" — по огибающей из файла + self.calib_mode: str = "live" + self.calib_file_envelope: Optional[np.ndarray] = None def _normalize(self, raw: np.ndarray, calib: np.ndarray) -> np.ndarray: + if self.calib_mode == "file" and self.calib_file_envelope is not None: + return normalize_by_envelope(raw, self.calib_file_envelope) return normalize_by_calib(raw, calib, self.norm_type) + def save_calib_envelope(self, path: str = CALIB_ENVELOPE_PATH) -> bool: + """Вычислить огибающую из last_calib_sweep и сохранить в файл. + + Возвращает True при успехе. + """ + if self.last_calib_sweep is None: + return False + try: + _lower, upper = build_calib_envelopes(self.last_calib_sweep) + np.save(path, upper) + return True + except Exception as exc: + import sys + sys.stderr.write(f"[warn] Не удалось сохранить огибающую: {exc}\n") + return False + + def load_calib_envelope(self, path: str = CALIB_ENVELOPE_PATH) -> bool: + """Загрузить огибающую из файла. + + Возвращает True при успехе. + """ + if not os.path.isfile(path): + return False + try: + env = np.load(path) + self.calib_file_envelope = np.asarray(env, dtype=np.float32) + return True + except Exception as exc: + import sys + sys.stderr.write(f"[warn] Не удалось загрузить огибающую: {exc}\n") + return False + + def set_calib_mode(self, mode: str): + """Переключить режим калибровки: 'live' или 'file'.""" + self.calib_mode = mode + def set_calib_enabled(self, enabled: bool): """Включить/выключить режим калибровки, пересчитать norm-свип.""" self.calib_enabled = enabled - if ( - self.calib_enabled - and self.current_sweep_raw is not None - and self.last_calib_sweep is not None - ): - self.current_sweep_norm = self._normalize( - self.current_sweep_raw, self.last_calib_sweep - ) + if self.calib_enabled and self.current_sweep_raw is not None: + if self.calib_mode == "file" and self.calib_file_envelope is not None: + self.current_sweep_norm = normalize_by_envelope( + self.current_sweep_raw, self.calib_file_envelope + ) + elif self.calib_mode == "live" and self.last_calib_sweep is not None: + self.current_sweep_norm = self._normalize( + self.current_sweep_raw, self.last_calib_sweep + ) + else: + self.current_sweep_norm = None else: self.current_sweep_norm = None @@ -86,11 +137,17 @@ class AppState: # Канал 0 — опорный (калибровочный) свип if ch == 0: self.last_calib_sweep = s + self.save_calib_envelope() self.current_sweep_norm = None sweep_for_ring = s else: - if self.calib_enabled and self.last_calib_sweep is not None: - self.current_sweep_norm = self._normalize(s, self.last_calib_sweep) + can_normalize = self.calib_enabled and ( + (self.calib_mode == "file" and self.calib_file_envelope is not None) + or (self.calib_mode == "live" and self.last_calib_sweep is not None) + ) + if can_normalize: + calib_ref = self.last_calib_sweep if self.last_calib_sweep is not None else s + self.current_sweep_norm = self._normalize(s, calib_ref) sweep_for_ring = self.current_sweep_norm else: self.current_sweep_norm = None -- 2.49.0 From 0ecb83751f5da0ad7fb1ec064d9b450de0a93edf Mon Sep 17 00:00:00 2001 From: awe Date: Fri, 13 Feb 2026 17:45:14 +0300 Subject: [PATCH 08/13] add background remove --- background.npy | Bin 0 -> 3164 bytes rfg_adc_plotter/gui/matplotlib_backend.py | 20 ++++++++- rfg_adc_plotter/gui/pyqtgraph_backend.py | 28 +++++++++++- rfg_adc_plotter/state/app_state.py | 51 ++++++++++++++++++++++ 4 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 background.npy diff --git a/background.npy b/background.npy new file mode 100644 index 0000000000000000000000000000000000000000..c3d18dadbddf1486d2f6ad0013ba757f99e44435 GIT binary patch literal 3164 zcmbVOX;f547A}nv+|jt26S-88A9#&J~0CEJ)Ffa?u6G`ssXJbg@Y(sVVc8MJJ^!TqNZa=Oq{xL2g()Z}}qZ z2aX&b;N#`vvcl#6{s@K(w)?ibc{R3AQ@h(D!h`55W5;^U}>c@rJYJHTY99`VWKs zJS}2Vpy;%xH(jV%!lTX%7o`?=ttopAe;`gO_dWcPgJi+jw6eN~d-&18D>RFD0QMQe zGvp$;7~xB*VCo8BnMA{!b~NjHF5;gq;v>Jd<&N1ralWWJdS7GAOeen2 zu=5#we256U?G6lZX9n?fr2{x`RI=)CD-y$Dn@xMa-U;V5JfPkM_EN=`?W;9rO@V%z z=vJKzenz_ure;BwEZXez6Cs!4MR1P-&a6fuG*|F#)Q+rfRG5A);)A%W54hsE5$Dow z$#|yEgxoAKiRsNaH;dwgM+&nBik563a_k4*YFUwC1kPQlp>KEES)GdYN~-ct<}KJ> z)afhUl0AX%Pcclu7$osU#LQK^tC+^OUd`u65@#bf!>O^!9XcaL{hB}W;-6n=PPRTG z&-b#8vAN2@{Li>$i3d3qIEv6ob9v~xSPGq#Z8I8o@rWz6z?3{Q$YM#?s=pZ_(!vgc z8?(X>J!5OeGv-pptXWhm?s3nv*ATOyH}NskZc8uje)giq^v=M@q^2fKi~HgjV)z|T z3p>n1yt+_M^=afr)>0NZ#2fi~H%C!fej9vW!Om+8IU`2Q04^D#%0ComEl^j8rjZ{m&Xj^9%!ammDevLS)<0^k2 zNYmyLrG=g3;o-U3w-3Lw1&tX?5m!E@9&@^C;0~LSRC%sK*}Q$N9p}TkF+`94g)806cveyh{fK&~X~%icg}JD$463|V$j7{#DE2OK zqEhee+*Gkoc{rsFMRe;#P2(0)d2$)zd;sylyTM2cJI;5k3xO|23cr%WLw-NSAE)F2 z3$|khQN*SI3hHuD#ufRF#hdk`mM)ICn@WkZI>HYJ+WROResbzi?Z!=0e8|+n8|Rsn z)+b*Ho%Ad2I#aPvDj8oM<{RCcP!C4BdVLqa_0PwAfo?W^fY?t*zw1)}is$VMgr8_94NFqrbcilZ6fam4O~(vt&_1J{rjP3~uB zLbjOZ>r%-vI+99%bf*1{5jZzdX3KcW`!$MQ7A~jZOB3k&p&(k&m;}C=WIki0h(C9F zm%}KBRLb?~O@*W5sNkn1bj2}%_y*Xq#!zyE8_~(p~WPDVSQEq#{LUJLA6jj}Fj{)K278I?d^t(!^{f9emp ztTQu(8d_1n-#u_IgQog~P)Q8y4*1cX$VGIcVJZDQ*PYJ! zyOFE5gaR%k1CPPpDAO<$Rx*g5tXZ#gsNQL-n1H&L*s2`pjdnY-{(%n+ncwDfnJ+2BUdmKCOFhh1$o2R} zNzSTVztNF$d?W30=~iH=pW!9G2~snNhHqNAbW~d7Ry??=KKB4XypZyGd@}2D-(0PsTxG!XQZ%sjX zb7#36GDeNrqv?auox%N?(r=C<>QUz0gm3v^^oD;x=QVc^2`9l_=@;G;Hv6D|#h^Dw zQbHYiCa@8AG9CrK+K0l!9njYgAxGfGBuD9sF%GkDwY zNemPE7ycK$#gVgK#!8-zrV|g*(^SdZOx@`dx_cpxYKrjYRH+9$`at~8sE03dzk(8r yoX9<7CWTB#e}PWOrJ?A@;q-9(vSxkoY&B*w4Or(&rR$yXJ=fF39;g$mf&L4)kdI&h literal 0 HcmV?d00001 diff --git a/rfg_adc_plotter/gui/matplotlib_backend.py b/rfg_adc_plotter/gui/matplotlib_backend.py index e7f737f..b936a22 100644 --- a/rfg_adc_plotter/gui/matplotlib_backend.py +++ b/rfg_adc_plotter/gui/matplotlib_backend.py @@ -12,7 +12,7 @@ from rfg_adc_plotter.constants import FFT_LEN, FREQ_SPAN_GHZ, IFFT_LEN _IFFT_T_MAX_NS = float((IFFT_LEN - 1) / (FREQ_SPAN_GHZ * 1e9) * 1e9) from rfg_adc_plotter.io.sweep_reader import SweepReader from rfg_adc_plotter.processing.normalizer import build_calib_envelopes -from rfg_adc_plotter.state.app_state import CALIB_ENVELOPE_PATH, AppState, format_status +from rfg_adc_plotter.state.app_state import BACKGROUND_PATH, CALIB_ENVELOPE_PATH, AppState, format_status from rfg_adc_plotter.state.ring_buffer import RingBuffer from rfg_adc_plotter.types import SweepPacket @@ -204,6 +204,24 @@ def run_matplotlib(args): state.set_calib_enabled(bool(calib_cb.get_status()[0])) fig.canvas.draw_idle() + ax_btn_bg = fig.add_axes([0.92, 0.27, 0.08, 0.05]) + ax_cb_bg = fig.add_axes([0.92, 0.20, 0.08, 0.06]) + from matplotlib.widgets import Button as MplButton + save_bg_btn = MplButton(ax_btn_bg, "Сохр. фон") + bg_cb = CheckButtons(ax_cb_bg, ["вычет фона"], [False]) + + def _on_save_bg(_event): + ok = state.save_background() + if ok: + state.load_background() + fig.canvas.draw_idle() + + def _on_bg_clicked(_v): + state.set_background_enabled(bool(bg_cb.get_status()[0])) + + save_bg_btn.on_clicked(_on_save_bg) + bg_cb.on_clicked(_on_bg_clicked) + ymin_slider.on_changed(_on_ylim_change) ymax_slider.on_changed(_on_ylim_change) contrast_slider.on_changed(lambda _v: fig.canvas.draw_idle()) diff --git a/rfg_adc_plotter/gui/pyqtgraph_backend.py b/rfg_adc_plotter/gui/pyqtgraph_backend.py index ed76229..97aa872 100644 --- a/rfg_adc_plotter/gui/pyqtgraph_backend.py +++ b/rfg_adc_plotter/gui/pyqtgraph_backend.py @@ -10,7 +10,7 @@ import numpy as np from rfg_adc_plotter.constants import FREQ_SPAN_GHZ, IFFT_LEN from rfg_adc_plotter.io.sweep_reader import SweepReader from rfg_adc_plotter.processing.normalizer import build_calib_envelopes -from rfg_adc_plotter.state.app_state import CALIB_ENVELOPE_PATH, AppState, format_status +from rfg_adc_plotter.state.app_state import BACKGROUND_PATH, CALIB_ENVELOPE_PATH, AppState, format_status from rfg_adc_plotter.state.ring_buffer import RingBuffer from rfg_adc_plotter.types import SweepPacket @@ -225,6 +225,32 @@ def run_pyqtgraph(args): calib_cb.stateChanged.connect(_on_calib_toggled) calib_file_cb.stateChanged.connect(lambda _v: _on_calib_file_toggled(calib_file_cb.isChecked())) + # Кнопка сохранения фона + чекбокс вычета фона + bg_widget = QtWidgets.QWidget() + bg_layout = QtWidgets.QHBoxLayout(bg_widget) + bg_layout.setContentsMargins(2, 2, 2, 2) + bg_layout.setSpacing(8) + + save_bg_btn = QtWidgets.QPushButton("Сохр. фон") + bg_cb = QtWidgets.QCheckBox("вычет фона") + bg_cb.setEnabled(False) + + bg_layout.addWidget(save_bg_btn) + bg_layout.addWidget(bg_cb) + + bg_container_proxy = QtWidgets.QGraphicsProxyWidget() + bg_container_proxy.setWidget(bg_widget) + win.addItem(bg_container_proxy, row=2, col=0) + + def _on_save_bg(): + ok = state.save_background() + if ok: + state.load_background() + bg_cb.setEnabled(True) + + save_bg_btn.clicked.connect(_on_save_bg) + bg_cb.stateChanged.connect(lambda _v: state.set_background_enabled(bg_cb.isChecked())) + # Статусная строка status = pg.LabelItem(justify="left") win.addItem(status, row=3, col=0, colspan=2) diff --git a/rfg_adc_plotter/state/app_state.py b/rfg_adc_plotter/state/app_state.py index 229b273..0530fb4 100644 --- a/rfg_adc_plotter/state/app_state.py +++ b/rfg_adc_plotter/state/app_state.py @@ -15,6 +15,7 @@ from rfg_adc_plotter.state.ring_buffer import RingBuffer from rfg_adc_plotter.types import SweepInfo, SweepPacket CALIB_ENVELOPE_PATH = "calib_envelope.npy" +BACKGROUND_PATH = "background.npy" def format_status(data: Mapping[str, Any]) -> str: @@ -54,6 +55,10 @@ class AppState: # "live" — нормировка по текущему ch0-свипу; "file" — по огибающей из файла self.calib_mode: str = "live" self.calib_file_envelope: Optional[np.ndarray] = None + # Вычет фона + self.background: Optional[np.ndarray] = None + self.background_enabled: bool = False + self._last_sweep_for_ring: Optional[np.ndarray] = None def _normalize(self, raw: np.ndarray, calib: np.ndarray) -> np.ndarray: if self.calib_mode == "file" and self.calib_file_envelope is not None: @@ -96,6 +101,43 @@ class AppState: """Переключить режим калибровки: 'live' или 'file'.""" self.calib_mode = mode + def save_background(self, path: str = BACKGROUND_PATH) -> bool: + """Сохранить текущий sweep_for_ring как фоновый спектр. + + Сохраняет последний свип, который был записан в ринг-буфер + (нормированный, если калибровка включена, иначе сырой). + Возвращает True при успехе. + """ + if self._last_sweep_for_ring is None: + return False + try: + np.save(path, self._last_sweep_for_ring) + return True + except Exception as exc: + import sys + sys.stderr.write(f"[warn] Не удалось сохранить фон: {exc}\n") + return False + + def load_background(self, path: str = BACKGROUND_PATH) -> bool: + """Загрузить фоновый спектр из файла. + + Возвращает True при успехе. + """ + if not os.path.isfile(path): + return False + try: + bg = np.load(path) + self.background = np.asarray(bg, dtype=np.float32) + return True + except Exception as exc: + import sys + sys.stderr.write(f"[warn] Не удалось загрузить фон: {exc}\n") + return False + + def set_background_enabled(self, enabled: bool): + """Включить/выключить вычет фона.""" + self.background_enabled = enabled + def set_calib_enabled(self, enabled: bool): """Включить/выключить режим калибровки, пересчитать norm-свип.""" self.calib_enabled = enabled @@ -140,6 +182,7 @@ class AppState: self.save_calib_envelope() self.current_sweep_norm = None sweep_for_ring = s + self._last_sweep_for_ring = sweep_for_ring else: can_normalize = self.calib_enabled and ( (self.calib_mode == "file" and self.calib_file_envelope is not None) @@ -153,6 +196,14 @@ class AppState: self.current_sweep_norm = None sweep_for_ring = s + # Вычет фона (в том же домене что и sweep_for_ring) + if self.background_enabled and self.background is not None and ch != 0: + w = min(sweep_for_ring.size, self.background.size) + sweep_for_ring = sweep_for_ring.copy() + sweep_for_ring[:w] -= self.background[:w] + self.current_sweep_norm = sweep_for_ring + + self._last_sweep_for_ring = sweep_for_ring ring.ensure_init(s.size) ring.push(sweep_for_ring) return drained -- 2.49.0 From 34d151aef105fef1f74997e26cd0ec7341e1a9a4 Mon Sep 17 00:00:00 2001 From: awe Date: Fri, 13 Feb 2026 17:49:43 +0300 Subject: [PATCH 09/13] fix bug --- background.npy | Bin 3164 -> 3164 bytes rfg_adc_plotter/gui/matplotlib_backend.py | 10 +++++++++- rfg_adc_plotter/gui/pyqtgraph_backend.py | 10 +++++++++- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/background.npy b/background.npy index c3d18dadbddf1486d2f6ad0013ba757f99e44435..b5c57efac4abc2ea0d95cdd41c0bd5f900bb15d0 100644 GIT binary patch literal 3164 zcmbVOdsLNG7C%?499|=+kfS-E@>Enzo+4hpvym<@k+>k>MezbY0OcVl%%Bv8pbQl_ zS&f+0$P}ZlvdI$1!h6nSt(mEXC4*v)NEoPKWK*+Pvtsr>_g`Q_!8o6Gznz5JpIR`@OU@+;U`wyP|6$HtvydHFE0h$`evVWqD{n@&j7Rk|HI${rYKrecxIAzC&hl z^Yo~?@4Lc98r*&5mu@c$*L87#fr+6kfJ0YCEVo z$NMOGBIcOz4y+ZMPB#j>-s)q!Wo2lfr6JkFO3U+r>NX##U%x!2b!IMKbHoJu2a|bn zrkjjUxGR|6Wb^w4(bMKG`!1fgG`Jfe;?%2X3w~W$;>a6$%C4gLeqJ$FFD{Ka$VVKS z6^$`xc{?Orbab>UeV(QUqDvYl0|yn)iQd^3v23$swJSyH`3^oY;Y2#+P*t>a8GMX* z0nZc-w%_8d-X}$#_fD|Mlx@AUh2zLlDD89Qp@$vh_Wc<$eX2J&u#YXCrfEu-O()8r zZ=7tAd-lAg^wXMT-uF3dAzen}GrWKJdod86Bi_;PmZjqbN;mOUxh#UzAA;fh+AozK zDerNx`l{h;pP8D^C!Vr% zC_}QFiy$kZkn%%bsJ|>&ZJKluzW}mdo2C-LFmufJ<&ix(+g z9ZOYrhnzY^=WvkLoAsvXjt!Q~D?x7dtJM1IJmq(KB@-}TG_*^QA1327D%WlChu8l+ zUHM{YIU|yHJ}sUda0Gle(hGOxZSslqpbwYOK5Kl6`!I)U&*MAX;P{rBx#=Rt<-Dlq zewUk@VnnEAtMbXvvK(Zx9_y?e`sG zH)sppabQpI3-zgFlWi~-l$R+#O4bX?DW*Rviu+uZe6*8hp!uFGKz_!^hIKiy@~d~^ z)qbHN9c;4b9{T%|<;;vA%+-EC}pUr;T4Se*pU=l;awr|B$J z$9BW5<{|#%r-Umi|DmaA??cZcs@nRCV4pI8qZ&<{pYa*oP40S zjjLG=R|j`#@d<^>&U9lKkdJqzsuk<~+LhdvZ)%@z9H#gJ4XkT8Uw@g?OnRpO9BZcQ z8b4Z8hIv#7h86~tBfl#T0bfH8pS5y2WCRAo&`|>rzBQlvfO|VF0O^teTB0LB)dlj4 zFBsjR6L9rixE z9{zcy63iydx!U>g;U`-Z|Ef(MkX;xI7dM(m8Ia@k$0vVb{5TQW121VZ!_uydrHn)YRlcQG`F?hT^5(vTnxINgt=Mes05GRgYaa zbU-*dWz%-Z&f3rIeU0!Nv5iMGuYfrBQdqEf4(jX2Jgo+ZexPQ1%x1K{GP$Q(q8g(( zQq1F8&Tx`Lyi|)+QS}>!ddP#J{Mm6M-fMC6uFP?K)XFueG#6}J*rI`CIVq1 z=DSqbh-cT&dP%z-M5q2ky0O*;<~jD@Hcow;u&%VP*^)Whi0e3kH7a$i1m$~3A49sd z;kY2oC!9=;_Xf-jJhy%)JK8z%p)N_im8b!EncVu0HYS{?7HMalZT|{*_kU=3PT0g4 z;Uf7(7=bkG7uGkUv!?=H<6D|yxM}ofmd`Sq5T_W6pZ1hSeZbd{E*@sbwL9TC+N{CH z@IRpe&#nIjN{*6$T+lzz9j8b^xJUjkH1wd|)v|fXH4F7Q?3EYkzoDu-#Dcs^ht(F< zXOxX(EBQ`1L~Hv%dDz#Upjg5dtf8{CI)!fobw^Z8Hu3_99XZQCk2Uj|G7azM;$08W zv8B{^)IGZ_q7#jJ4)qv{L;In>A^y%%I!OoR0LGouO#OrUC_C;9_^+VkDjdUFrMPEj zO;vW%J@V&Z+ryJ~S9FKqUF#rBqCtCnca@)Zo4&4!2JF+5_lTZ;<)`|i{rgz&G*jQe zTvF?xysMn@{G}H*fQL*|eT#U=H26S-88A9#&J~0CEJ)Ffa?u6G`ssXJbg@Y(sVVc8MJJ^!TqNZa=Oq{xL2g()Z}}qZ z2aX&b;N#`vvcl#6{s@K(w)?ibc{R3AQ@h(D!h`55W5;^U}>c@rJYJHTY99`VWKs zJS}2Vpy;%xH(jV%!lTX%7o`?=ttopAe;`gO_dWcPgJi+jw6eN~d-&18D>RFD0QMQe zGvp$;7~xB*VCo8BnMA{!b~NjHF5;gq;v>Jd<&N1ralWWJdS7GAOeen2 zu=5#we256U?G6lZX9n?fr2{x`RI=)CD-y$Dn@xMa-U;V5JfPkM_EN=`?W;9rO@V%z z=vJKzenz_ure;BwEZXez6Cs!4MR1P-&a6fuG*|F#)Q+rfRG5A);)A%W54hsE5$Dow z$#|yEgxoAKiRsNaH;dwgM+&nBik563a_k4*YFUwC1kPQlp>KEES)GdYN~-ct<}KJ> z)afhUl0AX%Pcclu7$osU#LQK^tC+^OUd`u65@#bf!>O^!9XcaL{hB}W;-6n=PPRTG z&-b#8vAN2@{Li>$i3d3qIEv6ob9v~xSPGq#Z8I8o@rWz6z?3{Q$YM#?s=pZ_(!vgc z8?(X>J!5OeGv-pptXWhm?s3nv*ATOyH}NskZc8uje)giq^v=M@q^2fKi~HgjV)z|T z3p>n1yt+_M^=afr)>0NZ#2fi~H%C!fej9vW!Om+8IU`2Q04^D#%0ComEl^j8rjZ{m&Xj^9%!ammDevLS)<0^k2 zNYmyLrG=g3;o-U3w-3Lw1&tX?5m!E@9&@^C;0~LSRC%sK*}Q$N9p}TkF+`94g)806cveyh{fK&~X~%icg}JD$463|V$j7{#DE2OK zqEhee+*Gkoc{rsFMRe;#P2(0)d2$)zd;sylyTM2cJI;5k3xO|23cr%WLw-NSAE)F2 z3$|khQN*SI3hHuD#ufRF#hdk`mM)ICn@WkZI>HYJ+WROResbzi?Z!=0e8|+n8|Rsn z)+b*Ho%Ad2I#aPvDj8oM<{RCcP!C4BdVLqa_0PwAfo?W^fY?t*zw1)}is$VMgr8_94NFqrbcilZ6fam4O~(vt&_1J{rjP3~uB zLbjOZ>r%-vI+99%bf*1{5jZzdX3KcW`!$MQ7A~jZOB3k&p&(k&m;}C=WIki0h(C9F zm%}KBRLb?~O@*W5sNkn1bj2}%_y*Xq#!zyE8_~(p~WPDVSQEq#{LUJLA6jj}Fj{)K278I?d^t(!^{f9emp ztTQu(8d_1n-#u_IgQog~P)Q8y4*1cX$VGIcVJZDQ*PYJ! zyOFE5gaR%k1CPPpDAO<$Rx*g5tXZ#gsNQL-n1H&L*s2`pjdnY-{(%n+ncwDfnJ+2BUdmKCOFhh1$o2R} zNzSTVztNF$d?W30=~iH=pW!9G2~snNhHqNAbW~d7Ry??=KKB4XypZyGd@}2D-(0PsTxG!XQZ%sjX zb7#36GDeNrqv?auox%N?(r=C<>QUz0gm3v^^oD;x=QVc^2`9l_=@;G;Hv6D|#h^Dw zQbHYiCa@8AG9CrK+K0l!9njYgAxGfGBuD9sF%GkDwY zNemPE7ycK$#gVgK#!8-zrV|g*(^SdZOx@`dx_cpxYKrjYRH+9$`at~8sE03dzk(8r yoX9<7CWTB#e}PWOrJ?A@;q-9(vSxkoY&B*w4Or(&rR$yXJ=fF39;g$mf&L4)kdI&h diff --git a/rfg_adc_plotter/gui/matplotlib_backend.py b/rfg_adc_plotter/gui/matplotlib_backend.py index b936a22..19e859a 100644 --- a/rfg_adc_plotter/gui/matplotlib_backend.py +++ b/rfg_adc_plotter/gui/matplotlib_backend.py @@ -268,7 +268,15 @@ def run_matplotlib(args): m = float(np.nanmax(np.abs(data))) return data / m if m > 0.0 else data line_obj.set_data(xs, _norm_to_max(raw)) - if state.last_calib_sweep is not None: + if state.calib_mode == "file" and state.calib_file_envelope is not None: + upper = state.calib_file_envelope + lower = -upper + m_env = float(np.nanmax(np.abs(upper))) + if m_env <= 0.0: + m_env = 1.0 + line_env_lo.set_data(xs[: upper.size], lower / m_env) + line_env_hi.set_data(xs[: upper.size], upper / m_env) + elif state.last_calib_sweep is not None: calib = state.last_calib_sweep m_calib = float(np.nanmax(np.abs(calib))) if m_calib <= 0.0: diff --git a/rfg_adc_plotter/gui/pyqtgraph_backend.py b/rfg_adc_plotter/gui/pyqtgraph_backend.py index 97aa872..9ac4174 100644 --- a/rfg_adc_plotter/gui/pyqtgraph_backend.py +++ b/rfg_adc_plotter/gui/pyqtgraph_backend.py @@ -290,7 +290,15 @@ def run_pyqtgraph(args): m = float(np.nanmax(np.abs(data))) return data / m if m > 0.0 else data curve.setData(xs, _norm_to_max(raw), autoDownsample=True) - if state.last_calib_sweep is not None: + if state.calib_mode == "file" and state.calib_file_envelope is not None: + upper = state.calib_file_envelope + lower = -upper + m_env = float(np.nanmax(np.abs(upper))) + if m_env <= 0.0: + m_env = 1.0 + curve_env_lo.setData(xs[: upper.size], lower / m_env, autoDownsample=True) + curve_env_hi.setData(xs[: upper.size], upper / m_env, autoDownsample=True) + elif state.last_calib_sweep is not None: calib = state.last_calib_sweep m_calib = float(np.nanmax(np.abs(calib))) if m_calib <= 0.0: -- 2.49.0 From 8b1d424cbe7d58964d7eed5a6653245a45d0815a Mon Sep 17 00:00:00 2001 From: Theodor Chikin Date: Tue, 17 Feb 2026 18:51:12 +0300 Subject: [PATCH 10/13] New tty parser: accepts binary format. Enable arg: --bin --- calib_envelope.npy | Bin 3164 -> 3164 bytes rfg_adc_plotter/gui/matplotlib_backend.py | 9 +- rfg_adc_plotter/gui/pyqtgraph_backend.py | 9 +- rfg_adc_plotter/io/sweep_reader.py | 212 +++++++++++++++------- rfg_adc_plotter/main.py | 6 + 5 files changed, 171 insertions(+), 65 deletions(-) mode change 100644 => 100755 rfg_adc_plotter/main.py diff --git a/calib_envelope.npy b/calib_envelope.npy index 9053d4f604ebba00a6d93003e6ac2ff91ef38a58..abc000b6ba0143bb2284f1bb9f8df48da3b3e3db 100644 GIT binary patch literal 3164 zcmeH{PiP!v7{*5wu|XjqEtd8$m$17Y0XilM05xn?&W=6ZaMMXWDg&*^N&-c9V z_kHudvsa$;o}D^vPl9S;oUpj!%p{HsZeO{_Ed>}{dch61OJmASmK;jn1fQ=g88<2i}~66<~091 zo`?4o<081=K&NF+0(xqU?j6K8kk9{sejPTU2|kpd*s{jymW|b0w)J+)${(U7eJE!g z)}RSjVHw^8zr~(g?47to>=BgX(5Ki#`>eb639 z;Q>&t%M(vpcNH&Z>whO{UK2gZeCe2+bieXzZVlF96Xfeaevg0L?=NVB+~+V9xnK1G zJ=6bx5ww}x*1ZSj-Nv&^+(A=35U^)-FJQ043GpiNJaMs?$>#%GnF;L1g}{d13aoN1 zu#G6oQJ$Fm4$lsrpYa?Bt#Tx^jmJZ3h4ewlI>e>WwiZHbTnw%JMrdPK(3-FY>#zw4 z?13BEjYE-bJQUf=eUVju4Q=vPXhT0T*XhOEW{q#q$W7y2VkhDq0d<^FD8dw!U=FIV z1pZ%emAQ5J8aj9IZb!VonA)*z9gVGVIJWYk*v1}48$^2$?Eu>SX!oKySu9;1`IW1u z#?s}LuN&`RY{4CtQ1T4~QD#Oj?UECV@d&z170#?qNrp7K>k^;B2&|8^a6)B1n%TzQ{bEow&8 z{)9C?W34a9N$w{2JbVAzv+mLRAg`@6$bTI=|B*fN)mQ3E7u2Ukn1T|V1Zj@|K7AYI zNBK@B_(q;VlSf|V$mhZ!;O+iaf)k9#GmpL>Zz%T;XPR@Ir)sEH398`dPmQH(eiYn1 qmhQ*gOU(Vm+*8bb#oSxW{V~^s<;;`T!rQpW8S3nPfpe6ZqsDJwtg3nd literal 3164 zcmbW3e~4676vwYW(Zy=}y@=Id+HT951J7TH)SLIPRQj=mFH(YL$sI&YhusP>ilI_A zu^L^CouOce%w$cvHx{nud3AC5`QbB%e@HKi@E!!?nNYf}4N6Yphw$u;)l z*zZApldOW+fC3;DIKH@q7CqwpZy4~thfF63KT{~U6T7+aASB3IF`4Pz?C3DEwOBOS|T zcEv2KH#S(=6H6rCLf6N-cS8SubSJQ##%}_(H&R~&F5;)X?|~Hlo%pXpj{5V!rkcn0 ztUane)tQDq$bn+WwgnoY1#FlD(_qBL4_-yCLKz0gl_%#uycR z1CGI2m_Z#iM#Yrh0Vw)$3;Es1TJtg}_jc&1BgwoSq99o{$u|y5pb>`Hdy4+=usv^Y zSc~crC8&Z4eIw+aOKq*pqoF+0wHlwbB5}sHtgphgT0e$jM8Y_d6}Mz(GauuB z&>pNDVD0Pur~0Ozfc{<--Bgc!0(*Dm%z8?+k$VWevFgN ztmJIDoS$W!qea-FumIGbWnfe92H1g|gDmJw={u?4tDy;s$^kkLTC4BU&${FE>3if$ za1!(l^{s4J2l^g5)BP|2MJR#3c^b5zdfL$?iM7{$UjVe-3Q|Y`f6y`d>TxIOXx0#KAKPF?VHFOI04x(PG_#SZx-AJ zx5FKvx8hc~7N&sWOk!++>!FEtGg+@S@|_7cf&7(wDoh6DH25~)do%KtzS>VA|9iOi zU&H-se_B7zVC6FB_-FcjhJK&IPd!vGRQIUg3(xxrSv?vJ^|H%PeH^Ed|CavASG`hy zRNqCY`TC%*iXokRRFB@BYd|$#2YORgtL)0Def$;aWRs72r#$CDd;O6-I{(_=4{#dv zEo-4|7`cqBd-4f#5spIzbUu{lJJ5Qa3)Lu}9Q1(h;U3Vv)LW}}_b_q^4naS>4LZkr zu?K$j_gMEx_bIp^$+~ep^EkAF4N-`|5|B>z`rnuqbn&EzeCDsSKk|83P9YFXXrY>0z=lqVOy zuiJflHnRqueEutnlYm~1`84!xpk7BndE}>aq5o-gr$>+npa*P_kEz3Eo`T#}(QlA`W7M}Ed0VeU* z&EP)XLR{tlXSn~=(tw{~JWCIT$yWlci$fapwra0>Yg3?}B*Rhju{T(<^jg;rHbnmw z&znc?R{UD%zkai4BS*q@`c2ch(f?l2P+pF#_$xp;mOzyE=T5)wY-YOu+Zyz>MlA-r gzDpxWuA;k=p#EQcf5ot@8|mdNV&26X)nQ_P0u2rk9smFU diff --git a/rfg_adc_plotter/gui/matplotlib_backend.py b/rfg_adc_plotter/gui/matplotlib_backend.py index 19e859a..b768553 100644 --- a/rfg_adc_plotter/gui/matplotlib_backend.py +++ b/rfg_adc_plotter/gui/matplotlib_backend.py @@ -89,7 +89,14 @@ def run_matplotlib(args): q: Queue[SweepPacket] = Queue(maxsize=1000) stop_event = threading.Event() - reader = SweepReader(args.port, args.baud, q, stop_event, fancy=bool(args.fancy)) + reader = SweepReader( + args.port, + args.baud, + q, + stop_event, + fancy=bool(args.fancy), + bin_mode=bool(getattr(args, "bin_mode", False)), + ) reader.start() max_sweeps = int(max(10, args.max_sweeps)) diff --git a/rfg_adc_plotter/gui/pyqtgraph_backend.py b/rfg_adc_plotter/gui/pyqtgraph_backend.py index 9ac4174..a9069b5 100644 --- a/rfg_adc_plotter/gui/pyqtgraph_backend.py +++ b/rfg_adc_plotter/gui/pyqtgraph_backend.py @@ -106,7 +106,14 @@ def run_pyqtgraph(args): q: Queue[SweepPacket] = Queue(maxsize=1000) stop_event = threading.Event() - reader = SweepReader(args.port, args.baud, q, stop_event, fancy=bool(args.fancy)) + reader = SweepReader( + args.port, + args.baud, + q, + stop_event, + fancy=bool(args.fancy), + bin_mode=bool(getattr(args, "bin_mode", False)), + ) reader.start() max_sweeps = int(max(10, args.max_sweeps)) diff --git a/rfg_adc_plotter/io/sweep_reader.py b/rfg_adc_plotter/io/sweep_reader.py index 31768a6..674cd4b 100644 --- a/rfg_adc_plotter/io/sweep_reader.py +++ b/rfg_adc_plotter/io/sweep_reader.py @@ -24,6 +24,7 @@ class SweepReader(threading.Thread): out_queue: "Queue[SweepPacket]", stop_event: threading.Event, fancy: bool = False, + bin_mode: bool = False, ): super().__init__(daemon=True) self._port_path = port_path @@ -32,11 +33,17 @@ class SweepReader(threading.Thread): self._stop = stop_event self._src: Optional[SerialLineSource] = None self._fancy = bool(fancy) + self._bin_mode = bool(bin_mode) self._max_width: int = 0 self._sweep_idx: int = 0 self._last_sweep_ts: Optional[float] = None self._n_valid_hist = deque() + @staticmethod + def _u16_to_i16(v: int) -> int: + """Преобразование 16-bit слова в знаковое значение.""" + return v - 0x10000 if (v & 0x8000) else v + def _finalize_current(self, xs, ys, channels: Optional[set]): if not xs: return @@ -135,11 +142,145 @@ class SweepReader(threading.Thread): except Exception: pass - def run(self): - xs: list = [] - ys: list = [] + def _run_ascii_stream(self, chunk_reader: SerialChunkReader): + xs: list[int] = [] + ys: list[int] = [] cur_channel: Optional[int] = None - cur_channels: set = set() + cur_channels: set[int] = set() + + buf = bytearray() + while not self._stop.is_set(): + data = chunk_reader.read_available() + if data: + buf += data + else: + time.sleep(0.0005) + continue + + while True: + nl = buf.find(b"\n") + if nl == -1: + break + line = bytes(buf[:nl]) + del buf[: nl + 1] + if line.endswith(b"\r"): + line = line[:-1] + if not line: + continue + + if line.startswith(b"Sweep_start"): + self._finalize_current(xs, ys, cur_channels) + xs.clear() + ys.clear() + cur_channel = None + cur_channels.clear() + continue + + if len(line) >= 3: + parts = line.split() + if len(parts) >= 3 and (parts[0].lower() == b"s" or parts[0].lower().startswith(b"s")): + try: + if parts[0].lower() == b"s": + if len(parts) >= 4: + ch = int(parts[1], 10) + x = int(parts[2], 10) + y = int(parts[3], 10) + else: + ch = 0 + x = int(parts[1], 10) + y = int(parts[2], 10) + else: + ch = int(parts[0][1:], 10) + x = int(parts[1], 10) + y = int(parts[2], 10) + except Exception: + continue + if cur_channel is None: + cur_channel = ch + cur_channels.add(ch) + xs.append(x) + ys.append(y) + + if len(buf) > 1_000_000: + del buf[:-262144] + + self._finalize_current(xs, ys, cur_channels) + + def _run_binary_stream(self, chunk_reader: SerialChunkReader): + xs: list[int] = [] + ys: list[int] = [] + cur_channel: Optional[int] = None + cur_channels: set[int] = set() + waiting_channel = False + waiting_first_point = False + point_word: Optional[int] = None + value_word: Optional[int] = None + + buf = bytearray() + while not self._stop.is_set(): + data = chunk_reader.read_available() + if data: + buf += data + else: + time.sleep(0.0005) + continue + + usable = len(buf) & ~1 + if usable == 0: + continue + + i = 0 + while i < usable: + w = int(buf[i]) | (int(buf[i + 1]) << 8) + i += 2 + + if waiting_channel: + cur_channel = int(w) + cur_channels.add(cur_channel) + waiting_channel = False + waiting_first_point = True + continue + + if w == 0xFFFF: + self._finalize_current(xs, ys, cur_channels) + xs.clear() + ys.clear() + cur_channel = None + cur_channels.clear() + waiting_channel = True + waiting_first_point = False + point_word = None + value_word = None + continue + + if point_word is None: + if waiting_first_point and (w == 0x0A0A or w == 0x000A): + continue + point_word = int(w) + waiting_first_point = False + continue + + if value_word is None: + value_word = int(w) + continue + + is_point_end = (w == 0x000A) or ((w & 0x00FF) == 0x0A) or ((w >> 8) == 0x0A) + if is_point_end: + if cur_channel is not None: + cur_channels.add(cur_channel) + xs.append(point_word) + ys.append(self._u16_to_i16(value_word)) + + point_word = None + value_word = None + + del buf[:usable] + if len(buf) > 1_000_000: + del buf[:-262144] + + self._finalize_current(xs, ys, cur_channels) + + def run(self): try: self._src = SerialLineSource(self._port_path, self._baud, timeout=1.0) @@ -150,66 +291,11 @@ class SweepReader(threading.Thread): try: chunk_reader = SerialChunkReader(self._src) - buf = bytearray() - while not self._stop.is_set(): - data = chunk_reader.read_available() - if data: - buf += data - else: - time.sleep(0.0005) - continue - - while True: - nl = buf.find(b"\n") - if nl == -1: - break - line = bytes(buf[:nl]) - del buf[: nl + 1] - if line.endswith(b"\r"): - line = line[:-1] - if not line: - continue - - if line.startswith(b"Sweep_start"): - self._finalize_current(xs, ys, cur_channels) - xs.clear() - ys.clear() - cur_channel = None - cur_channels.clear() - continue - - if len(line) >= 3: - parts = line.split() - if len(parts) >= 3 and (parts[0].lower() == b"s" or parts[0].lower().startswith(b"s")): - try: - if parts[0].lower() == b"s": - if len(parts) >= 4: - ch = int(parts[1], 10) - x = int(parts[2], 10) - y = int(parts[3], 10) - else: - ch = 0 - x = int(parts[1], 10) - y = int(parts[2], 10) - else: - ch = int(parts[0][1:], 10) - x = int(parts[1], 10) - y = int(parts[2], 10) - except Exception: - continue - if cur_channel is None: - cur_channel = ch - cur_channels.add(ch) - xs.append(x) - ys.append(y) - - if len(buf) > 1_000_000: - del buf[:-262144] + if self._bin_mode: + self._run_binary_stream(chunk_reader) + else: + self._run_ascii_stream(chunk_reader) finally: - try: - self._finalize_current(xs, ys, cur_channels) - except Exception: - pass try: if self._src is not None: self._src.close() diff --git a/rfg_adc_plotter/main.py b/rfg_adc_plotter/main.py old mode 100644 new mode 100755 index 78e4e02..85d4df7 --- a/rfg_adc_plotter/main.py +++ b/rfg_adc_plotter/main.py @@ -77,6 +77,12 @@ def build_parser() -> argparse.ArgumentParser: default="projector", help="Тип нормировки: projector (по огибающим в [-1000,+1000]) или simple (raw/calib)", ) + parser.add_argument( + "--bin", + dest="bin_mode", + action="store_true", + help="Бинарный протокол: 16-bit поток, 0xFFFF+канал для старта свипа, точки point,value,'\\n'", + ) return parser -- 2.49.0 From ece30f1cd5e23ac461023b9b8133e415aa0ecb54 Mon Sep 17 00:00:00 2001 From: Theodor Chikin Date: Wed, 18 Feb 2026 23:01:34 +0300 Subject: [PATCH 11/13] impoved tty parser binary mode: now it supports 32-bit values of intensity --- calib_envelope.npy | Bin 3164 -> 3164 bytes rfg_adc_plotter/io/sweep_reader.py | 71 +++++++++++++++-------------- rfg_adc_plotter/main.py | 5 +- 3 files changed, 41 insertions(+), 35 deletions(-) diff --git a/calib_envelope.npy b/calib_envelope.npy index abc000b6ba0143bb2284f1bb9f8df48da3b3e3db..31401e5c4a4201bbf8c98bb4c12e60148576cd18 100644 GIT binary patch literal 3164 zcmbW2du&ui6o&@|1#Gm)BdBOL25G^D)GRNN!0qm$jUq15TY(fPfv#8xlmfLuOa^G7 z)TS&?+fuY*McA!aKoOM3YS2_Hf)5O$CJj*}L}QKkh%v_Rw|hyJ_=mn zhxtS=v=2Iv^`0SPehRv7XD}W+6*T4;`}d=}&?a;PS_L(*9ya5z|=zN^t$)bcoIcmz8iX2Mc<7U-3FWXjO_XfaHHTObQY0`ct#bO?GEDz1fh1Fm~B zag~1=YY(A!f&=8R)RU~K5G|yJTztD@@8fJg!hoRPKPniB6a*U^%2DdE+gMl4E;g6~ zP=Ei#KL?%8ylS}#9g2n^55~iNFa}ifVCV~ec+}f70OkI;V`GK`XRtlcp5*RE4Zj2; zk&6Mp|4VXx1g}CZya~FK!>|=j!ZqxB2VFrAp5u<%uup*QvkvNE2XN1(0ycxzqA(9u zdA59&qXwP_^`-@sr<&MR#Fno`mor|5T?&<;SWTceqZ~dcfHlB7Gvi4CPXdIztnvzE<|{X8%ratej!yW-wQRtyqQNfcC4# z7%0z&a0%2y?lJjWI?wo1IG)B{Z1qH{`BQKXbU&*38~7f61^phsMNh!j&;@7UE!Ypr z`!Xn=YEhpLgJNGfgUGuZgTHfqB-tL+}W5epe$qvih z3f7~nzl5zi-vHIDI;r34++bC&(A}su`eR=~wWi)32klqS$Zb^vSk(ho_3$0DFQD`< z8SfaX--zz$b2tsU7sYCa4oIIn%J?AcqvoU3toLyiJ^}f@4{w9&)Ez3PdbbJ|fcjJm znv23lPc^QkA2swv{i&u;YnfX^eN`yfO0<%kYsp=MogPE)eJiNnx>Mzj;TOX{j@`dUd^Bz?5yHUM~7SC6`=6qIXx&Syx{bTdMQPhj(L-pqx3m=K#J(@Kygh znA3NMZ&EV1-mG%z{*+(J{aM|6GkbQhS9KHLzKC)bt8>+{rf*6FdlD2t5tIOL&*(c- z4o^V^F;?PB-;#Y+-%CNi?>V47i=hJahG)VQ2!Uch2J)3^toeM;4x^fPAO{9Qck;nBS{T(htS6)1JF3)w}!)^ol=sS2E+PyXH zH^l2g_07}%1bfb~e#u)?Jgr}Z&pnGWFmuzHE5?>ziqzah#zi|BipXujyd47Li{1kf-sE7R^^FPuZKi$FEWZYB^-KTRE)bF@%f9A}; X;Pdw7qOvoS{@SY;skn&=hQGf7vy17Y0XilM05xn?&W=6ZaMMXWDg&*^N&-c9V z_kHudvsa$;o}D^vPl9S;oUpj!%p{HsZeO{_Ed>}{dch61OJmASmK;jn1fQ=g88<2i}~66<~091 zo`?4o<081=K&NF+0(xqU?j6K8kk9{sejPTU2|kpd*s{jymW|b0w)J+)${(U7eJE!g z)}RSjVHw^8zr~(g?47to>=BgX(5Ki#`>eb639 z;Q>&t%M(vpcNH&Z>whO{UK2gZeCe2+bieXzZVlF96Xfeaevg0L?=NVB+~+V9xnK1G zJ=6bx5ww}x*1ZSj-Nv&^+(A=35U^)-FJQ043GpiNJaMs?$>#%GnF;L1g}{d13aoN1 zu#G6oQJ$Fm4$lsrpYa?Bt#Tx^jmJZ3h4ewlI>e>WwiZHbTnw%JMrdPK(3-FY>#zw4 z?13BEjYE-bJQUf=eUVju4Q=vPXhT0T*XhOEW{q#q$W7y2VkhDq0d<^FD8dw!U=FIV z1pZ%emAQ5J8aj9IZb!VonA)*z9gVGVIJWYk*v1}48$^2$?Eu>SX!oKySu9;1`IW1u z#?s}LuN&`RY{4CtQ1T4~QD#Oj?UECV@d&z170#?qNrp7K>k^;B2&|8^a6)B1n%TzQ{bEow&8 z{)9C?W34a9N$w{2JbVAzv+mLRAg`@6$bTI=|B*fN)mQ3E7u2Ukn1T|V1Zj@|K7AYI zNBK@B_(q;VlSf|V$mhZ!;O+iaf)k9#GmpL>Zz%T;XPR@Ir)sEH398`dPmQH(eiYn1 qmhQ*gOU(Vm+*8bb#oSxW{V~^s<;;`T!rQpW8S3nPfpe6ZqsDJwtg3nd diff --git a/rfg_adc_plotter/io/sweep_reader.py b/rfg_adc_plotter/io/sweep_reader.py index 674cd4b..705983c 100644 --- a/rfg_adc_plotter/io/sweep_reader.py +++ b/rfg_adc_plotter/io/sweep_reader.py @@ -40,9 +40,9 @@ class SweepReader(threading.Thread): self._n_valid_hist = deque() @staticmethod - def _u16_to_i16(v: int) -> int: - """Преобразование 16-bit слова в знаковое значение.""" - return v - 0x10000 if (v & 0x8000) else v + def _u32_to_i32(v: int) -> int: + """Преобразование 32-bit слова в знаковое значение.""" + return v - 0x1_0000_0000 if (v & 0x8000_0000) else v def _finalize_current(self, xs, ys, channels: Optional[set]): if not xs: @@ -211,10 +211,7 @@ class SweepReader(threading.Thread): ys: list[int] = [] cur_channel: Optional[int] = None cur_channels: set[int] = set() - waiting_channel = False - waiting_first_point = False - point_word: Optional[int] = None - value_word: Optional[int] = None + words = deque() buf = bytearray() while not self._stop.is_set(): @@ -232,47 +229,53 @@ class SweepReader(threading.Thread): i = 0 while i < usable: w = int(buf[i]) | (int(buf[i + 1]) << 8) + words.append(w) i += 2 - if waiting_channel: - cur_channel = int(w) - cur_channels.add(cur_channel) - waiting_channel = False - waiting_first_point = True - continue + # Бинарный протокол: + # старт свипа (актуальный): 0xFFFF, 0xFFFF, 0xFFFF, (ch<<8)|0x0A + # старт свипа (legacy): 0xFFFF, 0xFFFF, channel, 0x0A0A + # точка: step, value_hi, value_lo, 0x000A + while len(words) >= 4: + w0 = int(words[0]) + w1 = int(words[1]) + w2 = int(words[2]) + w3 = int(words[3]) - if w == 0xFFFF: + if w0 == 0xFFFF and w1 == 0xFFFF and w2 == 0xFFFF and (w3 & 0x00FF) == 0x000A: self._finalize_current(xs, ys, cur_channels) xs.clear() ys.clear() - cur_channel = None cur_channels.clear() - waiting_channel = True - waiting_first_point = False - point_word = None - value_word = None + cur_channel = (w3 >> 8) & 0x00FF + cur_channels.add(cur_channel) + for _ in range(4): + words.popleft() continue - if point_word is None: - if waiting_first_point and (w == 0x0A0A or w == 0x000A): - continue - point_word = int(w) - waiting_first_point = False + if w0 == 0xFFFF and w1 == 0xFFFF and w3 == 0x0A0A: + self._finalize_current(xs, ys, cur_channels) + xs.clear() + ys.clear() + cur_channels.clear() + cur_channel = w2 + cur_channels.add(cur_channel) + for _ in range(4): + words.popleft() continue - if value_word is None: - value_word = int(w) - continue - - is_point_end = (w == 0x000A) or ((w & 0x00FF) == 0x0A) or ((w >> 8) == 0x0A) - if is_point_end: + if w3 == 0x000A: if cur_channel is not None: cur_channels.add(cur_channel) - xs.append(point_word) - ys.append(self._u16_to_i16(value_word)) + xs.append(w0) + value_u32 = (w1 << 16) | w2 + ys.append(self._u32_to_i32(value_u32)) + for _ in range(4): + words.popleft() + continue - point_word = None - value_word = None + # Поток может начаться с середины пакета; сдвигаемся по слову до ресинхронизации. + words.popleft() del buf[:usable] if len(buf) > 1_000_000: diff --git a/rfg_adc_plotter/main.py b/rfg_adc_plotter/main.py index 85d4df7..ff1feb6 100755 --- a/rfg_adc_plotter/main.py +++ b/rfg_adc_plotter/main.py @@ -81,7 +81,10 @@ def build_parser() -> argparse.ArgumentParser: "--bin", dest="bin_mode", action="store_true", - help="Бинарный протокол: 16-bit поток, 0xFFFF+канал для старта свипа, точки point,value,'\\n'", + help=( + "Бинарный протокол: старт свипа 0xFFFF,0xFFFF,0xFFFF,(CH<<8)|0x0A; " + "точки step,uint32(hi16,lo16),0x000A" + ), ) return parser -- 2.49.0 From 02fa3645d7398c23e31f0c1b738cf1841f687f3f Mon Sep 17 00:00:00 2001 From: Theodor Chikin Date: Wed, 18 Feb 2026 23:07:17 +0300 Subject: [PATCH 12/13] Now software can be run by: run_dataplotter /dev/ttyACM0 --- calib_envelope.npy | Bin 3164 -> 3164 bytes run_dataplotter | 2 ++ 2 files changed, 2 insertions(+) create mode 100755 run_dataplotter diff --git a/calib_envelope.npy b/calib_envelope.npy index 31401e5c4a4201bbf8c98bb4c12e60148576cd18..bb4541fee116be89c4e3904d12757a92cb4b5f86 100644 GIT binary patch literal 3164 zcmbW%YfO_@9LMpx_`(>M;G)YkGed`>3voug&)dH`m3di3s({=r1(f?u5kV+Wpxj%a z&;l*@(w55$qb_lYW^tJY7Im9(I*oDJX5tH%`C`kqEc+hBWJ~sHCcpImJkNRl=X}n2 z&~`|FP!}~zQ>ZBpHYDer$PL~S7`)ZEE;uAG*qD`@pPQH&pOtG!R`>TLrspMdKQA>g zJDKa18`p0RSrrmk68OLW&DCghV%e{gg?62|p6KMg)raLm(P7zf{jl5!2$zVMaCtNw zE@>~q<;C_RQffIObM77y+tLVGk`W=E%Mr46wq8E{STB2>db#tXUSifBm7hwEO3sa= z^5=qMVoo?F^Zm!f`Rg%Ru`5z08YAU{`;l^ed6ejKqU8RSC`q0ZEzgfc%UM^n%zhRv zO&gBOBGYjhm^v=27sbdYh8Wp35hGvz5hIa%W955mtYkcjmETsyiK!q?UcVM6_IdHL zEHYmF{qeH#dAwZPk{}1n33B&#f+Q|UlxL}lQg|UzG@2yLNtlx`Ct*H;`2^+@m<^Z> zm<^Z>n3FLlV@}3w#B9WD#GHaT1#=4K6wIlZQ!%GvPQ#prISq3f=98FDVm^ua6y{Ty zPhn2SoQ^pib2{b>%o&(7FlS=U#GHva6LS{kEX-M$voU95&c>XBIR|qN<{Zqqm~%1b zV$Q>yhdB>(KIVMP`Iz%D7ho>HT!6U{b0OwJ%!QawV?K@fH0Cpy&tN`-xd?L+<|52R zn9pK9i}@_(V$8*ui!m2tK8N`n=5v@!FqdF1!CZ>D6mu!&Qq1QupT~S2OBp@O@RZTF z3{x4s%W##^zZ_dRbClyNXP$D5<;+!%)5LrxtS06(;WaU@33CN=SKzK-{tE0Btf2yb z1?#9}4=PzpCHqjxdMeqAO4d}#epIopD)yv`wN_Oa|7lE%#D~EF*jmv#N3Fv5pyHvCd^Hkn=m(FZo=Gzxe0SK=4Q;zn42*-V{XRW zg1H5A3+5KgEtp#{w_vtnwqmwowqmwowqmwowqdqmwqdqmwqdqmwqb6?+={ssb1UXn z%&nN)Ft=fD!`z0s4RagjHq7mq+cCFeZpYk?xgB#mW;%r49>%r49> z%r4As%x=tX%x=tX%x=tX%)OXKFocX`!M%m?!(-NxgT>s=6=lm znENsJWA4X1fO!D(0OkSA1DFRe4`3d|JcxM^^C0Fy%!8N*F%MxL!aRg|2=fr;AzS3c^LCBW)Ef$W)Ef$W)Ef$W)J2O%p;gbFppp!!90R_1hW^j7qb_$7qb_$ z7qb_$53>)m53>)m53>)mAG05`AG05`AG05`AM+^YQOu*5M=_6L9>qM0c?|Oy<}u7; zn8z@WVIIRgj(HsOIOcK8BG8lwIW zJVVk+0@+8_@J<0y-_XB%X*6GO&rM#v-$Csmml=PZdG1iZoL8gKXf>KSBtYx)zNyvg zmrw^$zd=2V`Z42wA+J%-(@sqWXdRskwMOG&ZD{B_Gh-Jsc0RT0^OW9dJ!;MgqSo?Q zrY64=N9VU7rOn~3V6oB37OAtaD2;N2DU*i3zZs4)>l z%@@u6Sn33#`lb@qJDcS5Jd@{X)CTG}>L}_6Y9n;sRUad{dv7V^jYTdi1*Ag1Kk>_jZ^&aUMzjBoO>f4AW>ibZ&8mHb-@2Vaj&D839 z(lO^D=03ps_p_F;nK5ck_1!4LN)kvGlDXtBzSpOG-%t3KA5!0wFzeT14Z1B4E>6kv hu$z+k;B&c@@fpvq&iq}fzyDjjb94Io<=>H8{sv57im3nq literal 3164 zcmbW2du&ui6o&@|1#Gm)BdBOL25G^D)GRNN!0qm$jUq15TY(fPfv#8xlmfLuOa^G7 z)TS&?+fuY*McA!aKoOM3YS2_Hf)5O$CJj*}L}QKkh%v_Rw|hyJ_=mn zhxtS=v=2Iv^`0SPehRv7XD}W+6*T4;`}d=}&?a;PS_L(*9ya5z|=zN^t$)bcoIcmz8iX2Mc<7U-3FWXjO_XfaHHTObQY0`ct#bO?GEDz1fh1Fm~B zag~1=YY(A!f&=8R)RU~K5G|yJTztD@@8fJg!hoRPKPniB6a*U^%2DdE+gMl4E;g6~ zP=Ei#KL?%8ylS}#9g2n^55~iNFa}ifVCV~ec+}f70OkI;V`GK`XRtlcp5*RE4Zj2; zk&6Mp|4VXx1g}CZya~FK!>|=j!ZqxB2VFrAp5u<%uup*QvkvNE2XN1(0ycxzqA(9u zdA59&qXwP_^`-@sr<&MR#Fno`mor|5T?&<;SWTceqZ~dcfHlB7Gvi4CPXdIztnvzE<|{X8%ratej!yW-wQRtyqQNfcC4# z7%0z&a0%2y?lJjWI?wo1IG)B{Z1qH{`BQKXbU&*38~7f61^phsMNh!j&;@7UE!Ypr z`!Xn=YEhpLgJNGfgUGuZgTHfqB-tL+}W5epe$qvih z3f7~nzl5zi-vHIDI;r34++bC&(A}su`eR=~wWi)32klqS$Zb^vSk(ho_3$0DFQD`< z8SfaX--zz$b2tsU7sYCa4oIIn%J?AcqvoU3toLyiJ^}f@4{w9&)Ez3PdbbJ|fcjJm znv23lPc^QkA2swv{i&u;YnfX^eN`yfO0<%kYsp=MogPE)eJiNnx>Mzj;TOX{j@`dUd^Bz?5yHUM~7SC6`=6qIXx&Syx{bTdMQPhj(L-pqx3m=K#J(@Kygh znA3NMZ&EV1-mG%z{*+(J{aM|6GkbQhS9KHLzKC)bt8>+{rf*6FdlD2t5tIOL&*(c- z4o^V^F;?PB-;#Y+-%CNi?>V47i=hJahG)VQ2!Uch2J)3^toeM;4x^fPAO{9Qck;nBS{T(htS6)1JF3)w}!)^ol=sS2E+PyXH zH^l2g_07}%1bfb~e#u)?Jgr}Z&pnGWFmuzHE5?>ziqzah#zi|BipXujyd47Li{1kf-sE7R^^FPuZKi$FEWZYB^-KTRE)bF@%f9A}; X;Pdw7qOvoS{@SY;skn&=hQGf7vy Date: Thu, 19 Feb 2026 18:34:59 +0300 Subject: [PATCH 13/13] ad to gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 11817c6..c18c73e 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,5 @@ __pycache__/ *.tmp *.bak *.swp -*.swo \ No newline at end of file +*.swo +acm_9 -- 2.49.0