Вьювер TMCGROUT — графики S-параметров по частоте
Назначение и место в пакете
TMCGROUT (tmcgrout.exe) строит графики элементов матрицы рассеяния по частоте. Данные
берутся из файлов .s, которые пишут счётные ядра PlanarRT_H/PlanarRT_X и TMCROS
(формат и чтение — библиотека sfile95). Программа ничего не считает
физически: она переводит комплексные значения в выбранную величину (КСВ,
потери в дБ, модуль, фаза) и рисует их, а также умеет строить кривые-выражения —
формулы над несколькими файлами .s (библиотеки Inter/Expr).
Список графиков, оси, цвета и шрифт хранятся в файле документа .soc — текстовом
файле, который можно править и вручную. Откуда берутся значения S и как они
нормированы, описано в теории: S-матрица по сигналам,
нормировка.
Программа собрана из двух слоёв:
src/viewers/tmcgrout— код Windows-версии без изменений: документ, вид, диалоги, выражения. Он обращается к классам MFC, которые реализует слой совместимости на Qt 6; рисование идёт через GDI поверх QPainter, в палитре проекта.src/viewers/Tmcgrout/qt— Qt-оболочка: точка входа, главное окно с меню, панелью и строкой состояния, разметка диалогов, тестовые программы.
Тот же код документа, вида и диалогов в изменённых копиях лежит у TMCROS
(viewers/tmcrtout, сигналы во времени) и TMC_DN (viewers/dianapgr, диаграммы
направленности). Общие для трёх вьюверов устройства — список графиков, окно графика,
оси, сетка, легенда, выражения — описаны на этой странице
(общее для вьюверов).
Состав
| Файл | Роль |
|---|---|
src/viewers/tmcgrout/tmcgroutdoc.h/.cpp |
CTMCGROUTDoc — документ: файл .soc, список графиков, чтение .s и выражений, пути |
src/viewers/tmcgrout/tmcgroutview.h/.cpp |
CTMCGROUTView — вид: подготовка точек, сетка, оси, линии, маркеры, легенда, мышь, масштаб, все команды меню; функции строки состояния PutTrace, PutStatistics |
src/viewers/tmcgrout/tmcgrexpression.cpp |
CTMCGrExpression — кривая-выражение (объявление — в общем src/Include/tmcgrexpression.h) |
src/viewers/tmcgrout/tmcgroutdialogview.h/.cpp |
окно Viewport (IDD_DIALOG1): оси, единицы, формат подписей, маркеры |
src/viewers/tmcgrout/dialogdoc.h/.cpp |
окно Characteristics (IDD_DIALOG2): 20 строк списка графиков |
src/viewers/tmcgrout/tmcgroutcolorgraphdialog.h/.cpp |
окно 16 стилей линий (IDD_DIALOGBARCOLORH) |
src/viewers/tmcgrout/tmcgrparcoltypwid.h/.cpp |
окно стиля одной линии (IDD_DIALOGGRPARALL) |
src/viewers/tmcgrout/mainfrm.h/.cpp |
CMainFrame — в Qt6-версии только носитель строки состояния |
src/viewers/tmcgrout/tmcgrout.h, stdafx.h, resource.h |
класс приложения MFC (не создаётся), общий заголовок, номера ресурсов |
src/Include/tmcgrviw.h |
общие константы и структуры вьюверов и ядер (ниже) |
src/Include/tmcgrexpression.h |
объявление CTMCGrExpression, флаг разворота фазы g_nTmcPhaseUnwrap |
src/Include/tmcgraph.h |
наследие TAMIC: объявления DOS-графики BGI; включается через postpro.h, функции не определены (наследие) |
apps/tmcgrout/main.cpp |
точка входа |
apps/tmcgrout/mainwindow.h/.cpp |
MainWindow — меню, панель, строка состояния, окна документов (MDI), передача команд виду |
apps/tmcgrout/dialogs/*.ui, dialog_registry.cpp |
разметка диалогов, порождённая из ресурса Windows-версии (диалоги из .rc) |
apps/tmcgrout/testtools/* |
тестовые программы (ниже) |
Сборка (apps/tmcgrout/CMakeLists.txt): библиотека tmcgrout_core (документ и выражения,
без Qt-интерфейса), tmcgrout_view (вид, рамка, диалоги), tmcgrout_gui (главное окно,
разметка, пиктограммы), программа tmcgrout и тестовые tmcgrout_doccheck,
tmcgrout_shot, tmcgrout_uitest. Вне сборки — childfrm.h/.cpp, stdafx.cpp,
tmcgrout.cpp (наследие).
Ключевые классы и их связи
MainWindow ─┬─ TmcDocumentWindow ×N ─┬─ CTMCGROUTDoc ── TMC_GR_DOC grdoc ── TMC_GR_DOC1[nGraph]
│ │ └─ CTMCGrExpression* (кривая-выражение)
│ ├─ CTMCGROUTView ── TMC_GR_WINDOW tmcgrwin ── TMC_GR_VIEW[nGraph]
│ ├─ MfcViewWidget (виджет-хозяин вида, gui_common)
│ └─ QMdiSubWindow
└─ CMainFrame m_frame (строка состояния для PutTrace/PutStatistics)
- Документ
CTMCGROUTDocхранит то, что пишется в файл.soc: список графиковgrdoc.psGraph(структураTMC_GR_DOC1: имя, подпись, входы и моды, признак показа, стиль линии и маркера, прочитанные частоты и S), параметры окна графика, цвета, шрифт, 16 стилей линий по умолчаниюsGrDoc[16]. - Вид
CTMCGROUTViewхранит подготовленные к рисованию точкиtmcgrwin.psGraph(TMC_GR_VIEW: значения в единицах осей и в логических координатах), диапазоны осей, прямоугольник области графика, форматы подписей, таблицы подписей осей. - Кривая-выражение
CTMCGrExpressionсоздаётся документом для строки графика в фигурных скобках и владеет данными всех своих файлов.
Жизненный цикл окна документа (MainWindow::createDocumentWindow): документ и вид
создаются фабриками TmcCreate, вид получает документ, виджет-хозяин — вид; затем
ReadGraphParametersDefault + ReadGraphParameters (чтобы задать фон виджета) и
initialUpdate, который вызывает CTMCGROUTView::OnInitialUpdate: повторное чтение
параметров, ReadDocFileW (документ и данные), восстановление настроек вида, подготовка
точек и запуск таймера. Всё выполняется в главном потоке; своих потоков у TMCGROUT нет.
Документ и его файл
Путь документа (GetPathName) задаётся при открытии. MakeDocFileName перед каждым
чтением решает, что это за файл:
| Путь | Что происходит |
|---|---|
| пустой (File > New) | путь = заголовок окна (TMCGROUT1 …); в текущей папке создаётся файл с одной меткой #TMCGROUT |
| файл не существует | ошибка документа file not found … |
первая строка файла начинается с #TMCGROUT |
это документ, читается как есть |
любой другой файл (обычно .s) |
путь меняется на то же имя с расширением .soc; если .soc уже есть — на .$OC (существующий .soc не перезаписывается). Создаётся документ с параметрами по умолчанию и одним графиком <имя.s> <имя.s> 1 1 1 1 1 |
Ошибка документа хранится в CTMCGROUTDoc::error; при непустой ошибке вид вместо графиков
выводит строку Error : <текст>. Ошибки отдельных графиков не останавливают чтение —
текст попадает в подпись графика в легенде (Error_when_read_<имя>,
Error_file_name_too_long, Error_expression_...).
Файл документа .soc
Текстовый файл. Строки, начинающиеся с #, — параметры; ! в начале строки или после
пробела вне квадратных скобок начинает комментарий; остальные непустые строки — графики.
Пробелы и табуляции вне [...] сжимаются до одного (del_bl2). Так файл пишет
WriteDocFile:
#TMCGROUT
!Graphics parameters
#dXAxiesUnit 0
#dXAxiesName
#PointDrawFlag 1; 1;
#nXType 0
#nYType 2
#Xmin 40
#Xmax 49.8
#Ymin 0
#Ymax 1
#nAFlagX 1
#nAFlagY 1
#EditorFileName winword.exe
#sDrawTextFont Times New Roman;0;0;0;0;400;0;0;0;2;
#sDrawTextColor 0;
#sDrawBckgrdColor 16777215;
#sDrawAxiesColor 0;
#sDrawGridColor 0;
#sDrawPointColor 255; 16711680; 0; 50; ... (16 троек «цвет; тип; толщина»)
!Graphics data
!file name : <путь документа>
!Data file for draw S-matrix graphics
!SFileName GraphicsName DrawFlag Input1 Mod1 Input2 Mod2
rths25.s S11 1 1 1 1 1
rths25.s S21 1 2 1 1 1
| Метка | Значение |
|---|---|
#dXAxiesUnit |
множитель единиц пользователя оси X (значение оси = частота в Гц × множитель) |
#dXAxiesName |
подпись оси X в единицах пользователя |
#PointDrawFlag a; b; |
a — рисовать маркеры точек, b — прореживать маркеры |
#nXType |
единицы оси X: 0 ГГц, 1 МГц, 2 кГц, 3 Гц, 4 единицы пользователя |
#nYType |
величина по оси Y: 0 КСВ, 1 L дБ, 2 |S|, 3 фаза (рад), 4 фаза (град) — подробнее |
#Xmin, #Xmax, #Ymin, #Ymax |
диапазоны осей в единицах осей |
#nAFlagX, #nAFlagY |
1 — автодиапазон оси по данным, 0 — диапазон из файла |
#EditorFileName |
внешний редактор для команды Edit > Editor |
#sDrawTextFont |
шрифт: имя; высота; ширина; наклон; ориентация; толщина; курсив; подчёркивание; зачёркивание; качество (LOGFONT) |
#sDraw…Color |
цвета текста, фона, осей, сетки в виде COLORREF (0x00BBGGRR, десятичное число) |
#sDrawPointColor |
цвет маркеров и 16 стилей линий: цвет, тип (стиль пера GDI: 0 сплошная, 1 штрих, 2 точки, 3 штрих-точка, 4 штрих-точка-точка), толщина в 0.01 мм |
Строка графика: имя подпись показ вход1 мода1 вход2 мода2. При чтении (ReadGraph)
пробуются 7 полей, затем 6 (без признака показа — показывать), 5 (без подписи — подпись
= имя), 1 (только имя: элемент S(1,1;1,1)). Имя и подпись не могут содержать пробелов вне
квадратных скобок: при записи пробелы из них удаляются (del_bl3). Пустая подпись или
подпись Error_… при записи заменяется именем.
Стиль графика с номером берётся из стиля по умолчанию (DocFileNewData).
Настройки программы
Кроме файла документа, вьювер хранит настройки программы (на Windows прежде — реестр,
в Qt6-версии — файл настроек, см. настройки слоя совместимости).
Раздел #TMCGROTS:
| Ключ | Кто пишет | Содержимое |
|---|---|---|
#TMCGROTS |
WriteDocFile |
те же строки #…, что в документе, одной строкой; разделитель строк — байт 0x01 |
#INIWNDVIEWPORT |
WriteIniWndPar |
размер области графика nXmax nYmax, 0.01 мм |
#TMCGROTS_X_AXIES_FORMAT, #TMCGROTS_Y_AXIES_FORMAT |
окно Viewport | формат подписей сетки |
#TMCGROTS_POINTSIZE |
окно Viewport | масштаб маркеров |
#INIWND |
CMainFrame::OnDestroy (MFC-каркас) |
положение окна |
Порядок чтения: сначала ReadGraphParametersDefault разбирает строку #TMCGROTS
(делит по 0x01 и подаёт каждую часть в тот же разборщик SetOneReadGraphParameters),
затем ReadGraphParameters читает строки файла документа — значения документа
перекрывают значения по умолчанию. Так последние сохранённые оси, цвета и стили
переходят в новые документы.
Разделитель 0x01 одинаков в записи и в чтении у всех трёх вьюверов. Если вместо него в исходнике окажется многобайтовый символ (например, после смены кодировки файла), чтение перестаёт делить строку, и программа «забывает» тип осей и цвета между запусками.
Чтение файлов .s
ReadDocFile → ReadGraph(i) → ReadGraph1 для каждого графика:
- Путь. Имя без
:и без начального\\считается путём относительно папки документа и дополняется ею; иначе берётся как есть. - Элемент S. Имя может начинаться с префикса
*вход1;мода1;вход2;мода2*— тогда элемент задан им (ReadInputModeFromFileName); без префикса номера берутся из строки графика. - Чтение —
read_S_matrix_elementбиблиотеки sfile95: S-файл TMC, затем текстовые таблицы HFSS и CST. Возвращаются массивы частот (Гц) и комплексных значений элемента (вход1, мода1; вход2, мода2); номера входов и мод исправляются в пределы файла и записываются обратно в график (их видно в легенде). - Ошибка — число точек , подпись
Error_when_read_<имя>; график не рисуется.
Массивы данных выделяет sfile95, освобождает документ (DocFileDelData) при каждом
перечитывании.
Слежение за изменениями
Документ запоминает время записи файла документа и файлов .s показываемых графиков
(IsDataModific). Вид проверяет их таймером раз в 10 с (OnTimer) и при двойном
щелчке; если хоть один файл изменился — документ перечитывается и график
перерисовывается. Поэтому TMCGROUT можно держать открытым во время расчёта ядра: новые
частотные точки появляются сами. Файл открывается с разрешением записи другим процессам,
чтобы не мешать ядру.
Одна частота в файле
Если в .s одна частота (директива SMATRIX задания считает S на одной частоте), у
графика одна точка: линия из одной точки нулевой длины, диапазон оси X вырождается и
расширяется TmcFixAxisRange на ±5 %. Видны в лучшем случае только маркер и легенда —
кривой нет. Это не ошибка программы: для кривой нужен частотный свип (серия шагов
#STEP с разными частотами, каждый дописывает точку в тот же .s) или
многочастотный расчёт.
Величины по осям
Ось X — частота из файла (Гц), делённая на , , , 1 или умноженная на
множитель пользователя (GetXAxiesUnit). Ось Y (PrepareDoubleGraph) — для обычного
графика из значения в точке:
nYType |
Подпись | Формула |
|---|---|---|
0 TMC_GR_TYPE_WSVR |
VSWR | ; при берётся (КСВ ≈ 19999) |
1 TMC_GR_TYPE_L |
L dB | , дБ (потери положительны) |
2 TMC_GR_TYPE_SM |
|S| | |
3 TMC_GR_TYPE_SFR |
Phase S - rad | $\varphi = $ cphase, радианы, диапазон |
4 TMC_GR_TYPE_SFD |
Phase S - grad | , градусы, |
Фаза обычного графика не разворачивается: каждая точка — угол на полном круге (угол комплексного числа), поэтому на кривой видны скачки на 360°. Разворот выполняется только у кривых-выражений.
Как строится и рисуется график
Рисунок готовится в два шага и рисуется третьим:
PrepareDoubleGraph— точки каждого показываемого графика в единицах осей (таблица выше). При включённом автодиапазоне ось X охватывает все частоты, ось Y — значения точек, попавших в диапазон X. Нечисловые значения пропускаются; пустой или вырожденный диапазон исправляетTmcFixAxisRange(0..1 или ±5 %).PrepareLogGraph— перевод в логические координаты вида (оси и масштаб).OnDraw— рамка выделения мышью, сетка, оси, затем по всем графикам: линии (OnDrawGraph1), маркеры (OnDrawGraph2), строки легенды (OnDrawGraph3).
Рисование идёт в контекст CDC слоя совместимости: перья и шрифты GDI
переводятся в QPainter, цвета документа — в палитру темы. Тот же
OnDraw рисует и на принтер (печать).
Оси и масштаб
Вид работает в режиме MM_HIMETRIC: логическая единица — 0.01 мм, ось Y направлена
вверх, поэтому точки области графика имеют отрицательный Y. Область графика
(TMC_GR_VIEWPORT): левый край , верх , правый
край и низ задаёт OnViewResizectrlr — 70 % ширины и 90 % высоты окна; размер
запоминается в настройках (#INIWNDVIEWPORT). Перевод значений:
Обе координаты прижимаются к краям области. Поэтому значения Y вне диапазона рисуются
по краю области, а точки вне диапазона X получают координаты предыдущей видимой точки
и не дают отрезков. Оси рисуются по нижнему и левому краю, со стрелками; подпись оси X —
справа (Freq GHz …, или подпись пользователя), оси Y — над осью (VSWR, L dB, …).
Диапазоны меняются командами меню (ниже): сдвиг на 10 % ширины/высоты, увеличение (диапазон ×0.5 относительно центра) и уменьшение (×2), подбор по данным, рамка мышью. Любое явное изменение диапазона выключает автодиапазон этой оси и записывает документ.
Сетка
onDrawGrid делит область на 10 × 10 клеток пунктиром цвета сетки и подписывает 11
линий по каждой оси: по X — под областью, по Y — у левого края окна. Формат подписи —
строка printf из окна Viewport (по умолчанию %4.3lg). Перед использованием формат
проверяет TmcSafeAxisFormat: допускается ровно одно преобразование e, E, f, g,
G (с флагами, шириной, точностью, l) и длина до 64 символов; иначе берётся %4.3lg.
Легенда
Справа от области (x = 1.10…1.15 правого края) для каждого показываемого графика на
высоте мм от верха рисуются отрезок линии с двумя маркерами и текст
- <подпись> - вход1 мода1 вход2 мода2. Входы и моды — фактические, после исправления
по файлу; у графика с ошибкой подпись — текст ошибки. Текст выводит VTextOut шрифтом
документа, высота шрифта на время вывода умножается на 20 (точки экрана → 0.01 мм).
Стиль линий и маркеров
У каждого графика: цвет LineColor, тип LineType (стиль пера GDI) и толщина
LineWidth в 0.01 мм (по умолчанию 50 = 0.5 мм). Не сплошные линии GDI рисует только
толщиной 1, поэтому для них толщина игнорируется (OnDrawLine). Маркер точки —
ломаная из 10 вершин piPoint (у каждого из 16 стилей своя форма: квадрат, крест,
треугольник, ромб …, размер ±2 мм), масштабируется размером маркеров из окна Viewport;
цвет маркеров общий для всех графиков. При прореживании рисуется каждая
-я точка, где — число точек в диапазоне X, —
около 20 маркеров на график.
Окно Config > Color > Graphics (CTmcGroutColorGraphDialog) меняет 16 стилей по
умолчанию; внутри окна толщина хранится делённой на 15 (номера толщин 1…5 окна стиля
линии CTmcGrParColTypWid), в документ записывается умноженной на 15.
Кривые-выражения
Строка графика, имя которой начинается с { и кончается }, — кривая-выражение,
например:
{[a.s]-[b.s]} разность 1 1 1 1 1
{([*2;1;1;1*dev.s]+[*1;1;1;1*dev.s])/2} среднее 1 1 1 1 1
Разбор (CTMCGrExpression::InitData). Пары квадратных скобок верхнего уровня —
файлы, текст между ними — части формулы; частей на одну больше, чем файлов (первая
начинается с {, последняя кончается }). Непарные скобки или их отсутствие — ошибка
Error_expression_absent_or_bad_file_name_…. Имя файла в скобках подчиняется тем же
правилам, что имя графика: путь относительно документа, префикс *вход;мода;вход;мода*.
Чтение. Документ читает каждый файл в массивы объекта (ReadGraph1Expession).
Частоты всех файлов должны совпадать по числу и значению (относительное расхождение не
более , IsFreqCorrect), иначе Error_expression_different_freq_array_….
Значение в точке (GetExpressionValue*):
- Переменной
fбиблиотеки выражений присваивается частота точки в Гц (вычисляется программа{f=(…)}), её можно использовать в формуле. - Значение каждого файла в точке переводится в величину оси Y (КСВ, , , фаза) — по тем же формулам, что у обычного графика.
- Строка
часть₀(v₁)часть₁(v₂)…частьₙвычисляется интерпретаторомi1nte_atof_1(Inter). Ошибка вычисления даёт 0 только в этой точке.
Например, при оси Y в дБ {[a.s]-[b.s]} — разность потерь , при оси —
разность модулей. Ось X у выражения — частоты первого файла.
Разворот фазы
Для фазы кривой-выражения значение файла разворачивается по частоте (GetCPhase): по
точкам считается число переходов , результат . Способ
задаёт глобальная переменная g_nTmcPhaseUnwrap (флажок Config > «Phase unwrapping:
standard (threshold pi)», хранится в настройках Settings/PhaseUnwrap):
| Значение | Правило перехода между точками и |
|---|---|
| 0 (по умолчанию) | → : фаза считается монотонно убывающей |
| 1 | → ; → (стандартный разворот) |
Если по оси X выбраны единицы пользователя, вид вызывает варианты …_User, и фаза не
разворачивается. Обычные графики фазу не разворачивают никогда. Теория —
развёртка фазы. Чтобы развернуть фазу одного файла,
достаточно записать его как выражение: {[имя.s]}.
Мышь
| Действие | Где | Результат |
|---|---|---|
| левая кнопка | в области графика | координаты точки в левой ячейке строки состояния (<ось X>=<x>; <ось Y>=<y>), начало рамки |
| перетаскивание | в области | рамка выделения; координаты обновляются |
| отпускание | — | рамка больше 10 % диапазона по оси → новый диапазон этой оси, автодиапазон её выключается; ось Y, не попавшая в рамку, переходит в автодиапазон; рамка меньше 10 % по обеим осям — просто щелчок |
| двойной щелчок | в области / вне | автодиапазон по обеим осям / подгонка области под окно и запись её размера |
| правая кнопка | в области / вне | окно Viewport / окно Characteristics |
Правая ячейка строки состояния показывает величину по оси Y (PutStatistics1).
Команды меню и их обработчики
Главное окно Qt строит меню и панель по таблицам mainwindow.cpp (подписи и сочетания
клавиш — из ресурса Windows-версии) и передаёт номер команды MainWindow::dispatch.
Тот сначала ищет обработчик в карте сообщений вида активного окна
(TmcBuildMessageMap — карта сообщений), затем — у себя.
Доступность и отметки пунктов перед показом меню спрашиваются у вида
(обновление состояния команд).
| Меню | Пункт (клавиши) | Номер | Обработчик |
|---|---|---|---|
| File | New (Ctrl+N), Open (Ctrl+O), Close | ID_FILE_NEW/OPEN/CLOSE |
MainWindow::onNewDocument/onOpenDocument/onCloseDocument |
| File | Save (Ctrl+S) | ID_FILE_SAVE |
OnFileSave — WriteDocFile |
| File | Save As | ID_FILE_SAVE_AS |
OnFileSaveAs — новый путь, RebaseGraphPaths, запись |
| File | Print (Ctrl+P), Print Preview, Print Setup | ID_FILE_PRINT… |
tmcprint в dispatch (печать) |
| Edit | Characteristics (Ctrl+D) | ID_EDIT_DOCUMENT |
OnEditDocument — окно 20 строк |
| Edit | Add characteristics (Ctrl+A) | ID_EDIT_ADDCHARACTERISTICS |
OnEditAddcharacteristics — выбор .s, AddGraphicsInDoc |
| Edit | Editor (Alt+F7) | ID_EDIT_EDIT |
OnEditEdit — .soc во внешнем редакторе |
| View | Viewport (Ctrl+H) | ID_EDIT_GRAPHICSPARAMETERS |
OnEditGraphicsparameters |
| View | Redraw data (Ctrl+W) | ID_VIEW_GRAPHICS |
OnViewGraphics — перечитать и перерисовать |
| View > Zoom | ReSize viewport (Ctrl+R) | ID_VIEW_RESIZECTRLR |
OnViewResizectrlr |
| View > Zoom | Zoom + (+), +X (X), +Y (Y) | ID_VIEW_ZOOM_ZOOMP/XP/YP |
OnViewZoomZoomp/xp/yp — диапазон ×0.5 |
| View > Zoom | Zoom − (−), −X (Shift+X), −Y (Shift+Y) | ID_VIEW_ZOOM_ZOOM/X/Y |
OnViewZoomZoom/x/y — диапазон ×2 |
| View > Zoom | Resize window (Ctrl+T) | ID_VIEW_RESIZEWINDOW |
OnViewResizewindow — автодиапазон X и Y |
| View > Zoom | Auto X size (Alt+X), Auto Y size (Alt+Y) | ID_VIEW_AUTOXSIZE/AUTOYSIZE |
OnViewAutoxsize/ysize (+ OnUpdate… — отметка) |
| View > Translate > Change X | Decrement (←), Increment (→) | ID_VIEW_CHANGEXMAXXMIN_… |
сдвиг на 10 % ширины |
| View > Translate > Change X | Home, End | ID_VIEW_TRANSLATE_HOME/END |
OnViewTranslateHome/End — к первой/последней частоте, ширина сохраняется; только без автодиапазона X |
| View > Translate > Change Y | Decrement (V), Increment (↑) | ID_VIEW_CHANGEYMAXYMIN_… |
сдвиг на 10 % высоты |
| Config | Editor | ID_CONFIG_EDITOR |
OnConfigEditor |
| Config > Color | Background, Grid, Axies, Point, Graphics | ID_CONFIG_COLOR_…, ID_CONFIG_COLORPOINT |
OnConfigColor… |
| Config | Font | ID_CONFIG_FONT |
OnConfigFont |
| Config | Phase unwrapping | — | лямбда в MainWindow::createMenus (разворот фазы) |
| Config | Language | — | tmci18n::addLanguageMenu (перевод) |
| Window | New Window, Cascade, Tile | — | MainWindow (QMdiArea) |
| Help | About | ID_APP_ABOUT |
MainWindow::onAbout |
Окно Viewport (CTMCGROUTDIALOGView) кроме полей имеет кнопки шрифта и цветов: каждая
закрывает окно как OK со своим флажком, вид применяет параметры, открывает окно
шрифта/цвета и снова Viewport. Номера переключателей единиц X и величины Y в окне равны
TMC_GR_TYPE_*. Окно Characteristics (CDialogDoc) показывает первые 20 графиков;
графики с номером больше 20 при OK сохраняются без изменений в конце списка.
Qt-оболочка
main.cpp создаёт QApplication, задаёт имя настроек CWinApp::SetAppName("TMCGROUT"),
применяет оформление и открывает файл из командной строки.
MainWindow:
- регистрирует разметку диалогов (
TmcInstallDialogs_tmcgrout,dialog_registry.cpp) и пиктограммы явным вызовом — файлы лежат в статической библиотеке; - создаёт рамку
CMainFrameи делает еёAfxGetApp()->m_pMainWnd: код вьювера (PutTrace,PutStatistics) пишет в еёm_wndStatusBar, а та переадресует текст виджету активного документа (SetHostвcreateDocumentWindowиonSubWindowActivated) — так в одной строке состояния всегда данные активного окна; - открывает документы в подокнах MDI, развёрнутыми, как в Windows-версии; несуществующий файл и путь с символами вне кодовой страницы не открываются (проверка пути);
- ведёт список недавних файлов (недавние файлы) и положение окна (положение окон);
- при уничтожении сначала отвязывает виды от виджетов, затем удаляет виды и документы.
Общее для трёх вьюверов
TMCROS и TMC_DN построены на копиях этого кода. Общее, на что можно ссылаться с их страниц:
- документ со списком графиков
TMC_GR_DOC/TMC_GR_DOC1, формат строк#метка значение, комментарии!, сжатие пробеловdel_bl2, стили по умолчаниюsGrDoc[16]— документ, файл документа; - строка параметров по умолчанию в настройках с разделителем 0x01 — настройки;
- окно графика
TMC_GR_WINDOW, режимMM_HIMETRIC, перевод координат, прижатие к краям — оси и масштаб; сетка и проверка формата — сетка; легенда — легенда; стили линий и маркеров — стиль; - мышь, масштаб и сдвиг — мышь, команды;
- кривые-выражения
CTMCGrExpression(у TMCROS добавленGetExpressionValueRe— выражение над значениями сигналов) — выражения; - строка состояния через
CMainFrame— Qt-оболочка.
Отличаются величины по осям (у TMCROS и TMC_DN — время и сигналы, константы
TMC_GROTS_TYPE_*), метки файлов документов и окна.
Общие константы tmcgrviw.h
Заголовок общий для вьюверов, ядер, TMCIndan и FieldView:
- типы величин осей:
TMC_GR_TYPE_*(TMCGROUT),TMC_GROTS_TYPE_*(сигналы и время); - метки файла документа (
TMC_GROUT_DOCFILE_*,TMC_TOPVIEW_DOCFILE_*) и ключи настроек (TMC_GROTS_DOCFILE_*); - метки заголовков выходных файлов ядер: сигналы
.t(TMC_GROTS_FILEOUT_ID,TMC_GROTS_FLOUT*), поля (TMC_GROFLD_DOCFILE_*), топология (TMC_RTH_FILETOP_ID); - ключевые слова блоков задания
.tpl(CTMCRTH_INDANBLCK_*) и коды блоков и узлов: 0 — диэлектрик, 100 — поглотитель, 101 — металл, 102…105 — входы (слева, справа, сверху, снизу), 107 — магнитная стенка,ABSR_*— коды соседства узлов поглотителя (ядро H: типы узлов, поглотитель); - структуры документа и окна графика (
TMC_GR_DOC1,TMC_GR_DOC,TMC_GR_VIEW,TMC_GR_WINDOW…).
Значения записаны в файлы пользователей и в настройки программ — их менять нельзя. Метки
разделов задания TAMIC (#STEP, #EOF, BLOCK …), TMC_DNOUT_DOCFILE_ID, единицы фазы
TMC_GR_TYPE_PRad/PGradus и свободные функции в конце файла (RunExeFileG,
MakeRelatPathFile …) в коде Qt6-версии не используются; у функций нет определений.
Тестовые программы
В поставку не входят.
| Программа | Что делает |
|---|---|
tmcgrout_doccheck <документ> [--dump] |
открывает документ тем же кодом, что программа, без графики и печатает оси, диапазоны, список графиков, входы и моды, число точек и первые три значения; с --dump — строки файла с видимыми <CR>/<LF>/<TAB>. Отделяет ошибки разбора файлов от ошибок рисования |
tmcgrout_shot <файл.png> [документ] [ширина] [высота] |
рисует главное окно в картинку (работает и с QT_QPA_PLATFORM=offscreen); с --dialogs <папка> снимает все диалоги (снимки диалогов) |
tmcgrout_uitest <документ> [секунд] |
нажимает все команды, меняет размер окна, щёлкает и дважды щёлкает по графику (5 повторов), проверяет, что мышь не осталась захваченной; при зависании печатает шаг и стек. Только не под Windows (SIGALRM, execinfo.h) |
Типичные ошибки и подводные камни
WriteDocFileвозвращает FALSE при успехе и TRUE при ошибке — обратно обычному.- Пустое окно у файла с одной частотой — не ошибка, нужен свип (выше).
- Фаза обычного графика не разворачивается — запишите график как выражение
{[имя.s]}(разворот фазы). - Значения вне диапазона Y рисуются по краю области, а не обрезаются — при ручном диапазоне кривая может «лежать» на рамке.
- Абсолютный путь распознаётся только по
:или начальному\\. Путь вида/home/...считается относительным и дополняется папкой документа. - Открытие
.sсоздаёт файл рядом с ним (.soc, или.$OC, если.socуже есть) — в папке с данными нужны права на запись;.$OCперезаписывается при каждом открытии. - Выражение
{{...}}при оси Y в дБ не вычисляется: ветка вPrepareDoubleGraphзакомментирована, значения точек остаются незаполненными. - Пробелы в именах вне квадратных скобок недопустимы: строка графика делится по пробелам, а при записи пробелы из имени и подписи удаляются.
- Внешний редактор по умолчанию —
winword.exe; если его нет, Edit > Editor ничего не откроет — укажите редактор в Config > Editor.
Файлы вне сборки
childfrm.h/.cpp (дочернее окно MDI MFC — заменено QMdiSubWindow), tmcgrout.cpp
(приложение MFC — заменено apps/tmcgrout/main.cpp и MainWindow), stdafx.cpp
(предкомпилированный заголовок). Оставлены для сверки с MFC-версией; см. также
файлы вне сборки.
TMCGROUT viewer — plots of S-parameters versus frequency
Purpose and place in the package
TMCGROUT (tmcgrout.exe) plots elements of the scattering matrix versus frequency. The data
come from .s files written by the compute kernels PlanarRT_H/PlanarRT_X and by TMCROS
(the format and reading are in the sfile95 library). The program does no physical
computation: it converts the complex values into the selected quantity (VSWR,
loss in dB, magnitude, phase) and plots them, and it can also build expression curves —
formulas over several .s files (the Inter/Expr libraries).
The list of plots, the axes, colors and font are stored in the document file .soc — a text
file that can also be edited by hand. Where the S values come from and how they are
normalized is described in the theory: S-matrix from signals,
normalization.
The program is assembled from two layers:
src/viewers/tmcgrout— the Windows version code without changes: document, view, dialogs, expressions. It uses MFC classes, which are implemented by the compatibility layer on Qt 6; drawing goes through GDI on top of QPainter, in the project palette.src/viewers/Tmcgrout/qt— the Qt shell: entry point, main window with menu, toolbar and status bar, dialog layouts, test programs.
The same document, view and dialog code, in modified copies, is used by TMCROS
(viewers/tmcrtout, time-domain signals) and TMC_DN (viewers/dianapgr, radiation
patterns). The mechanisms common to the three viewers — the list of plots, the plot window,
axes, grid, legend, expressions — are described on this page
(common to the viewers).
Contents
| File | Role |
|---|---|
src/viewers/tmcgrout/tmcgroutdoc.h/.cpp |
CTMCGROUTDoc — document: the .soc file, list of plots, reading .s files and expressions, paths |
src/viewers/tmcgrout/tmcgroutview.h/.cpp |
CTMCGROUTView — view: preparing points, grid, axes, lines, markers, legend, mouse, zoom, all menu commands; status bar functions PutTrace, PutStatistics |
src/viewers/tmcgrout/tmcgrexpression.cpp |
CTMCGrExpression — expression curve (declared in the common src/Include/tmcgrexpression.h) |
src/viewers/tmcgrout/tmcgroutdialogview.h/.cpp |
Viewport window (IDD_DIALOG1): axes, units, label format, markers |
src/viewers/tmcgrout/dialogdoc.h/.cpp |
Characteristics window (IDD_DIALOG2): 20 rows of the list of plots |
src/viewers/tmcgrout/tmcgroutcolorgraphdialog.h/.cpp |
window of 16 line styles (IDD_DIALOGBARCOLORH) |
src/viewers/tmcgrout/tmcgrparcoltypwid.h/.cpp |
window of the style of one line (IDD_DIALOGGRPARALL) |
src/viewers/tmcgrout/mainfrm.h/.cpp |
CMainFrame — in the Qt6 version only the carrier of the status bar |
src/viewers/tmcgrout/tmcgrout.h, stdafx.h, resource.h |
MFC application class (not created), common header, resource numbers |
src/Include/tmcgrviw.h |
common constants and structures of the viewers and kernels (below) |
src/Include/tmcgrexpression.h |
declaration of CTMCGrExpression, phase unwrapping flag g_nTmcPhaseUnwrap |
src/Include/tmcgraph.h |
TAMIC legacy: declarations of BGI DOS graphics; included through postpro.h, the functions are not defined (legacy) |
apps/tmcgrout/main.cpp |
entry point |
apps/tmcgrout/mainwindow.h/.cpp |
MainWindow — menu, toolbar, status bar, document windows (MDI), passing commands to the view |
apps/tmcgrout/dialogs/*.ui, dialog_registry.cpp |
dialog layouts generated from the Windows version resource (dialogs from .rc) |
apps/tmcgrout/testtools/* |
test programs (below) |
Build (apps/tmcgrout/CMakeLists.txt): the library tmcgrout_core (document and expressions,
without the Qt interface), tmcgrout_view (view, frame, dialogs), tmcgrout_gui (main window,
layouts, icons), the program tmcgrout and the test programs tmcgrout_doccheck,
tmcgrout_shot, tmcgrout_uitest. Outside the build — childfrm.h/.cpp, stdafx.cpp,
tmcgrout.cpp (legacy).
Key classes and their relations
MainWindow ─┬─ TmcDocumentWindow ×N ─┬─ CTMCGROUTDoc ── TMC_GR_DOC grdoc ── TMC_GR_DOC1[nGraph]
│ │ └─ CTMCGrExpression* (expression curve)
│ ├─ CTMCGROUTView ── TMC_GR_WINDOW tmcgrwin ── TMC_GR_VIEW[nGraph]
│ ├─ MfcViewWidget (view host widget, gui_common)
│ └─ QMdiSubWindow
└─ CMainFrame m_frame (status bar for PutTrace/PutStatistics)
- The document
CTMCGROUTDocstores what is written to the.socfile: the list of plotsgrdoc.psGraph(structureTMC_GR_DOC1: name, caption, ports and modes, visibility flag, line and marker style, the frequencies and S values read), the plot window parameters, colors, font, the 16 default line stylessGrDoc[16]. - The view
CTMCGROUTViewstores the points prepared for drawingtmcgrwin.psGraph(TMC_GR_VIEW: values in axis units and in logical coordinates), the axis ranges, the rectangle of the plot area, label formats, the axis label tables. - The expression curve
CTMCGrExpressionis created by the document for a plot row in curly braces and owns the data of all its files.
Life cycle of a document window (MainWindow::createDocumentWindow): the document and the view
are created by the TmcCreate factories, the view gets the document, the host widget gets the view; then
ReadGraphParametersDefault + ReadGraphParameters (to set the widget background) and
initialUpdate, which calls CTMCGROUTView::OnInitialUpdate: re-reading the
parameters, ReadDocFileW (document and data), restoring the view settings, preparing the
points and starting the timer. Everything runs in the main thread; TMCGROUT has no threads of its own.
The document and its file
The document path (GetPathName) is set on opening. Before each read MakeDocFileName
decides what kind of file it is:
| Path | What happens |
|---|---|
| empty (File > New) | path = window title (TMCGROUT1 …); a file containing a single #TMCGROUT tag is created in the current folder |
| file does not exist | document error file not found … |
the first line of the file starts with #TMCGROUT |
this is a document, read as is |
any other file (usually .s) |
the path is changed to the same name with the .soc extension; if a .soc already exists — to .$OC (the existing .soc is not overwritten). A document is created with default parameters and one plot <name.s> <name.s> 1 1 1 1 1 |
The document error is stored in CTMCGROUTDoc::error; if the error is not empty, the view outputs the string
Error : <text> instead of the plots. Errors of individual plots do not stop reading —
the text goes into the plot caption in the legend (Error_when_read_<name>,
Error_file_name_too_long, Error_expression_...).
Document file .soc
A text file. Lines starting with # are parameters; ! at the start of a line or after
a space outside square brackets starts a comment; the other non-empty lines are plots.
Spaces and tabs outside [...] are collapsed to one (del_bl2). This is how
WriteDocFile writes the file:
#TMCGROUT
!Graphics parameters
#dXAxiesUnit 0
#dXAxiesName
#PointDrawFlag 1; 1;
#nXType 0
#nYType 2
#Xmin 40
#Xmax 49.8
#Ymin 0
#Ymax 1
#nAFlagX 1
#nAFlagY 1
#EditorFileName winword.exe
#sDrawTextFont Times New Roman;0;0;0;0;400;0;0;0;2;
#sDrawTextColor 0;
#sDrawBckgrdColor 16777215;
#sDrawAxiesColor 0;
#sDrawGridColor 0;
#sDrawPointColor 255; 16711680; 0; 50; ... (16 triples "color; type; width")
!Graphics data
!file name : <document path>
!Data file for draw S-matrix graphics
!SFileName GraphicsName DrawFlag Input1 Mod1 Input2 Mod2
rths25.s S11 1 1 1 1 1
rths25.s S21 1 2 1 1 1
| Tag | Meaning |
|---|---|
#dXAxiesUnit |
multiplier of the user units of the X axis (axis value = frequency in Hz × multiplier) |
#dXAxiesName |
X axis label in user units |
#PointDrawFlag a; b; |
a — draw point markers, b — thin out the markers |
#nXType |
X axis units: 0 GHz, 1 MHz, 2 kHz, 3 Hz, 4 user units |
#nYType |
quantity on the Y axis: 0 VSWR, 1 L dB, 2 |S|, 3 phase (rad), 4 phase (deg) — details |
#Xmin, #Xmax, #Ymin, #Ymax |
axis ranges in axis units |
#nAFlagX, #nAFlagY |
1 — automatic axis range from the data, 0 — range from the file |
#EditorFileName |
external editor for the Edit > Editor command |
#sDrawTextFont |
font: name; height; width; escapement; orientation; weight; italic; underline; strikeout; quality (LOGFONT) |
#sDraw…Color |
colors of text, background, axes, grid as COLORREF (0x00BBGGRR, decimal number) |
#sDrawPointColor |
color of the markers and the 16 line styles: color, type (GDI pen style: 0 solid, 1 dash, 2 dot, 3 dash-dot, 4 dash-dot-dot), width in 0.01 mm |
Plot row: name caption visible port1 mode1 port2 mode2. When reading (ReadGraph),
7 fields are tried, then 6 (without the visibility flag — shown), 5 (without the caption — caption
= name), 1 (name only: element S(1,1;1,1)). The name and the caption cannot contain spaces outside
square brackets: on writing, spaces are removed from them (del_bl3). An empty caption or
a caption Error_… is replaced with the name on writing.
The style of the plot with number is taken from the default style (DocFileNewData).
Program settings
Besides the document file, the viewer stores program settings (on Windows formerly the registry,
in the Qt6 version a settings file, see compatibility layer settings).
Section #TMCGROTS:
| Key | Written by | Contents |
|---|---|---|
#TMCGROTS |
WriteDocFile |
the same #… lines as in the document, as a single line; the line separator is byte 0x01 |
#INIWNDVIEWPORT |
WriteIniWndPar |
size of the plot area nXmax nYmax, 0.01 mm |
#TMCGROTS_X_AXIES_FORMAT, #TMCGROTS_Y_AXIES_FORMAT |
Viewport window | format of the grid labels |
#TMCGROTS_POINTSIZE |
Viewport window | marker scale |
#INIWND |
CMainFrame::OnDestroy (MFC framework) |
window position |
Reading order: first ReadGraphParametersDefault parses the #TMCGROTS line
(splits it by 0x01 and feeds each part to the same parser SetOneReadGraphParameters),
then ReadGraphParameters reads the lines of the document file — the document values
override the default values. In this way the last saved axes, colors and styles
carry over to new documents.
The 0x01 separator is the same for writing and reading in all three viewers. If a multibyte character ends up in its place in the source (for example, after the file encoding is changed), reading stops splitting the line, and the program "forgets" the axis type and colors between runs.
Reading .s files
ReadDocFile → ReadGraph(i) → ReadGraph1 for each plot:
- Path. A name without
:and without a leading\\is treated as a path relative to the document folder and is prefixed with it; otherwise it is taken as is. - S element. The name may start with the prefix
*port1;mode1;port2;mode2*— then the element is given by it (ReadInputModeFromFileName); without the prefix the numbers are taken from the plot row. - Reading —
read_S_matrix_elementof the sfile95 library: a TMC S-file, then HFSS and CST text tables. Arrays of frequencies (Hz) and complex values of the element (port1, mode1; port2, mode2) are returned; port and mode numbers are corrected to the limits of the file and written back to the plot (they are visible in the legend). - Error — number of points , caption
Error_when_read_<name>; the plot is not drawn.
The data arrays are allocated by sfile95 and freed by the document (DocFileDelData) on every
re-read.
Tracking changes
The document remembers the modification time of the document file and of the .s files of the visible plots
(IsDataModific). The view checks them with a timer every 10 s (OnTimer) and on a double
click; if at least one file has changed, the document is re-read and the plot
is redrawn. Therefore TMCGROUT can be kept open while a kernel is computing: new
frequency points appear by themselves. The file is opened allowing other processes to write to it,
so as not to interfere with the kernel.
A single frequency in the file
If a .s file contains a single frequency (the SMATRIX directive of the task file computes S at one frequency), the
plot has one point: a line of one point has zero length, the X axis range degenerates and
is expanded by TmcFixAxisRange by ±5 %. At best only the marker and the legend are visible —
there is no curve. This is not a program error: a curve requires a frequency sweep (a series of
#STEP steps with different frequencies, each appending a point to the same .s) or
a multi-frequency computation.
Quantities on the axes
The X axis is the frequency from the file (Hz) divided by , , , 1, or multiplied by the
user multiplier (GetXAxiesUnit). The Y axis (PrepareDoubleGraph) — for an ordinary
plot, computed from the value of at the point:
nYType |
Label | Formula |
|---|---|---|
0 TMC_GR_TYPE_WSVR |
VSWR | ; when , is used (VSWR ≈ 19999) |
1 TMC_GR_TYPE_L |
L dB | , dB (loss is positive) |
2 TMC_GR_TYPE_SM |
|S| | |
3 TMC_GR_TYPE_SFR |
Phase S - rad | $\varphi = $ cphase, radians, range |
4 TMC_GR_TYPE_SFD |
Phase S - grad | , degrees, |
The phase of an ordinary plot is not unwrapped: each point is an angle on the full circle (angle of a complex number), so jumps of 360° are visible on the curve. Unwrapping is performed only for expression curves.
How a plot is built and drawn
The picture is prepared in two steps and drawn in the third:
PrepareDoubleGraph— the points of each visible plot in axis units (the table above). With the automatic range enabled, the X axis covers all frequencies, the Y axis covers the values of the points that fall within the X range. Non-numeric values are skipped; an empty or degenerate range is corrected byTmcFixAxisRange(0..1 or ±5 %).PrepareLogGraph— conversion to the logical coordinates of the view (axes and scale).OnDraw— the mouse selection frame, grid, axes, then for all plots: lines (OnDrawGraph1), markers (OnDrawGraph2), legend rows (OnDrawGraph3).
Drawing goes into the CDC context of the compatibility layer: GDI pens and fonts
are converted to QPainter, the document colors to the theme palette. The same
OnDraw also draws to the printer (printing).
Axes and scale
The view works in MM_HIMETRIC mode: the logical unit is 0.01 mm, the Y axis points
up, so the points of the plot area have negative Y. The plot area
(TMC_GR_VIEWPORT): left edge , top ; the right
edge and the bottom are set by OnViewResizectrlr — 70 % of the width and 90 % of the height of the window; the size
is remembered in the settings (#INIWNDVIEWPORT). Value conversion:
Both coordinates are clamped to the edges of the area. Therefore Y values outside the range are drawn
along the edge of the area, and points outside the X range get the coordinates of the previous visible point
and produce no segments. The axes are drawn along the bottom and left edges, with arrows; the X axis label is
on the right (Freq GHz …, or the user label), the Y axis label is above the axis (VSWR, L dB, …).
The ranges are changed by menu commands (below): shift by 10 % of the width/height, zoom in (range ×0.5 about the center) and zoom out (×2), fit to the data, a mouse frame. Any explicit change of a range turns off the automatic range of that axis and writes the document.
Grid
onDrawGrid divides the area into 10 × 10 cells with dashed lines of the grid color and labels 11
lines on each axis: on X — below the area, on Y — at the left edge of the window. The label format is
a printf string from the Viewport window (default %4.3lg). Before use, the format is
checked by TmcSafeAxisFormat: exactly one conversion e, E, f, g,
G is allowed (with flags, width, precision, l) and a length of up to 64 characters; otherwise %4.3lg is used.
Legend
To the right of the area (x = 1.10…1.15 of the right edge), for each visible plot , at a
height of mm from the top, a line segment with two markers and the text
- <caption> - port1 mode1 port2 mode2 are drawn. The ports and modes are the actual ones, after correction
against the file; for a plot with an error the caption is the error text. The text is output by VTextOut in the
document font; the font height is multiplied by 20 for the output (screen points → 0.01 mm).
Line and marker style
Each plot has: a color LineColor, a type LineType (GDI pen style) and a width
LineWidth in 0.01 mm (default 50 = 0.5 mm). GDI draws non-solid lines only with
width 1, so the width is ignored for them (OnDrawLine). A point marker is
a polyline of 10 vertices piPoint (each of the 16 styles has its own shape: square, cross,
triangle, diamond …, size ±2 mm), scaled by the marker size from the Viewport window;
the marker color is common to all plots. When thinning out, every
-th point is drawn, where is the number of points in the X range —
about 20 markers per plot.
The Config > Color > Graphics window (CTmcGroutColorGraphDialog) changes the 16 default
styles; inside the window the width is stored divided by 15 (the width numbers 1…5 of the line style
window CTmcGrParColTypWid), and it is written to the document multiplied by 15.
Expression curves
A plot row whose name starts with { and ends with } is an expression curve,
for example:
{[a.s]-[b.s]} difference 1 1 1 1 1
{([*2;1;1;1*dev.s]+[*1;1;1;1*dev.s])/2} average 1 1 1 1 1
Parsing (CTMCGrExpression::InitData). Top-level pairs of square brackets are
files, the text between them is parts of the formula; there is one more part than there are files (the first
starts with {, the last ends with }). Unpaired brackets or no brackets at all are the error
Error_expression_absent_or_bad_file_name_…. A file name in brackets follows the same
rules as a plot name: path relative to the document, prefix *port;mode;port;mode*.
Reading. The document reads each file into the arrays of the object (ReadGraph1Expession).
The frequencies of all files must coincide in number and value (relative discrepancy not
more than , IsFreqCorrect), otherwise Error_expression_different_freq_array_….
Value at point (GetExpressionValue*):
- The variable
fof the expression library is assigned the frequency of the point in Hz (the program{f=(…)}is evaluated), and it can be used in the formula. - The value of each file at the point is converted into the Y axis quantity (VSWR, , , phase) — by the same formulas as for an ordinary plot.
- The string
part₀(v₁)part₁(v₂)…partₙis evaluated by the interpreteri1nte_atof_1(Inter). An evaluation error gives 0 only at this point.
For example, with the Y axis in dB, {[a.s]-[b.s]} is the loss difference , with the axis —
the difference of magnitudes. The X axis of an expression is the frequencies of the first file.
Phase unwrapping
For the phase of an expression curve, the file value is unwrapped over frequency (GetCPhase): over the
points the number of transitions is counted, and the result is . The method
is set by the global variable g_nTmcPhaseUnwrap (the check box Config > "Phase unwrapping:
standard (threshold pi)", stored in the settings Settings/PhaseUnwrap):
| Value | Transition rule between points and |
|---|---|
| 0 (default) | → : the phase is assumed to decrease monotonically |
| 1 | → ; → (standard unwrapping) |
If user units are selected for the X axis, the view calls the …_User variants, and the phase is not
unwrapped. Ordinary plots never unwrap the phase. Theory —
phase unwrapping. To unwrap the phase of a single file,
it is enough to write it as an expression: {[name.s]}.
Mouse
| Action | Where | Result |
|---|---|---|
| left button | in the plot area | coordinates of the point in the left cell of the status bar (<X axis>=<x>; <Y axis>=<y>), start of the frame |
| dragging | in the area | selection frame; the coordinates are updated |
| release | — | frame larger than 10 % of the range along an axis → new range of that axis, its automatic range is turned off; a Y axis not covered by the frame switches to the automatic range; a frame smaller than 10 % along both axes is just a click |
| double click | in the area / outside | automatic range along both axes / fit the area to the window and write its size |
| right button | in the area / outside | Viewport window / Characteristics window |
The right cell of the status bar shows the Y axis quantity (PutStatistics1).
Menu commands and their handlers
The Qt main window builds the menu and the toolbar from the tables in mainwindow.cpp (captions and keyboard
shortcuts are from the Windows version resource) and passes the command number to MainWindow::dispatch.
It first looks for a handler in the message map of the view of the active window
(TmcBuildMessageMap — message map), then in itself.
The availability and check marks of the items are requested from the view before the menu is shown
(command state update).
| Menu | Item (keys) | Number | Handler |
|---|---|---|---|
| File | New (Ctrl+N), Open (Ctrl+O), Close | ID_FILE_NEW/OPEN/CLOSE |
MainWindow::onNewDocument/onOpenDocument/onCloseDocument |
| File | Save (Ctrl+S) | ID_FILE_SAVE |
OnFileSave — WriteDocFile |
| File | Save As | ID_FILE_SAVE_AS |
OnFileSaveAs — new path, RebaseGraphPaths, writing |
| File | Print (Ctrl+P), Print Preview, Print Setup | ID_FILE_PRINT… |
tmcprint in dispatch (printing) |
| Edit | Characteristics (Ctrl+D) | ID_EDIT_DOCUMENT |
OnEditDocument — the 20-row window |
| Edit | Add characteristics (Ctrl+A) | ID_EDIT_ADDCHARACTERISTICS |
OnEditAddcharacteristics — choosing a .s, AddGraphicsInDoc |
| Edit | Editor (Alt+F7) | ID_EDIT_EDIT |
OnEditEdit — the .soc in the external editor |
| View | Viewport (Ctrl+H) | ID_EDIT_GRAPHICSPARAMETERS |
OnEditGraphicsparameters |
| View | Redraw data (Ctrl+W) | ID_VIEW_GRAPHICS |
OnViewGraphics — re-read and redraw |
| View > Zoom | ReSize viewport (Ctrl+R) | ID_VIEW_RESIZECTRLR |
OnViewResizectrlr |
| View > Zoom | Zoom + (+), +X (X), +Y (Y) | ID_VIEW_ZOOM_ZOOMP/XP/YP |
OnViewZoomZoomp/xp/yp — range ×0.5 |
| View > Zoom | Zoom − (−), −X (Shift+X), −Y (Shift+Y) | ID_VIEW_ZOOM_ZOOM/X/Y |
OnViewZoomZoom/x/y — range ×2 |
| View > Zoom | Resize window (Ctrl+T) | ID_VIEW_RESIZEWINDOW |
OnViewResizewindow — automatic range of X and Y |
| View > Zoom | Auto X size (Alt+X), Auto Y size (Alt+Y) | ID_VIEW_AUTOXSIZE/AUTOYSIZE |
OnViewAutoxsize/ysize (+ OnUpdate… — check mark) |
| View > Translate > Change X | Decrement (←), Increment (→) | ID_VIEW_CHANGEXMAXXMIN_… |
shift by 10 % of the width |
| View > Translate > Change X | Home, End | ID_VIEW_TRANSLATE_HOME/END |
OnViewTranslateHome/End — to the first/last frequency, the width is preserved; only without the automatic X range |
| View > Translate > Change Y | Decrement (V), Increment (↑) | ID_VIEW_CHANGEYMAXYMIN_… |
shift by 10 % of the height |
| Config | Editor | ID_CONFIG_EDITOR |
OnConfigEditor |
| Config > Color | Background, Grid, Axies, Point, Graphics | ID_CONFIG_COLOR_…, ID_CONFIG_COLORPOINT |
OnConfigColor… |
| Config | Font | ID_CONFIG_FONT |
OnConfigFont |
| Config | Phase unwrapping | — | a lambda in MainWindow::createMenus (phase unwrapping) |
| Config | Language | — | tmci18n::addLanguageMenu (translation) |
| Window | New Window, Cascade, Tile | — | MainWindow (QMdiArea) |
| Help | About | ID_APP_ABOUT |
MainWindow::onAbout |
Besides the fields, the Viewport window (CTMCGROUTDIALOGView) has font and color buttons: each
closes the window like OK with its own flag, the view applies the parameters, opens the
font/color window and then Viewport again. The numbers of the X unit and Y quantity radio buttons in the window equal
TMC_GR_TYPE_*. The Characteristics window (CDialogDoc) shows the first 20 plots;
plots with numbers greater than 20 are kept unchanged at the end of the list on OK.
Qt shell
main.cpp creates QApplication, sets the settings name CWinApp::SetAppName("TMCGROUT"),
applies the theme and opens the file from the command line.
MainWindow:
- registers the dialog layouts (
TmcInstallDialogs_tmcgrout,dialog_registry.cpp) and the icons with an explicit call — the files are in a static library; - creates the
CMainFrameframe and makes itAfxGetApp()->m_pMainWnd: the viewer code (PutTrace,PutStatistics) writes to itsm_wndStatusBar, which forwards the text to the widget of the active document (SetHostincreateDocumentWindowandonSubWindowActivated) — so the single status bar always shows the data of the active window; - opens documents in MDI subwindows, maximized, as in the Windows version; a nonexistent file and a path with characters outside the code page are not opened (path check);
- maintains the list of recent files (recent files) and the window position (window placement);
- on destruction first detaches the views from the widgets, then deletes the views and documents.
Common to the three viewers
TMCROS and TMC_DN are built on copies of this code. What is common and can be referenced from their pages:
- the document with the list of plots
TMC_GR_DOC/TMC_GR_DOC1, the line format#tag value,!comments, space collapsingdel_bl2, the default stylessGrDoc[16]— document, document file; - the default parameter line in the settings with the 0x01 separator — settings;
- the plot window
TMC_GR_WINDOW, theMM_HIMETRICmode, coordinate conversion, clamping to the edges — axes and scale; grid and format check — grid; legend — legend; line and marker styles — style; - mouse, zoom and shift — mouse, commands;
- expression curves
CTMCGrExpression(TMCROS addsGetExpressionValueRe— an expression over signal values) — expressions; - the status bar through
CMainFrame— Qt shell.
What differs are the quantities on the axes (for TMCROS and TMC_DN — time and signals, constants
TMC_GROTS_TYPE_*), the document file tags and the windows.
Common constants tmcgrviw.h
The header is shared by the viewers, the kernels, TMCIndan and FieldView:
- axis quantity types:
TMC_GR_TYPE_*(TMCGROUT),TMC_GROTS_TYPE_*(signals and time); - document file tags (
TMC_GROUT_DOCFILE_*,TMC_TOPVIEW_DOCFILE_*) and settings keys (TMC_GROTS_DOCFILE_*); - header tags of the kernel output files: signals
.t(TMC_GROTS_FILEOUT_ID,TMC_GROTS_FLOUT*), fields (TMC_GROFLD_DOCFILE_*), topology (TMC_RTH_FILETOP_ID); - keywords of the
.tpltask file blocks (CTMCRTH_INDANBLCK_*) and the block and node codes: 0 — dielectric, 100 — absorber, 101 — metal, 102…105 — ports (left, right, top, bottom), 107 — magnetic wall,ABSR_*— neighborhood codes of absorber nodes (kernel H: node types, absorber); - structures of the document and the plot window (
TMC_GR_DOC1,TMC_GR_DOC,TMC_GR_VIEW,TMC_GR_WINDOW…).
The values are written into user files and program settings — they must not be changed. The tags
of the TAMIC task file sections (#STEP, #EOF, BLOCK …), TMC_DNOUT_DOCFILE_ID, the phase units
TMC_GR_TYPE_PRad/PGradus and the free functions at the end of the file (RunExeFileG,
MakeRelatPathFile …) are not used in the Qt6 version code; the functions have no definitions.
Test programs
Not included in the distribution.
| Program | What it does |
|---|---|
tmcgrout_doccheck <document> [--dump] |
opens the document with the same code as the program, without graphics, and prints the axes, ranges, list of plots, ports and modes, number of points and the first three values; with --dump — the lines of the file with visible <CR>/<LF>/<TAB>. Separates file parsing errors from drawing errors |
tmcgrout_shot <file.png> [document] [width] [height] |
renders the main window into an image (works with QT_QPA_PLATFORM=offscreen too); with --dialogs <folder> captures all dialogs (dialog screenshots) |
tmcgrout_uitest <document> [seconds] |
triggers all commands, resizes the window, clicks and double-clicks on the plot (5 repetitions), checks that the mouse has not remained captured; on a hang prints the step and the stack. Not on Windows (SIGALRM, execinfo.h) |
Typical errors and pitfalls
WriteDocFilereturns FALSE on success and TRUE on error — the opposite of the usual convention.- An empty window for a file with a single frequency is not an error; a sweep is needed (above).
- The phase of an ordinary plot is not unwrapped — write the plot as an expression
{[name.s]}(phase unwrapping). - Values outside the Y range are drawn along the edge of the area rather than clipped — with a manual range the curve may "lie" on the frame.
- An absolute path is recognized only by
:or a leading\\. A path like/home/...is considered relative and is prefixed with the document folder. - Opening a
.screates a file next to it (.soc, or.$OCif a.socalready exists) — write permission is needed in the data folder;.$OCis overwritten on every opening. - An expression
{{...}}with the Y axis in dB is not evaluated: the branch inPrepareDoubleGraphis commented out, and the point values remain unfilled. - Spaces in names outside square brackets are not allowed: the plot row is split at spaces, and on writing spaces are removed from the name and the caption.
- The default external editor is
winword.exe; if it is not installed, Edit > Editor opens nothing — specify an editor in Config > Editor.
Files outside the build
childfrm.h/.cpp (MFC MDI child window — replaced by QMdiSubWindow), tmcgrout.cpp
(MFC application — replaced by apps/tmcgrout/main.cpp and MainWindow), stdafx.cpp
(precompiled header). Kept for comparison with the MFC version; see also
files outside the build.