Матрица рассеяния

Матрица рассеяния — частотная характеристика устройства, а счётные ядра пакета работают во временной области: на каждом такте они пересчитывают напряжения узлов сетки и записывают падающую и отражённую волны на каждом порту. Матрицу S строят по этим временным сигналам. На этой странице описано, что именно записывается на портах, как программа переходит от сигналов к комплексным амплитудам, как нормируется результат, как за один расчёт получить S на многих частотах и как показывается фаза. Источник по устройству пакета — [Климов, 2007, гл. 9] (состав программ и файлов, рис. 9.1, тесты разд. 9.5); алгоритмы обработки сигналов описаны по коду программ — ядер PlanarRT_H, PlanarRT_X и вьюверов TMCROS, TMCGROUT.

Путь данных: ядро пишет сигналы портов в файл .t (файл .t); по окончании шага расчёта (строка SMATRIX секции #OUTPUT) или по команде вьювера TMCROS Edit > To S-matrix сигналы пересчитываются в столбец матрицы рассеяния и дописываются в файл .s; графики элементов S по частоте показывает вьювер TMCGROUT.

Запись сигналов на портах

Что такое столбец S. Матрица рассеяния N-портового устройства связывает нормированные падающие волны an и отражённые (уходящие) волны bi на его входах [Сазонов и др., 1981]:

bi=∑n=1NSinan,Sin=bian|am=0, m≠n.(1)

Элемент Sin — отношение волны, ушедшей из порта i, к волне, падающей на порт n, когда остальные порты нагружены на согласованные нагрузки. Во временном расчёте это условие выполняется само собой: каждый порт — трансформатор возбуждения и поглощения, который поглощает приходящую основную волну без отражения, а сигнал задаётся только на одном порту. Поэтому один расчёт даёт один столбец матрицы — столбец возбуждённого порта n; для полной матрицы порты возбуждают по очереди.

Что пишется в .t. На каждом подтакте ядра (подтакты) в файл добавляется строка: номер такта, время t (с) и для каждого порта тройка «номер блока, Up, Uo», где

  • Up=a(t) — падающая волна, т. е. сигнал порта (сигнал);
  • Uo — отражённая (уходящая) волна: проекция отражённых напряжений узлов апертуры на профиль основной волны порта (формула Uo, [Климов, 2007, (6.44)]).

В заголовке файла записаны частота задания FREQ (строка #TMC_GROTS_Freq, Гц) и число портов; при падающей волне из файла — ещё признак многочастотного сигнала, список его частот и данные каждого порта для поправки на рассогласование (заголовок .t). Числа пишутся текстом с семью значащими цифрами. Номер порта в матрице — порядковый номер тройки в строке, а не номер блока.

Как смотреть сигналы. Вьювер TMCROS показывает Up(t) и Uo(t), их огибающую, КСВ и потери L=−20lgA по огибающей A (величины TMCROS). Так в [Климов, 2007, разд. 9.5.1] проверялось качество согласования порта: в прямоугольном волноводе, нагруженном на два трансформатора, строилась зависимость L11=10lg(1/|S11|2) от времени; идеальное значение — бесконечность, а достигнутое ограничено конечной разрядностью вычислений.

Переход в частотную область

Почему это возможно. Сетка ядер линейна и не меняется во времени: все её элементы — отрезки линий, шлейфы и проводимости с постоянными параметрами, в том числе в модели плазмы (модель плазмы). Поэтому уходящая волна uo(t) — свёртка падающей волны a(t) с импульсной характеристикой тракта «порт n → порт i», а для спектров выполняется

Uo(f)=Sin(f)Up(f),Sin(f)=Uo(f)Up(f)(2)

на каждой частоте f, где спектр падающей волны не равен нулю. Это основа всех способов обработки, которыми пользуется программа.

Спектр сигнала x(t), записанного отсчётами x(ti), вычисляется по определению преобразования Фурье, интеграл заменяется суммой прямоугольников по правым точкам:

X(f)=∫x(t)e−j2πftdt≈∑ix(ti)e−j2πfti(ti−ti−1).(3)

Какой способ где используется (быстрого преобразования Фурье в программе нет — спектр считается только на нужных частотах):

Сигнал Способ получить комплексную амплитуду Где
синус частоты FREQ, установившийся режим подбор синуса по парам соседних отсчётов, среднее по окну — без преобразования Фурье (ниже) одночастотный путь, CTmcSMatrix
сумма тонов (многотон) совместная подгонка всех тонов методом наименьших квадратов (ниже) многочастотный путь, CTmcWideband
импульс интеграл Фурье по всей записи (сумма выше) многочастотный путь, CTmcWideband
поле в узлах для ДН квадратуры на одной частоте за целое число периодов контур ДН

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

Нормировка

Нормировка волн по мощности. Падающая и отражённая волны порта нормированы так, что мощность падающей волны не зависит от размера сечения и типа волны [Климов, 2007, (6.41)–(6.43)] (трансформатор). В программе профиль падающей волны порта ri=Unpi имеет множитель Un=1/y1Δ2∑ipi2, где y1 — проводимость генератора порта, согласованная с основной волной. Поэтому мощность, которую порт вводит при сигнале a, пропорциональна y1Un2a2∑ipi2=a2/Δ2 и одинакова для портов любой ширины и среды, а отражённая волна Uo — проекция на тот же профиль. Отсюда |Sin|2 — доля мощности, переходящая из порта n в порт i. Для устройства без потерь и излучения сумма по столбцу

∑i=1N|Sin|2=1(4)

(закон сохранения энергии); отличие суммы от 1 на таком устройстве — удобная проверка расчёта.

Нормировка на падающую волну. Сигнал порта a(t)=Ampsin(2πFREQ·t−Faza) может иметь любую амплитуду и фазу (сигнал): масштаба напряжения в языке заданий нет. Поэтому столбец делится на комплексную амплитуду падающей волны возбуждённого порта:

Sin=U˙o,iU˙p,n,i=1…N.(5)

Деление снимает и амплитуду, и фазу возбуждения, поэтому Amp≠1 и Faza≠0 допустимы. Фаза Sin отсчитывается в сечениях портов, где записываются Up и Uo.

В программе (нормировка в коде):

  • возбуждённым считается порт, у которого в окне есть ненулевая падающая волна; в одночастотном пути он должен быть ровно один (иначе ошибка), в многочастотном берётся первый такой порт;
  • в одночастотном пути при |U˙p,n−1|<10−3 деление не выполняется: отличие от единицы считается шумом семи значащих цифр .t, и Sin=U˙o,i;
  • в многочастотном пути деление выполняется всегда;
  • нулевая падающая волна (|U˙p,n|2≤10−24) и нечисловые значения в столбце (расчёт разошёлся) — ошибка, а не запись NaN в .s.

Согласованность нагрузок, без которой (6.43)–(6.44) не дают S, у портов выполняется только для основной волны и только на частоте FREQ; на других частотах порт сам отражает — это снимается поправкой на рассогласование.

S-матрица по временным сигналам

Одночастотный расчёт. Сигнал на окне Tmin…Tmax считается синусом частоты f, взятой из заголовка .t (это FREQ шага, на которой шёл расчёт):

u(t)=Asin(ωt+φ),ω=2πf.(6)

По двум соседним отсчётам (t1,u1), (t2,u2) амплитуда и фаза находятся точно: из u2sin(ωt1+φ)=u1sin(ωt2+φ) следует

tgφ=−u2sinωt1−u1sinωt2u2cosωt1−u1cosωt2,A=uksin(ωtk+φ),(7)

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

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

Для чистого синуса все пары дают одно и то же; усреднение сглаживает округление чисел в .t и остатки переходного процесса. Так считаются U˙o,i всех портов и U˙p,n возбуждённого порта, затем нормировка. Отсчётов в окне должно быть больше пяти; пара из двух нулевых отсчётов входит в среднее с нулевым вкладом (поэтому окно не должно захватывать время, когда сигнал ещё не пришёл), вырожденная пара не учитывается.

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

Частота расчёта и частота записи. Амплитуды восстанавливаются на частоте из заголовка .t, а точка в .s записывается под частотой вызывающей программы: частотой строки SMATRIX ядра или значением «X value» окна TMCROS (подробно). В ядре несовпадение частоты SMATRIX с FREQ шага в одночастотном расчёте — ошибка задания; в TMCROS частоту записи нужно проверять самому.

Запись в .s. Столбец номер n дописывается в файл: файла нет — он создаётся, частота уже есть — столбец заменяется, иначе добавляется новая частотная точка (запись столбца). Частотная характеристика по одночастотным расчётам — это свип: серия шагов #STEP с разными FREQ, каждый дописывает свою точку (в одном .s — не больше 99 частот). Если шаг посчитан с ошибкой, ядро записывает на его частоте нулевую матрицу, чтобы ошибочная точка была видна на графике (вывод ядра).

Многочастотный расчёт за один проход

Идея. Из линейности следует, что широкополосная падающая волна возбуждает устройство сразу на всех своих частотах, и одна запись .t содержит отклик на каждой из них. Падающую волну задают файлом .sig вместо выражения Amp (падающая волна из файла); ядро отмечает это в заголовке .t, и тогда такой файл многочастотным путём обрабатывают и ядро (строка SMATRIX), и TMCROS (код). Время расчёта то же, что у одного одночастотного прохода.

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

Частоты. Если в файле .sig есть строка #FREQ, частоты берутся из неё. Иначе они ищутся по спектру падающей волны возбуждённого порта: на сетке из 2048 частот до Fmax=min(Fs/4, 3f0) (Fs — частота отсчётов, f0 — частота согласования порта) находятся пики не ниже −20 дБ от наибольшего; положение пика уточняется параболой по трём точкам. Если пиков не больше двух (импульс — один широкий горб), берётся 21 частота равномерно по полосе, где уровень спектра выше −20 дБ (частоты в коде).

Комплексные амплитуды. Для импульса — интеграл Фурье по всей записи в окне. Для многотона — совместная подгонка всех K тонов методом наименьших квадратов на окне длиной в целое число периодов разноса частот Δf:

x(t)≈∑k=1K(akcosωkt−bksinωkt)=Re∑k=1Kckejωkt,ck=ak+jbk.(9)

Нормальные уравнения размера 2K решаются методом Гаусса. Тоны подгоняются вместе, а не по отдельности, потому что на произвольном окне они не ортогональны; тоны, разнесённые меньше чем на 1/T (T — длина окна), не разделяются — система вырождается.

Столбец S на каждой частоте fk — по нормировке:

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

затем поправка на рассогласование порта и запись столбца в .s под частотой fk. Если на какой-то частоте падающей волны практически нет (|Up,n(fk)|2<10−12maxk|Up,n|2), частота ниже отсечки порта или не удалась подгонка, на этой частоте пишется нулевой столбец, а расчёт остальных частот продолжается; в конце выдаётся общая ошибка со списком частот. В одном расчёте — не больше 99 частот.

Требования к сигналу и окну. Импульс должен затухнуть внутри окна: если в последних 5 % окна сигнал больше 1 % пика или окно начинается во время импульса, выдаётся предупреждение. FREQ задания нужна и здесь — на ней согласованы порты и поглотители, и её ставят внутри полосы сигнала.

Проверка. На примере samples/MULTIFREQ (волновод 60 мм со вставкой ε=2, полоса 3,0–4,8 ГГц, 10 частот, ядро H) один проход занял 4,5 с против 35,1 с у свипа из 10 шагов, расхождение с эталонным свипом — 0,0016 дБ и 0,01° (руководство пользователя TMC Suite, раздел «Многочастотный расчёт»). Диаграмма направленности при многочастотном сигнале строится на каждой частоте (ДН).

Развёртка фазы

Фаза элемента S. Вьюверы показывают фазу S функцией cphase — это atan2(ImS,ReS), приведённый в диапазон (−2π,0] (угол комплексного числа). Каждая частотная точка получает угол на полном круге, поэтому на графике фазы обычного элемента видны скачки на 360°.

Почему фаза убывает. Для прохождения по тракту с групповым временем задержки τg фаза передачи с ростом частоты убывает: φ(f)≈φ0−2πfτg, где τg=−12πdφdf. Между соседними точками свипа с шагом Δf фаза меняется на −2πτgΔf, а cphase возвращает её по модулю 2π. Развёртка восстанавливает непрерывную кривую φk−2πnk, где nk — число переходов через границу диапазона по точкам 1…k.

В программе (TMCGROUT, разворот фазы) — два правила выбора перехода между точками j−1 и j:

Режим Правило Когда верно
0 (по умолчанию) φj>φj−1 → n++: фаза считается монотонно убывающей фаза действительно убывает и за шаг меняется меньше чем на 2π: Δf<1/τg
1, флажок Config > «Phase unwrapping: standard (threshold pi)» φj−φj−1>π → n++; <−π → n−− изменение за шаг меньше π по модулю: Δf<1/(2τg); фаза может и расти

Если шаг свипа крупнее, переходы не различимы ни одним правилом — нужен более частый свип. Развёртка применяется только к кривым-выражениям; чтобы развернуть фазу одного файла, его записывают выражением {[имя.s]}. При единицах пользователя на оси X фаза не разворачивается.

Фаза сигнала в TMCROS — другая величина: фаза временного сигнала относительно начала периода частоты f из заголовка .t. Её находят по моментам перехода сигнала через ноль сверху вниз (линейной интерполяцией между отсчётами tj−1, tj):

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

для u=Asin(2πft+ψ) это −ψ по модулю 2π, а у падающей волны — Faza порта (фаза в TMCROS). Она не разворачивается, и у сигнала многочастотного расчёта смысла не имеет.

Соответствие в коде

Символ / действие Переменная, функция Файл (src/)
Up, Uo в строке .t dUp, dUo; OutputUpUo kernels/planarrt_*/tmcrthnodediel.cpp
заголовок .t (частоты, порты) CTmcRTHRectNode::PutPortInfo kernels/planarrt_*/tmcrthrectnode.cpp
вызов после шага, строка SMATRIX; нулевая матрица при ошибке CTmcRTH_IndanOutput::PutSmatrix, PutSmatrixZero libs/tmcindan/tmcrth_indanoutput.cpp
вызов из TMCROS (окно To S-matrix) CDialogTtoS::ConvertOne viewers/tmcrtout/dialogttos.cpp
выбор пути: многочастотный / одночастотный CTmcWideband::IsWidebandFile; CTmcTtoS::TtoS viewers/tmcrtout/tmcwideband.cpp, tmcttos.cpp
окно Tmin…Tmax, частота f из #TMC_GROTS_Freq CTmcSMatrix::ReadTFile viewers/tmcrtout/tmcsmatrix.cpp
A, φ по паре отсчётов (формула) CTmcSMatrix::TtoSOneInputOnePoint то же
U˙ — среднее по парам (формула) CTmcSMatrix::TtoSOneInput то же
Sin=U˙o,i/U˙p,n, порог 10−3, проверка NaN CTmcSMatrix::MakeSmatrix то же
запись столбца в .s под частотой вызывающего CTmcSMatrix::Save, save_S_matrix_element viewers/tmcrtout/tmcsmatrix.cpp, libs/sfile95/s_wemt.cpp
вид сигнала (импульс / многотон), окно CTmcWideband::DetectSignalKind, ApplyWindow viewers/tmcrtout/tmcwideband.cpp
поиск частот CTmcWideband::FindFrequencies, Project то же
спектр импульса CTmcWideband::Integrate то же
подгонка тонов CTmcWideband::FitTones, SolveLinear то же
Sin(fk), поправка, запись CTmcWideband::MakeAndSave, FixMismatch, PortGamma то же
cphase — фаза в (−2π,0] cphase libs/complex/cmplxall.cpp
развёртка фазы, режим CTMCGrExpression::GetCPhase, g_nTmcPhaseUnwrap viewers/tmcgrout/tmcgrexpression.cpp
фаза сигнала по переходу через ноль CTMCGROUTView::PrepareDoubleGraph (ветка TMC_GROTS_TYPE_PHAS_R) viewers/tmcrtout/tmcgroutview.cpp

Подробное описание кода — время → S-параметры, многочастотная обработка, файл .t, графики S в TMCGROUT.

Источники

  • [Климов, 2007] — гл. 6, разд. 6.4 ((6.41)–(6.44): нормировка падающей волны и выделение отражённой); гл. 9: разд. 9.1 (состав пакета и файлов, рис. 9.1), 9.5.1 (качество возбуждения и согласования, L11 по времени).
  • [Сазонов и др., 1981] — определение матрицы рассеяния через нормированные волны.
  • Код программ TMCROS, TMCGROUT и ядер — алгоритмы перехода от сигналов к S, многочастотная обработка и развёртка фазы описаны по коду.
  • Руководство пользователя TMC Suite, раздел «Многочастотный расчёт» — проверочный пример samples/MULTIFREQ.
  • Полный список литературы — Литература.

Scattering matrix

The scattering matrix is a frequency-domain characteristic of a device, whereas the compute kernels of the package work in the time domain: at every time step they update the grid node voltages and record the incident and reflected waves at each port. The matrix S is built from these time-domain signals. This page describes what exactly is recorded at the ports, how the program passes from signals to complex amplitudes, how the result is normalized, how to obtain S at many frequencies in a single computation, and how the phase is displayed. The source on the structure of the package is [Klimov, 2007, Ch. 9] (composition of programs and files, Fig. 9.1, tests in Sec. 9.5); the signal-processing algorithms are described from the code of the programs — the PlanarRT_H and PlanarRT_X kernels and the TMCROS and TMCGROUT viewers.

Data flow: the kernel writes the port signals to the .t file (.t file); at the end of a computation step (the SMATRIX line of the #OUTPUT section) or on the TMCROS viewer command Edit > To S-matrix, the signals are converted into a column of the scattering matrix and appended to the .s file; plots of the elements of S versus frequency are displayed by the TMCGROUT viewer.

Recording signals at the ports

What a column of S is. The scattering matrix of an N-port device relates the normalized incident waves an and the reflected (outgoing) waves bi at its inputs [Sazonov et al., 1981]:

bi=∑n=1NSinan,Sin=bian|am=0, m≠n.(1)

The element Sin is the ratio of the wave leaving port i to the wave incident on port n when the other ports are terminated in matched loads. In a time-domain computation this condition is satisfied automatically: each port is an excitation and absorption transformer that absorbs the arriving fundamental mode without reflection, and the signal is applied at only one port. Therefore one computation gives one column of the matrix — the column of the excited port n; for the full matrix, the ports are excited in turn.

What is written to .t. At every sub-step of the kernel (sub-steps), a line is added to the file: the time-step number, the time t (s) and, for each port, the triple "block number, Up, Uo", where

  • Up=a(t) is the incident wave, i.e. the port signal (signal);
  • Uo is the reflected (outgoing) wave: the projection of the reflected voltages of the aperture nodes onto the profile of the fundamental mode of the port (formula for Uo, [Klimov, 2007, (6.44)]).

The file header contains the task frequency FREQ (the #TMC_GROTS_Freq line, Hz) and the number of ports; for an incident wave from a file, it also contains a multi-frequency signal flag, the list of its frequencies and the data of each port for the mismatch correction (.t header). The numbers are written as text with seven significant digits. The port number in the matrix is the ordinal number of the triple in the line, not the block number.

How to view the signals. The TMCROS viewer displays Up(t) and Uo(t), their envelope, the VSWR and the losses L=−20lgA from the envelope A (TMCROS quantities). This is how the quality of port matching was checked in [Klimov, 2007, Sec. 9.5.1]: for a rectangular waveguide terminated by two transformers, the dependence of L11=10lg(1/|S11|2) on time was plotted; the ideal value is infinity, and the value achieved is limited by the finite precision of the computations.

Transition to the frequency domain

Why this is possible. The kernel grid is linear and time-invariant: all its elements are line sections, stubs and conductances with constant parameters, including in the plasma model (plasma model). Therefore the outgoing wave uo(t) is the convolution of the incident wave a(t) with the impulse response of the path "port n → port i", and for the spectra the following holds

Uo(f)=Sin(f)Up(f),Sin(f)=Uo(f)Up(f)(2)

at every frequency f at which the spectrum of the incident wave is non-zero. This is the basis of all the processing methods used by the program.

The spectrum of a signal x(t) recorded as samples x(ti) is computed from the definition of the Fourier transform, with the integral replaced by a right-endpoint rectangle sum:

X(f)=∫x(t)e−j2πftdt≈∑ix(ti)e−j2πfti(ti−ti−1).(3)

Which method is used where (the program has no fast Fourier transform — the spectrum is computed only at the required frequencies):

Signal Method of obtaining the complex amplitude Where
sine at frequency FREQ, steady state sine fitting over pairs of adjacent samples, averaged over the window — without a Fourier transform (below) single-frequency path, CTmcSMatrix
sum of tones (multitone) joint least-squares fitting of all tones (below) multi-frequency path, CTmcWideband
pulse Fourier integral over the entire record (sum above) multi-frequency path, CTmcWideband
nodal field for the RP quadratures at a single frequency over an integer number of periods RP contour

Time window. Not the whole signal is processed, but only the window Tmin…Tmax. For the single-frequency path, the window must lie in the steady-state interval: the transient after the signal is switched on distorts the amplitude and phase. For a pulse, the window must cover the entire response — the signal must decay by the end of the window, otherwise the spectrum is distorted. For a multitone, the window is chosen equal to an integer number of periods of the frequency spacing: on such a window the tones are orthogonal. The influence of the finite window is one of the components of the computational error (accuracy).

Normalization

Power normalization of the waves. The incident and reflected waves of a port are normalized so that the power of the incident wave does not depend on the cross-section size or the wave type [Klimov, 2007, (6.41)–(6.43)] (transformer). In the program, the incident-wave profile of a port ri=Unpi has the factor Un=1/y1Δ2∑ipi2, where y1 is the generator admittance of the port, matched to the fundamental mode. Therefore the power that the port delivers with signal a is proportional to y1Un2a2∑ipi2=a2/Δ2 and is the same for ports of any width and medium, while the reflected wave Uo is the projection onto the same profile. Hence |Sin|2 is the fraction of power transferred from port n to port i. For a device without losses or radiation, the column sum is

∑i=1N|Sin|2=1(4)

(conservation of energy); a deviation of the sum from 1 for such a device is a convenient check of the computation.

Normalization to the incident wave. The port signal a(t)=Ampsin(2πFREQ·t−Faza) can have any amplitude and phase (signal): the task language has no voltage scale. Therefore the column is divided by the complex amplitude of the incident wave of the excited port:

Sin=U˙o,iU˙p,n,i=1…N.(5)

The division removes both the amplitude and the phase of the excitation, so Amp≠1 and Faza≠0 are allowed. The phase of Sin is referred to the port cross-sections where Up and Uo are recorded.

In the program (normalization in the code):

  • the excited port is the one that has a non-zero incident wave in the window; in the single-frequency path there must be exactly one such port (otherwise an error is reported), and in the multi-frequency path the first such port is taken;
  • in the single-frequency path, if |U˙p,n−1|<10−3, the division is not performed: the deviation from unity is regarded as noise of the seven significant digits of .t, and Sin=U˙o,i;
  • in the multi-frequency path the division is always performed;
  • a zero incident wave (|U˙p,n|2≤10−24) and non-numeric values in the column (the computation diverged) produce an error rather than NaN being written to .s.

The matching of the loads, without which (6.43)–(6.44) do not give S, holds at the ports only for the fundamental mode and only at the frequency FREQ; at other frequencies the port itself reflects — this is removed by the mismatch correction.

S-matrix from time-domain signals

Single-frequency computation. The signal in the window Tmin…Tmax is assumed to be a sine at the frequency f taken from the .t header (this is the FREQ of the step at which the computation was performed):

u(t)=Asin(ωt+φ),ω=2πf.(6)

From two adjacent samples (t1,u1), (t2,u2), the amplitude and phase are found exactly: from u2sin(ωt1+φ)=u1sin(ωt2+φ) it follows that

tgφ=−u2sinωt1−u1sinωt2u2cosωt1−u1cosωt2,A=uksin(ωtk+φ),(7)

where k is the one of the two samples for which |sin(ωtk+φ)| is larger (smaller division error); if A<0, −A and φ−π are taken. The complex amplitude of the signal is the average over all M pairs in the window:

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

For a pure sine, all pairs give the same result; the averaging smooths out the rounding of the numbers in .t and the remnants of the transient. In this way U˙o,i of all ports and U˙p,n of the excited port are computed, followed by the normalization. The window must contain more than five samples; a pair of two zero samples enters the average with a zero contribution (so the window must not include the time before the signal has arrived), and a degenerate pair is ignored.

The method requires neither an integer number of periods in the window nor a uniform time step, but it assumes that the signal in the window contains only one frequency f and that the steady state has been reached: higher harmonics, beats and transients cause a spread of the pairs and shift the average.

Computation frequency and recording frequency. The amplitudes are reconstructed at the frequency from the .t header, while the point in .s is recorded under the frequency of the calling program: the frequency of the kernel's SMATRIX line or the "X value" of the TMCROS window (details). In the kernel, a mismatch between the SMATRIX frequency and the FREQ of the step in a single-frequency computation is a task-file error; in TMCROS the recording frequency must be checked by the user.

Writing to .s. Column number n is appended to the file: if the file does not exist, it is created; if the frequency already exists, the column is replaced; otherwise a new frequency point is added (writing a column). A frequency response from single-frequency computations is a sweep: a series of #STEP steps with different FREQ values, each of which appends its own point (a single .s can contain no more than 99 frequencies). If a step is computed with an error, the kernel writes a zero matrix at its frequency so that the erroneous point is visible on the plot (kernel output).

Multi-frequency computation in a single pass

Idea. It follows from linearity that a wideband incident wave excites the device at all of its frequencies at once, and a single .t record contains the response at each of them. The incident wave is specified by a .sig file instead of an Amp expression (incident wave from a file); the kernel marks this in the .t header, and such a file is then processed along the multi-frequency path both by the kernel (the SMATRIX line) and by TMCROS (code). The computation time is the same as for a single single-frequency pass.

Signal kind. If in the last quarter of the record the incident wave of any port exceeds 1 % of its maximum, the signal is regarded as a continuous multitone, otherwise as a pulse.

Frequencies. If the .sig file contains a #FREQ line, the frequencies are taken from it. Otherwise they are found from the spectrum of the incident wave of the excited port: on a grid of 2048 frequencies up to Fmax=min(Fs/4, 3f0) (Fs is the sampling frequency, f0 is the port matching frequency), peaks no lower than −20 dB below the largest one are found; the peak position is refined by a parabola through three points. If there are no more than two peaks (a pulse is a single broad hump), 21 frequencies are taken uniformly over the band in which the spectrum level is above −20 dB (frequencies in the code).

Complex amplitudes. For a pulse — the Fourier integral over the entire record in the window. For a multitone — joint least-squares fitting of all K tones on a window whose length is an integer number of periods of the frequency spacing Δf:

x(t)≈∑k=1K(akcosωkt−bksinωkt)=Re∑k=1Kckejωkt,ck=ak+jbk.(9)

The normal equations of size 2K are solved by Gaussian elimination. The tones are fitted together rather than separately, because on an arbitrary window they are not orthogonal; tones spaced by less than 1/T (T is the window length) cannot be separated — the system becomes degenerate.

Column of S at each frequency fk — according to the normalization:

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

followed by the port mismatch correction and writing of the column to .s under the frequency fk. If at some frequency there is practically no incident wave (|Up,n(fk)|2<10−12maxk|Up,n|2), the frequency is below the port cutoff, or the fitting failed, a zero column is written at this frequency, and the computation of the other frequencies continues; at the end, a general error with the list of frequencies is reported. A single computation can include no more than 99 frequencies.

Requirements for the signal and the window. A pulse must decay within the window: if in the last 5 % of the window the signal exceeds 1 % of the peak, or the window starts during the pulse, a warning is issued. The task frequency FREQ is needed here as well — the ports and absorbers are matched at it, and it is placed within the signal band.

Verification. In the samples/MULTIFREQ example (a 60 mm waveguide with an ε=2 insert, band 3.0–4.8 GHz, 10 frequencies, H kernel), one pass took 4.5 s versus 35.1 s for a sweep of 10 steps, and the discrepancy with the reference sweep was 0.0016 dB and 0.01° (TMC Suite user manual, section "Multi-frequency computation"). With a multi-frequency signal, the radiation pattern is built at each frequency (RP).

Phase unwrapping

Phase of an S element. The viewers display the phase of S with the cphase function — this is atan2(ImS,ReS) reduced to the range (−2π,0] (argument of a complex number). Each frequency point receives an angle on the full circle, so the phase plot of a typical element shows jumps of 360°.

Why the phase decreases. For transmission through a path with group delay τg, the transmission phase decreases with increasing frequency: φ(f)≈φ0−2πfτg, where τg=−12πdφdf. Between adjacent sweep points with step Δf, the phase changes by −2πτgΔf, while cphase returns it modulo 2π. Unwrapping restores the continuous curve φk−2πnk, where nk is the number of crossings of the range boundary over the points 1…k.

In the program (TMCGROUT, phase unwrapping), there are two rules for choosing a crossing between points j−1 and j:

Mode Rule When it is correct
0 (default) φj>φj−1 → n++: the phase is assumed to decrease monotonically the phase actually decreases and changes by less than 2π per step: Δf<1/τg
1, checkbox Config > "Phase unwrapping: standard (threshold pi)" φj−φj−1>π → n++; <−π → n−− the change per step is less than π in absolute value: Δf<1/(2τg); the phase may also increase

If the sweep step is coarser, the crossings cannot be distinguished by either rule — a denser sweep is needed. Unwrapping is applied only to expression curves; to unwrap the phase of a single file, it is written as the expression {[name.s]}. With user units on the X axis, the phase is not unwrapped.

Signal phase in TMCROS is a different quantity: the phase of the time-domain signal relative to the start of a period of the frequency f from the .t header. It is found from the instants at which the signal crosses zero from above (by linear interpolation between the samples tj−1, tj):

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

for u=Asin(2πft+ψ) this is −ψ modulo 2π, and for the incident wave it is the Faza of the port (phase in TMCROS). It is not unwrapped and has no meaning for a signal of a multi-frequency computation.

Mapping to the code

Symbol / action Variable, function File (src/)
Up, Uo in a .t line dUp, dUo; OutputUpUo kernels/planarrt_*/tmcrthnodediel.cpp
.t header (frequencies, ports) CTmcRTHRectNode::PutPortInfo kernels/planarrt_*/tmcrthrectnode.cpp
call after a step, SMATRIX line; zero matrix on error CTmcRTH_IndanOutput::PutSmatrix, PutSmatrixZero libs/tmcindan/tmcrth_indanoutput.cpp
call from TMCROS (To S-matrix window) CDialogTtoS::ConvertOne viewers/tmcrtout/dialogttos.cpp
path selection: multi-frequency / single-frequency CTmcWideband::IsWidebandFile; CTmcTtoS::TtoS viewers/tmcrtout/tmcwideband.cpp, tmcttos.cpp
window Tmin…Tmax, frequency f from #TMC_GROTS_Freq CTmcSMatrix::ReadTFile viewers/tmcrtout/tmcsmatrix.cpp
A, φ from a pair of samples (formula) CTmcSMatrix::TtoSOneInputOnePoint same file
U˙ — average over pairs (formula) CTmcSMatrix::TtoSOneInput same file
Sin=U˙o,i/U˙p,n, threshold 10−3, NaN check CTmcSMatrix::MakeSmatrix same file
writing a column to .s under the caller's frequency CTmcSMatrix::Save, save_S_matrix_element viewers/tmcrtout/tmcsmatrix.cpp, libs/sfile95/s_wemt.cpp
signal kind (pulse / multitone), window CTmcWideband::DetectSignalKind, ApplyWindow viewers/tmcrtout/tmcwideband.cpp
frequency search CTmcWideband::FindFrequencies, Project same file
pulse spectrum CTmcWideband::Integrate same file
tone fitting CTmcWideband::FitTones, SolveLinear same file
Sin(fk), correction, writing CTmcWideband::MakeAndSave, FixMismatch, PortGamma same file
cphase — phase in (−2π,0] cphase libs/complex/cmplxall.cpp
phase unwrapping, mode CTMCGrExpression::GetCPhase, g_nTmcPhaseUnwrap viewers/tmcgrout/tmcgrexpression.cpp
signal phase from zero crossings CTMCGROUTView::PrepareDoubleGraph (branch TMC_GROTS_TYPE_PHAS_R) viewers/tmcrtout/tmcgroutview.cpp

A detailed description of the code: time → S-parameters, multi-frequency processing, .t file, S plots in TMCGROUT.

Sources

  • [Klimov, 2007] — Ch. 6, Sec. 6.4 ((6.41)–(6.44): normalization of the incident wave and extraction of the reflected wave); Ch. 9: Sec. 9.1 (composition of the package and files, Fig. 9.1), 9.5.1 (quality of excitation and matching, L11 versus time).
  • [Sazonov et al., 1981] — definition of the scattering matrix in terms of normalized waves.
  • Code of the TMCROS and TMCGROUT programs and the kernels — the algorithms for passing from signals to S, the multi-frequency processing and the phase unwrapping are described from the code.
  • TMC Suite user manual, section "Multi-frequency computation" — the verification example samples/MULTIFREQ.
  • The full reference list is given in References.