Compare commits
1 Commits
stupid
...
64c813bf02
| Author | SHA1 | Date | |
|---|---|---|---|
| 64c813bf02 |
@ -36,11 +36,6 @@ FFT_LEN = 1024 # длина БПФ для спектра/водопада сп
|
|||||||
# Порог для инверсии сырых данных: если среднее значение свипа ниже порога —
|
# Порог для инверсии сырых данных: если среднее значение свипа ниже порога —
|
||||||
# считаем, что сигнал «меньше нуля» и домножаем свип на -1
|
# считаем, что сигнал «меньше нуля» и домножаем свип на -1
|
||||||
DATA_INVERSION_THRASHOLD = 10.0
|
DATA_INVERSION_THRASHOLD = 10.0
|
||||||
LOG_DETECTOR_OFFSET = 0.0
|
|
||||||
LOG_DETECTOR_SCALER = -0.001
|
|
||||||
LOG_DETECTOR_BASE = 2.0
|
|
||||||
LOG_DETECTOR_EXP_MIN = -149.0
|
|
||||||
LOG_DETECTOR_EXP_MAX = 128.0
|
|
||||||
|
|
||||||
Number = Union[int, float]
|
Number = Union[int, float]
|
||||||
SweepInfo = Dict[str, Any]
|
SweepInfo = Dict[str, Any]
|
||||||
@ -64,8 +59,7 @@ def _format_status_kv(data: Mapping[str, Any]) -> str:
|
|||||||
return f"{fv:.3g}"
|
return f"{fv:.3g}"
|
||||||
return f"{fv:.3f}".rstrip("0").rstrip(".")
|
return f"{fv:.3f}".rstrip("0").rstrip(".")
|
||||||
|
|
||||||
hidden_keys = {"pre_exp_sweep", "sweep_1", "sweep_2"}
|
parts = [f"{k}:{_fmt(v)}" for k, v in data.items()]
|
||||||
parts = [f"{k}:{_fmt(v)}" for k, v in data.items() if k not in hidden_keys]
|
|
||||||
return " ".join(parts)
|
return " ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
@ -390,8 +384,6 @@ class SweepReader(threading.Thread):
|
|||||||
out_queue: Queue[SweepPacket],
|
out_queue: Queue[SweepPacket],
|
||||||
stop_event: threading.Event,
|
stop_event: threading.Event,
|
||||||
fancy: bool = False,
|
fancy: bool = False,
|
||||||
bin_mode: bool = False,
|
|
||||||
logdetector: bool = False,
|
|
||||||
):
|
):
|
||||||
super().__init__(daemon=True)
|
super().__init__(daemon=True)
|
||||||
self._port_path = port_path
|
self._port_path = port_path
|
||||||
@ -400,26 +392,12 @@ class SweepReader(threading.Thread):
|
|||||||
self._stop = stop_event
|
self._stop = stop_event
|
||||||
self._src: Optional[SerialLineSource] = None
|
self._src: Optional[SerialLineSource] = None
|
||||||
self._fancy = bool(fancy)
|
self._fancy = bool(fancy)
|
||||||
self._bin_mode = bool(bin_mode)
|
|
||||||
self._logdetector = bool(logdetector)
|
|
||||||
self._max_width: int = 0
|
self._max_width: int = 0
|
||||||
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()
|
||||||
|
|
||||||
@staticmethod
|
def _finalize_current(self, xs, ys, channels: Optional[set[int]]):
|
||||||
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[int]],
|
|
||||||
ys1: Optional[list[int]] = None,
|
|
||||||
ys2: Optional[list[int]] = None,
|
|
||||||
):
|
|
||||||
if not xs:
|
if not xs:
|
||||||
return
|
return
|
||||||
ch_list = sorted(channels) if channels else [0]
|
ch_list = sorted(channels) if channels else [0]
|
||||||
@ -428,26 +406,17 @@ class SweepReader(threading.Thread):
|
|||||||
width = max_x + 1
|
width = max_x + 1
|
||||||
self._max_width = max(self._max_width, width)
|
self._max_width = max(self._max_width, width)
|
||||||
target_width = self._max_width if self._fancy else width
|
target_width = self._max_width if self._fancy else width
|
||||||
def _build_sweep(values) -> np.ndarray:
|
# Быстрый векторизованный путь
|
||||||
arr = np.full((target_width,), np.nan, dtype=np.float32)
|
sweep = np.full((target_width,), np.nan, dtype=np.float32)
|
||||||
try:
|
try:
|
||||||
idx = np.asarray(xs, dtype=np.int64)
|
idx = np.asarray(xs, dtype=np.int64)
|
||||||
vals = np.asarray(values, dtype=np.float32)
|
vals = np.asarray(ys, dtype=np.float32)
|
||||||
arr[idx] = vals
|
sweep[idx] = vals
|
||||||
except Exception:
|
except Exception:
|
||||||
for x, y in zip(xs, values):
|
# Запасной путь
|
||||||
|
for x, y in zip(xs, ys):
|
||||||
if 0 <= x < target_width:
|
if 0 <= x < target_width:
|
||||||
arr[x] = float(y)
|
sweep[x] = float(y)
|
||||||
return arr
|
|
||||||
|
|
||||||
sweep_1: Optional[np.ndarray] = None
|
|
||||||
sweep_2: Optional[np.ndarray] = None
|
|
||||||
if ys1 is not None and ys2 is not None and len(ys1) == len(xs) and len(ys2) == len(xs):
|
|
||||||
sweep_1 = _build_sweep(ys1)
|
|
||||||
sweep_2 = _build_sweep(ys2)
|
|
||||||
sweep = sweep_1 - sweep_2
|
|
||||||
else:
|
|
||||||
sweep = _build_sweep(ys)
|
|
||||||
# Метрики валидных точек до заполнения пропусков
|
# Метрики валидных точек до заполнения пропусков
|
||||||
finite_pre = np.isfinite(sweep)
|
finite_pre = np.isfinite(sweep)
|
||||||
n_valid_cur = int(np.count_nonzero(finite_pre))
|
n_valid_cur = int(np.count_nonzero(finite_pre))
|
||||||
@ -472,45 +441,13 @@ class SweepReader(threading.Thread):
|
|||||||
except Exception:
|
except Exception:
|
||||||
# В случае ошибки просто оставляем как есть
|
# В случае ошибки просто оставляем как есть
|
||||||
pass
|
pass
|
||||||
'''
|
|
||||||
# Инверсия данных при «отрицательном» уровне (среднее ниже порога)
|
# Инверсия данных при «отрицательном» уровне (среднее ниже порога)
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
m = float(np.nanmean(sweep))
|
m = float(np.nanmean(sweep))
|
||||||
if np.isfinite(m) and m < DATA_INVERSION_THRASHOLD:
|
if np.isfinite(m) and m < DATA_INVERSION_THRASHOLD:
|
||||||
sweep *= -1.0
|
sweep *= -1.0
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
'''
|
|
||||||
|
|
||||||
pre_exp_sweep: Optional[np.ndarray] = None
|
|
||||||
if self._logdetector:
|
|
||||||
try:
|
|
||||||
if sweep_1 is not None and sweep_2 is not None:
|
|
||||||
s1_pre = (sweep_1 - LOG_DETECTOR_OFFSET) * LOG_DETECTOR_SCALER
|
|
||||||
s2_pre = (sweep_2 - LOG_DETECTOR_OFFSET) * LOG_DETECTOR_SCALER
|
|
||||||
s1_pre = np.clip(s1_pre, LOG_DETECTOR_EXP_MIN, LOG_DETECTOR_EXP_MAX)
|
|
||||||
s2_pre = np.clip(s2_pre, LOG_DETECTOR_EXP_MIN, LOG_DETECTOR_EXP_MAX)
|
|
||||||
# with np.errstate(over="ignore", invalid="ignore"):
|
|
||||||
# sweep_1 = np.power(LOG_DETECTOR_BASE, np.asarray(s1_pre, dtype=np.float64)).astype(np.float32)
|
|
||||||
# sweep_2 = np.power(LOG_DETECTOR_BASE, np.asarray(s2_pre, dtype=np.float64)).astype(np.float32)
|
|
||||||
sweep_1 = np.power(LOG_DETECTOR_BASE, np.asarray(s1_pre, dtype=np.float64)).astype(np.float32)
|
|
||||||
sweep_2 = np.power(LOG_DETECTOR_BASE, np.asarray(s2_pre, dtype=np.float64)).astype(np.float32)
|
|
||||||
sweep_1[~np.isfinite(sweep_1)] = np.nan
|
|
||||||
sweep_2[~np.isfinite(sweep_2)] = np.nan
|
|
||||||
sweep = sweep_1 - sweep_2
|
|
||||||
else:
|
|
||||||
sweep = (sweep - LOG_DETECTOR_OFFSET) * LOG_DETECTOR_SCALER
|
|
||||||
sweep = np.clip(sweep, LOG_DETECTOR_EXP_MIN, LOG_DETECTOR_EXP_MAX)
|
|
||||||
pre_exp_sweep = sweep.copy()
|
|
||||||
with np.errstate(over="ignore", invalid="ignore"):
|
|
||||||
sweep = np.power(LOG_DETECTOR_BASE, np.asarray(sweep, dtype=np.float64)).astype(np.float32)
|
|
||||||
sweep[~np.isfinite(sweep)] = np.nan
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
#print(sweep)
|
|
||||||
#sweep -= float(np.nanmean(sweep))
|
#sweep -= float(np.nanmean(sweep))
|
||||||
|
|
||||||
# Метрики для статусной строки (вид словаря: переменная -> значение)
|
# Метрики для статусной строки (вид словаря: переменная -> значение)
|
||||||
@ -551,11 +488,6 @@ class SweepReader(threading.Thread):
|
|||||||
"std": std,
|
"std": std,
|
||||||
"dt_ms": dt_ms,
|
"dt_ms": dt_ms,
|
||||||
}
|
}
|
||||||
if pre_exp_sweep is not None:
|
|
||||||
info["pre_exp_sweep"] = pre_exp_sweep
|
|
||||||
if sweep_1 is not None and sweep_2 is not None:
|
|
||||||
info["sweep_1"] = sweep_1
|
|
||||||
info["sweep_2"] = sweep_2
|
|
||||||
|
|
||||||
# Кладём готовый свип (если очередь полна — выбрасываем самый старый)
|
# Кладём готовый свип (если очередь полна — выбрасываем самый старый)
|
||||||
try:
|
try:
|
||||||
@ -570,21 +502,34 @@ class SweepReader(threading.Thread):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def _run_ascii_stream(self, chunk_reader: SerialChunkReader):
|
def run(self):
|
||||||
|
# Состояние текущего свипа
|
||||||
xs: list[int] = []
|
xs: list[int] = []
|
||||||
ys: list[int] = []
|
ys: list[int] = []
|
||||||
cur_channel: Optional[int] = None
|
cur_channel: Optional[int] = None
|
||||||
cur_channels: set[int] = set()
|
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()
|
buf = bytearray()
|
||||||
while not self._stop.is_set():
|
while not self._stop.is_set():
|
||||||
data = chunk_reader.read_available()
|
data = chunk_reader.read_available()
|
||||||
if data:
|
if data:
|
||||||
buf += data
|
buf += data
|
||||||
else:
|
else:
|
||||||
|
# Короткая уступка CPU, если нет новых данных
|
||||||
time.sleep(0.0005)
|
time.sleep(0.0005)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# Обрабатываем все полные строки
|
||||||
while True:
|
while True:
|
||||||
nl = buf.find(b"\n")
|
nl = buf.find(b"\n")
|
||||||
if nl == -1:
|
if nl == -1:
|
||||||
@ -604,6 +549,7 @@ class SweepReader(threading.Thread):
|
|||||||
cur_channels.clear()
|
cur_channels.clear()
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# sCH X Y или s CH X Y (все целые со знаком). Разделяем по любым пробелам/табам.
|
||||||
if len(line) >= 3:
|
if len(line) >= 3:
|
||||||
parts = line.split()
|
parts = line.split()
|
||||||
if len(parts) >= 3 and (parts[0].lower() == b"s" or parts[0].lower().startswith(b"s")):
|
if len(parts) >= 3 and (parts[0].lower() == b"s" or parts[0].lower().startswith(b"s")):
|
||||||
@ -612,15 +558,16 @@ class SweepReader(threading.Thread):
|
|||||||
if len(parts) >= 4:
|
if len(parts) >= 4:
|
||||||
ch = int(parts[1], 10)
|
ch = int(parts[1], 10)
|
||||||
x = int(parts[2], 10)
|
x = int(parts[2], 10)
|
||||||
y = int(parts[3], 10)
|
y = int(parts[3], 10) # поддержка знака: "+…" и "-…"
|
||||||
else:
|
else:
|
||||||
ch = 0
|
ch = 0
|
||||||
x = int(parts[1], 10)
|
x = int(parts[1], 10)
|
||||||
y = int(parts[2], 10)
|
y = int(parts[2], 10) # поддержка знака: "+…" и "-…"
|
||||||
else:
|
else:
|
||||||
|
# формат вида "s0"
|
||||||
ch = int(parts[0][1:], 10)
|
ch = int(parts[0][1:], 10)
|
||||||
x = int(parts[1], 10)
|
x = int(parts[1], 10)
|
||||||
y = int(parts[2], 10)
|
y = int(parts[2], 10) # поддержка знака: "+…" и "-…"
|
||||||
except Exception:
|
except Exception:
|
||||||
continue
|
continue
|
||||||
if cur_channel is None:
|
if cur_channel is None:
|
||||||
@ -629,104 +576,15 @@ class SweepReader(threading.Thread):
|
|||||||
xs.append(x)
|
xs.append(x)
|
||||||
ys.append(y)
|
ys.append(y)
|
||||||
|
|
||||||
|
# Защита от переполнения буфера при отсутствии переводов строки
|
||||||
if len(buf) > 1_000_000:
|
if len(buf) > 1_000_000:
|
||||||
del buf[:-262144]
|
del buf[:-262144]
|
||||||
|
|
||||||
self._finalize_current(xs, ys, cur_channels)
|
|
||||||
|
|
||||||
def _run_binary_stream(self, chunk_reader: SerialChunkReader):
|
|
||||||
xs: list[int] = []
|
|
||||||
ys: list[int] = []
|
|
||||||
ys1: list[int] = []
|
|
||||||
ys2: list[int] = []
|
|
||||||
cur_channel: Optional[int] = None
|
|
||||||
cur_channels: set[int] = set()
|
|
||||||
words = deque()
|
|
||||||
|
|
||||||
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)
|
|
||||||
words.append(w)
|
|
||||||
i += 2
|
|
||||||
|
|
||||||
# Новый бинарный формат:
|
|
||||||
# - старт: FFFF,FFFF,FFFF,FFFF,FFFF,(CH<<8)|0x0A
|
|
||||||
# - точка: X,avg1_hi,avg1_lo,avg2_hi,avg2_lo,0x000A
|
|
||||||
while len(words) >= 6:
|
|
||||||
w0 = int(words[0])
|
|
||||||
w1 = int(words[1])
|
|
||||||
w2 = int(words[2])
|
|
||||||
w3 = int(words[3])
|
|
||||||
w4 = int(words[4])
|
|
||||||
w5 = int(words[5])
|
|
||||||
|
|
||||||
if (
|
|
||||||
w0 == 0xFFFF and w1 == 0xFFFF and w2 == 0xFFFF
|
|
||||||
and w3 == 0xFFFF and w4 == 0xFFFF and (w5 & 0x00FF) == 0x000A
|
|
||||||
):
|
|
||||||
self._finalize_current(xs, ys, cur_channels, ys1=ys1, ys2=ys2)
|
|
||||||
xs.clear()
|
|
||||||
ys.clear()
|
|
||||||
ys1.clear()
|
|
||||||
ys2.clear()
|
|
||||||
cur_channels.clear()
|
|
||||||
cur_channel = (w5 >> 8) & 0x00FF
|
|
||||||
cur_channels.add(cur_channel)
|
|
||||||
for _ in range(6):
|
|
||||||
words.popleft()
|
|
||||||
continue
|
|
||||||
|
|
||||||
if w5 == 0x000A:
|
|
||||||
if cur_channel is not None:
|
|
||||||
cur_channels.add(cur_channel)
|
|
||||||
xs.append(w0)
|
|
||||||
avg1_u32 = (w1 << 16) | w2
|
|
||||||
avg2_u32 = (w3 << 16) | w4
|
|
||||||
avg1 = self._u32_to_i32(avg1_u32)
|
|
||||||
avg2 = self._u32_to_i32(avg2_u32)
|
|
||||||
ys1.append(avg1)
|
|
||||||
ys2.append(avg2)
|
|
||||||
ys.append(avg1 - avg2)
|
|
||||||
for _ in range(6):
|
|
||||||
words.popleft()
|
|
||||||
continue
|
|
||||||
|
|
||||||
words.popleft()
|
|
||||||
|
|
||||||
del buf[:usable]
|
|
||||||
if len(buf) > 1_000_000:
|
|
||||||
del buf[:-262144]
|
|
||||||
|
|
||||||
self._finalize_current(xs, ys, cur_channels, ys1=ys1, ys2=ys2)
|
|
||||||
|
|
||||||
def run(self):
|
|
||||||
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)
|
|
||||||
if self._bin_mode:
|
|
||||||
self._run_binary_stream(chunk_reader)
|
|
||||||
else:
|
|
||||||
self._run_ascii_stream(chunk_reader)
|
|
||||||
finally:
|
finally:
|
||||||
|
try:
|
||||||
|
# Завершаем оставшийся свип
|
||||||
|
self._finalize_current(xs, ys, cur_channels)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
try:
|
try:
|
||||||
if self._src is not None:
|
if self._src is not None:
|
||||||
self._src.close()
|
self._src.close()
|
||||||
@ -753,7 +611,7 @@ def main():
|
|||||||
"--spec-clip",
|
"--spec-clip",
|
||||||
default="2,98",
|
default="2,98",
|
||||||
help=(
|
help=(
|
||||||
"Процентильная обрезка уровней водопада спектров, %% (min,max). "
|
"Процентильная обрезка уровней водопада спектров, % (min,max). "
|
||||||
"Напр. 2,98. 'off' — отключить"
|
"Напр. 2,98. 'off' — отключить"
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@ -790,21 +648,6 @@ def main():
|
|||||||
default="projector",
|
default="projector",
|
||||||
help="Тип нормировки: projector (по огибающим в [-1,+1]) или simple (raw/calib)",
|
help="Тип нормировки: projector (по огибающим в [-1,+1]) или simple (raw/calib)",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
|
||||||
"--bin",
|
|
||||||
dest="bin_mode",
|
|
||||||
action="store_true",
|
|
||||||
default=True,
|
|
||||||
help=(
|
|
||||||
"Бинарный протокол: старт FFFFx5,(CH<<8)|0x0A; "
|
|
||||||
"точки X,avg1_hi,avg1_lo,avg2_hi,avg2_lo,0x000A (sweep=avg1-avg2)"
|
|
||||||
),
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--logdetector",
|
|
||||||
action="store_true",
|
|
||||||
help="Лог-детектор: после инверсии ((sweep-OFFSET)*SCALER) и затем BASE**sweep",
|
|
||||||
)
|
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
@ -830,15 +673,7 @@ def main():
|
|||||||
# Очередь завершённых свипов и поток чтения
|
# Очередь завершённых свипов и поток чтения
|
||||||
q: Queue[SweepPacket] = Queue(maxsize=1000)
|
q: Queue[SweepPacket] = Queue(maxsize=1000)
|
||||||
stop_event = threading.Event()
|
stop_event = threading.Event()
|
||||||
reader = SweepReader(
|
reader = SweepReader(args.port, args.baud, q, stop_event, fancy=bool(args.fancy))
|
||||||
args.port,
|
|
||||||
args.baud,
|
|
||||||
q,
|
|
||||||
stop_event,
|
|
||||||
fancy=bool(args.fancy),
|
|
||||||
bin_mode=bool(getattr(args, "bin_mode", False)),
|
|
||||||
logdetector=bool(getattr(args, "logdetector", False)),
|
|
||||||
)
|
|
||||||
reader.start()
|
reader.start()
|
||||||
|
|
||||||
# Графика
|
# Графика
|
||||||
@ -850,9 +685,6 @@ def main():
|
|||||||
|
|
||||||
# Состояние для отображения
|
# Состояние для отображения
|
||||||
current_sweep_raw: Optional[np.ndarray] = None
|
current_sweep_raw: Optional[np.ndarray] = None
|
||||||
current_sweep_1: Optional[np.ndarray] = None
|
|
||||||
current_sweep_2: Optional[np.ndarray] = None
|
|
||||||
current_sweep_pre_exp: Optional[np.ndarray] = None
|
|
||||||
current_sweep_norm: Optional[np.ndarray] = None
|
current_sweep_norm: Optional[np.ndarray] = None
|
||||||
last_calib_sweep: Optional[np.ndarray] = None
|
last_calib_sweep: Optional[np.ndarray] = None
|
||||||
current_info: Optional[SweepInfo] = None
|
current_info: Optional[SweepInfo] = None
|
||||||
@ -877,7 +709,6 @@ def main():
|
|||||||
contrast_slider = None
|
contrast_slider = None
|
||||||
calib_enabled = False
|
calib_enabled = False
|
||||||
norm_type = str(getattr(args, "norm_type", "projector")).strip().lower()
|
norm_type = str(getattr(args, "norm_type", "projector")).strip().lower()
|
||||||
logdetector_enabled = bool(getattr(args, "logdetector", False))
|
|
||||||
cb = None
|
cb = None
|
||||||
|
|
||||||
# Статусная строка (внизу окна)
|
# Статусная строка (внизу окна)
|
||||||
@ -893,10 +724,10 @@ def main():
|
|||||||
|
|
||||||
# Линейный график последнего свипа
|
# Линейный график последнего свипа
|
||||||
line_obj, = ax_line.plot([], [], lw=1, color="tab:blue")
|
line_obj, = ax_line.plot([], [], lw=1, color="tab:blue")
|
||||||
line_calib_obj, = ax_line.plot([], [], lw=1, color="gold")
|
line_calib_obj, = ax_line.plot([], [], lw=1, color="tab:red")
|
||||||
line_norm_obj, = ax_line.plot([], [], lw=1, color="tab:green")
|
line_norm_obj, = ax_line.plot([], [], lw=1, color="tab:green")
|
||||||
ax_line.set_title("Сырые данные", pad=1)
|
ax_line.set_title("Сырые данные", pad=1)
|
||||||
ax_line.set_xlabel("ГГц")
|
ax_line.set_xlabel("F")
|
||||||
ax_line.set_ylabel("")
|
ax_line.set_ylabel("")
|
||||||
channel_text = ax_line.text(
|
channel_text = ax_line.text(
|
||||||
0.98,
|
0.98,
|
||||||
@ -912,8 +743,8 @@ def main():
|
|||||||
# Линейный график спектра текущего свипа
|
# Линейный график спектра текущего свипа
|
||||||
fft_line_obj, = ax_fft.plot([], [], lw=1)
|
fft_line_obj, = ax_fft.plot([], [], lw=1)
|
||||||
ax_fft.set_title("FFT", pad=1)
|
ax_fft.set_title("FFT", pad=1)
|
||||||
ax_fft.set_xlabel("Время")
|
ax_fft.set_xlabel("X")
|
||||||
ax_fft.set_ylabel("дБ")
|
ax_fft.set_ylabel("Амплитуда, дБ")
|
||||||
|
|
||||||
# Диапазон по Y для последнего свипа: авто по умолчанию (поддерживает отрицательные значения)
|
# Диапазон по Y для последнего свипа: авто по умолчанию (поддерживает отрицательные значения)
|
||||||
fixed_ylim: Optional[Tuple[float, float]] = None
|
fixed_ylim: Optional[Tuple[float, float]] = None
|
||||||
@ -937,7 +768,7 @@ def main():
|
|||||||
)
|
)
|
||||||
ax_img.set_title("Сырые данные", pad=12)
|
ax_img.set_title("Сырые данные", pad=12)
|
||||||
ax_img.set_xlabel("")
|
ax_img.set_xlabel("")
|
||||||
ax_img.set_ylabel("ГГц")
|
ax_img.set_ylabel("частота")
|
||||||
# Не показываем численные значения по времени на водопаде сырых данных
|
# Не показываем численные значения по времени на водопаде сырых данных
|
||||||
try:
|
try:
|
||||||
ax_img.tick_params(axis="x", labelbottom=False)
|
ax_img.tick_params(axis="x", labelbottom=False)
|
||||||
@ -1014,15 +845,15 @@ def main():
|
|||||||
if ring is not None:
|
if ring is not None:
|
||||||
return
|
return
|
||||||
width = WF_WIDTH
|
width = WF_WIDTH
|
||||||
x_shared = np.linspace(3.3, 14.3, width, dtype=np.float32)
|
x_shared = np.arange(width, dtype=np.int32)
|
||||||
ring = np.full((max_sweeps, width), np.nan, dtype=np.float32)
|
ring = np.full((max_sweeps, width), np.nan, dtype=np.float32)
|
||||||
ring_time = np.full((max_sweeps,), np.nan, dtype=np.float64)
|
ring_time = np.full((max_sweeps,), np.nan, dtype=np.float64)
|
||||||
head = 0
|
head = 0
|
||||||
# Обновляем изображение под новые размеры: время по X (горизонталь), X по Y
|
# Обновляем изображение под новые размеры: время по X (горизонталь), X по Y
|
||||||
img_obj.set_data(np.zeros((width, max_sweeps), dtype=np.float32))
|
img_obj.set_data(np.zeros((width, max_sweeps), dtype=np.float32))
|
||||||
img_obj.set_extent((0, max_sweeps - 1, 3.3, 14.3))
|
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_xlim(0, max_sweeps - 1)
|
||||||
ax_img.set_ylim(3.3, 14.3)
|
ax_img.set_ylim(0, max(1, width - 1))
|
||||||
# FFT буферы: время по X, бин по Y
|
# FFT буферы: время по X, бин по Y
|
||||||
ring_fft = np.full((max_sweeps, fft_bins), np.nan, dtype=np.float32)
|
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_data(np.zeros((fft_bins, max_sweeps), dtype=np.float32))
|
||||||
@ -1094,7 +925,7 @@ def main():
|
|||||||
# Окно Хэннинга
|
# Окно Хэннинга
|
||||||
win = np.hanning(take_fft).astype(np.float32)
|
win = np.hanning(take_fft).astype(np.float32)
|
||||||
fft_in[:take_fft] = seg * win
|
fft_in[:take_fft] = seg * win
|
||||||
spec = np.fft.ifft(fft_in)
|
spec = np.fft.rfft(fft_in)
|
||||||
mag = np.abs(spec).astype(np.float32)
|
mag = np.abs(spec).astype(np.float32)
|
||||||
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:
|
||||||
@ -1111,7 +942,7 @@ def main():
|
|||||||
y_max_fft = float(fr_max)
|
y_max_fft = float(fr_max)
|
||||||
|
|
||||||
def drain_queue():
|
def drain_queue():
|
||||||
nonlocal current_sweep_raw, current_sweep_1, current_sweep_2, current_sweep_pre_exp, current_sweep_norm, current_info, last_calib_sweep
|
nonlocal current_sweep_raw, current_sweep_norm, current_info, last_calib_sweep
|
||||||
drained = 0
|
drained = 0
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
@ -1121,12 +952,6 @@ def main():
|
|||||||
drained += 1
|
drained += 1
|
||||||
current_sweep_raw = s
|
current_sweep_raw = s
|
||||||
current_info = info
|
current_info = info
|
||||||
s1 = info.get("sweep_1") if isinstance(info, dict) else None
|
|
||||||
s2 = info.get("sweep_2") if isinstance(info, dict) else None
|
|
||||||
current_sweep_1 = s1 if isinstance(s1, np.ndarray) else None
|
|
||||||
current_sweep_2 = s2 if isinstance(s2, np.ndarray) else None
|
|
||||||
pre = info.get("pre_exp_sweep") if isinstance(info, dict) else None
|
|
||||||
current_sweep_pre_exp = pre if isinstance(pre, np.ndarray) else None
|
|
||||||
ch = 0
|
ch = 0
|
||||||
try:
|
try:
|
||||||
ch = int(info.get("ch", 0)) if isinstance(info, dict) else 0
|
ch = int(info.get("ch", 0)) if isinstance(info, dict) else 0
|
||||||
@ -1195,16 +1020,6 @@ def main():
|
|||||||
else:
|
else:
|
||||||
xs = np.arange(current_sweep_raw.size, dtype=np.int32)
|
xs = np.arange(current_sweep_raw.size, dtype=np.int32)
|
||||||
line_obj.set_data(xs, current_sweep_raw)
|
line_obj.set_data(xs, current_sweep_raw)
|
||||||
if current_sweep_1 is not None and current_sweep_2 is not None:
|
|
||||||
line_calib_obj.set_data(xs[: current_sweep_1.size], current_sweep_1)
|
|
||||||
line_norm_obj.set_data(xs[: current_sweep_2.size], current_sweep_2)
|
|
||||||
elif logdetector_enabled:
|
|
||||||
line_calib_obj.set_data([], [])
|
|
||||||
if current_sweep_pre_exp is not None:
|
|
||||||
line_norm_obj.set_data(xs[: current_sweep_pre_exp.size], current_sweep_pre_exp)
|
|
||||||
else:
|
|
||||||
line_norm_obj.set_data([], [])
|
|
||||||
else:
|
|
||||||
if last_calib_sweep is not None:
|
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], last_calib_sweep)
|
||||||
else:
|
else:
|
||||||
@ -1213,18 +1028,12 @@ def main():
|
|||||||
line_norm_obj.set_data(xs[: current_sweep_norm.size], current_sweep_norm)
|
line_norm_obj.set_data(xs[: current_sweep_norm.size], current_sweep_norm)
|
||||||
else:
|
else:
|
||||||
line_norm_obj.set_data([], [])
|
line_norm_obj.set_data([], [])
|
||||||
# Лимиты по X: 3.3 ГГц .. 14.3 ГГц
|
# Лимиты по X постоянные под текущую ширину
|
||||||
ax_line.set_xlim(3.3, 14.3)
|
ax_line.set_xlim(0, max(1, current_sweep_raw.size - 1))
|
||||||
# Адаптивные Y-лимиты (если не задан --ylim)
|
# Адаптивные Y-лимиты (если не задан --ylim)
|
||||||
if fixed_ylim is None:
|
if fixed_ylim is None:
|
||||||
y_candidates = [current_sweep_raw]
|
y0 = float(np.nanmin(current_sweep_raw))
|
||||||
if current_sweep_1 is not None and current_sweep_2 is not None:
|
y1 = float(np.nanmax(current_sweep_raw))
|
||||||
y_candidates.extend([current_sweep_1, current_sweep_2])
|
|
||||||
elif logdetector_enabled and current_sweep_pre_exp is not None:
|
|
||||||
y_candidates.append(current_sweep_pre_exp)
|
|
||||||
y_concat = np.concatenate([np.asarray(v, dtype=np.float32) for v in y_candidates])
|
|
||||||
y0 = float(np.nanmin(y_concat))
|
|
||||||
y1 = float(np.nanmax(y_concat))
|
|
||||||
if np.isfinite(y0) and np.isfinite(y1):
|
if np.isfinite(y0) and np.isfinite(y1):
|
||||||
if y0 == y1:
|
if y0 == y1:
|
||||||
pad = max(1.0, abs(y0) * 0.05)
|
pad = max(1.0, abs(y0) * 0.05)
|
||||||
@ -1244,7 +1053,7 @@ def main():
|
|||||||
seg = np.nan_to_num(sweep_for_fft[:take_fft], nan=0.0).astype(np.float32, copy=False)
|
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)
|
win = np.hanning(take_fft).astype(np.float32)
|
||||||
fft_in[:take_fft] = seg * win
|
fft_in[:take_fft] = seg * win
|
||||||
spec = np.fft.ifft(fft_in)
|
spec = np.fft.rfft(fft_in)
|
||||||
mag = np.abs(spec).astype(np.float32)
|
mag = np.abs(spec).astype(np.float32)
|
||||||
fft_vals = 20.0 * np.log10(mag + 1e-9)
|
fft_vals = 20.0 * np.log10(mag + 1e-9)
|
||||||
xs_fft = freq_shared
|
xs_fft = freq_shared
|
||||||
@ -1253,7 +1062,7 @@ def main():
|
|||||||
fft_line_obj.set_data(xs_fft[: fft_vals.size], fft_vals)
|
fft_line_obj.set_data(xs_fft[: fft_vals.size], fft_vals)
|
||||||
# Авто-диапазон по Y для спектра
|
# Авто-диапазон по Y для спектра
|
||||||
if np.isfinite(np.nanmin(fft_vals)) and np.isfinite(np.nanmax(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) * 1.5)
|
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)))
|
||||||
|
|
||||||
# Обновление водопада
|
# Обновление водопада
|
||||||
@ -1359,15 +1168,7 @@ def run_pyqtgraph(args):
|
|||||||
# Очередь завершённых свипов и поток чтения
|
# Очередь завершённых свипов и поток чтения
|
||||||
q: Queue[SweepPacket] = Queue(maxsize=1000)
|
q: Queue[SweepPacket] = Queue(maxsize=1000)
|
||||||
stop_event = threading.Event()
|
stop_event = threading.Event()
|
||||||
reader = SweepReader(
|
reader = SweepReader(args.port, args.baud, q, stop_event, fancy=bool(args.fancy))
|
||||||
args.port,
|
|
||||||
args.baud,
|
|
||||||
q,
|
|
||||||
stop_event,
|
|
||||||
fancy=bool(args.fancy),
|
|
||||||
bin_mode=bool(getattr(args, "bin_mode", False)),
|
|
||||||
logdetector=bool(getattr(args, "logdetector", False)),
|
|
||||||
)
|
|
||||||
reader.start()
|
reader.start()
|
||||||
|
|
||||||
# Настройки скорости
|
# Настройки скорости
|
||||||
@ -1385,9 +1186,9 @@ def run_pyqtgraph(args):
|
|||||||
p_line = win.addPlot(row=0, col=0, title="Сырые данные")
|
p_line = win.addPlot(row=0, col=0, title="Сырые данные")
|
||||||
p_line.showGrid(x=True, y=True, alpha=0.3)
|
p_line.showGrid(x=True, y=True, alpha=0.3)
|
||||||
curve = p_line.plot(pen=pg.mkPen((80, 120, 255), width=1))
|
curve = p_line.plot(pen=pg.mkPen((80, 120, 255), width=1))
|
||||||
curve_calib = p_line.plot(pen=pg.mkPen((220, 200, 60), 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))
|
curve_norm = p_line.plot(pen=pg.mkPen((60, 180, 90), width=1))
|
||||||
p_line.setLabel("bottom", "ГГц")
|
p_line.setLabel("bottom", "X")
|
||||||
p_line.setLabel("left", "Y")
|
p_line.setLabel("left", "Y")
|
||||||
ch_text = pg.TextItem("", anchor=(1, 1))
|
ch_text = pg.TextItem("", anchor=(1, 1))
|
||||||
ch_text.setZValue(10)
|
ch_text.setZValue(10)
|
||||||
@ -1402,7 +1203,7 @@ def run_pyqtgraph(args):
|
|||||||
p_img.getAxis("bottom").setStyle(showValues=False)
|
p_img.getAxis("bottom").setStyle(showValues=False)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
p_img.setLabel("left", "ГГц")
|
p_img.setLabel("left", "X (0 снизу)")
|
||||||
img = pg.ImageItem()
|
img = pg.ImageItem()
|
||||||
p_img.addItem(img)
|
p_img.addItem(img)
|
||||||
|
|
||||||
@ -1410,8 +1211,8 @@ def run_pyqtgraph(args):
|
|||||||
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 (дБ)")
|
||||||
@ -1443,9 +1244,6 @@ def run_pyqtgraph(args):
|
|||||||
width: Optional[int] = None
|
width: Optional[int] = None
|
||||||
x_shared: Optional[np.ndarray] = None
|
x_shared: Optional[np.ndarray] = None
|
||||||
current_sweep_raw: Optional[np.ndarray] = None
|
current_sweep_raw: Optional[np.ndarray] = None
|
||||||
current_sweep_1: Optional[np.ndarray] = None
|
|
||||||
current_sweep_2: Optional[np.ndarray] = None
|
|
||||||
current_sweep_pre_exp: Optional[np.ndarray] = None
|
|
||||||
current_sweep_norm: Optional[np.ndarray] = None
|
current_sweep_norm: Optional[np.ndarray] = None
|
||||||
last_calib_sweep: Optional[np.ndarray] = None
|
last_calib_sweep: Optional[np.ndarray] = None
|
||||||
current_info: Optional[SweepInfo] = None
|
current_info: Optional[SweepInfo] = None
|
||||||
@ -1460,7 +1258,6 @@ def run_pyqtgraph(args):
|
|||||||
spec_mean_sec = float(getattr(args, "spec_mean_sec", 0.0))
|
spec_mean_sec = float(getattr(args, "spec_mean_sec", 0.0))
|
||||||
calib_enabled = False
|
calib_enabled = False
|
||||||
norm_type = str(getattr(args, "norm_type", "projector")).strip().lower()
|
norm_type = str(getattr(args, "norm_type", "projector")).strip().lower()
|
||||||
logdetector_enabled = bool(getattr(args, "logdetector", False))
|
|
||||||
# Диапазон по Y: авто по умолчанию (поддерживает отрицательные значения)
|
# Диапазон по Y: авто по умолчанию (поддерживает отрицательные значения)
|
||||||
fixed_ylim: Optional[Tuple[float, float]] = None
|
fixed_ylim: Optional[Tuple[float, float]] = None
|
||||||
if args.ylim:
|
if args.ylim:
|
||||||
@ -1496,15 +1293,14 @@ def run_pyqtgraph(args):
|
|||||||
if ring is not None:
|
if ring is not None:
|
||||||
return
|
return
|
||||||
width = WF_WIDTH
|
width = WF_WIDTH
|
||||||
x_shared = np.linspace(3.3, 14.3, width, dtype=np.float32)
|
x_shared = np.arange(width, dtype=np.int32)
|
||||||
ring = np.full((max_sweeps, width), np.nan, dtype=np.float32)
|
ring = np.full((max_sweeps, width), np.nan, dtype=np.float32)
|
||||||
ring_time = np.full((max_sweeps,), np.nan, dtype=np.float64)
|
ring_time = np.full((max_sweeps,), np.nan, dtype=np.float64)
|
||||||
head = 0
|
head = 0
|
||||||
# Водопад: время по оси X, X по оси Y (ось Y: 3.3..14.3 ГГц)
|
# Водопад: время по оси X, X по оси Y
|
||||||
img.setImage(ring.T, autoLevels=False)
|
img.setImage(ring.T, autoLevels=False)
|
||||||
img.setRect(0, 3.3, max_sweeps, 14.3 - 3.3)
|
p_img.setRange(xRange=(0, max_sweeps - 1), yRange=(0, max(1, width - 1)), padding=0)
|
||||||
p_img.setRange(xRange=(0, max_sweeps - 1), yRange=(3.3, 14.3), padding=0)
|
p_line.setXRange(0, max(1, width - 1), padding=0)
|
||||||
p_line.setXRange(3.3, 14.3, padding=0)
|
|
||||||
# FFT: время по оси X, бин по оси Y
|
# FFT: время по оси X, бин по оси Y
|
||||||
ring_fft = np.full((max_sweeps, fft_bins), np.nan, dtype=np.float32)
|
ring_fft = np.full((max_sweeps, fft_bins), np.nan, dtype=np.float32)
|
||||||
img_fft.setImage(ring_fft.T, autoLevels=False)
|
img_fft.setImage(ring_fft.T, autoLevels=False)
|
||||||
@ -1564,7 +1360,7 @@ def run_pyqtgraph(args):
|
|||||||
seg = np.nan_to_num(s[:take_fft], nan=0.0).astype(np.float32, copy=False)
|
seg = np.nan_to_num(s[:take_fft], nan=0.0).astype(np.float32, copy=False)
|
||||||
win = np.hanning(take_fft).astype(np.float32)
|
win = np.hanning(take_fft).astype(np.float32)
|
||||||
fft_in[:take_fft] = seg * win
|
fft_in[:take_fft] = seg * win
|
||||||
spec = np.fft.ifft(fft_in)
|
spec = np.fft.rfft(fft_in)
|
||||||
mag = np.abs(spec).astype(np.float32)
|
mag = np.abs(spec).astype(np.float32)
|
||||||
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:
|
||||||
@ -1580,7 +1376,7 @@ def run_pyqtgraph(args):
|
|||||||
y_max_fft = float(fr_max)
|
y_max_fft = float(fr_max)
|
||||||
|
|
||||||
def drain_queue():
|
def drain_queue():
|
||||||
nonlocal current_sweep_raw, current_sweep_1, current_sweep_2, current_sweep_pre_exp, current_sweep_norm, current_info, last_calib_sweep
|
nonlocal current_sweep_raw, current_sweep_norm, current_info, last_calib_sweep
|
||||||
drained = 0
|
drained = 0
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
@ -1590,12 +1386,6 @@ def run_pyqtgraph(args):
|
|||||||
drained += 1
|
drained += 1
|
||||||
current_sweep_raw = s
|
current_sweep_raw = s
|
||||||
current_info = info
|
current_info = info
|
||||||
s1 = info.get("sweep_1") if isinstance(info, dict) else None
|
|
||||||
s2 = info.get("sweep_2") if isinstance(info, dict) else None
|
|
||||||
current_sweep_1 = s1 if isinstance(s1, np.ndarray) else None
|
|
||||||
current_sweep_2 = s2 if isinstance(s2, np.ndarray) else None
|
|
||||||
pre = info.get("pre_exp_sweep") if isinstance(info, dict) else None
|
|
||||||
current_sweep_pre_exp = pre if isinstance(pre, np.ndarray) else None
|
|
||||||
ch = 0
|
ch = 0
|
||||||
try:
|
try:
|
||||||
ch = int(info.get("ch", 0)) if isinstance(info, dict) else 0
|
ch = int(info.get("ch", 0)) if isinstance(info, dict) else 0
|
||||||
@ -1633,16 +1423,6 @@ def run_pyqtgraph(args):
|
|||||||
else:
|
else:
|
||||||
xs = np.arange(current_sweep_raw.size)
|
xs = np.arange(current_sweep_raw.size)
|
||||||
curve.setData(xs, current_sweep_raw, autoDownsample=True)
|
curve.setData(xs, current_sweep_raw, autoDownsample=True)
|
||||||
if current_sweep_1 is not None and current_sweep_2 is not None:
|
|
||||||
curve_calib.setData(xs[: current_sweep_1.size], current_sweep_1, autoDownsample=True)
|
|
||||||
curve_norm.setData(xs[: current_sweep_2.size], current_sweep_2, autoDownsample=True)
|
|
||||||
elif logdetector_enabled:
|
|
||||||
curve_calib.setData([], [])
|
|
||||||
if current_sweep_pre_exp is not None:
|
|
||||||
curve_norm.setData(xs[: current_sweep_pre_exp.size], current_sweep_pre_exp, autoDownsample=True)
|
|
||||||
else:
|
|
||||||
curve_norm.setData([], [])
|
|
||||||
else:
|
|
||||||
if last_calib_sweep is not None:
|
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], last_calib_sweep, autoDownsample=True)
|
||||||
else:
|
else:
|
||||||
@ -1652,14 +1432,8 @@ def run_pyqtgraph(args):
|
|||||||
else:
|
else:
|
||||||
curve_norm.setData([], [])
|
curve_norm.setData([], [])
|
||||||
if fixed_ylim is None:
|
if fixed_ylim is None:
|
||||||
y_candidates = [current_sweep_raw]
|
y0 = float(np.nanmin(current_sweep_raw))
|
||||||
if current_sweep_1 is not None and current_sweep_2 is not None:
|
y1 = float(np.nanmax(current_sweep_raw))
|
||||||
y_candidates.extend([current_sweep_1, current_sweep_2])
|
|
||||||
elif logdetector_enabled and current_sweep_pre_exp is not None:
|
|
||||||
y_candidates.append(current_sweep_pre_exp)
|
|
||||||
y_concat = np.concatenate([np.asarray(v, dtype=np.float32) for v in y_candidates])
|
|
||||||
y0 = float(np.nanmin(y_concat))
|
|
||||||
y1 = float(np.nanmax(y_concat))
|
|
||||||
if np.isfinite(y0) and np.isfinite(y1):
|
if np.isfinite(y0) and np.isfinite(y1):
|
||||||
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)
|
||||||
@ -1672,14 +1446,13 @@ def run_pyqtgraph(args):
|
|||||||
seg = np.nan_to_num(sweep_for_fft[:take_fft], nan=0.0).astype(np.float32, copy=False)
|
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)
|
win = np.hanning(take_fft).astype(np.float32)
|
||||||
fft_in[:take_fft] = seg * win
|
fft_in[:take_fft] = seg * win
|
||||||
spec = np.fft.ifft(fft_in)
|
spec = np.fft.rfft(fft_in)
|
||||||
mag = np.abs(spec).astype(np.float32)
|
mag = np.abs(spec).astype(np.float32)
|
||||||
fft_vals = 20.0 * np.log10(mag + 1e-9)
|
fft_vals = 20.0 * np.log10(mag + 1e-9)
|
||||||
xs_fft = freq_shared
|
xs_fft = freq_shared
|
||||||
if fft_vals.size > xs_fft.size:
|
if fft_vals.size > xs_fft.size:
|
||||||
fft_vals = fft_vals[: xs_fft.size]
|
fft_vals = fft_vals[: xs_fft.size]
|
||||||
curve_fft.setData(xs_fft[: fft_vals.size], fft_vals)
|
curve_fft.setData(xs_fft[: fft_vals.size], fft_vals)
|
||||||
p_fft.setXRange(0, max(1, xs_fft.size - 1) * 1.5, padding=0)
|
|
||||||
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)
|
||||||
|
|
||||||
if changed and ring is not None:
|
if changed and ring is not None:
|
||||||
|
|||||||
Reference in New Issue
Block a user