Матрица рассеяния
Матрица рассеяния — частотная характеристика устройства, а счётные ядра пакета работают во временной области: на каждом такте они пересчитывают напряжения узлов сетки и записывают падающую и отражённую волны на каждом порту. Матрицу строят по этим временным сигналам. На этой странице описано, что именно записывается на портах, как программа переходит от сигналов к комплексным амплитудам, как нормируется результат, как за один расчёт получить на многих частотах и как показывается фаза. Источник по устройству пакета — [Климов, 2007, гл. 9] (состав программ и файлов, рис. 9.1, тесты разд. 9.5); алгоритмы обработки сигналов описаны по коду программ — ядер PlanarRT_H, PlanarRT_X и вьюверов TMCROS, TMCGROUT.
Путь данных: ядро пишет сигналы портов в файл .t (файл .t);
по окончании шага расчёта (строка SMATRIX секции #OUTPUT) или по команде вьювера TMCROS
Edit > To S-matrix сигналы пересчитываются в столбец матрицы рассеяния и дописываются в файл
.s; графики элементов по частоте показывает вьювер TMCGROUT.
Запись сигналов на портах
Что такое столбец S. Матрица рассеяния -портового устройства связывает нормированные падающие волны и отражённые (уходящие) волны на его входах [Сазонов и др., 1981]:
Элемент — отношение волны, ушедшей из порта , к волне, падающей на порт , когда остальные порты нагружены на согласованные нагрузки. Во временном расчёте это условие выполняется само собой: каждый порт — трансформатор возбуждения и поглощения, который поглощает приходящую основную волну без отражения, а сигнал задаётся только на одном порту. Поэтому один расчёт даёт один столбец матрицы — столбец возбуждённого порта ; для полной матрицы порты возбуждают по очереди.
Что пишется в .t. На каждом подтакте ядра (подтакты) в файл
добавляется строка: номер такта, время (с) и для каждого порта тройка «номер блока, ,
», где
- — падающая волна, т. е. сигнал порта (сигнал);
- — отражённая (уходящая) волна: проекция отражённых напряжений узлов апертуры на профиль основной волны порта (формула , [Климов, 2007, (6.44)]).
В заголовке файла записаны частота задания FREQ (строка #TMC_GROTS_Freq, Гц) и число
портов; при падающей волне из файла — ещё признак многочастотного сигнала, список его частот
и данные каждого порта для поправки на рассогласование
(заголовок .t). Числа пишутся текстом с семью значащими
цифрами. Номер порта в матрице — порядковый номер тройки в строке, а не номер блока.
Как смотреть сигналы. Вьювер TMCROS показывает и , их огибающую, КСВ и потери по огибающей (величины TMCROS). Так в [Климов, 2007, разд. 9.5.1] проверялось качество согласования порта: в прямоугольном волноводе, нагруженном на два трансформатора, строилась зависимость от времени; идеальное значение — бесконечность, а достигнутое ограничено конечной разрядностью вычислений.
Переход в частотную область
Почему это возможно. Сетка ядер линейна и не меняется во времени: все её элементы — отрезки линий, шлейфы и проводимости с постоянными параметрами, в том числе в модели плазмы (модель плазмы). Поэтому уходящая волна — свёртка падающей волны с импульсной характеристикой тракта «порт → порт », а для спектров выполняется
на каждой частоте , где спектр падающей волны не равен нулю. Это основа всех способов обработки, которыми пользуется программа.
Спектр сигнала , записанного отсчётами , вычисляется по определению преобразования Фурье, интеграл заменяется суммой прямоугольников по правым точкам:
Какой способ где используется (быстрого преобразования Фурье в программе нет — спектр считается только на нужных частотах):
| Сигнал | Способ получить комплексную амплитуду | Где |
|---|---|---|
синус частоты FREQ, установившийся режим |
подбор синуса по парам соседних отсчётов, среднее по окну — без преобразования Фурье (ниже) | одночастотный путь, CTmcSMatrix |
| сумма тонов (многотон) | совместная подгонка всех тонов методом наименьших квадратов (ниже) | многочастотный путь, CTmcWideband |
| импульс | интеграл Фурье по всей записи (сумма выше) | многочастотный путь, CTmcWideband |
| поле в узлах для ДН | квадратуры на одной частоте за целое число периодов | контур ДН |
Окно времени. Сигнал обрабатывается не весь, а на окне . Для одночастотного пути окно должно лежать на установившемся участке: переходный процесс после включения сигнала искажает амплитуду и фазу. Для импульса окно должно охватывать весь отклик — сигнал к концу окна должен затухнуть, иначе спектр искажается. Для многотона окно берут равным целому числу периодов разноса частот: на таком окне тоны ортогональны. Влияние конечного окна — одна из составляющих погрешности расчёта (точность).
Нормировка
Нормировка волн по мощности. Падающая и отражённая волны порта нормированы так, что мощность падающей волны не зависит от размера сечения и типа волны [Климов, 2007, (6.41)–(6.43)] (трансформатор). В программе профиль падающей волны порта имеет множитель , где — проводимость генератора порта, согласованная с основной волной. Поэтому мощность, которую порт вводит при сигнале , пропорциональна и одинакова для портов любой ширины и среды, а отражённая волна — проекция на тот же профиль. Отсюда — доля мощности, переходящая из порта в порт . Для устройства без потерь и излучения сумма по столбцу
(закон сохранения энергии); отличие суммы от 1 на таком устройстве — удобная проверка расчёта.
Нормировка на падающую волну. Сигнал порта может иметь любую амплитуду и фазу (сигнал): масштаба напряжения в языке заданий нет. Поэтому столбец делится на комплексную амплитуду падающей волны возбуждённого порта:
Деление снимает и амплитуду, и фазу возбуждения, поэтому и допустимы. Фаза отсчитывается в сечениях портов, где записываются и .
В программе (нормировка в коде):
- возбуждённым считается порт, у которого в окне есть ненулевая падающая волна; в одночастотном пути он должен быть ровно один (иначе ошибка), в многочастотном берётся первый такой порт;
- в одночастотном пути при деление не выполняется:
отличие от единицы считается шумом семи значащих цифр
.t, и ; - в многочастотном пути деление выполняется всегда;
- нулевая падающая волна () и нечисловые значения в столбце
(расчёт разошёлся) — ошибка, а не запись
NaNв.s.
Согласованность нагрузок, без которой (6.43)–(6.44) не дают , у портов выполняется только
для основной волны и только на частоте FREQ; на других частотах порт сам отражает — это
снимается поправкой на рассогласование.
S-матрица по временным сигналам
Одночастотный расчёт. Сигнал на окне считается синусом частоты ,
взятой из заголовка .t (это FREQ шага, на которой шёл расчёт):
По двум соседним отсчётам , амплитуда и фаза находятся точно: из следует
где — тот из двух отсчётов, у которого больше (меньше ошибка деления); при берутся и . Комплексная амплитуда сигнала — среднее по всем парам окна:
Для чистого синуса все пары дают одно и то же; усреднение сглаживает округление чисел в .t
и остатки переходного процесса. Так считаются всех портов и
возбуждённого порта, затем нормировка. Отсчётов в окне должно быть больше
пяти; пара из двух нулевых отсчётов входит в среднее с нулевым вкладом (поэтому окно не должно
захватывать время, когда сигнал ещё не пришёл), вырожденная пара не учитывается.
Способ не требует ни целого числа периодов в окне, ни равномерного шага по времени, но предполагает, что на окне в сигнале только одна частота и режим установился: высшие гармоники, биения и переходный процесс дают разброс пар и смещают среднее.
Частота расчёта и частота записи. Амплитуды восстанавливаются на частоте из заголовка
.t, а точка в .s записывается под частотой вызывающей программы: частотой строки
SMATRIX ядра или значением «X value» окна TMCROS
(подробно). В ядре несовпадение частоты SMATRIX с FREQ
шага в одночастотном расчёте — ошибка задания; в TMCROS частоту записи нужно проверять самому.
Запись в .s. Столбец номер дописывается в файл: файла нет — он создаётся, частота
уже есть — столбец заменяется, иначе добавляется новая частотная точка
(запись столбца). Частотная характеристика по
одночастотным расчётам — это свип: серия шагов #STEP с разными FREQ, каждый
дописывает свою точку (в одном .s — не больше 99 частот). Если шаг посчитан с ошибкой, ядро
записывает на его частоте нулевую матрицу, чтобы ошибочная точка была видна на графике
(вывод ядра).
Многочастотный расчёт за один проход
Идея. Из линейности следует, что широкополосная падающая волна возбуждает
устройство сразу на всех своих частотах, и одна запись .t содержит отклик на каждой из них.
Падающую волну задают файлом .sig вместо выражения Amp (падающая волна из
файла); ядро отмечает это в заголовке .t, и тогда такой файл
многочастотным путём обрабатывают и ядро (строка SMATRIX), и TMCROS
(код). Время расчёта то же, что у одного одночастотного прохода.
Вид сигнала. Если в последней четверти записи падающая волна какого-либо порта больше 1 % своего максимума, сигнал считается непрерывным многотоном, иначе — импульсом.
Частоты. Если в файле .sig есть строка #FREQ, частоты берутся из неё. Иначе они
ищутся по спектру падающей волны возбуждённого порта: на сетке из 2048 частот до
( — частота отсчётов, — частота согласования порта)
находятся пики не ниже −20 дБ от наибольшего; положение пика уточняется параболой по трём
точкам. Если пиков не больше двух (импульс — один широкий горб), берётся 21 частота равномерно
по полосе, где уровень спектра выше −20 дБ (частоты в коде).
Комплексные амплитуды. Для импульса — интеграл Фурье по всей записи в окне. Для многотона — совместная подгонка всех тонов методом наименьших квадратов на окне длиной в целое число периодов разноса частот :
Нормальные уравнения размера решаются методом Гаусса. Тоны подгоняются вместе, а не по отдельности, потому что на произвольном окне они не ортогональны; тоны, разнесённые меньше чем на ( — длина окна), не разделяются — система вырождается.
Столбец S на каждой частоте — по нормировке:
затем поправка на рассогласование порта и запись столбца в .s под
частотой . Если на какой-то частоте падающей волны практически нет
(), частота ниже отсечки порта или не удалась
подгонка, на этой частоте пишется нулевой столбец, а расчёт остальных частот продолжается; в
конце выдаётся общая ошибка со списком частот. В одном расчёте — не больше 99 частот.
Требования к сигналу и окну. Импульс должен затухнуть внутри окна: если в последних 5 %
окна сигнал больше 1 % пика или окно начинается во время импульса, выдаётся предупреждение.
FREQ задания нужна и здесь — на ней согласованы порты и поглотители, и её ставят внутри полосы
сигнала.
Проверка. На примере samples/MULTIFREQ (волновод 60 мм со вставкой ,
полоса 3,0–4,8 ГГц, 10 частот, ядро H) один проход занял 4,5 с против 35,1 с у свипа из
10 шагов, расхождение с эталонным свипом — 0,0016 дБ и 0,01° (руководство пользователя TMC
Suite, раздел «Многочастотный расчёт»). Диаграмма направленности при многочастотном сигнале
строится на каждой частоте (ДН).
Развёртка фазы
Фаза элемента S. Вьюверы показывают фазу функцией cphase — это
, приведённый в диапазон
(угол комплексного числа). Каждая частотная точка получает
угол на полном круге, поэтому на графике фазы обычного элемента видны скачки на 360°.
Почему фаза убывает. Для прохождения по тракту с групповым временем задержки фаза
передачи с ростом частоты убывает: , где
. Между соседними точками свипа с шагом фаза
меняется на , а cphase возвращает её по модулю . Развёртка
восстанавливает непрерывную кривую , где — число переходов через
границу диапазона по точкам .
В программе (TMCGROUT, разворот фазы) — два правила выбора перехода между точками и :
| Режим | Правило | Когда верно |
|---|---|---|
| 0 (по умолчанию) | → : фаза считается монотонно убывающей | фаза действительно убывает и за шаг меняется меньше чем на : |
| 1, флажок Config > «Phase unwrapping: standard (threshold pi)» | → ; → | изменение за шаг меньше по модулю: ; фаза может и расти |
Если шаг свипа крупнее, переходы не различимы ни одним правилом — нужен более частый свип.
Развёртка применяется только к кривым-выражениям; чтобы развернуть фазу одного файла, его
записывают выражением {[имя.s]}. При единицах пользователя на оси X фаза не разворачивается.
Фаза сигнала в TMCROS — другая величина: фаза временного сигнала относительно начала периода
частоты из заголовка .t. Её находят по моментам перехода сигнала через ноль сверху вниз
(линейной интерполяцией между отсчётами , ):
для это по модулю , а у падающей волны — Faza порта (фаза в TMCROS). Она не разворачивается, и у сигнала многочастотного расчёта смысла не имеет.
Соответствие в коде
| Символ / действие | Переменная, функция | Файл (src/) |
|---|---|---|
, в строке .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 |
окно , частота из #TMC_GROTS_Freq |
CTmcSMatrix::ReadTFile |
viewers/tmcrtout/tmcsmatrix.cpp |
| , по паре отсчётов (формула) | CTmcSMatrix::TtoSOneInputOnePoint |
то же |
| — среднее по парам (формула) | CTmcSMatrix::TtoSOneInput |
то же |
| , порог , проверка 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 |
то же |
| , поправка, запись | CTmcWideband::MakeAndSave, FixMismatch, PortGamma |
то же |
cphase — фаза в |
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 (качество возбуждения и согласования, по времени).
- [Сазонов и др., 1981] — определение матрицы рассеяния через нормированные волны.
- Код программ TMCROS, TMCGROUT и ядер — алгоритмы перехода от сигналов к , многочастотная обработка и развёртка фазы описаны по коду.
- Руководство пользователя 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 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 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 versus frequency are displayed by the TMCGROUT viewer.
Recording signals at the ports
What a column of S is. The scattering matrix of an -port device relates the normalized incident waves and the reflected (outgoing) waves at its inputs [Sazonov et al., 1981]:
The element is the ratio of the wave leaving port to the wave incident on port 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 ; 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 (s) and, for each port, the triple "block number, ,
", where
- is the incident wave, i.e. the port signal (signal);
- 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 , [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 and , their envelope, the VSWR and the losses from the envelope (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 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 is the convolution of the incident wave with the impulse response of the path "port → port ", and for the spectra the following holds
at every frequency 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 recorded as samples is computed from the definition of the Fourier transform, with the integral replaced by a right-endpoint rectangle sum:
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 . 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 has the factor , where is the generator admittance of the port, matched to the fundamental mode. Therefore the power that the port delivers with signal is proportional to and is the same for ports of any width and medium, while the reflected wave is the projection onto the same profile. Hence is the fraction of power transferred from port to port . For a device without losses or radiation, the column sum is
(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 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:
The division removes both the amplitude and the phase of the excitation, so and are allowed. The phase of is referred to the port cross-sections where and 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 , the division is not performed:
the deviation from unity is regarded as noise of the seven significant digits of
.t, and ; - in the multi-frequency path the division is always performed;
- a zero incident wave () and non-numeric values in the column
(the computation diverged) produce an error rather than
NaNbeing written to.s.
The matching of the loads, without which (6.43)–(6.44) do not give , 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 is assumed to be a sine at the frequency
taken from the .t header (this is the FREQ of the step at which the computation was performed):
From two adjacent samples , , the amplitude and phase are found exactly: from it follows that
where is the one of the two samples for which is larger (smaller division error); if , and are taken. The complex amplitude of the signal is the average over all pairs in the window:
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 of all ports and 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 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 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
( is the sampling frequency, 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 tones on a window whose length is an integer number of periods of the frequency spacing :
The normal equations of size 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 ( is the window length) cannot be separated — the system becomes degenerate.
Column of S at each frequency — according to the normalization:
followed by the port mismatch correction and writing of the column to .s under
the frequency . If at some frequency there is practically no incident wave
(), 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 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 with the cphase function — this is
reduced to the range
(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 , the transmission
phase decreases with increasing frequency: , where
. Between adjacent sweep points with step , the phase
changes by , while cphase returns it modulo . Unwrapping
restores the continuous curve , where is the number of crossings of
the range boundary over the points .
In the program (TMCGROUT, phase unwrapping), there are two rules for choosing a crossing between points and :
| Mode | Rule | When it is correct |
|---|---|---|
| 0 (default) | → : the phase is assumed to decrease monotonically | the phase actually decreases and changes by less than per step: |
| 1, checkbox Config > "Phase unwrapping: standard (threshold pi)" | → ; → | the change per step is less than in absolute value: ; 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 from the .t header. It is found from the instants at which the signal crosses zero from above
(by linear interpolation between the samples , ):
for this is modulo , 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/) |
|---|---|---|
, 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 , frequency from #TMC_GROTS_Freq |
CTmcSMatrix::ReadTFile |
viewers/tmcrtout/tmcsmatrix.cpp |
| , from a pair of samples (formula) | CTmcSMatrix::TtoSOneInputOnePoint |
same file |
| — average over pairs (formula) | CTmcSMatrix::TtoSOneInput |
same file |
| , threshold , 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 |
| , correction, writing | CTmcWideband::MakeAndSave, FixMismatch, PortGamma |
same file |
cphase — phase in |
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, 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 , 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.