Вьювер TMCROS — сигналы портов во времени и S-матрица по сигналам

Назначение и место в пакете

TMCROS (tmcros.exe) показывает сигналы на портах, которые счётное ядро PlanarRT_H или PlanarRT_X пишет во время расчёта в файл .t: падающую волну Up(t) и уходящую (отражённую на возбуждённом порту, прошедшую на остальных) Uo(t). По тем же сигналам программа строит матрицу рассеяния: команда Edit > To S-matrix пересчитывает один или несколько файлов .t в файл .s, который затем открывает TMCGROUT.

Подсистема «время → S-параметры» — классы CTmcTtoS, CTmcSMatrix (одна частота) и CTmcWideband (многочастотный расчёт) — компилируется не только во вьювер, но и в ядра H и X (библиотеки planarrt_h_ttos, planarrt_x_ttos): при директиве SMATRIX задания ядро само пишет .s после шага тем же кодом (ниже). Поэтому TMCROS и ядро дают одинаковый результат по одному и тому же .t.

Программа собрана из двух слоёв, как TMCGROUT:

  • src/viewers/tmcrtout — код Windows-версии: документ, вид, диалоги, выражения и пересчёт «время → S». Классы MFC реализует слой совместимости.
  • src/viewers/Tmcrtout/qt — Qt-оболочка: точка входа, главное окно, разметка диалогов, тестовые программы.

Документ, вид и диалоги — копии кода TMCGROUT с отличиями (ось X — время, метка документа #TMCGROTS, данные .t). Всё, что совпадает, описано на странице TMCGROUT (общее для вьюверов); здесь — только отличия и пересчёт в S-матрицу.

Состав

Файл Роль
src/viewers/tmcrtout/tmcgroutdoc.h/.cpp CTMCGROUTDoc — документ .tos, список графиков, чтение сигналов из .t
src/viewers/tmcrtout/tmcgroutview.h/.cpp CTMCGROUTView — вид: величины по осям, прореживание точек, рисование, мышь, команды меню, вызов окна To S-matrix
src/viewers/tmcrtout/tmcgrexpression.cpp CTMCGrExpression — кривая-выражение над сигналами (объявление — общий tmcgrexpression.h)
src/viewers/tmcrtout/dialogttos.h/.cpp CDialogTtoS — окно To S-matrix (IDD_DIALOG3)
src/viewers/tmcrtout/tmcttos.cpp CTmcTtoS — пересчёт .t → столбец S на одной частоте (объявление — src/Include/tmcttos.h)
src/viewers/tmcrtout/tmcsmatrix.cpp CTmcSMatrix — чтение отсчётов, восстановление амплитуд, нормировка, запись (объявление — src/Include/tmcsmatrix.h)
src/viewers/tmcrtout/tmcwideband.cpp CTmcWideband — многочастотная обработка (объявление — src/Include/tmcwideband.h)
src/viewers/tmcrtout/dialogdoc.h/.cpp окно Characteristics (IDD_DIALOG2): 20 строк графиков, без полей входа 2 и моды 2
src/viewers/tmcrtout/tmcgroutdialogview.h/.cpp окно Viewport (IDD_DIALOG1): диапазоны, единицы времени, величина Y, формат подписей
src/viewers/tmcrtout/tmcgroutcolorgraphdialog.h/.cpp, tmcgrparcoltypwid.h/.cpp окна стилей линий — копии окон TMCGROUT (стиль линий)
src/viewers/tmcrtout/mainfrm.h/.cpp CMainFrame — носитель строки состояния
src/viewers/tmcrtout/tmcgrout.h, stdafx.h, resource.h класс приложения MFC (не создаётся), общий заголовок, номера ресурсов
apps/tmcros/main.cpp, mainwindow.h/.cpp точка входа и главное окно (ниже)
apps/tmcros/dialogs/*.ui, dialog_registry.cpp разметка диалогов, порождённая из ресурса (диалоги из .rc)
apps/tmcros/testtools/* тестовые программы (ниже)

Сборка (apps/tmcros/CMakeLists.txt): tmcros_core (документ, tmcsmatrix, tmcttos, tmcwideband, выражения — без Qt), tmcros_view (вид, рамка, диалоги), tmcros_gui (главное окно, разметка, пиктограммы), программа tmcros, тестовые tmcros_doccheck, tmcros_shot, tmcros_uitest. Вне сборки — наследие.

Ключевые классы и их связи

MainWindow ─┬─ TmcDocumentWindow ×N ─┬─ CTMCGROUTDoc ── TMC_GR_DOC1[nGraph] (время, сигнал, dFreq)
            │                        │                 └─ CTMCGrExpression* (кривая-выражение)
            │                        └─ CTMCGROUTView ─┬─ tmcgrwin  (все точки в единицах осей)
            │                                          └─ tmcgrwin1 (прореженные точки для рисования)
            └─ CMainFrame m_frame (строка состояния)

CTMCGROUTView::OnEditTosmatrix ── CDialogTtoS ── ConvertOne ─┬─ CTmcWideband   (файл помечен как многочастотный)
                                                             └─ CTmcTtoS ── CTmcSMatrix
CTmcRTH_IndanOutput::PutSmatrix (ядра H и X) ────────────────┘ (тот же выбор)

Жизненный цикл окна документа и передача команд — как у TMCGROUT (классы TMCGROUT, Qt-оболочка). Пересчёт в S-матрицу выполняется синхронно в главном потоке; своих потоков у TMCROS нет.

Документ и его файл

Документ TMCROS устроен как документ TMCGROUT (документ, настройки) со следующими отличиями:

TMCGROUT TMCROS
метка первой строки #TMCGROUT #TMCGROTS
документ, созданный рядом с файлом данных .soc, если есть — .$OC .tos, если есть — .$os
файл данных графика .s (элемент S по частоте) .t (сигнал входа во времени)
единицы пользователя оси X (#dXAxiesUnit, #dXAxiesName) есть нет
умолчания КСВ по частоте в ГГц, точки рисуются сигнал по номеру отсчёта, точки не рисуются

Открытие файла .t создаёт документ с одним графиком имя имя 1 1 1 1 1 — уходящая волна первого входа. Строка графика в .tos имеет тот же вид, что в .soc (файл документа), но поля значат другое:

Поле Смысл в TMCROS
TFileName файл .t (относительно папки документа) или выражение {...}
GraphicsName подпись в легенде
DrawFlag 1 — показывать
Input1 номер входа — порядковый номер тройки чисел в строке данных .t, с 1
Mod1 0 — падающая волна Up, 1 — уходящая Uo
Input2, Mod2 не используются (Input2 приводится к 1, Mod2 — к 0..1)

Префикс *вход;мода;вход;мода* в имени файла, который понимает TMCGROUT, в TMCROS не разбирается.

Чтение файла .t

Формат файла — на странице ядра (файл .t). Строка данных начинается с пробела: номер такта, время (с), затем у каждого порта тройка «номер блока, Up, Uo».

ReadGraph1 → read_RT_output_signal читает файл за один проход:

  1. Строки, начинающиеся с пробела, — данные; из них берутся время и значение (gets_f1, gets_sss: пропустить номер такта, время и тройки предыдущих входов). Строка, которую не удалось разобрать (нет такого входа, строка недописана ядром), не прерывает чтение, а пропускается.
  2. Строка #TMC_GROTS_Freq f задаёт частоту расчёта графика (TMC_GR_DOC1::dFreq) и документа (CTMCGROUTDoc::dFreq); без неё — 1010 Гц. Частоту документа строка состояния показывает в ГГц, частота графика нужна для фазы.
  3. Массивы растут удвоением (с 4096 точек). Массив «частот» графика pFreq хранит время, с; массив pSmatr — значения сигнала (мнимая часть 0).

Ноль прочитанных точек — подпись Error_when_read_<имя>. Слежение за изменением файлов (таймер 10 с) — как у TMCGROUT (слежение): график растёт во время расчёта; файл читается с разрешением записи ядру.

Величины по осям

Ось X (nXType, TMC_GROTS_TYPE_*): 0 — номер отсчёта в файле (индекс строки данных, не номер такта из файла), 5 — с, 4 — мс, 3 — мкс, 2 — нс, 1 — пс. Множитель единиц — GetXAxiesUnit (1012 для пс … 1 для с).

Ось Y (nYType, PrepareDoubleGraph):

nYType Подпись Значение
0 TMC_GROTS_TYPE_FULL Signal сам сигнал u(tj)
1 TMC_GROTS_TYPE_AMPL Amplitude огибающая A (ниже)
4 TMC_GROTS_TYPE_WSVR WSVR (1+A)/(1−A); при |A−1|<10−4 берётся A=0.9999
5 TMC_GROTS_TYPE_LDB L dB −20lgA; при A=0 — 0
2 TMC_GROTS_TYPE_PHAS_R Phase in radian фаза по переходам через ноль (ниже), (0,2π)
3 TMC_GROTS_TYPE_PHAS_G Phase in gradus то же в градусах, (0°,360°)
6 TMC_GROTS_TYPE_PHASD Delta Phase отдельной ветки нет — показывается сам сигнал

КСВ и потери считаются по огибающей сигнала одного входа, а не по отношению волн: величина имеет смысл КСВ, только если график — уходящая волна возбуждённого входа при единичной падающей.

Огибающая

По трём последовательным отсчётам uj−2,uj−1,uj ищется локальный экстремум: если (uj−1−uj−2)(uj−uj−1)<0, огибающая A=|uj−1|; до первого экстремума A=|uj−1|. Точка j получает значение, найденное на прошлых точках, поэтому огибающая запаздывает на 1–2 отсчёта, а первые три точки равны 0.

Фаза по переходам через ноль

Когда сигнал переходит через ноль сверху вниз между tj−1 и tj (uj−1>0, uj<0), момент перехода находится линейной интерполяцией, а фаза — относительно начала периода частоты графика f:

t0=tj−1+uj−1(tj−tj−1)uj−1−uj,φ=2πf(t0−n+1/2f),n=⌊ftj−1⌋.(1)

Для u=Asin(2πft+ψ) это φ=−ψ(mod2π); у падающей волны ядра a(t)=Ampsin(ωt−Faza) (порт ядра) фаза равна Faza. Значение держится до следующего перехода и приводится к (0,2π). Частота f — из заголовка .t, поэтому у сигнала многочастотного расчёта такая «фаза» смысла не имеет.

Рисование

Сетка, оси, легенда, масштаб и мышь — как у TMCGROUT (оси, сетка, легенда, мышь). Отличия:

  • Прореживание точек. Сигнал содержит сотни тысяч отсчётов, поэтому PrepareLogGraph после перевода в логические координаты строит копию tmcgrwin1: только точки диапазона X, кроме тех, у которых логическая координата Y совпадает с Y обоих соседей (середины горизонтальных участков на экране). Линии и маркеры рисуются по этой копии.
  • Легенда: - <подпись> - <вход> falling для падающей волны, ... scattering — для уходящей.
  • Строка состояния, правая ячейка: <величина Y>; Freq=<f> GHz (частота документа).
  • OnDrawMouseScrol вызывается из OnDraw, но тело закомментировано.

Кривые-выражения

Синтаксис и разбор — как у TMCGROUT (выражения). Отличия TMCROS:

  • все файлы выражения читаются с входом и волной строки графика (Input1, Mod1);
  • время всех файлов должно совпадать (IsFreqCorrect сравнивает массивы времени);
  • значения вычисляются один раз при чтении (GetExpressionValueRe): в формулу подставляются значения сигналов в точке, переменная f библиотеки выражений равна времени точки, с; результат хранится как сигнал и проходит все величины оси Y, как обычный график — например, {[a.t]-[b.t]} с осью Amplitude даёт огибающую разности;
  • флажок Config > «Phase unwrapping» в TMCROS на графики не влияет: функции фазы выражений вид не вызывает.

Время → S-параметры

Кто пользуется

Вызывающий Когда Окно времени Частота записи в .s
TMCROS, CDialogTtoS::ConvertOne Edit > To S-matrix, для каждого отмеченного файла Tmin..Tmax окна × единица оси X столбец «X value» окна (по умолчанию FREQ из .t)
ядро H/X, CTmcRTH_IndanOutput::PutSmatrix конец шага #STEP, если задан SMATRIX Tmin..Tmax строки SMATRIX частота строки SMATRIX

Оба вызывающих делают одно и то же: если CTmcWideband::IsWidebandFile находит в заголовке #TMC_GROTS_Wideband 1, файл обрабатывает многочастотный путь, иначе — CTmcTtoS::TtoS на одной частоте. Результат — один столбец S-матрицы (номер — возбуждённый вход), который save_S_matrix_element дописывает в .s (запись столбца): нет файла — создаётся, частота уже есть — столбец заменяется, иначе добавляется частотная точка. Теория — S-матрица по сигналам, запись сигналов.

CTmcTtoS::TtoS → MakeSmatrixFromFileT (CTmcSMatrix::ReadTFile, MakeSmatrix) → SaveSmatrixToFileS (CTmcSMatrix::Save). Каждый шаг при уже возникшей ошибке ничего не делает; текст ошибки — GetErrorMessage().

Чтение (ReadTFile): число входов — по первой строке данных, (Nчисел−2)/3; отсчёты — строки с временем Tmin≤t≤Tmax, их должно быть больше 5; частота расчёта f — из строки #TMC_GROTS_Freq.

Одна частота: синус по двум отсчётам

Преобразования Фурье в одночастотном пути нет. Сигнал на установившемся участке считается синусом частоты f, и по каждой паре соседних отсчётов (t1,u1),(t2,u2) восстанавливаются его амплитуда и фаза (TtoSOneInputOnePoint):

u(t)=Asin(ωt+φ),ω=2πf,(2)
tgφ=−u2sinωt1−u1sinωt2u2cosωt1−u1cosωt2,A=uksin(ωtk+φ),(3)

где k — отсчёт с бо́льшим |sin(ωtk+φ)|; при A<0 берутся −A и φ−π. Комплексная амплитуда сигнала — среднее по всем парам окна:

U˙=1M∑m=1MAmejφm.(4)

Пара из двух нулевых отсчётов входит в среднее с вкладом 0; вырожденная пара (система не решается) не учитывается. Так считается U˙o каждого входа (TtoSOneInput).

Нормировка на падающую волну

MakeSmatrix:

  1. Возбуждённый вход n — вход, у которого в окне есть падающая волна (|Up|>10DBL_MIN хотя бы в одном отсчёте). Он должен быть ровно один: ни одного — There are no exited inputs, больше — Not one is exited of inputs.
  2. Тем же способом по двум отсчётам — комплексная амплитуда падающей волны U˙p,n. Нет ни одной учтённой пары или |U˙p,n|2≤10−24 — ошибка No incident wave (Up).
  3. Если |U˙p,n−1|≥10−3, столбец делится на неё:
Sin=U˙o,iU˙p,n,i=1..Nвх;(5)

при |U˙p,n−1|<10−3 деления нет (разница считается шумом семи значащих цифр .t), Sin=U˙o,i. 4. NaN или бесконечность в столбце — ошибка (S of input N is not a number), а не нечисловое значение в .s.

Поскольку падающая волна ядра a(t)=Ampsin(ωt−Faza), деление снимает и амплитуду, и фазу возбуждения: Amp ≠ 1 и Faza ≠ 0 допустимы. Теория — нормировка.

Частота расчёта и частота записи

Амплитуды восстанавливаются на частоте из заголовка .t (FREQ шага, на которой шёл расчёт), а в .s точка записывается под частотой вызывающего: значение «X value» окна TMCROS или частота SMATRIX ядра (CTmcSMatrix::Save(имя, частота) заменяет частоту только при записи). Если они различаются, в .s окажется S, посчитанная на одной частоте, под подписью другой. Окно TMCROS по умолчанию подставляет FREQ из .t, но кнопка заполнения «X value» (Xmin + k·dX) эти значения перезаписывает.

Многочастотная обработка

Если падающая волна порта задана файлом .sig (падающая волна из файла), один расчёт несёт много частот. CTmcWideband::Process строит по нему S на всех частотах сразу (теория):

ReadHeader → ReadSignals → DetectSignalKind → ApplyWindow → FindFrequencies → MakeAndSave

Заголовок .t

Ядро (PutPortInfo) дописывает в заголовок (файл .t):

Строка Значение
#TMC_GROTS_Wideband 1 хотя бы у одного порта сигнал из файла (0 — нет, файл обрабатывается одночастотным путём)
#TMC_GROTS_SigFreq f1 f2 … частоты из строки #FREQ файла .sig, Гц (если она есть)
#TMC_GROTS_Port блок Δ b f0 файл по строке на порт: номер блока, шаг сетки (м), апертура (м), частота согласования = FREQ шага (Гц), признак сигнала из файла

Портов и частот — не больше TMC_WIDEBAND_MAXFREQ = 99. Строки данных — как обычно; меньше 8 отсчётов — ошибка.

Вид сигнала и окно

DetectSignalKind: если в последней четверти записи |Up| какого-либо порта больше 1 % максимума — непрерывный многотон, иначе — импульс. Вид определяется по всей записи, до применения окна.

ApplyWindow: при Tmax>Tmin остаются отсчёты окна (меньше 8 — ошибка). В ядре строка SMATRIX имя; F; без Tmin, Tmax означает окно 0..TIME задания. Для импульса — предупреждения (S-матрица всё равно пишется):

  • в последних 5 % окна сигнал (max(|Up|,|Uo|) всех портов) больше 1 % пика — отклик не затух, спектр искажён;
  • окно отрезало начало записи, а в первых 5 % окна сигнал больше 1 % пика — окно начинается во время импульса.

Частоты расчёта

FindFrequencies:

  1. Частоты из заголовка (#TMC_GROTS_SigFreq) берутся как есть. Для многотона окно подгонки — конец записи длиной в целое число периодов шага частот Δf=(flast−ffirst)/(N−1): T=round(T1/2Δf)/Δf, где T1/2 — половина записи (тогда тоны на окне ортогональны).
  2. Иначе — по спектру падающей волны возбуждённого порта (первый порт с |Up|>10−12). Сетка из 2048 частот fk=(k+1)Fmax/2048, Fmax=min(Fs/4, 3f0), Fs — частота отсчётов, f0 — частота согласования первого порта. Уровень — |X(fk)|: для многотона — проекция на второй половине записи, для импульса — интеграл по всей записи (ниже).
  3. Пики: точка, не меньшая всех точек в пределах ±1/(Tδf) отсчётов сетки (ширина разрешения 1/T), не ниже −20 дБ от наибольшей и не меньше соседей. Положение уточняется параболой по трём точкам: f=(k+1+δ)δf, δ=12ak−1−ak+1ak−1−2ak+ak+1, |δ|≤1.
  4. Не больше двух пиков (импульс — один широкий горб): 21 частота равномерно по полосе, где уровень выше −20 дБ.
  5. Многотон, не меньше двух пиков: окно укорачивается до целого числа периодов среднего шага найденных пиков, и пики ищутся заново (утечка между соседними тонами на неровном окне раздвигает их примерно на процент).

Ни одной частоты — ошибка no frequency carries energy.

Спектры и столбец S

Комплексные амплитуды на частоте f (MakeAndSave):

  • импульс — интеграл по записи (Integrate, прямоугольники по правым точкам):
X(f)=∑ix(ti)e−j2πfti(ti−ti−1);(6)
  • многотон — совместная подгонка всех тонов методом наименьших квадратов на окне подгонки (FitTones):
x(t)≈∑k(akcosωkt−bksinωkt)=Re∑kckejωkt,ck=ak+jbk,(7)

нормальные уравнения размера 2N решаются методом Гаусса с выбором главного элемента (SolveLinear); вырожденная система (тоны ближе 1/T или повторяются) — ошибка. По отдельности тоны не подгоняются: на произвольном окне они не ортогональны. Проекция для поиска частот (Project) — X=2T∑x(ti)e−jωtiΔti.

Для каждой частоты fk и каждого порта i:

Sin(fk)=Uo,i(fk)Up,n(fk),(8)

n — возбуждённый порт. Если |Up,n(fk)|2<10−12maxk|Up,n(fk)|2 — на частоте нет падающей волны, ошибка. Затем поправка на рассогласование и запись столбца save_S_matrix_element(n+1, …, f_k). Порог «единичной» падающей волны одночастотного пути здесь не действует — деление выполняется всегда.

Поправка на рассогласование порта

Ядро согласует нагрузку порта с основной волной только на частоте задания f0 (порты ядра); на других частотах сам порт отражает. PortGamma считает коэффициент отражения порта по данным строки #TMC_GROTS_Port:

Y(f)=sin(arccos(2cosa−cos(πΔ/b)))sina,a=2πΔfc,Γ(f)=Y(f)−Y(f0)Y(f)+Y(f0).(9)

Если аргумент arccos вне [−1,1] — частота ниже отсечки порта, ошибка на этой частоте.

Теория (рассогласование) даёт матричную поправку

Sист=(Sизм+G)(I+GSизм)−1,G=diag(Γ1,Γ2,…).(10)

Один расчёт даёт один столбец, поэтому FixMismatch реализует её частные случаи:

  • два порта: структура считается симметричной (S22=S11, S12=S21), и обоим портам приписывается Γ возбуждённого. Тогда матрицы S и G=ΓI диагонализуются чётной и нечётной волнами, и формула распадается на две скалярные:
Ge,o=S11±S21,G′=G+Γ1+ΓG,S11=Ge′+Go′2,S21=Ge′−Go′2;(11)
  • другое число портов: исправляется только отражение возбуждённого порта Snn′=(Snn+Γ)/(1+ΓSnn); остальные элементы не меняются.

Для несимметричной структуры точная поправка требует обоих возбуждений и полной матрицы — в коде её нет.

Ошибки по частотам

Ошибка на отдельной частоте (нет падающей волны, ниже отсечки, не удалась подгонка) не останавливает расчёт: в .s на этой частоте пишется нулевой столбец, следующие частоты считаются. В конце — общая ошибка Wideband: error at N of M frequencies (...) с первыми десятью частотами и текстом первой ошибки. Окно TMCROS при этом не закрывается, ядро сохраняет текст в csSMatrixError.

Диалоги

Окна Viewport, Characteristics и стилей линий — копии окон TMCGROUT (команды TMCGROUT). У Viewport переключатели единиц X — время (номер переключателя = TMC_GROTS_TYPE_*: 0 отсчёт, 1 пс, 2 нс, 3 мкс, 4 мс, 5 с), величины Y — 0 сигнал, 1 огибающая, 2 фаза рад, 3 фаза град, 4 КСВ, 5 L дБ; полей единиц пользователя нет. У Characteristics нет полей входа 2 и моды 2.

Окно To S-matrix

CDialogTtoS (IDD_DIALOG3) открывает CTMCGROUTView::OnEditTosmatrix:

  • строки 1..20 — первые 20 графиков документа: путь .t (относительный дополняется папкой документа в DoModal), признак обработки = признак показа, частота записи = частота из заголовка .t;
  • окно времени — текущий диапазон оси X и подпись единиц; dTUnit переводит единицы оси в секунды. При оси в номерах отсчётов — 0..1 с (практически вся запись);
  • файл .s по умолчанию — путь документа с расширением .s.
Кнопка Действие
Export to S (OnExportCharacteristics) ConvertOne для каждой отмеченной непустой строки по порядку, до первой ошибки; окно остаётся открытым
OK то же; при ошибке окно не закрывается, при предупреждении многочастотной обработки — сообщение и закрытие
Fill X value частоты строк =Xmin+kdX, k=0..19 (по умолчанию 1010 и 108 Гц)
Add выбор .t, путь в первую пустую строку
Change выбор файла .s
Delete сразу удаляет файл .s (без подтверждения)

Пересчёт всех строк пишет в один файл .s: каждая строка (каждый .t) добавляет точку (или заменяет столбец на той же частоте). Чтобы получить свип, перечисляют файлы .t расчётов на разных частотах с правильными частотами записи.

Команды меню

Меню и обработчики — как у TMCGROUT (команды), кроме:

Меню Пункт (клавиши) Номер Обработчик
Edit To S-matrix (Alt+T) ID_EDIT_TOSMATRIX OnEditTosmatrix — окно To S-matrix
Edit Add characteristics (Ctrl+A) ID_EDIT_ADDCHARACTERISTICS выбор .t
View > Translate > Change X Home, End ID_VIEW_TRANSLATE_CHANGEXMAXXMIN_HOME/END окно X к первому/последнему отсчёту, ширина сохраняется (ось в отсчётах: Home — к 0, End — к номеру последнего); только без автодиапазона X
File Save As ID_FILE_SAVE_AS расширение .tos
Config Phase unwrapping — меняет g_nTmcPhaseUnwrap; в TMCROS на графики не влияет

Номера команд TMCROS (resource.h) отличаются от номеров TMCGROUT с теми же именами.

Qt-оболочка

Как у TMCGROUT (Qt-оболочка): main.cpp задаёт имя настроек TMCROS, оформление tmcros и открывает файл из командной строки; MainWindow регистрирует разметку (TmcInstallDialogs_tmcros, в том числе IDD_DIALOG3), создаёт рамку CMainFrame для строки состояния, открывает документы в подокнах MDI. Фильтр окна открытия — *.toc *.$oc *.t *.tos *.$os; новый документ получает заголовок TMCRTOS<номер>.

Тестовые программы

В поставку не входят; устроены как у TMCGROUT (тестовые программы).

Программа Что делает
tmcros_doccheck <документ> [--dump] открывает документ кодом программы без графики и печатает оси, список графиков, число точек и первые значения; --dump — строки файла с видимыми <CR>/<LF>/<TAB>
tmcros_shot <файл.png> [документ] [ширина] [высота] [команда] рисует главное окно в картинку; пятый довод — номер команды из resource.h, выполняемой перед снимком; --dialogs <папка> — снимки всех диалогов
tmcros_uitest <документ> [секунд] нажимает все команды, меняет размер окна, щёлкает по графику; при зависании печатает шаг и стек. Только не под Windows

Типичные ошибки и подводные камни

  • Частота расчёта ≠ частота записи. S считается на FREQ из .t, а записывается под «X value» окна или частотой SMATRIX (подробнее). После «Fill X value» проверьте частоты.
  • Окно времени должно лежать на установившемся участке. Пары отсчётов, где сигнал ещё нулевой, входят в среднее с нулевым вкладом и занижают амплитуду; переходный процесс искажает и амплитуду, и фазу.
  • Ровно один возбуждённый вход. Расчёт с несколькими возбуждёнными портами одночастотным путём не пересчитывается. Многочастотный путь берёт первый порт с ненулевой падающей волной и единственность не проверяет.
  • При |Up−1|<10−3 деления на падающую волну нет — это допущение, а не ошибка.
  • .s дописывается. Старые точки остаются; повторный пересчёт на той же частоте заменяет столбец, на другой — добавляет точку. Кнопка Delete удаляет файл без вопроса.
  • Поправка на рассогласование — только для симметричного двухполюсника, с Γ возбуждённого порта на обоих портах; при другом числе портов исправляется только отражение. Формула Y(f) в PortGamma — для порта без среды (W=0) и без учёта типа стенок; у ядра нагрузка порта учитывает проводимость шлейфа yW (порты).
  • Вид многочастотного сигнала определяется по всей записи, а не по окну.
  • Ошибка на части частот даёт нули в .s на этих частотах и общую ошибку — окно не закрывается, но файл уже записан.
  • КСВ и L по огибающей имеют смысл только для уходящей волны возбуждённого входа при единичной падающей; огибающая больше 1 даёт отрицательный КСВ.
  • Delta Phase (nYType = 6) отдельно не вычисляется — показывается сигнал.
  • Флажок разворота фазы в TMCROS ни на что не влияет.
  • Номер входа — порядковый номер тройки в строке .t, а не номер блока порта.

Файлы вне сборки

childfrm.h/.cpp (дочернее окно MDI MFC — заменено QMdiSubWindow), tmcgrout.cpp (приложение MFC — заменено apps/tmcros/main.cpp и MainWindow), stdafx.cpp (предкомпилированный заголовок), tmcgrparcoltypwid1.h/.cpp (старая копия окна стиля линии со ссылкой на несуществующий ресурс; не входила и в проект MFC-версии). См. также файлы вне сборки.

TMCROS viewer — port signals in time and the S-matrix from signals

Purpose and place in the package

TMCROS (tmcros.exe) shows the port signals that the PlanarRT_H or PlanarRT_X compute kernel writes to a .t file during the computation: the incident wave Up(t) and the outgoing wave Uo(t) (reflected at the excited port, transmitted at the others). From the same signals the program builds the scattering matrix: the command Edit > To S-matrix converts one or several .t files into a .s file, which is then opened by TMCGROUT.

The "time → S-parameters" subsystem — the classes CTmcTtoS, CTmcSMatrix (one frequency) and CTmcWideband (multi-frequency computation) — is compiled not only into the viewer but also into the H and X kernels (the libraries planarrt_h_ttos, planarrt_x_ttos): with the SMATRIX directive of the task file the kernel itself writes .s after a step with the same code (below). Therefore TMCROS and the kernel give the same result from the same .t.

The program is built from two layers, like TMCGROUT:

  • src/viewers/tmcrtout — code of the Windows version: document, view, dialogs, expressions and the "time → S" conversion. The MFC classes are implemented by the compatibility layer.
  • src/viewers/Tmcrtout/qt — the Qt shell: entry point, main window, dialog layouts, test programs.

The document, the view and the dialogs are copies of the TMCGROUT code with differences (the X axis is time, the document label is #TMCGROTS, the data are .t). Everything that coincides is described on the TMCGROUT page (common to the viewers); here only the differences and the conversion to the S-matrix are given.

Contents

File Role
src/viewers/tmcrtout/tmcgroutdoc.h/.cpp CTMCGROUTDoc — the .tos document, list of plots, reading signals from .t
src/viewers/tmcrtout/tmcgroutview.h/.cpp CTMCGROUTView — the view: axis quantities, point thinning, drawing, mouse, menu commands, opening the To S-matrix dialog
src/viewers/tmcrtout/tmcgrexpression.cpp CTMCGrExpression — an expression curve over signals (declaration — the shared tmcgrexpression.h)
src/viewers/tmcrtout/dialogttos.h/.cpp CDialogTtoS — the To S-matrix dialog (IDD_DIALOG3)
src/viewers/tmcrtout/tmcttos.cpp CTmcTtoS — conversion .t → S column at one frequency (declaration — src/Include/tmcttos.h)
src/viewers/tmcrtout/tmcsmatrix.cpp CTmcSMatrix — reading samples, recovering amplitudes, normalisation, writing (declaration — src/Include/tmcsmatrix.h)
src/viewers/tmcrtout/tmcwideband.cpp CTmcWideband — multi-frequency processing (declaration — src/Include/tmcwideband.h)
src/viewers/tmcrtout/dialogdoc.h/.cpp the Characteristics dialog (IDD_DIALOG2): 20 plot rows, without the Input 2 and Mode 2 fields
src/viewers/tmcrtout/tmcgroutdialogview.h/.cpp the Viewport dialog (IDD_DIALOG1): ranges, time units, Y quantity, label format
src/viewers/tmcrtout/tmcgroutcolorgraphdialog.h/.cpp, tmcgrparcoltypwid.h/.cpp line-style dialogs — copies of the TMCGROUT dialogs (line style)
src/viewers/tmcrtout/mainfrm.h/.cpp CMainFrame — carrier of the status bar
src/viewers/tmcrtout/tmcgrout.h, stdafx.h, resource.h the MFC application class (not created), common header, resource IDs
apps/tmcros/main.cpp, mainwindow.h/.cpp entry point and main window (below)
apps/tmcros/dialogs/*.ui, dialog_registry.cpp dialog layouts generated from the resource (dialogs from .rc)
apps/tmcros/testtools/* test programs (below)

Build (apps/tmcros/CMakeLists.txt): tmcros_core (document, tmcsmatrix, tmcttos, tmcwideband, expressions — without Qt), tmcros_view (view, frame, dialogs), tmcros_gui (main window, layouts, icons), the program tmcros, the test programs tmcros_doccheck, tmcros_shot, tmcros_uitest. Outside the build — legacy.

Key classes and their relations

MainWindow ─┬─ TmcDocumentWindow ×N ─┬─ CTMCGROUTDoc ── TMC_GR_DOC1[nGraph] (time, signal, dFreq)
            │                        │                 └─ CTMCGrExpression* (expression curve)
            │                        └─ CTMCGROUTView ─┬─ tmcgrwin  (all points in axis units)
            │                                          └─ tmcgrwin1 (thinned points for drawing)
            └─ CMainFrame m_frame (status bar)

CTMCGROUTView::OnEditTosmatrix ── CDialogTtoS ── ConvertOne ─┬─ CTmcWideband   (file marked as multi-frequency)
                                                             └─ CTmcTtoS ── CTmcSMatrix
CTmcRTH_IndanOutput::PutSmatrix (H and X kernels) ───────────┘ (the same choice)

The life cycle of the document window and command routing are the same as in TMCGROUT (TMCGROUT classes, Qt shell). The conversion to the S-matrix is performed synchronously in the main thread; TMCROS has no threads of its own.

The document and its file

The TMCROS document is organised like the TMCGROUT document (document, settings) with the following differences:

TMCGROUT TMCROS
label of the first line #TMCGROUT #TMCGROTS
document created next to the data file .soc, if it exists — .$OC .tos, if it exists — .$os
data file of a plot .s (S element versus frequency) .t (port signal versus time)
user units of the X axis (#dXAxiesUnit, #dXAxiesName) yes no
defaults VSWR versus frequency in GHz, points are drawn signal versus sample number, points are not drawn

Opening a .t file creates a document with one plot name name 1 1 1 1 1 — the outgoing wave of the first port. A plot line in .tos has the same form as in .soc (document file), but the fields mean different things:

Field Meaning in TMCROS
TFileName the .t file (relative to the document folder) or an expression {...}
GraphicsName label in the legend
DrawFlag 1 — show
Input1 port number — the ordinal number of the triple of numbers in a .t data line, from 1
Mod1 0 — incident wave Up, 1 — outgoing wave Uo
Input2, Mod2 not used (Input2 is clamped to 1, Mod2 to 0..1)

The prefix *port;mode;port;mode* in the file name, which TMCGROUT understands, is not parsed in TMCROS.

Reading the .t file

The file format is described on the kernel page (the .t file). A data line starts with a space: the time-step number, the time (s), then for each port a triple "block number, Up, Uo".

ReadGraph1 → read_RT_output_signal reads the file in a single pass:

  1. Lines starting with a space are data; the time and the value are taken from them (gets_f1, gets_sss: skip the time-step number, the time and the triples of the preceding ports). A line that could not be parsed (no such port, a line not yet completely written by the kernel) does not interrupt reading but is skipped.
  2. The line #TMC_GROTS_Freq f sets the computation frequency of the plot (TMC_GR_DOC1::dFreq) and of the document (CTMCGROUTDoc::dFreq); without it — 1010 Hz. The status bar shows the document frequency in GHz; the plot frequency is needed for the phase.
  3. The arrays grow by doubling (starting from 4096 points). The "frequency" array of the plot pFreq stores the time, s; the array pSmatr stores the signal values (imaginary part 0).

Zero points read gives the label Error_when_read_<name>. Watching for file changes (10 s timer) works as in TMCGROUT (watching): the plot grows during the computation; the file is read while allowing the kernel to write to it.

Axis quantities

X axis (nXType, TMC_GROTS_TYPE_*): 0 — sample number in the file (index of the data line, not the time-step number from the file), 5 — s, 4 — ms, 3 — µs, 2 — ns, 1 — ps. The unit multiplier is GetXAxiesUnit (1012 for ps … 1 for s).

Y axis (nYType, PrepareDoubleGraph):

nYType Label Value
0 TMC_GROTS_TYPE_FULL Signal the signal itself u(tj)
1 TMC_GROTS_TYPE_AMPL Amplitude the envelope A (below)
4 TMC_GROTS_TYPE_WSVR WSVR (1+A)/(1−A); for |A−1|<10−4, A=0.9999 is taken
5 TMC_GROTS_TYPE_LDB L dB −20lgA; for A=0 — 0
2 TMC_GROTS_TYPE_PHAS_R Phase in radian phase from zero crossings (below), (0,2π)
3 TMC_GROTS_TYPE_PHAS_G Phase in gradus the same in degrees, (0°,360°)
6 TMC_GROTS_TYPE_PHASD Delta Phase there is no separate branch — the signal itself is shown

VSWR and loss are computed from the envelope of the signal of a single port, not from the ratio of the waves: the quantity has the meaning of VSWR only if the plot is the outgoing wave of the excited port with a unit incident wave.

Envelope

A local extremum is searched for over three consecutive samples uj−2,uj−1,uj: if (uj−1−uj−2)(uj−uj−1)<0, the envelope is A=|uj−1|; before the first extremum A=|uj−1|. Point j gets the value found at previous points, so the envelope lags by 1–2 samples, and the first three points are 0.

Phase from zero crossings

When the signal crosses zero from above between tj−1 and tj (uj−1>0, uj<0), the moment of the crossing is found by linear interpolation, and the phase relative to the beginning of a period of the plot frequency f:

t0=tj−1+uj−1(tj−tj−1)uj−1−uj,φ=2πf(t0−n+1/2f),n=⌊ftj−1⌋.(1)

For u=Asin(2πft+ψ) this gives φ=−ψ(mod2π); for the incident wave of the kernel a(t)=Ampsin(ωt−Faza) (kernel port) the phase equals Faza. The value is held until the next crossing and is reduced to (0,2π). The frequency f comes from the .t header, so for the signal of a multi-frequency computation such a "phase" has no meaning.

Drawing

Grid, axes, legend, scale and mouse work as in TMCGROUT (axes, grid, legend, mouse). Differences:

  • Point thinning. A signal contains hundreds of thousands of samples, so PrepareLogGraph, after conversion to logical coordinates, builds a copy tmcgrwin1: only the points within the X range, except those whose logical Y coordinate coincides with the Y of both neighbours (the middles of horizontal segments on the screen). Lines and markers are drawn from this copy.
  • Legend: - <label> - <port> falling for the incident wave, ... scattering for the outgoing wave.
  • Status bar, right pane: <Y quantity>; Freq=<f> GHz (the document frequency).
  • OnDrawMouseScrol is called from OnDraw, but its body is commented out.

Expression curves

Syntax and parsing are as in TMCGROUT (expressions). Differences in TMCROS:

  • all files of an expression are read with the port and wave of the plot line (Input1, Mod1);
  • the time of all files must coincide (IsFreqCorrect compares the time arrays);
  • the values are evaluated once on reading (GetExpressionValueRe): the signal values at the point are substituted into the formula, the variable f of the expression library equals the time of the point, s; the result is stored as a signal and goes through all Y-axis quantities like an ordinary plot — for example, {[a.t]-[b.t]} with the Amplitude axis gives the envelope of the difference;
  • the Config > "Phase unwrapping" check box has no effect on the plots in TMCROS: the view does not call the phase functions of expressions.

Time → S-parameters

Who uses it

Caller When Time window Frequency written to .s
TMCROS, CDialogTtoS::ConvertOne Edit > To S-matrix, for each checked file Tmin..Tmax of the dialog × X-axis unit the "X value" column of the dialog (by default FREQ from .t)
H/X kernel, CTmcRTH_IndanOutput::PutSmatrix end of a #STEP, if SMATRIX is given Tmin..Tmax of the SMATRIX line the frequency of the SMATRIX line

Both callers do the same thing: if CTmcWideband::IsWidebandFile finds #TMC_GROTS_Wideband 1 in the header, the file is processed by the multi-frequency path, otherwise by CTmcTtoS::TtoS at a single frequency. The result is one column of the S-matrix (its number is the excited port), which save_S_matrix_element appends to .s (writing a column): if there is no file, it is created; if the frequency already exists, the column is replaced; otherwise a frequency point is added. Theory — S-matrix from signals, signal recording.

CTmcTtoS::TtoS → MakeSmatrixFromFileT (CTmcSMatrix::ReadTFile, MakeSmatrix) → SaveSmatrixToFileS (CTmcSMatrix::Save). Each step does nothing if an error has already occurred; the error text is GetErrorMessage().

Reading (ReadTFile): the number of ports is taken from the first data line, (Nnum−2)/3; the samples are the lines with time Tmin≤t≤Tmax, and there must be more than 5 of them; the computation frequency f is taken from the #TMC_GROTS_Freq line.

One frequency: a sine from two samples

There is no Fourier transform in the single-frequency path. The signal on the steady-state segment is assumed to be a sine of frequency f, and from each pair of adjacent samples (t1,u1),(t2,u2) its amplitude and phase are recovered (TtoSOneInputOnePoint):

u(t)=Asin(ωt+φ),ω=2πf,(2)
tgφ=−u2sinωt1−u1sinωt2u2cosωt1−u1cosωt2,A=uksin(ωtk+φ),(3)

where k is the sample with the larger |sin(ωtk+φ)|; for A<0, −A and φ−π are taken. The complex amplitude of the signal is the mean over all pairs of the window:

U˙=1M∑m=1MAmejφm.(4)

A pair of two zero samples enters the mean with a contribution of 0; a degenerate pair (the system cannot be solved) is not taken into account. This is how U˙o of each port is computed (TtoSOneInput).

Normalisation to the incident wave

MakeSmatrix:

  1. The excited port n is the port that has an incident wave in the window (|Up|>10DBL_MIN in at least one sample). There must be exactly one: none — There are no exited inputs, more than one — Not one is exited of inputs.
  2. In the same way, from two samples, the complex amplitude of the incident wave U˙p,n is found. If no pair has been taken into account or |U˙p,n|2≤10−24, the error is No incident wave (Up).
  3. If |U˙p,n−1|≥10−3, the column is divided by it:
Sin=U˙o,iU˙p,n,i=1..Nports;(5)

for |U˙p,n−1|<10−3 there is no division (the difference is considered noise of the seven significant digits of .t), Sin=U˙o,i. 4. NaN or infinity in the column is an error (S of input N is not a number), rather than a non-numeric value in .s.

Since the incident wave of the kernel is a(t)=Ampsin(ωt−Faza), the division removes both the amplitude and the phase of the excitation: Amp ≠ 1 and Faza ≠ 0 are allowed. Theory — normalisation.

Computation frequency and written frequency

The amplitudes are recovered at the frequency from the .t header (the FREQ of the step at which the computation ran), while the point is written to .s under the frequency of the caller: the "X value" of the TMCROS dialog or the SMATRIX frequency of the kernel (CTmcSMatrix::Save(name, frequency) replaces the frequency only when writing). If they differ, .s will contain S computed at one frequency under the label of another. The TMCROS dialog fills in FREQ from .t by default, but the "X value" fill button (Xmin + k·dX) overwrites these values.

Multi-frequency processing

If the incident wave of a port is given by a .sig file (incident wave from a file), one computation carries many frequencies. CTmcWideband::Process builds S at all frequencies from it at once (theory):

ReadHeader → ReadSignals → DetectSignalKind → ApplyWindow → FindFrequencies → MakeAndSave

The .t header

The kernel (PutPortInfo) adds to the header (the .t file):

Line Meaning
#TMC_GROTS_Wideband 1 at least one port has a signal from a file (0 — none, the file is processed by the single-frequency path)
#TMC_GROTS_SigFreq f1 f2 … frequencies from the #FREQ line of the .sig file, Hz (if there is one)
#TMC_GROTS_Port block Δ b f0 file one line per port: block number, grid step (m), aperture (m), matching frequency = FREQ of the step (Hz), flag of a signal from a file

There are at most TMC_WIDEBAND_MAXFREQ = 99 ports and frequencies. The data lines are as usual; fewer than 8 samples is an error.

Signal kind and window

DetectSignalKind: if in the last quarter of the record |Up| of any port exceeds 1 % of the maximum — a continuous multitone, otherwise — a pulse. The kind is determined from the whole record, before the window is applied.

ApplyWindow: for Tmax>Tmin the samples of the window remain (fewer than 8 is an error). In the kernel the line SMATRIX name; F; without Tmin, Tmax means the window 0..TIME of the task file. For a pulse there are warnings (the S-matrix is written anyway):

  • in the last 5 % of the window the signal (max(|Up|,|Uo|) of all ports) exceeds 1 % of the peak — the response has not decayed, the spectrum is distorted;
  • the window has cut off the beginning of the record, and in the first 5 % of the window the signal exceeds 1 % of the peak — the window starts during the pulse.

Computation frequencies

FindFrequencies:

  1. Frequencies from the header (#TMC_GROTS_SigFreq) are taken as they are. For a multitone the fitting window is the end of the record with a length of a whole number of periods of the frequency step Δf=(flast−ffirst)/(N−1): T=round(T1/2Δf)/Δf, where T1/2 is half of the record (then the tones are orthogonal over the window).
  2. Otherwise — from the spectrum of the incident wave of the excited port (the first port with |Up|>10−12). A grid of 2048 frequencies fk=(k+1)Fmax/2048, Fmax=min(Fs/4, 3f0), Fs is the sampling frequency, f0 is the matching frequency of the first port. The level is |X(fk)|: for a multitone — the projection over the second half of the record, for a pulse — the integral over the whole record (below).
  3. Peaks: a point not less than all points within ±1/(Tδf) grid samples (resolution width 1/T), not lower than −20 dB from the largest and not less than its neighbours. The position is refined by a parabola through three points: f=(k+1+δ)δf, δ=12ak−1−ak+1ak−1−2ak+ak+1, |δ|≤1.
  4. No more than two peaks (a pulse is one wide hump): 21 frequencies uniformly over the band where the level is above −20 dB.
  5. Multitone, at least two peaks: the window is shortened to a whole number of periods of the mean spacing of the peaks found, and the peaks are searched for again (leakage between adjacent tones over an uneven window pushes them apart by about a percent).

No frequency at all is the error no frequency carries energy.

Spectra and the S column

Complex amplitudes at frequency f (MakeAndSave):

  • pulse — the integral over the record (Integrate, rectangles at the right points):
X(f)=∑ix(ti)e−j2πfti(ti−ti−1);(6)
  • multitone — a joint least-squares fit of all tones over the fitting window (FitTones):
x(t)≈∑k(akcosωkt−bksinωkt)=Re∑kckejωkt,ck=ak+jbk,(7)

the normal equations of size 2N are solved by Gaussian elimination with pivoting (SolveLinear); a degenerate system (tones closer than 1/T or repeated) is an error. The tones are not fitted separately: over an arbitrary window they are not orthogonal. The projection for frequency search (Project) is X=2T∑x(ti)e−jωtiΔti.

For each frequency fk and each port i:

Sin(fk)=Uo,i(fk)Up,n(fk),(8)

n is the excited port. If |Up,n(fk)|2<10−12maxk|Up,n(fk)|2, there is no incident wave at the frequency, which is an error. Then follow the mismatch correction and writing the column with save_S_matrix_element(n+1, …, f_k). The "unit" incident wave threshold of the single-frequency path does not apply here — the division is always performed.

Port mismatch correction

The kernel matches the port load to the fundamental wave only at the task-file frequency f0 (kernel ports); at other frequencies the port itself reflects. PortGamma computes the reflection coefficient of the port from the data of the #TMC_GROTS_Port line:

Y(f)=sin(arccos(2cosa−cos(πΔ/b)))sina,a=2πΔfc,Γ(f)=Y(f)−Y(f0)Y(f)+Y(f0).(9)

If the argument of arccos is outside [−1,1], the frequency is below the port cutoff, which is an error at that frequency.

The theory (mismatch) gives the matrix correction

Strue=(Smeas+G)(I+GSmeas)−1,G=diag(Γ1,Γ2,…).(10)

One computation gives one column, so FixMismatch implements special cases of it:

  • two ports: the structure is assumed to be symmetric (S22=S11, S12=S21), and both ports are assigned the Γ of the excited one. Then the matrices S and G=ΓI are diagonalised by the even and odd waves, and the formula splits into two scalar ones:
Ge,o=S11±S21,G′=G+Γ1+ΓG,S11=Ge′+Go′2,S21=Ge′−Go′2;(11)
  • another number of ports: only the reflection of the excited port is corrected, Snn′=(Snn+Γ)/(1+ΓSnn); the other elements are not changed.

For an asymmetric structure an exact correction requires both excitations and the full matrix — the code does not have it.

Per-frequency errors

An error at a particular frequency (no incident wave, below cutoff, fitting failed) does not stop the computation: a zero column is written to .s at that frequency, and the following frequencies are computed. At the end there is a general error Wideband: error at N of M frequencies (...) with the first ten frequencies and the text of the first error. The TMCROS dialog does not close in this case, and the kernel stores the text in csSMatrixError.

Dialogs

The Viewport, Characteristics and line-style dialogs are copies of the TMCGROUT dialogs (TMCGROUT commands). In Viewport the X unit radio buttons are time (the radio-button number = TMC_GROTS_TYPE_*: 0 sample, 1 ps, 2 ns, 3 µs, 4 ms, 5 s), the Y quantities are 0 signal, 1 envelope, 2 phase in rad, 3 phase in deg, 4 VSWR, 5 L dB; there are no user-unit fields. Characteristics has no Input 2 and Mode 2 fields.

The To S-matrix dialog

CDialogTtoS (IDD_DIALOG3) is opened by CTMCGROUTView::OnEditTosmatrix:

  • rows 1..20 are the first 20 plots of the document: the .t path (a relative one is completed with the document folder in DoModal), the processing flag = the display flag, the written frequency = the frequency from the .t header;
  • the time window is the current range of the X axis and the unit label; dTUnit converts the axis units to seconds. With the axis in sample numbers — 0..1 s (practically the whole record);
  • the default .s file is the document path with the .s extension.
Button Action
Export to S (OnExportCharacteristics) ConvertOne for each checked non-empty row in order, up to the first error; the dialog stays open
OK the same; on an error the dialog does not close, on a warning of multi-frequency processing — a message and closing
Fill X value row frequencies =Xmin+kdX, k=0..19 (by default 1010 and 108 Hz)
Add choose a .t, the path goes into the first empty row
Change choose the .s file
Delete immediately deletes the .s file (without confirmation)

Converting all rows writes to one .s file: each row (each .t) adds a point (or replaces the column at the same frequency). To obtain a sweep, list the .t files of computations at different frequencies with the correct written frequencies.

Menu commands

Menus and handlers are as in TMCGROUT (commands), except:

Menu Item (keys) ID Handler
Edit To S-matrix (Alt+T) ID_EDIT_TOSMATRIX OnEditTosmatrix — the To S-matrix dialog
Edit Add characteristics (Ctrl+A) ID_EDIT_ADDCHARACTERISTICS choose a .t
View > Translate > Change X Home, End ID_VIEW_TRANSLATE_CHANGEXMAXXMIN_HOME/END the X window to the first/last sample, the width is kept (axis in samples: Home — to 0, End — to the number of the last one); only without X auto-range
File Save As ID_FILE_SAVE_AS extension .tos
Config Phase unwrapping — changes g_nTmcPhaseUnwrap; has no effect on the plots in TMCROS

The TMCROS command IDs (resource.h) differ from the TMCGROUT IDs with the same names.

Qt shell

As in TMCGROUT (Qt shell): main.cpp sets the settings name TMCROS, the theme tmcros and opens the file from the command line; MainWindow registers the layouts (TmcInstallDialogs_tmcros, including IDD_DIALOG3), creates the CMainFrame frame for the status bar, and opens documents in MDI subwindows. The open-dialog filter is *.toc *.$oc *.t *.tos *.$os; a new document gets the title TMCRTOS<number>.

Test programs

Not part of the distribution; organised as in TMCGROUT (test programs).

Program What it does
tmcros_doccheck <document> [--dump] opens the document with the program code without graphics and prints the axes, the list of plots, the number of points and the first values; --dump — the file lines with visible <CR>/<LF>/<TAB>
tmcros_shot <file.png> [document] [width] [height] [command] renders the main window into an image; the fifth argument is a command ID from resource.h executed before the snapshot; --dialogs <folder> — snapshots of all dialogs
tmcros_uitest <document> [seconds] presses all commands, resizes the window, clicks on the plot; on a hang prints the step and the stack. Non-Windows builds only

Typical errors and pitfalls

  • Computation frequency ≠ written frequency. S is computed at FREQ from .t but written under the "X value" of the dialog or the SMATRIX frequency (details). After "Fill X value" check the frequencies.
  • The time window must lie on the steady-state segment. Pairs of samples where the signal is still zero enter the mean with a zero contribution and underestimate the amplitude; the transient distorts both amplitude and phase.
  • Exactly one excited port. A computation with several excited ports is not converted by the single-frequency path. The multi-frequency path takes the first port with a non-zero incident wave and does not check uniqueness.
  • For |Up−1|<10−3 there is no division by the incident wave — this is an assumption, not an error.
  • .s is appended to. Old points remain; converting again at the same frequency replaces the column, at a different one — adds a point. The Delete button deletes the file without asking.
  • The mismatch correction is only for a symmetric two-port, with the Γ of the excited port on both ports; with another number of ports only the reflection is corrected. The formula Y(f) in PortGamma is for a port without a medium (W=0) and does not take the wall type into account; in the kernel the port load takes the stub admittance yW into account (ports).
  • The kind of a multi-frequency signal is determined from the whole record, not from the window.
  • An error at some of the frequencies gives zeros in .s at those frequencies and a general error — the dialog does not close, but the file has already been written.
  • VSWR and L from the envelope make sense only for the outgoing wave of the excited port with a unit incident wave; an envelope greater than 1 gives a negative VSWR.
  • Delta Phase (nYType = 6) is not computed separately — the signal is shown.
  • The phase unwrapping check box has no effect in TMCROS.
  • The port number is the ordinal number of the triple in a .t line, not the block number of the port.

Files outside the build

childfrm.h/.cpp (MFC MDI child window — replaced by QMdiSubWindow), tmcgrout.cpp (the MFC application — replaced by apps/tmcros/main.cpp and MainWindow), stdafx.cpp (precompiled header), tmcgrparcoltypwid1.h/.cpp (an old copy of the line-style dialog referring to a non-existent resource; it was not part of the MFC-version project either). See also files outside the build.