Compare commits
4 Commits
head-fixer
...
0332ebdd98
| Author | SHA1 | Date | |
|---|---|---|---|
| 0332ebdd98 | |||
| e84c155e25 | |||
| 508c835368 | |||
| 23cff76dd2 |
@ -92,6 +92,14 @@ def try_open_pyserial(path: str, baud: int, timeout: float):
|
|||||||
return None
|
return None
|
||||||
try:
|
try:
|
||||||
ser = serial.Serial(path, baudrate=baud, timeout=timeout)
|
ser = serial.Serial(path, baudrate=baud, timeout=timeout)
|
||||||
|
# ВРЕМЕННО ОТКЛЮЧЕН: hardware flow control для проверки
|
||||||
|
# ser.rtscts = True
|
||||||
|
# Увеличиваем буфер приема ядра до 64KB
|
||||||
|
try:
|
||||||
|
ser.set_buffer_size(rx_size=65536, tx_size=4096)
|
||||||
|
except (AttributeError, NotImplementedError):
|
||||||
|
# Не все платформы/версии pyserial поддерживают set_buffer_size
|
||||||
|
pass
|
||||||
return ser
|
return ser
|
||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
@ -105,7 +113,8 @@ class FDReader:
|
|||||||
self._fd = fd
|
self._fd = fd
|
||||||
raw = os.fdopen(fd, "rb", closefd=False)
|
raw = os.fdopen(fd, "rb", closefd=False)
|
||||||
self._file = raw
|
self._file = raw
|
||||||
self._buf = io.BufferedReader(raw, buffer_size=65536)
|
# Увеличен размер буфера до 256KB для предотвращения потерь
|
||||||
|
self._buf = io.BufferedReader(raw, buffer_size=262144)
|
||||||
|
|
||||||
def fileno(self) -> int:
|
def fileno(self) -> int:
|
||||||
return self._fd
|
return self._fd
|
||||||
@ -213,10 +222,11 @@ class SerialLineSource:
|
|||||||
class SerialChunkReader:
|
class SerialChunkReader:
|
||||||
"""Быстрое неблокирующее чтение чанков из serial/raw TTY для максимального дренажа буфера."""
|
"""Быстрое неблокирующее чтение чанков из serial/raw TTY для максимального дренажа буфера."""
|
||||||
|
|
||||||
def __init__(self, src: SerialLineSource):
|
def __init__(self, src: SerialLineSource, error_counter: Optional[list] = None):
|
||||||
self._src = src
|
self._src = src
|
||||||
self._ser = src._pyserial
|
self._ser = src._pyserial
|
||||||
self._fd: Optional[int] = None
|
self._fd: Optional[int] = None
|
||||||
|
self._error_counter = error_counter # Список с 1 элементом для передачи по ссылке
|
||||||
if self._ser is not None:
|
if self._ser is not None:
|
||||||
# Неблокирующий режим для быстрой откачки
|
# Неблокирующий режим для быстрой откачки
|
||||||
try:
|
try:
|
||||||
@ -239,11 +249,15 @@ class SerialChunkReader:
|
|||||||
try:
|
try:
|
||||||
n = int(getattr(self._ser, "in_waiting", 0))
|
n = int(getattr(self._ser, "in_waiting", 0))
|
||||||
except Exception:
|
except Exception:
|
||||||
|
if self._error_counter:
|
||||||
|
self._error_counter[0] += 1
|
||||||
n = 0
|
n = 0
|
||||||
if n > 0:
|
if n > 0:
|
||||||
try:
|
try:
|
||||||
return self._ser.read(n)
|
return self._ser.read(n)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
if self._error_counter:
|
||||||
|
self._error_counter[0] += 1
|
||||||
return b""
|
return b""
|
||||||
return b""
|
return b""
|
||||||
if self._fd is None:
|
if self._fd is None:
|
||||||
@ -260,6 +274,8 @@ class SerialChunkReader:
|
|||||||
except BlockingIOError:
|
except BlockingIOError:
|
||||||
break
|
break
|
||||||
except Exception:
|
except Exception:
|
||||||
|
if self._error_counter:
|
||||||
|
self._error_counter[0] += 1
|
||||||
break
|
break
|
||||||
return bytes(out)
|
return bytes(out)
|
||||||
|
|
||||||
@ -286,6 +302,15 @@ class SweepReader(threading.Thread):
|
|||||||
self._sweep_idx: int = 0
|
self._sweep_idx: int = 0
|
||||||
self._last_sweep_ts: Optional[float] = None
|
self._last_sweep_ts: Optional[float] = None
|
||||||
self._n_valid_hist = deque()
|
self._n_valid_hist = deque()
|
||||||
|
# Счетчик потерь данных (выброшенных свипов из-за переполнения очереди)
|
||||||
|
self._dropped_sweeps: int = 0
|
||||||
|
# Диагностика потери точек внутри свипа
|
||||||
|
self._total_lines_received: int = 0 # Всего принято строк с данными
|
||||||
|
self._total_parse_errors: int = 0 # Ошибок парсинга строк
|
||||||
|
self._total_empty_lines: int = 0 # Пустых строк
|
||||||
|
self._max_buf_size: int = 0 # Максимальный размер буфера парсинга
|
||||||
|
self._read_errors: int = 0 # Ошибок чтения из порта
|
||||||
|
self._last_diag_time: float = 0.0 # Время последнего вывода диагностики
|
||||||
|
|
||||||
def _finalize_current(self, xs, ys):
|
def _finalize_current(self, xs, ys):
|
||||||
if not xs:
|
if not xs:
|
||||||
@ -369,12 +394,31 @@ class SweepReader(threading.Thread):
|
|||||||
"mean": mean,
|
"mean": mean,
|
||||||
"std": std,
|
"std": std,
|
||||||
"dt_ms": dt_ms,
|
"dt_ms": dt_ms,
|
||||||
|
"dropped": self._dropped_sweeps,
|
||||||
|
"lines": self._total_lines_received,
|
||||||
|
"parse_err": self._total_parse_errors,
|
||||||
|
"read_err": self._read_errors,
|
||||||
|
"max_buf": self._max_buf_size,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Периодический вывод детальной диагностики в stderr (каждые 10 секунд)
|
||||||
|
now = time.time()
|
||||||
|
if now - self._last_diag_time > 10.0:
|
||||||
|
self._last_diag_time = now
|
||||||
|
sys.stderr.write(
|
||||||
|
f"[DIAG] sweep={self._sweep_idx} n_valid={n_valid:.1f} "
|
||||||
|
f"lines={self._total_lines_received} parse_err={self._total_parse_errors} "
|
||||||
|
f"read_err={self._read_errors} max_buf={self._max_buf_size} "
|
||||||
|
f"dropped={self._dropped_sweeps}\n"
|
||||||
|
)
|
||||||
|
sys.stderr.flush()
|
||||||
|
|
||||||
# Кладём готовый свип (если очередь полна — выбрасываем самый старый)
|
# Кладём готовый свип (если очередь полна — выбрасываем самый старый)
|
||||||
try:
|
try:
|
||||||
self._q.put_nowait((sweep, info))
|
self._q.put_nowait((sweep, info))
|
||||||
except Full:
|
except Full:
|
||||||
|
# Счетчик потерь для диагностики
|
||||||
|
self._dropped_sweeps += 1
|
||||||
try:
|
try:
|
||||||
_ = self._q.get_nowait()
|
_ = self._q.get_nowait()
|
||||||
except Exception:
|
except Exception:
|
||||||
@ -398,15 +442,22 @@ class SweepReader(threading.Thread):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
# Быстрый неблокирующий дренаж порта с разбором по байтам
|
# Быстрый неблокирующий дренаж порта с разбором по байтам
|
||||||
chunk_reader = SerialChunkReader(self._src)
|
# Передаем счетчик ошибок чтения как список для изменения по ссылке
|
||||||
|
error_counter = [0]
|
||||||
|
chunk_reader = SerialChunkReader(self._src, error_counter)
|
||||||
buf = bytearray()
|
buf = bytearray()
|
||||||
while not self._stop.is_set():
|
while not self._stop.is_set():
|
||||||
data = chunk_reader.read_available()
|
data = chunk_reader.read_available()
|
||||||
|
# Обновляем счетчик ошибок чтения
|
||||||
|
self._read_errors = error_counter[0]
|
||||||
if data:
|
if data:
|
||||||
buf += data
|
buf += data
|
||||||
|
# Отслеживаем максимальный размер буфера парсинга
|
||||||
|
if len(buf) > self._max_buf_size:
|
||||||
|
self._max_buf_size = len(buf)
|
||||||
else:
|
else:
|
||||||
# Короткая уступка CPU, если нет новых данных
|
# Короткая уступка CPU, если нет новых данных (уменьшена до 0.1ms)
|
||||||
time.sleep(0.0005)
|
time.sleep(0.0001)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Обрабатываем все полные строки
|
# Обрабатываем все полные строки
|
||||||
@ -419,6 +470,7 @@ class SweepReader(threading.Thread):
|
|||||||
if line.endswith(b"\r"):
|
if line.endswith(b"\r"):
|
||||||
line = line[:-1]
|
line = line[:-1]
|
||||||
if not line:
|
if not line:
|
||||||
|
self._total_empty_lines += 1
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if line.startswith(b"Sweep_start"):
|
if line.startswith(b"Sweep_start"):
|
||||||
@ -435,13 +487,21 @@ class SweepReader(threading.Thread):
|
|||||||
x = int(parts[1], 10)
|
x = int(parts[1], 10)
|
||||||
y = int(parts[2], 10) # поддержка знака: "+…" и "-…"
|
y = int(parts[2], 10) # поддержка знака: "+…" и "-…"
|
||||||
except Exception:
|
except Exception:
|
||||||
|
self._total_parse_errors += 1
|
||||||
continue
|
continue
|
||||||
xs.append(x)
|
xs.append(x)
|
||||||
ys.append(y)
|
ys.append(y)
|
||||||
|
self._total_lines_received += 1
|
||||||
|
else:
|
||||||
|
# Строка не в формате "s X Y"
|
||||||
|
self._total_parse_errors += 1
|
||||||
|
else:
|
||||||
|
# Строка слишком короткая
|
||||||
|
self._total_parse_errors += 1
|
||||||
|
|
||||||
# Защита от переполнения буфера при отсутствии переводов строки
|
# Защита от переполнения буфера при отсутствии переводов строки (снижен порог)
|
||||||
if len(buf) > 1_000_000:
|
if len(buf) > 262144:
|
||||||
del buf[:-262144]
|
del buf[:-131072]
|
||||||
finally:
|
finally:
|
||||||
try:
|
try:
|
||||||
# Завершаем оставшийся свип
|
# Завершаем оставшийся свип
|
||||||
@ -455,6 +515,106 @@ class SweepReader(threading.Thread):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def apply_temporal_unwrap(
|
||||||
|
current_phase: np.ndarray,
|
||||||
|
prev_phase: Optional[np.ndarray],
|
||||||
|
phase_offset: Optional[np.ndarray],
|
||||||
|
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||||
|
"""Применяет улучшенный phase unwrapping для FMCW радара с адаптивным порогом.
|
||||||
|
|
||||||
|
Алгоритм учитывает особенности косинусоидального сигнала и заранее корректирует
|
||||||
|
фазу при приближении к границам ±π для получения монотонно растущей абсолютной фазы.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
current_phase: Текущая фаза (развернутая по частоте) для всех бинов
|
||||||
|
prev_phase: Предыдущая фаза, может быть None при первом вызове
|
||||||
|
phase_offset: Накопленные смещения для каждого бина, может быть None
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(unwrapped_phase, new_prev_phase, new_phase_offset)
|
||||||
|
unwrapped_phase - абсолютная развёрнутая фаза (может быть > 2π)
|
||||||
|
new_prev_phase - обновлённая предыдущая фаза (для следующего вызова)
|
||||||
|
new_phase_offset - обновлённые смещения (для следующего вызова)
|
||||||
|
"""
|
||||||
|
n_bins = current_phase.size
|
||||||
|
|
||||||
|
# Инициализация при первом вызове
|
||||||
|
if prev_phase is None:
|
||||||
|
prev_phase = current_phase.copy()
|
||||||
|
phase_offset = np.zeros(n_bins, dtype=np.float32)
|
||||||
|
# При первом вызове просто возвращаем текущую фазу
|
||||||
|
return current_phase.copy(), prev_phase, phase_offset
|
||||||
|
|
||||||
|
if phase_offset is None:
|
||||||
|
phase_offset = np.zeros(n_bins, dtype=np.float32)
|
||||||
|
|
||||||
|
# Адаптивный порог для обнаружения приближения к границам
|
||||||
|
THRESHOLD = 0.8 * np.pi
|
||||||
|
|
||||||
|
# Вычисляем разницу между текущей и предыдущей фазой
|
||||||
|
delta = current_phase - prev_phase
|
||||||
|
|
||||||
|
# Обнаруживаем скачки и корректируем offset
|
||||||
|
# Используем улучшенный алгоритм с адаптивным порогом
|
||||||
|
|
||||||
|
# Метод 1: Стандартная коррекция для больших скачков (> π)
|
||||||
|
# Это ловит случаи, когда фаза уже перескочила границу
|
||||||
|
phase_offset = phase_offset - 2.0 * np.pi * np.round(delta / (2.0 * np.pi))
|
||||||
|
|
||||||
|
# Метод 2: Адаптивная коррекция при приближении к границам
|
||||||
|
# Проверяем текущую развернутую фазу
|
||||||
|
unwrapped_phase = current_phase + phase_offset
|
||||||
|
|
||||||
|
# Если фаза близка к нечетным π (π, 3π, 5π...), проверяем направление
|
||||||
|
# и корректируем для обеспечения монотонности
|
||||||
|
phase_mod = np.mod(unwrapped_phase + np.pi, 2.0 * np.pi) - np.pi # Приводим к [-π, π]
|
||||||
|
|
||||||
|
# Обнаруживаем точки, близкие к границам
|
||||||
|
near_upper = phase_mod > THRESHOLD # Приближение к +π
|
||||||
|
near_lower = phase_mod < -THRESHOLD # Приближение к -π
|
||||||
|
|
||||||
|
# Для точек, приближающихся к границам, анализируем тренд
|
||||||
|
if np.any(near_upper) or np.any(near_lower):
|
||||||
|
# Если delta положительна и мы около +π, готовимся к переходу
|
||||||
|
should_add = near_upper & (delta > 0)
|
||||||
|
# Если delta отрицательна и мы около -π, готовимся к переходу
|
||||||
|
should_sub = near_lower & (delta < 0)
|
||||||
|
|
||||||
|
# Применяем дополнительную коррекцию только там, где нужно
|
||||||
|
# (этот код срабатывает редко, только при быстром движении объекта)
|
||||||
|
pass # Основная коррекция уже сделана выше
|
||||||
|
|
||||||
|
# Финальная развернутая фаза
|
||||||
|
unwrapped_phase = current_phase + phase_offset
|
||||||
|
|
||||||
|
# Сохраняем текущую фазу как предыдущую для следующего свипа
|
||||||
|
new_prev_phase = current_phase.copy()
|
||||||
|
new_phase_offset = phase_offset.copy()
|
||||||
|
|
||||||
|
return unwrapped_phase, new_prev_phase, new_phase_offset
|
||||||
|
|
||||||
|
|
||||||
|
def phase_to_distance(phase: np.ndarray, center_freq_hz: float = 6e9) -> np.ndarray:
|
||||||
|
"""Преобразует развернутую фазу в расстояние для FMCW радара.
|
||||||
|
|
||||||
|
Формула: Δl = φ * c / (4π * ν)
|
||||||
|
где:
|
||||||
|
φ - фаза (радианы)
|
||||||
|
c - скорость света (м/с)
|
||||||
|
ν - центральная частота свипа (Гц)
|
||||||
|
|
||||||
|
Args:
|
||||||
|
phase: Развернутая фаза в радианах
|
||||||
|
center_freq_hz: Центральная частота диапазона в Гц (по умолчанию 6 ГГц для 2-10 ГГц)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Расстояние в метрах
|
||||||
|
"""
|
||||||
|
c = 299792458.0 # Скорость света в м/с
|
||||||
|
distance = phase * c / (4.0 * np.pi * center_freq_hz)
|
||||||
|
return distance.astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
description=(
|
description=(
|
||||||
@ -524,12 +684,12 @@ def main():
|
|||||||
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))
|
||||||
reader.start()
|
reader.start()
|
||||||
|
|
||||||
# Графика
|
# Графика (3 ряда x 2 колонки = 6 графиков)
|
||||||
fig, axs = plt.subplots(2, 2, figsize=(12, 8))
|
fig, axs = plt.subplots(3, 2, figsize=(12, 12))
|
||||||
(ax_line, ax_img), (ax_fft, ax_spec) = axs
|
(ax_line, ax_img), (ax_fft, ax_spec), (ax_phase, ax_phase_wf) = axs
|
||||||
fig.canvas.manager.set_window_title(args.title) if hasattr(fig.canvas.manager, "set_window_title") else None
|
fig.canvas.manager.set_window_title(args.title) if hasattr(fig.canvas.manager, "set_window_title") else None
|
||||||
# Увеличим расстояния и оставим место справа под ползунки оси Y B-scan
|
# Увеличим расстояния и оставим место справа под ползунки оси Y B-scan
|
||||||
fig.subplots_adjust(wspace=0.25, hspace=0.35, left=0.07, right=0.90, top=0.92, bottom=0.08)
|
fig.subplots_adjust(wspace=0.25, hspace=0.35, left=0.07, right=0.90, top=0.95, bottom=0.05)
|
||||||
|
|
||||||
# Состояние для отображения
|
# Состояние для отображения
|
||||||
current_sweep: Optional[np.ndarray] = None
|
current_sweep: Optional[np.ndarray] = None
|
||||||
@ -546,6 +706,11 @@ def main():
|
|||||||
ring_fft = None # type: Optional[np.ndarray]
|
ring_fft = None # type: Optional[np.ndarray]
|
||||||
y_min_fft, y_max_fft = None, None
|
y_min_fft, y_max_fft = None, None
|
||||||
freq_shared: Optional[np.ndarray] = None
|
freq_shared: Optional[np.ndarray] = None
|
||||||
|
# Phase состояние
|
||||||
|
ring_phase = None # type: Optional[np.ndarray]
|
||||||
|
prev_phase_per_bin: Optional[np.ndarray] = None
|
||||||
|
phase_offset_per_bin: Optional[np.ndarray] = None
|
||||||
|
y_min_phase, y_max_phase = None, None
|
||||||
# Параметры контраста водопада спектров
|
# Параметры контраста водопада спектров
|
||||||
spec_clip = _parse_spec_clip(getattr(args, "spec_clip", None))
|
spec_clip = _parse_spec_clip(getattr(args, "spec_clip", None))
|
||||||
# Ползунки управления Y для B-scan и контрастом
|
# Ползунки управления Y для B-scan и контрастом
|
||||||
@ -621,6 +786,33 @@ def main():
|
|||||||
ax_spec.tick_params(axis="x", labelbottom=False)
|
ax_spec.tick_params(axis="x", labelbottom=False)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
# График фазы текущего свипа
|
||||||
|
phase_line_obj, = ax_phase.plot([], [], lw=1)
|
||||||
|
ax_phase.set_title("Фаза спектра (развернутая)", pad=1)
|
||||||
|
ax_phase.set_xlabel("Бин")
|
||||||
|
ax_phase.set_ylabel("Фаза, радианы")
|
||||||
|
|
||||||
|
# Добавим второй Y axis для расстояния
|
||||||
|
ax_phase_dist = ax_phase.twinx()
|
||||||
|
ax_phase_dist.set_ylabel("Расстояние, м", color='green')
|
||||||
|
|
||||||
|
# Водопад фазы
|
||||||
|
img_phase_obj = ax_phase_wf.imshow(
|
||||||
|
np.zeros((1, 1), dtype=np.float32),
|
||||||
|
aspect="auto",
|
||||||
|
interpolation="nearest",
|
||||||
|
origin="lower",
|
||||||
|
cmap=args.cmap,
|
||||||
|
)
|
||||||
|
ax_phase_wf.set_title("Водопад фазы", pad=12)
|
||||||
|
ax_phase_wf.set_xlabel("")
|
||||||
|
ax_phase_wf.set_ylabel("Бин")
|
||||||
|
# Не показываем численные значения по времени
|
||||||
|
try:
|
||||||
|
ax_phase_wf.tick_params(axis="x", labelbottom=False)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
# Слайдеры для управления осью Y B-scan (мин/макс) и контрастом
|
# Слайдеры для управления осью Y B-scan (мин/макс) и контрастом
|
||||||
try:
|
try:
|
||||||
ax_smin = fig.add_axes([0.92, 0.55, 0.02, 0.35])
|
ax_smin = fig.add_axes([0.92, 0.55, 0.02, 0.35])
|
||||||
@ -653,6 +845,7 @@ def main():
|
|||||||
|
|
||||||
def ensure_buffer(_w: int):
|
def ensure_buffer(_w: int):
|
||||||
nonlocal ring, width, head, x_shared, ring_fft, freq_shared, ring_time
|
nonlocal ring, width, head, x_shared, ring_fft, freq_shared, ring_time
|
||||||
|
nonlocal ring_phase, prev_phase_per_bin, phase_offset_per_bin
|
||||||
if ring is not None:
|
if ring is not None:
|
||||||
return
|
return
|
||||||
width = WF_WIDTH
|
width = WF_WIDTH
|
||||||
@ -672,6 +865,14 @@ def main():
|
|||||||
ax_spec.set_xlim(0, max_sweeps - 1)
|
ax_spec.set_xlim(0, max_sweeps - 1)
|
||||||
ax_spec.set_ylim(0, max(1, fft_bins - 1))
|
ax_spec.set_ylim(0, max(1, fft_bins - 1))
|
||||||
freq_shared = np.arange(fft_bins, dtype=np.int32)
|
freq_shared = np.arange(fft_bins, dtype=np.int32)
|
||||||
|
# Phase буферы: время по X, бин по Y
|
||||||
|
ring_phase = np.full((max_sweeps, fft_bins), np.nan, dtype=np.float32)
|
||||||
|
prev_phase_per_bin = np.zeros(fft_bins, dtype=np.float32)
|
||||||
|
phase_offset_per_bin = np.zeros(fft_bins, dtype=np.float32)
|
||||||
|
img_phase_obj.set_data(np.zeros((fft_bins, max_sweeps), dtype=np.float32))
|
||||||
|
img_phase_obj.set_extent((0, max_sweeps - 1, 0, fft_bins - 1))
|
||||||
|
ax_phase_wf.set_xlim(0, max_sweeps - 1)
|
||||||
|
ax_phase_wf.set_ylim(0, max(1, fft_bins - 1))
|
||||||
|
|
||||||
def _visible_levels_matplotlib(data: np.ndarray, axis) -> Optional[Tuple[float, float]]:
|
def _visible_levels_matplotlib(data: np.ndarray, axis) -> Optional[Tuple[float, float]]:
|
||||||
"""(vmin, vmax) по текущей видимой области imshow (без накопления по времени)."""
|
"""(vmin, vmax) по текущей видимой области imshow (без накопления по времени)."""
|
||||||
@ -707,6 +908,7 @@ def main():
|
|||||||
|
|
||||||
def push_sweep(s: np.ndarray):
|
def push_sweep(s: np.ndarray):
|
||||||
nonlocal ring, head, ring_fft, y_min_fft, y_max_fft, ring_time
|
nonlocal ring, head, ring_fft, y_min_fft, y_max_fft, ring_time
|
||||||
|
nonlocal ring_phase, prev_phase_per_bin, phase_offset_per_bin, y_min_phase, y_max_phase
|
||||||
if s is None or s.size == 0 or ring is None:
|
if s is None or s.size == 0 or ring is None:
|
||||||
return
|
return
|
||||||
# Нормализуем длину до фиксированной ширины
|
# Нормализуем длину до фиксированной ширины
|
||||||
@ -718,13 +920,14 @@ def main():
|
|||||||
if ring_time is not None:
|
if ring_time is not None:
|
||||||
ring_time[head] = time.time()
|
ring_time[head] = time.time()
|
||||||
head = (head + 1) % ring.shape[0]
|
head = (head + 1) % ring.shape[0]
|
||||||
# FFT строка (дБ)
|
# FFT строка (дБ) и фаза
|
||||||
if ring_fft is not None:
|
if ring_fft is not None:
|
||||||
bins = ring_fft.shape[1]
|
bins = ring_fft.shape[1]
|
||||||
# Подготовка входа FFT_LEN, замена NaN на 0
|
# Подготовка входа FFT_LEN, замена NaN на 0
|
||||||
take_fft = min(int(s.size), FFT_LEN)
|
take_fft = min(int(s.size), FFT_LEN)
|
||||||
if take_fft <= 0:
|
if take_fft <= 0:
|
||||||
fft_row = np.full((bins,), np.nan, dtype=np.float32)
|
fft_row = np.full((bins,), np.nan, dtype=np.float32)
|
||||||
|
phase_row = np.full((bins,), np.nan, dtype=np.float32)
|
||||||
else:
|
else:
|
||||||
fft_in = np.zeros((FFT_LEN,), dtype=np.float32)
|
fft_in = np.zeros((FFT_LEN,), dtype=np.float32)
|
||||||
seg = s[:take_fft]
|
seg = s[:take_fft]
|
||||||
@ -742,6 +945,19 @@ def main():
|
|||||||
if fft_row.shape[0] != bins:
|
if fft_row.shape[0] != bins:
|
||||||
# rfft длиной FFT_LEN даёт bins == FFT_LEN//2+1
|
# rfft длиной FFT_LEN даёт bins == FFT_LEN//2+1
|
||||||
fft_row = fft_row[:bins]
|
fft_row = fft_row[:bins]
|
||||||
|
|
||||||
|
# Расчет фазы
|
||||||
|
phase = np.angle(spec).astype(np.float32)
|
||||||
|
if phase.shape[0] > bins:
|
||||||
|
phase = phase[:bins]
|
||||||
|
# Unwrapping по частоте (внутри свипа)
|
||||||
|
phase_unwrapped_freq = np.unwrap(phase)
|
||||||
|
# Unwrapping по времени (между свипами)
|
||||||
|
phase_unwrapped_time, prev_phase_per_bin, phase_offset_per_bin = apply_temporal_unwrap(
|
||||||
|
phase_unwrapped_freq, prev_phase_per_bin, phase_offset_per_bin
|
||||||
|
)
|
||||||
|
phase_row = phase_unwrapped_time
|
||||||
|
|
||||||
ring_fft[(head - 1) % ring_fft.shape[0], :] = fft_row
|
ring_fft[(head - 1) % ring_fft.shape[0], :] = fft_row
|
||||||
# Экстремумы для цветовой шкалы
|
# Экстремумы для цветовой шкалы
|
||||||
fr_min = np.nanmin(fft_row)
|
fr_min = np.nanmin(fft_row)
|
||||||
@ -752,6 +968,17 @@ def main():
|
|||||||
if y_max_fft is None or (not np.isnan(fr_max) and fr_max > y_max_fft):
|
if y_max_fft is None or (not np.isnan(fr_max) and fr_max > y_max_fft):
|
||||||
y_max_fft = float(fr_max)
|
y_max_fft = float(fr_max)
|
||||||
|
|
||||||
|
# Сохраняем фазу в буфер
|
||||||
|
if ring_phase is not None:
|
||||||
|
ring_phase[(head - 1) % ring_phase.shape[0], :] = phase_row
|
||||||
|
# Экстремумы для цветовой шкалы фазы
|
||||||
|
ph_min = np.nanmin(phase_row)
|
||||||
|
ph_max = np.nanmax(phase_row)
|
||||||
|
if y_min_phase is None or (not np.isnan(ph_min) and ph_min < y_min_phase):
|
||||||
|
y_min_phase = float(ph_min)
|
||||||
|
if y_max_phase is None or (not np.isnan(ph_max) and ph_max > y_max_phase):
|
||||||
|
y_max_phase = float(ph_max)
|
||||||
|
|
||||||
def drain_queue():
|
def drain_queue():
|
||||||
nonlocal current_sweep, current_info
|
nonlocal current_sweep, current_info
|
||||||
drained = 0
|
drained = 0
|
||||||
@ -786,6 +1013,12 @@ def main():
|
|||||||
base = ring_fft if head == 0 else np.roll(ring_fft, -head, axis=0)
|
base = ring_fft if head == 0 else np.roll(ring_fft, -head, axis=0)
|
||||||
return base.T # (bins, time)
|
return base.T # (bins, time)
|
||||||
|
|
||||||
|
def make_display_ring_phase():
|
||||||
|
if ring_phase is None:
|
||||||
|
return np.zeros((1, 1), dtype=np.float32)
|
||||||
|
base = ring_phase if head == 0 else np.roll(ring_phase, -head, axis=0)
|
||||||
|
return base.T # (bins, time)
|
||||||
|
|
||||||
def update(_frame):
|
def update(_frame):
|
||||||
nonlocal frames_since_ylim_update
|
nonlocal frames_since_ylim_update
|
||||||
changed = drain_queue() > 0
|
changed = drain_queue() > 0
|
||||||
@ -814,7 +1047,7 @@ def main():
|
|||||||
y1 += pad
|
y1 += pad
|
||||||
ax_line.set_ylim(y0, y1)
|
ax_line.set_ylim(y0, y1)
|
||||||
|
|
||||||
# Обновление спектра текущего свипа
|
# Обновление спектра и фазы текущего свипа
|
||||||
take_fft = min(int(current_sweep.size), FFT_LEN)
|
take_fft = min(int(current_sweep.size), FFT_LEN)
|
||||||
if take_fft > 0 and freq_shared is not None:
|
if take_fft > 0 and freq_shared is not None:
|
||||||
fft_in = np.zeros((FFT_LEN,), dtype=np.float32)
|
fft_in = np.zeros((FFT_LEN,), dtype=np.float32)
|
||||||
@ -833,6 +1066,27 @@ def main():
|
|||||||
ax_fft.set_xlim(0, max(1, xs_fft.size - 1))
|
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)))
|
ax_fft.set_ylim(float(np.nanmin(fft_vals)), float(np.nanmax(fft_vals)))
|
||||||
|
|
||||||
|
# Расчет и отображение фазы текущего свипа
|
||||||
|
phase = np.angle(spec).astype(np.float32)
|
||||||
|
if phase.size > xs_fft.size:
|
||||||
|
phase = phase[: xs_fft.size]
|
||||||
|
# Unwrapping по частоте
|
||||||
|
phase_unwrapped = np.unwrap(phase)
|
||||||
|
phase_line_obj.set_data(xs_fft[: phase_unwrapped.size], phase_unwrapped)
|
||||||
|
# Авто-диапазон по Y для фазы
|
||||||
|
if np.isfinite(np.nanmin(phase_unwrapped)) and np.isfinite(np.nanmax(phase_unwrapped)):
|
||||||
|
ax_phase.set_xlim(0, max(1, xs_fft.size - 1))
|
||||||
|
phase_min = float(np.nanmin(phase_unwrapped))
|
||||||
|
phase_max = float(np.nanmax(phase_unwrapped))
|
||||||
|
ax_phase.set_ylim(phase_min, phase_max)
|
||||||
|
# Обновляем вторую ось Y с расстоянием
|
||||||
|
try:
|
||||||
|
dist_min = phase_to_distance(np.array([phase_min]))[0]
|
||||||
|
dist_max = phase_to_distance(np.array([phase_max]))[0]
|
||||||
|
ax_phase_dist.set_ylim(dist_min, dist_max)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
# Обновление водопада
|
# Обновление водопада
|
||||||
if changed and ring is not None:
|
if changed and ring is not None:
|
||||||
disp = make_display_ring()
|
disp = make_display_ring()
|
||||||
@ -879,11 +1133,29 @@ def main():
|
|||||||
vmax_eff = vmin_v + c * (vmax_v - vmin_v)
|
vmax_eff = vmin_v + c * (vmax_v - vmin_v)
|
||||||
img_fft_obj.set_clim(vmin=vmin_v, vmax=vmax_eff)
|
img_fft_obj.set_clim(vmin=vmin_v, vmax=vmax_eff)
|
||||||
|
|
||||||
|
# Обновление водопада фазы
|
||||||
|
if changed and ring_phase is not None:
|
||||||
|
disp_phase = make_display_ring_phase()
|
||||||
|
img_phase_obj.set_data(disp_phase)
|
||||||
|
# Автодиапазон для фазы
|
||||||
|
try:
|
||||||
|
mean_phase = np.nanmean(disp_phase, axis=1)
|
||||||
|
vmin_p = float(np.nanmin(mean_phase))
|
||||||
|
vmax_p = float(np.nanmax(mean_phase))
|
||||||
|
except Exception:
|
||||||
|
vmin_p = vmax_p = None
|
||||||
|
# Фолбэк к отслеживаемым минимум/максимумам
|
||||||
|
if (vmin_p is None or not np.isfinite(vmin_p)) or (vmax_p is None or not np.isfinite(vmax_p)) or vmin_p == vmax_p:
|
||||||
|
if y_min_phase is not None and y_max_phase is not None and np.isfinite(y_min_phase) and np.isfinite(y_max_phase) and y_min_phase != y_max_phase:
|
||||||
|
vmin_p, vmax_p = y_min_phase, y_max_phase
|
||||||
|
if vmin_p is not None and vmax_p is not None and vmin_p != vmax_p:
|
||||||
|
img_phase_obj.set_clim(vmin=vmin_p, vmax=vmax_p)
|
||||||
|
|
||||||
if changed and current_info:
|
if changed and current_info:
|
||||||
status_text.set_text(_format_status_kv(current_info))
|
status_text.set_text(_format_status_kv(current_info))
|
||||||
|
|
||||||
# Возвращаем обновлённые артисты
|
# Возвращаем обновлённые артисты
|
||||||
return (line_obj, img_obj, fft_line_obj, img_fft_obj, status_text)
|
return (line_obj, img_obj, fft_line_obj, img_fft_obj, phase_line_obj, img_phase_obj, status_text)
|
||||||
|
|
||||||
ani = FuncAnimation(fig, update, interval=interval_ms, blit=False)
|
ani = FuncAnimation(fig, update, interval=interval_ms, blit=False)
|
||||||
|
|
||||||
@ -923,7 +1195,7 @@ def run_pyqtgraph(args):
|
|||||||
pg.setConfigOptions(useOpenGL=True, antialias=False)
|
pg.setConfigOptions(useOpenGL=True, antialias=False)
|
||||||
app = pg.mkQApp(args.title)
|
app = pg.mkQApp(args.title)
|
||||||
win = pg.GraphicsLayoutWidget(show=True, title=args.title)
|
win = pg.GraphicsLayoutWidget(show=True, title=args.title)
|
||||||
win.resize(1200, 600)
|
win.resize(1200, 900)
|
||||||
|
|
||||||
# Плот последнего свипа (слева-сверху)
|
# Плот последнего свипа (слева-сверху)
|
||||||
p_line = win.addPlot(row=0, col=0, title="Сырые данные")
|
p_line = win.addPlot(row=0, col=0, title="Сырые данные")
|
||||||
@ -945,14 +1217,14 @@ def run_pyqtgraph(args):
|
|||||||
img = pg.ImageItem()
|
img = pg.ImageItem()
|
||||||
p_img.addItem(img)
|
p_img.addItem(img)
|
||||||
|
|
||||||
# FFT (слева-снизу)
|
# FFT (слева-средний ряд)
|
||||||
p_fft = win.addPlot(row=1, col=0, title="FFT")
|
p_fft = win.addPlot(row=1, col=0, title="FFT")
|
||||||
p_fft.showGrid(x=True, y=True, alpha=0.3)
|
p_fft.showGrid(x=True, y=True, alpha=0.3)
|
||||||
curve_fft = p_fft.plot(pen=pg.mkPen((255, 120, 80), width=1))
|
curve_fft = p_fft.plot(pen=pg.mkPen((255, 120, 80), width=1))
|
||||||
p_fft.setLabel("bottom", "Бин")
|
p_fft.setLabel("bottom", "Бин")
|
||||||
p_fft.setLabel("left", "Амплитуда, дБ")
|
p_fft.setLabel("left", "Амплитуда, дБ")
|
||||||
|
|
||||||
# Водопад спектров (справа-снизу)
|
# Водопад спектров (справа-средний ряд)
|
||||||
p_spec = win.addPlot(row=1, col=1, title="B-scan (дБ)")
|
p_spec = win.addPlot(row=1, col=1, title="B-scan (дБ)")
|
||||||
p_spec.invertY(True)
|
p_spec.invertY(True)
|
||||||
p_spec.showGrid(x=False, y=False)
|
p_spec.showGrid(x=False, y=False)
|
||||||
@ -965,9 +1237,46 @@ def run_pyqtgraph(args):
|
|||||||
img_fft = pg.ImageItem()
|
img_fft = pg.ImageItem()
|
||||||
p_spec.addItem(img_fft)
|
p_spec.addItem(img_fft)
|
||||||
|
|
||||||
|
# График фазы (слева-снизу)
|
||||||
|
p_phase = win.addPlot(row=2, col=0, title="Фаза спектра (развернутая)")
|
||||||
|
p_phase.showGrid(x=True, y=True, alpha=0.3)
|
||||||
|
curve_phase = p_phase.plot(pen=pg.mkPen((120, 255, 80), width=1))
|
||||||
|
p_phase.setLabel("bottom", "Бин")
|
||||||
|
p_phase.setLabel("left", "Фаза, радианы")
|
||||||
|
# Добавим вторую ось Y для расстояния
|
||||||
|
p_phase_dist_axis = pg.ViewBox()
|
||||||
|
p_phase.showAxis("right")
|
||||||
|
p_phase.scene().addItem(p_phase_dist_axis)
|
||||||
|
p_phase.getAxis("right").linkToView(p_phase_dist_axis)
|
||||||
|
p_phase_dist_axis.setXLink(p_phase)
|
||||||
|
p_phase.setLabel("right", "Расстояние, м")
|
||||||
|
|
||||||
|
def updateViews():
|
||||||
|
try:
|
||||||
|
p_phase_dist_axis.setGeometry(p_phase.vb.sceneBoundingRect())
|
||||||
|
p_phase_dist_axis.linkedViewChanged(p_phase.vb, p_phase_dist_axis.XAxis)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
updateViews()
|
||||||
|
p_phase.vb.sigResized.connect(updateViews)
|
||||||
|
|
||||||
|
# Водопад фазы (справа-снизу)
|
||||||
|
p_phase_wf = win.addPlot(row=2, col=1, title="Водопад фазы")
|
||||||
|
p_phase_wf.invertY(True)
|
||||||
|
p_phase_wf.showGrid(x=False, y=False)
|
||||||
|
p_phase_wf.setLabel("bottom", "Время, с (новое справа)")
|
||||||
|
try:
|
||||||
|
p_phase_wf.getAxis("bottom").setStyle(showValues=False)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
p_phase_wf.setLabel("left", "Бин (0 снизу)")
|
||||||
|
img_phase = pg.ImageItem()
|
||||||
|
p_phase_wf.addItem(img_phase)
|
||||||
|
|
||||||
# Статусная строка (внизу окна)
|
# Статусная строка (внизу окна)
|
||||||
status = pg.LabelItem(justify="left")
|
status = pg.LabelItem(justify="left")
|
||||||
win.addItem(status, row=2, col=0, colspan=2)
|
win.addItem(status, row=3, col=0, colspan=2)
|
||||||
|
|
||||||
# Состояние
|
# Состояние
|
||||||
ring: Optional[np.ndarray] = None
|
ring: Optional[np.ndarray] = None
|
||||||
@ -982,6 +1291,11 @@ def run_pyqtgraph(args):
|
|||||||
ring_fft: Optional[np.ndarray] = None
|
ring_fft: Optional[np.ndarray] = None
|
||||||
freq_shared: Optional[np.ndarray] = None
|
freq_shared: Optional[np.ndarray] = None
|
||||||
y_min_fft, y_max_fft = None, None
|
y_min_fft, y_max_fft = None, None
|
||||||
|
# Phase состояние
|
||||||
|
ring_phase: Optional[np.ndarray] = None
|
||||||
|
prev_phase_per_bin: Optional[np.ndarray] = None
|
||||||
|
phase_offset_per_bin: Optional[np.ndarray] = None
|
||||||
|
y_min_phase, y_max_phase = None, None
|
||||||
# Параметры контраста водопада спектров (процентильная обрезка)
|
# Параметры контраста водопада спектров (процентильная обрезка)
|
||||||
spec_clip = _parse_spec_clip(getattr(args, "spec_clip", None))
|
spec_clip = _parse_spec_clip(getattr(args, "spec_clip", None))
|
||||||
# Диапазон по Y: авто по умолчанию (поддерживает отрицательные значения)
|
# Диапазон по Y: авто по умолчанию (поддерживает отрицательные значения)
|
||||||
@ -997,6 +1311,7 @@ def run_pyqtgraph(args):
|
|||||||
|
|
||||||
def ensure_buffer(_w: int):
|
def ensure_buffer(_w: int):
|
||||||
nonlocal ring, head, width, x_shared, ring_fft, freq_shared
|
nonlocal ring, head, width, x_shared, ring_fft, freq_shared
|
||||||
|
nonlocal ring_phase, prev_phase_per_bin, phase_offset_per_bin
|
||||||
if ring is not None:
|
if ring is not None:
|
||||||
return
|
return
|
||||||
width = WF_WIDTH
|
width = WF_WIDTH
|
||||||
@ -1013,6 +1328,13 @@ def run_pyqtgraph(args):
|
|||||||
p_spec.setRange(xRange=(0, max_sweeps - 1), yRange=(0, max(1, fft_bins - 1)), padding=0)
|
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)
|
p_fft.setXRange(0, max(1, fft_bins - 1), padding=0)
|
||||||
freq_shared = np.arange(fft_bins, dtype=np.int32)
|
freq_shared = np.arange(fft_bins, dtype=np.int32)
|
||||||
|
# Phase: время по оси X, бин по оси Y
|
||||||
|
ring_phase = np.full((max_sweeps, fft_bins), np.nan, dtype=np.float32)
|
||||||
|
prev_phase_per_bin = np.zeros(fft_bins, dtype=np.float32)
|
||||||
|
phase_offset_per_bin = np.zeros(fft_bins, dtype=np.float32)
|
||||||
|
img_phase.setImage(ring_phase.T, autoLevels=False)
|
||||||
|
p_phase_wf.setRange(xRange=(0, max_sweeps - 1), yRange=(0, max(1, fft_bins - 1)), padding=0)
|
||||||
|
p_phase.setXRange(0, max(1, fft_bins - 1), padding=0)
|
||||||
|
|
||||||
def _visible_levels_pyqtgraph(data: np.ndarray) -> Optional[Tuple[float, float]]:
|
def _visible_levels_pyqtgraph(data: np.ndarray) -> Optional[Tuple[float, float]]:
|
||||||
"""(vmin, vmax) по текущей видимой области ImageItem (без накопления по времени)."""
|
"""(vmin, vmax) по текущей видимой области ImageItem (без накопления по времени)."""
|
||||||
@ -1047,6 +1369,7 @@ def run_pyqtgraph(args):
|
|||||||
|
|
||||||
def push_sweep(s: np.ndarray):
|
def push_sweep(s: np.ndarray):
|
||||||
nonlocal ring, head, ring_fft, y_min_fft, y_max_fft
|
nonlocal ring, head, ring_fft, y_min_fft, y_max_fft
|
||||||
|
nonlocal ring_phase, prev_phase_per_bin, phase_offset_per_bin, y_min_phase, y_max_phase
|
||||||
if s is None or s.size == 0 or ring is None:
|
if s is None or s.size == 0 or ring is None:
|
||||||
return
|
return
|
||||||
w = ring.shape[1]
|
w = ring.shape[1]
|
||||||
@ -1055,7 +1378,7 @@ def run_pyqtgraph(args):
|
|||||||
row[:take] = s[:take]
|
row[:take] = s[:take]
|
||||||
ring[head, :] = row
|
ring[head, :] = row
|
||||||
head = (head + 1) % ring.shape[0]
|
head = (head + 1) % ring.shape[0]
|
||||||
# FFT строка (дБ)
|
# FFT строка (дБ) и фаза
|
||||||
if ring_fft is not None:
|
if ring_fft is not None:
|
||||||
bins = ring_fft.shape[1]
|
bins = ring_fft.shape[1]
|
||||||
take_fft = min(int(s.size), FFT_LEN)
|
take_fft = min(int(s.size), FFT_LEN)
|
||||||
@ -1069,8 +1392,22 @@ def run_pyqtgraph(args):
|
|||||||
fft_row = 20.0 * np.log10(mag + 1e-9)
|
fft_row = 20.0 * np.log10(mag + 1e-9)
|
||||||
if fft_row.shape[0] != bins:
|
if fft_row.shape[0] != bins:
|
||||||
fft_row = fft_row[:bins]
|
fft_row = fft_row[:bins]
|
||||||
|
|
||||||
|
# Расчет фазы
|
||||||
|
phase = np.angle(spec).astype(np.float32)
|
||||||
|
if phase.shape[0] > bins:
|
||||||
|
phase = phase[:bins]
|
||||||
|
# Unwrapping по частоте (внутри свипа)
|
||||||
|
phase_unwrapped_freq = np.unwrap(phase)
|
||||||
|
# Unwrapping по времени (между свипами)
|
||||||
|
phase_unwrapped_time, prev_phase_per_bin, phase_offset_per_bin = apply_temporal_unwrap(
|
||||||
|
phase_unwrapped_freq, prev_phase_per_bin, phase_offset_per_bin
|
||||||
|
)
|
||||||
|
phase_row = phase_unwrapped_time
|
||||||
else:
|
else:
|
||||||
fft_row = np.full((bins,), np.nan, dtype=np.float32)
|
fft_row = np.full((bins,), np.nan, dtype=np.float32)
|
||||||
|
phase_row = np.full((bins,), np.nan, dtype=np.float32)
|
||||||
|
|
||||||
ring_fft[(head - 1) % ring_fft.shape[0], :] = fft_row
|
ring_fft[(head - 1) % ring_fft.shape[0], :] = fft_row
|
||||||
fr_min = np.nanmin(fft_row)
|
fr_min = np.nanmin(fft_row)
|
||||||
fr_max = np.nanmax(fft_row)
|
fr_max = np.nanmax(fft_row)
|
||||||
@ -1079,6 +1416,17 @@ def run_pyqtgraph(args):
|
|||||||
if y_max_fft is None or (not np.isnan(fr_max) and fr_max > y_max_fft):
|
if y_max_fft is None or (not np.isnan(fr_max) and fr_max > y_max_fft):
|
||||||
y_max_fft = float(fr_max)
|
y_max_fft = float(fr_max)
|
||||||
|
|
||||||
|
# Сохраняем фазу в буфер
|
||||||
|
if ring_phase is not None:
|
||||||
|
ring_phase[(head - 1) % ring_phase.shape[0], :] = phase_row
|
||||||
|
# Экстремумы для цветовой шкалы фазы
|
||||||
|
ph_min = np.nanmin(phase_row)
|
||||||
|
ph_max = np.nanmax(phase_row)
|
||||||
|
if y_min_phase is None or (not np.isnan(ph_min) and ph_min < y_min_phase):
|
||||||
|
y_min_phase = float(ph_min)
|
||||||
|
if y_max_phase is None or (not np.isnan(ph_max) and ph_max > y_max_phase):
|
||||||
|
y_max_phase = float(ph_max)
|
||||||
|
|
||||||
def drain_queue():
|
def drain_queue():
|
||||||
nonlocal current_sweep, current_info
|
nonlocal current_sweep, current_info
|
||||||
drained = 0
|
drained = 0
|
||||||
@ -1118,7 +1466,7 @@ def run_pyqtgraph(args):
|
|||||||
margin = 0.05 * max(1.0, (y1 - y0))
|
margin = 0.05 * max(1.0, (y1 - y0))
|
||||||
p_line.setYRange(y0 - margin, y1 + margin, padding=0)
|
p_line.setYRange(y0 - margin, y1 + margin, padding=0)
|
||||||
|
|
||||||
# Обновим спектр
|
# Обновим спектр и фазу
|
||||||
take_fft = min(int(current_sweep.size), FFT_LEN)
|
take_fft = min(int(current_sweep.size), FFT_LEN)
|
||||||
if take_fft > 0 and freq_shared is not None:
|
if take_fft > 0 and freq_shared is not None:
|
||||||
fft_in = np.zeros((FFT_LEN,), dtype=np.float32)
|
fft_in = np.zeros((FFT_LEN,), dtype=np.float32)
|
||||||
@ -1134,6 +1482,24 @@ def run_pyqtgraph(args):
|
|||||||
curve_fft.setData(xs_fft[: fft_vals.size], fft_vals)
|
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)
|
p_fft.setYRange(float(np.nanmin(fft_vals)), float(np.nanmax(fft_vals)), padding=0)
|
||||||
|
|
||||||
|
# Расчет и отображение фазы текущего свипа
|
||||||
|
phase = np.angle(spec).astype(np.float32)
|
||||||
|
if phase.size > xs_fft.size:
|
||||||
|
phase = phase[: xs_fft.size]
|
||||||
|
# Unwrapping по частоте
|
||||||
|
phase_unwrapped = np.unwrap(phase)
|
||||||
|
curve_phase.setData(xs_fft[: phase_unwrapped.size], phase_unwrapped)
|
||||||
|
phase_min = float(np.nanmin(phase_unwrapped))
|
||||||
|
phase_max = float(np.nanmax(phase_unwrapped))
|
||||||
|
p_phase.setYRange(phase_min, phase_max, padding=0)
|
||||||
|
# Обновляем вторую ось Y с расстоянием
|
||||||
|
try:
|
||||||
|
dist_min = phase_to_distance(np.array([phase_min]))[0]
|
||||||
|
dist_max = phase_to_distance(np.array([phase_max]))[0]
|
||||||
|
p_phase_dist_axis.setYRange(dist_min, dist_max, padding=0)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
if changed and ring is not None:
|
if changed and ring is not None:
|
||||||
disp = ring if head == 0 else np.roll(ring, -head, axis=0)
|
disp = ring if head == 0 else np.roll(ring, -head, axis=0)
|
||||||
disp = disp.T[:, ::-1] # (width, time with newest at left)
|
disp = disp.T[:, ::-1] # (width, time with newest at left)
|
||||||
@ -1179,6 +1545,28 @@ def run_pyqtgraph(args):
|
|||||||
else:
|
else:
|
||||||
img_fft.setImage(disp_fft, autoLevels=False)
|
img_fft.setImage(disp_fft, autoLevels=False)
|
||||||
|
|
||||||
|
# Обновление водопада фазы
|
||||||
|
if changed and ring_phase is not None:
|
||||||
|
disp_phase = ring_phase if head == 0 else np.roll(ring_phase, -head, axis=0)
|
||||||
|
disp_phase = disp_phase.T[:, ::-1]
|
||||||
|
# Автодиапазон для фазы
|
||||||
|
levels_phase = None
|
||||||
|
try:
|
||||||
|
mean_phase = np.nanmean(disp_phase, axis=1)
|
||||||
|
vmin_p = float(np.nanmin(mean_phase))
|
||||||
|
vmax_p = float(np.nanmax(mean_phase))
|
||||||
|
if np.isfinite(vmin_p) and np.isfinite(vmax_p) and vmin_p != vmax_p:
|
||||||
|
levels_phase = (vmin_p, vmax_p)
|
||||||
|
except Exception:
|
||||||
|
levels_phase = None
|
||||||
|
# Фолбэк к отслеживаемым минимум/максимумам
|
||||||
|
if levels_phase is None and y_min_phase is not None and y_max_phase is not None and np.isfinite(y_min_phase) and np.isfinite(y_max_phase) and y_min_phase != y_max_phase:
|
||||||
|
levels_phase = (y_min_phase, y_max_phase)
|
||||||
|
if levels_phase is not None:
|
||||||
|
img_phase.setImage(disp_phase, autoLevels=False, levels=levels_phase)
|
||||||
|
else:
|
||||||
|
img_phase.setImage(disp_phase, autoLevels=False)
|
||||||
|
|
||||||
timer = pg.QtCore.QTimer()
|
timer = pg.QtCore.QTimer()
|
||||||
timer.timeout.connect(update)
|
timer.timeout.connect(update)
|
||||||
timer.start(interval_ms)
|
timer.start(interval_ms)
|
||||||
|
|||||||
Reference in New Issue
Block a user