Библиотека TMCIndan: чтение задания и интегрирование поля для ДН
Назначение и место в пакете
TMCIndan — статическая библиотека, через которую оба счётных ядра (PlanarRT_H и PlanarRT_X)
читают задание .tpl и строят данные для диаграммы направленности (ДН). Она:
- запускает препроцессор PREPR (макросы,
#include) и пишет развёрнутое задание во временный файл; - находит в нём шаг
#STEPс нужным номером и разбирает его секции#PARM,#TOPOLOGY,#LINK_LIST,#OUTPUT; - переводит все величины в СИ, выравнивает область расчёта по сетке, проверяет корректность;
- хранит список блоков (геометрия, материал, входы-порты, плазма) в виде, удобном ядру;
- после шага пересчитывает временные сигналы
.tв матрицу рассеяния.s; - накапливает во времени гармонику поля на частоте ДН и записывает файл эквивалентных излучателей
.DAT, по которому программа TMC_DN строит ДН.
Библиотека не считает поле: сетку узлов и расчёт во времени выполняет ядро
(kernel-h, kernel-x). TMCIndan зависит от библиотек prepr
(препроцессор), exprint (вычисление выражений i1nte_atof_1), TMCLibError (объект ошибки),
а также от SFILE95 и вьюверных классов CTmcTtoS/CTmcWideband при записи .s.
Состав
| Файл | Роль |
|---|---|
libs/tmcindan/tmcrth_indan.cpp, include/tmcrth_indan.h |
CTmcRTH_Indan — точка входа: препроцессор, поиск шага и секций, метки секций; MainPrepr |
libs/tmcindan/tmcrth_indanparam.cpp, include/tmcrth_indanparam.h |
CTmcRTH_IndanParam — секция #PARM, единицы, сетка, номера узлов; механический шаг SetDeltaT |
libs/tmcindan/tmcrth_indantopology.cpp, include/tmcrth_indantopology.h |
CTmcRTH_IndanTopology — обёртка списка блоков, секция #LINK_LIST, сторона входов |
libs/tmcindan/tmcrth_bolcklist.cpp, include/tmcrth_bolcklist.h |
CTmcRTH_BlockList — блок и список блоков, разбор всех примитивов, сохранение/загрузка |
libs/tmcindan/tmcrth_indanoutput.cpp, include/tmcrth_indanoutput.h |
CTmcRTH_IndanOutput — секция #OUTPUT, имена файлов, запись .s |
libs/tmcindan/fieldintegrated.cpp, include/fieldintegrated.h |
CFieldIntegrated — накопление квадратур поля, амплитуда/фаза, файл излучателей .DAT |
libs/tmcindan/tmcrth_input.cpp, tmcrth_inputnode.cpp и их заголовки |
CTmcRTH_Input, CTmcRTH_InputNode — компилируются, но не используются (см. ниже) |
libs/tmcindan/stdafx.h |
подключает afx.h/afxwin.h слоя совместимости compat |
include/typerth.h |
тип _real, тип значения узла, физические константы, прототипы служебных функций ядра |
include/tmcidx.h |
тип номера узла TmcIdx и чтение/запись номера в 4 байта |
include/tmclimit.h, include/label/rth.h |
пределы таблиц TAMIC и метки заголовка файла .s |
libs/tmcindan/stdafx.cpp, include/indan/* |
в сборку не входят (старые копии) |
Список компилируемых файлов задаётся в src/CMakeLists.txt (tmc_add_library(TMCIndan ...)).
Классы и их связи
CTmcRTH_Indan (ядро: CTmcRTHRectNode::cIndan)
├── cParam : CTmcRTH_IndanParam — #PARM шагов 1..N
├── cTopology : CTmcRTH_IndanTopology — #TOPOLOGY + #LINK_LIST шага N
│ ├── pcParam -> cParam (указатель, не владеет)
│ └── cBlockList : CTmcRTH_BlockList -> блок -> блок -> ... -> пустой
├── cOut : CTmcRTH_IndanOutput — #OUTPUT шага N
│ └── cFieldDistr : CFieldIntegrated (копия параметров шага)
└── cError : CTmcLibError
Жизненный цикл. Ядро создаёт CTmcRTH_Indan вместе с документом. Для каждого шага свипа оно
вызывает ReadData(файл, N); затем читает геттерами параметры и список блоков, строит сетку
узлов, вызывает GetOutput()->GetFieldIntegrated().InitAllFile(...), на каждом шаге по времени —
Integrate(...), после счёта — PutSmatrix() (или PutSmatrixZero() при ошибке шага).
Временный файл препроцессора удаляется при следующем SetTplFileName и в деструкторе.
Потоки. Разбор задания идёт в потоке чтения ядра, интегрирование и запись .s — в расчётном
потоке. Классы не потокобезопасны; ядро не вызывает их одновременно из двух потоков.
Ошибки. Исключения не используются. Каждый класс хранит CTmcLibError; методы в начале
проверяют IsError() и при уже взведённой ошибке ничего не делают. Текст ошибки — по-английски,
с цитатой проблемной строки задания в фигурных скобках; ядро показывает его в строке состояния
и в консоли.
Чтение задания
Порядок работы CTmcRTH_Indan::ReadData(csFileName, nStepNum):
SetTplFileName. Сбрасывает данные, проверяет, что файл открывается, вычисляет папку задания (полный путь до последнего разделителя). Имя временного файла —<задание>~$Prepr$~<номер процесса>; номер процесса нужен, чтобы два одновременных запуска одного задания не мешали друг другу. В Windows путь задания и временного файла должен быть короче 260 символов (иначе — понятная ошибка; если с номером не помещается — номер не добавляется).- Препроцессор.
MainPreprвызываетMainPrepr1библиотеки PREPR (lib-prepr): разворачиваются макросы и#include, результат пишется во временный файл. - Число шагов.
GetNStepMaxодин раз проходит файл: проверяет парность#STEP/#END_STEP, считает шаги и для каждого файлаSMATRIXсобирает множество частот (частоты сравниваются после нормализации%.12g). Больше 99 частот на один файл.s— ошибка: в файл S-матрицы помещается не болееFREQ_MAX_NUM - 1= 99 частот. - Номер шага проверяется: от 1 до числа шагов.
- Секции.
ReadParamSection→ReadTopologySection→ReadLinkListSection→ReadOutputSection. Каждая секция ищется заново:FindStep(N)открывает временный файл с начала и встаёт после N-й метки#STEP,FindSectionищет метку начала секции до#END_STEP,GetLineSectionотдаёт строки до метки конца секции.
Построчное чтение (GetLine):
- пустые строки и строки-комментарии (начинаются с
!) пропускаются; - ведущие пробелы удаляются, серия пробелов/табуляций сжимается в один символ; первый промежуток
после ключевого слова всегда становится пробелом — ключевые слова сравниваются вместе с ним
(
"BLOCK ","FREQ ","RECT_STAT "); #EOFзавершает чтение; конец файла без#EOF— ошибкаMissing #EOF;- строка длиннее
CTMCRTH_INDAN_LINELEN - 2= 19998 символов — ошибка (длинный комментарий пропускается целиком).
Параметры внутри строк разделяются ;. Разделитель ищется только вне скобок {}, (), []
(Search_1Param), поэтому внутри выражений и в [имя] точка с запятой допустима. Значения —
выражения библиотеки expr: числа, переменные #define, функции.
Параметры: секция #PARM
| Ключевое слово | Значение | Хранится (СИ) |
|---|---|---|
LONG_UNIT m\|cm\|mm; |
единица длины (по умолчанию mm) | rLongUnit, м в единице |
TIME_UNIT s\|ms\|mks\|ns\|ps; |
единица времени (по умолчанию s) | rTimeUnit |
FREQ_UNIT Hz\|kHz\|MHz\|GHz; |
единица частоты (по умолчанию GHz) | rFreqUnit |
ANGLE_UNIT radian\|gradus; |
единица угла (по умолчанию radian); переключает и тригонометрию выражений | rAngleUnit |
B_UNIT, N_UNIT |
разбираются, ядрами не применяются (см. ниже) | — |
FREQ F; |
рабочая частота | rFreq, Гц |
DELTA d; |
шаг сетки | rDelta, м; заодно шаг по времени rt |
TIME Tmin; Tmax; |
интервал расчёта | rTmin, rTmax, с |
X_MIN, X_MAX, Y_MIN, Y_MAX |
границы области | rXmin … rYmax, м |
HEIGHT, DELTA_T_MECHANICAL |
разбираются, на расчёт не влияют | rHeight, rDeltaTMechanical |
Значение переводится в СИ сразу при чтении текущей единицей, поэтому строки единиц должны
стоять в секции раньше величин. Параметры накапливаются по шагам: для шага N читаются секции
#PARM шагов 1, 2, …, N; шаг 1 обязателен, в следующих шагах секции может не быть.
Шаг по времени Rt-сетки (теория):
Число шагов по времени — nGetTmax() .
Проверки IsCorrectly: , , , ,
и , где — длина волны в вакууме.
Выравнивание области по сетке
После проверок IsCorrectly один раз вычисляет число узлов и переносит правую и верхнюю границы
на резервный столбец/строку узлов:
Так же по Y. Узлы нумеруются , , координата узла
. Значения X_MAX/Y_MAX из задания сохраняются в rXmaxUser/rYmaxUser;
новая граница или новый DELTA в следующем шаге сбрасывают nXGrid/nYGrid, и сетка
вычисляется заново. Блоки задания должны лежать на узлах, а границы — быть кратны шагу
(правила сетки).
Номера узлов и тип TmcIdx
Глобальный номер узла — . На больших сетках он превышает , поэтому все номера
и размеры массивов узлов имеют тип TmcIdx (ptrdiff_t: 64 бита в сборке win64). Ядра отказываются
от сетки, у которой (с запасом на число значений в узле) не помещается в TMC_IDX_MAX.
Пересчёт координат (CTmcRTH_IndanParam):
| Метод | Результат |
|---|---|
CalcnNodeGlobal(x, y) |
номер ближайшего узла; точка вне области прижимается к границе; точка ближе полушага к левому/правому краю — крайний столбец |
CalcnNodeGlobalFM(x, y) |
то же, но полоса у левого/правого края — 1,5 шага, и точка в ней относится ко второму столбцу от края |
CalcnNodeGlobalNorm(x, y) |
номер узла или −1, если точка ближе двух шагов к границе |
CalcX(n), CalcY(n) |
координаты узла, м |
IsnInRegion(x, y) |
точка не дальше полушага за границей области |
В файлах распределения .eps номер узла по-прежнему хранится 4-байтовым int (формат не менялся):
чтение и запись — TmcReadIdx32/TmcWriteIdx32.
Топология и размещение блоков
Блоки секции #TOPOLOGY описываются в локальных координатах. Секция #LINK_LIST собирает
устройство: строка
T n; X0; Y0;
переносит начало локальных координат блока n в точку (X0, Y0) области (единицы LONG_UNIT).
Каждый блок должен быть размещён ровно одной строкой. Внутри списка это видно по знаку номера:
после #TOPOLOGY номер блока хранится со знаком минус, SetLink делает его положительным;
повторная строка T для того же блока — ошибка, неразмещённый блок — ошибка BLOCK n is absent
in #LINK_LIST section.
Для входов здесь же определяется сторона (порты):
INPUT_X(вход вдоль оси Y) — левый, если X0 в пределах шага отXminили в левой половине области; правый (CTMCRTH_BLCKNTYPE_INPXRIGHT), если в пределах шага отXmaxили в правой половине;INPUT_Y(вход вдоль оси X) — нижний (CTMCRTH_BLCKNTYPE_INPYBOT) или верхний — так же по Y0.
X0/Y0 вне области — ошибка с подсказкой допустимых значений.
Блоки топологии
Текст блока, переданный в CTmcRTH_BlockList::Add:
BLOCK n;
<ПРИМИТИВ> <параметр 1>; <параметр 2>; ...;
[L x; y; — только для многоугольников]
END_B
Номер n >= 1. Примитив определяется по началу второй строки; метки сравниваются целиком с
завершающим пробелом, поэтому RECT_STAT_N не принимается за RECT_STAT.
Первый параметр — значение блока или одно из слов, задающих тип (nType, коды из tmcgrviw.h):
| Первый параметр | nType |
Смысл |
|---|---|---|
| выражение | 0 (EPS) |
диэлектрик: выражение для eps (или N, B, Y, sigma у плазменных блоков) |
METAL |
101 | металл |
MAGNETIC |
107 | магнитная стенка |
ABSORBER |
100 | поглотитель |
| (входы) | 102…105 | вход слева, справа, сверху, снизу |
Макрос _MODEL_RTE__ в tmcgrviw.h поменял бы слова METAL и MAGNETIC местами, но в сборке он
не задаётся: METAL всегда даёт тип 101 в обоих ядрах. Что означают эти типы в X-ядре — см.
двойственность стенок. Первый параметр может начинаться с
[имя] — признак записи распределения в файл .eps; этот префикс разбирает ядро.
Примитивы и их параметры
| Примитив | Параметры после первого | Где хранится |
|---|---|---|
RECT_STAT |
Xmin; Xmax; Ymin; Ymax; (LONG_UNIT, min < max) |
dXmin…dYmax, м |
CIRCLE_STAT |
Rmin; Rmax; FImin; FImax; (0 <= Rmin < Rmax, 0 <= FImin < FImax <= 2*pi, углы в ANGLE_UNIT) |
dXmin/dXmax — радиусы, м; dYmin/dYmax — углы, рад |
POLYGON_STAT |
строки вершин L x; y;, не меньше трёх |
dX[], dY[], nXY |
FILE <имя>; |
библиотекой не читаются (имя файла — первый параметр) | csEpsExpr; к имени без расширения дописывается .eps, к относительному пути — папка задания |
INPUT_X |
Ymin; Ymax; Tmin; Tmax; [Amp]; [Faza]; [W]; |
dXmin/dXmax — пределы по Y, м; dYmin/dYmax — время, с; csVx, csVy, csW |
INPUT_Y |
Xmin; Xmax; Tmin; Tmax; [Amp]; [Faza]; [W]; |
то же, пределы по X |
RECT_MOVE, CIRCLE_MOVE, POLYGON_MOVE |
как статические, плюс скорости Vx; Vy; W и др. |
csVx, csVy, csW — скорости |
Необязательный хвост статических примитивов (mu; Dz; Hx; Hy; Ro; Sigma;, у круга ещё внешний
Dz и проводимость) сохраняется текстом; на первом отсутствующем ; разбор просто заканчивается.
Ядра эти поля не используют.
Плазменные варианты (X-ядро)
| Суффикс | Примитивы | Величина | Единица |
|---|---|---|---|
_N |
RECT_STAT_N, CIRCLE_STAT_N, POLYGON_STAT_N, FILE_N |
концентрация электронов N | м^-3 (теория) |
_B |
RECT_STAT_B, CIRCLE_STAT_B, POLYGON_STAT_B, FILE_B |
индукция подмагничивающего поля B | Тл (теория) |
_Y |
RECT_STAT_Y, CIRCLE_STAT_Y, POLYGON_STAT_Y, FILE_Y |
потери (проводимость Y сетки) | — (теория) |
_S |
RECT_STAT_S, CIRCLE_STAT_S, POLYGON_STAT_S |
проводимость sigma | См/м |
Для _N, _B, _Y, _S первым параметром допустимо только выражение (не METAL и т. п.).
*_STAT_S разбирается тем же кодом, что *_STAT_Y, но сохраняет метку _S — пересчёт sigma
выполняет ядро. FILE_N, FILE_B, FILE_Y сохраняют свою метку, чтобы ядро направило значения
файла в N, B или Y. Единицы плазменных величин фиксированы (единицы):
строки N_UNIT/B_UNIT на них не действуют.
Входы
Восемь параметров входа (сигнал на порту):
| № | Параметр | Разбор |
|---|---|---|
| 1 | тип: пусто или METAL — волна H10 волновода, MAGNETIC — плоская волна |
другое слово — ошибка |
| 2, 3 | пределы входа вдоль стороны | LONG_UNIT, min < max |
| 4, 5 | время радиоимпульса Tmin, Tmax | TIME_UNIT, Tmin < Tmax |
| 6 | Amp — выражение от t, f или [файл] |
[файл] — падающая волна из файла .sig (теория) |
| 7 | Faza — выражение от t, f (в ANGLE_UNIT) |
обязателен, если задан Amp |
| 8 | W — добавка eps в сечении входа | eps = 1 + W > 0; переменные t и f запрещены (теория) |
Запрет t/f в W проверяет TmcExprUsesTorF: однобуквенное имя t или f не перед (;
числа с порядком (1.5e-3) пропускаются целиком.
Сохранение и загрузка списка
Save пишет список в текст между #BlockListBegin и #BlockListEnd: для каждого блока пять строк
(примитив, первый параметр, Vx, Vy, W), строку dX0 dXmax dXmin dY0 dYmax dYmin nBlock nMemory nType nXY
и nXY строк вершин. Load читает этот формат. Выражения mu, Dz, Hx, Hy и силовые параметры не
сохраняются.
Выходные файлы: секция #OUTPUT
| Строка | Действие |
|---|---|
FILE имя; |
базовое имя (точка в имени файла запрещена): .t — сигналы на входах, .ex, .ey, .hz — поле, .tt — топология, .s — S-матрица, а также .em, .ef, .q, .ix, .iy; обязательна |
TOPOLOGY |
записывать топологию |
FIELDS |
записывать поля .ex, .ey, .hz |
SMATRIX файл; F; [Tmin; Tmax;] |
S-матрица на частоте F по окну Tmin..Tmax; без расширения у имени — .s |
FIELD_DISTRIBUTION имя; F; Tmin; Tmax; |
ДН, квадратуры в файлах |
FIELD_DISTRIBUTION_M имя; F; Tmin; Tmax; |
ДН, квадратуры в памяти |
К относительным именам приписывается папка задания. Проверки при чтении шага
(CTmcRTH_Indan::ReadOutputSection):
- одночастотный расчёт: окно
Tmin; TmaxуSMATRIXобязательно (Tmin — в установившемся режиме), а частотаSMATRIXдолжна совпадать сFREQшага (допуск относительный) — S-матрица считается наFREQ; - расчёт с падающей волной из файла (
[имя]у Amp входа): окно по умолчанию — весь интервал0..Tmax, частота не сверяется.
PutSmatrix после шага: файл .t с многочастотным заголовком обрабатывает CTmcWideband
(все тоны за один проход, теория), иначе CTmcTtoS на одной
частоте (S-матрица по сигналам). Ошибка и предупреждение
сохраняются в csSMatrixError/csSMatrixWarning. Если шаг посчитан с ошибкой, ядро вызывает
PutSmatrixZero: в .s записывается нулевая S-матрица на частоте SMATRIX (число портов — число
входов), чтобы ошибочная точка свипа была видна сразу.
Интегрирование поля для ДН
CFieldIntegrated строит исходные данные для ДН: амплитуду и фазу гармоники поля вблизи границы
области и набор эквивалентных излучателей вдоль замкнутого контура
(контур в ближней зоне). Сама ДН в дальней зоне считается программой
TMC_DN (tmc-dn) по файлу .DAT.
Файлы (базовое имя из FIELD_DISTRIBUTION[_M]):
| Файл | Содержимое |
|---|---|
.COS, .SIN |
квадратуры C и S по сетке (только файловый режим) |
.AMP, .FAZ |
амплитуда и фаза по сетке (кроме режима полос) |
.DAT |
эквивалентные излучатели для TMC_DN; при нескольких тонах — <имя>_<F>MHz.DAT на каждый тон |
Формат .COS/.SIN/.AMP/.FAZ: текстовый заголовок из строк #TMC_GraphicsOutputFieldFile FormVer2.0 2000,
#TMCGROFLD_nT, _Time, _Delta, _Xmin, _Ymin, _Accuracy (байт на значение), _LongUnit,
_TimeUnit, _nX, _nY (через CR LF), затем nY строк узлов: CR LF и nX двоичных значений _real.
Режимы хранения:
| Режим | Задаётся | Память | Скорость |
|---|---|---|---|
| файловый | FIELD_DISTRIBUTION |
— | на каждом шаге по времени файлы .COS/.SIN читаются и перезаписываются поштучно — очень медленно |
| память, вся область | FIELD_DISTRIBUTION_M |
значений _real |
быстро |
| память, полосы | FIELD_DISTRIBUTION_M на большой сетке или при нескольких тонах |
nBorderSize на тон |
быстро |
Значение узла в массиве ядра — prUNode1[n*nNodeStep]: шаг 2 у H-ядра (по умолчанию), 6 у X-ядра
(SetNodeStep(6)). Код называет накапливаемую величину Ez; это значение узла сетки ядра.
Накопление квадратур
На каждом шаге по времени Integrate(t, n, prUNode1):
- вне окна ничего не делается;
- в окне к квадратурам каждого хранимого узла прибавляется
- на первом шаге с окно закрывается и строятся амплитуда и фаза
(фаза делится на множитель ANGLE_UNIT), затем пишется .DAT.
При чтении #OUTPUT конец окна округляется вверх до целого числа периодов частоты F:
(в коде — (int)(...*F + 0.9999)).
Поэтому окно может закончиться позже, чем записано в задании; если оно кончается после конца
расчёта TIME, ядро сообщает ошибку «DN files are not written» (IsWindowOpen()).
При нескольких тонах падающей волны (SetFreqList, вызывает ядро для входа с файлом .sig)
квадратуры каждого тона накапливаются в своём срезе массивов
[k*nBorderSize, (k+1)*nBorderSize), а .DAT пишется на каждый тон. Многочастотная ДН требует
FIELD_DISTRIBUTION_M — с FIELD_DISTRIBUTION ядро выдаёт ошибку.
Режим полос у контура
ДН строится по контуру, а не по всей области, поэтому на большой сетке хранить квадратуры всех узлов
незачем (теория). Режим полос включается
(SetBorderModeIfNeeded), если:
- задана переменная окружения
TMC_FORCE_BORDER=1(проверка режима на малых заданиях); - тонов больше одного;
- или сетка не меньше 32×32 узлов и четыре массива на всю область,
sizeof(_real)байт, заняли бы больше четверти свободной физической памяти.
Контур в номерах узлов расширяется на узел наружу: nBX0..nBX1, nBY0..nBY1. Хранятся четыре полосы
толщиной 3 узла (по узлу с каждой стороны линии контура — столько нужно для разностей поля):
| Диапазон в массиве | Полоса |
|---|---|
[0, 3W) |
нижняя: строки nBY0..nBY0+2, все столбцы nBX0..nBX1 |
[3W, 6W) |
верхняя: строки nBY1-2..nBY1 |
[6W, 6W+3Hm) |
левая: столбцы nBX0..nBX0+2, строки между нижней и верхней |
[6W+3Hm, 6W+6Hm) |
правая: столбцы nBX1-2..nBX1 |
Здесь W = nBX1-nBX0+1, Hm — высота боковых полос между нижней и верхней, nBorderSize = 6W + 6Hm;
ни один узел не хранится дважды. BorderSlot(ix, iy) отдаёт место узла в массиве или −1. В режиме
полос файлы .AMP/.FAZ не пишутся: амплитуда и фаза считаются прямо в память (MakeAmpFazFromMemory).
Файл излучателей .DAT
Контур интегрирования — прямоугольник в 10 шагах сетки от краёв области
(SetDirectionalPatternParamDefault; другого способа задать контур в коде нет), независимо от
геометрии задания. Проверка IsDirectionalPatternDataCorrect требует не меньше 9 шагов до краёв.
Как размещать излучающую структуру относительно контура — см. теорию.
Точки контура — через шаг , посередине между узлами. В каждой точке:
- Ez — среднее комплексных значений двух соседних узлов вдоль стороны;
- касательная составляющая H — из разности Ez по нормали к стороне (через шаг):
фаза сдвигается на ; для вертикальных сторон это Hy, для горизонтальных — Hx;
- если по соотношению фаз (cos(fH - fEz), знак условия зависит от стороны) точка не проходит
проверку, её амплитуды Ez и H обнуляются; затем фазы меняют знак.
Каждая точка даёт три записи — Ez с множителем «1.», Hy с множителем «cos(f)» и Hx с множителем «sin(f)» — с сектором излучения своей стороны: правая , верхняя , левая , нижняя (границы смещены на 0,001°). Амплитуды умножаются на
Формат файла:
Frequence = <F в ГГц> Ghz;
N = <число записей>;
1.
1 X = <мм>; Y = <мм>; Amplitude = <A*k>; Faza = <градусы>; FiMin = <градусы>; FiMax = <градусы>; 1.
2 X = ...; ...; cos(f)
3 X = ...; ...; sin(f)
...
Связь с КНД, КИП и решётками — на странице теории (ДН).
Типы и константы
typerth.h задаёт точность расчёта: _PREC_DOUBLE → _real = double (8 байт; размер пишется в
файлы полей и сверяется при чтении), значение узла _ELEM_VAL_RTH = _real. Константы: C0___ — c,
м/с; MU0___, EPS0___ — mu0, eps0; PI___; ELECTRON_Q___, ELECTRON_M___ — заряд и масса
электрона для модели плазмы X-ядра. Остальная часть файла — прототипы функций, реализованных в ядре
(pl_glfun.cpp): строка состояния (PutTrace, PutStatistics), звуковые сигналы, проверка точки
в треугольнике IsPointInTr, функции потоков ReadDataGlobal, RunStepGlobal, RunAllGlobal.
SetAutoStartRun*, IsAutoStartRun, RunStepGlobalOneTacts объявлены, но не реализованы.
Пределы и метки TAMIC
tmclimit.h — наследие TAMIC. В Qt6-версии используются только FREQ_MAX_NUM = 100 (не более 99 частот
в файле .s), MAX_INPUT_NUM = 20 (входов в S-матрице) и MAX_WINDOW_NUM; остальные макросы не
используются. label/rth.h — строки-метки: MAIN_LABEL и TWP_LABEL записываются библиотекой SFILE95
в заголовок файла .s, COPYRIGHT_TITLE и TITLE_STR используются SFILE95. Тексты меток — часть
формата, их не меняют.
Неиспользуемые части
| Что | Состояние |
|---|---|
CTmcRTH_Input, CTmcRTH_InputNode |
компилируются, но не используются: открытых методов заполнения нет; узлы входов строят ядра |
CTmcRTH_Indan::WriteFileForMaple |
вспомогательный экспорт параметров модели «ролик — статор» в Maple; ядрами не вызывается |
| необязательные mu, Dz, Hx, Hy, Ro, Sigma и др. у блоков | разбираются и хранятся текстом, ядра их не читают |
RECT_MOVE, CIRCLE_MOVE, POLYGON_MOVE |
разбираются; поля скоростей совпадают с полями сигнала входа (csVx, csVy, csW) |
HEIGHT, DELTA_T_MECHANICAL |
разбираются, на расчёт не влияют |
B_UNIT, N_UNIT |
разбираются, ядрами не применяются |
CalcnNodeGlobalNorm |
не вызывается |
libs/tmcindan/stdafx.cpp |
не входит в список файлов библиотеки |
include/indan/* |
старые копии заголовков; никто не подключает indan/...; действующие — в include/ и в папках ядер |
Подводные камни
- Порядок строк
#PARM. Единицы применяются к значениям при чтении:DELTA 0.1;передLONG_UNIT m;будет прочитан в миллиметрах (единица по умолчанию). - Длинный путь (Windows). Путь к заданию и временному файлу
~$Prepr$~должен быть короче 260 символов. - Длинная строка. Строка задания после препроцессора длиннее 19998 символов — ошибка.
- Окно ДН за пределами расчёта.
Tmaxокна округляется вверх до целого числа периодов; если оно выходит заTIME, файлы ДН не пишутся (ошибка ядра). - Частота
SMATRIX≠FREQ. В одночастотном расчёте — ошибка: S-матрица считается наFREQ. - Больше 99 частот в одном
.s. Ошибка ещё до расчёта; свип надо разбить на несколько файлов. - Файловый режим ДН (
FIELD_DISTRIBUTION) на каждом шаге по времени перечитывает и перезаписывает файлы квадратур по одному числу — на больших сетках это очень медленно; используйтеFIELD_DISTRIBUTION_M. - Тоны ДН.
SetFreqListмолча отбрасывает тоны сверх 99, а список длиннее 2047 символов игнорирует целиком (тогда ДН строится на одной частоте). N_UNITзаписывает имя и множитель в поля единицы B (csBUnit,rBUnit). На расчёт не влияет, так как обе единицы ядрами не применяются.ANGLE_UNIT gradusи ДН. Фаза в.FAZхранится в единицахANGLE_UNIT, а построение.DATподставляет её вcos/sinи пересчитывает в градусы как радианы — при градусах фазы излучателей неверны.- Сверка заголовков
.AMP/.FAZ(ReadParamFromFile) не замечает разных единиц времени: условие сравниваетdTimeUnitAсамо с собой.
TMCIndan library: reading the task file and integrating the field for the RP
Purpose and place in the package
TMCIndan is a static library through which both compute kernels (PlanarRT_H and PlanarRT_X)
read the .tpl task file and build the data for the radiation pattern (RP). It:
- runs the PREPR preprocessor (macros,
#include) and writes the expanded task file to a temporary file; - finds in it the
#STEPwith the required number and parses its sections#PARM,#TOPOLOGY,#LINK_LIST,#OUTPUT; - converts all quantities to SI, aligns the computational region to the grid, checks correctness;
- keeps the list of blocks (geometry, material, ports, plasma) in a form convenient for the kernel;
- after a step, converts the time signals
.tinto the scattering matrix.s; - accumulates over time the field harmonic at the RP frequency and writes the file of equivalent radiators
.DAT, from which the TMC_DN program builds the RP.
The library does not compute the field: the node grid and the time-domain computation are handled by the kernel
(kernel-h, kernel-x). TMCIndan depends on the libraries prepr
(preprocessor), exprint (expression evaluation i1nte_atof_1), TMCLibError (error object),
and also on SFILE95 and the viewer classes CTmcTtoS/CTmcWideband when writing .s.
Contents
| File | Role |
|---|---|
libs/tmcindan/tmcrth_indan.cpp, include/tmcrth_indan.h |
CTmcRTH_Indan — entry point: preprocessor, search for the step and sections, section labels; MainPrepr |
libs/tmcindan/tmcrth_indanparam.cpp, include/tmcrth_indanparam.h |
CTmcRTH_IndanParam — the #PARM section, units, grid, node indices; mechanical step SetDeltaT |
libs/tmcindan/tmcrth_indantopology.cpp, include/tmcrth_indantopology.h |
CTmcRTH_IndanTopology — wrapper of the block list, the #LINK_LIST section, port side |
libs/tmcindan/tmcrth_bolcklist.cpp, include/tmcrth_bolcklist.h |
CTmcRTH_BlockList — a block and the list of blocks, parsing of all primitives, saving/loading |
libs/tmcindan/tmcrth_indanoutput.cpp, include/tmcrth_indanoutput.h |
CTmcRTH_IndanOutput — the #OUTPUT section, file names, writing .s |
libs/tmcindan/fieldintegrated.cpp, include/fieldintegrated.h |
CFieldIntegrated — accumulation of field quadratures, amplitude/phase, radiator file .DAT |
libs/tmcindan/tmcrth_input.cpp, tmcrth_inputnode.cpp and their headers |
CTmcRTH_Input, CTmcRTH_InputNode — compiled but not used (see below) |
libs/tmcindan/stdafx.h |
includes afx.h/afxwin.h of the compat compatibility layer |
include/typerth.h |
the _real type, the node value type, physical constants, prototypes of kernel utility functions |
include/tmcidx.h |
the node index type TmcIdx and reading/writing an index in 4 bytes |
include/tmclimit.h, include/label/rth.h |
TAMIC table limits and the header labels of the .s file |
libs/tmcindan/stdafx.cpp, include/indan/* |
not part of the build (old copies) |
The list of compiled files is given in src/CMakeLists.txt (tmc_add_library(TMCIndan ...)).
Classes and their relations
CTmcRTH_Indan (kernel: CTmcRTHRectNode::cIndan)
├── cParam : CTmcRTH_IndanParam — #PARM of steps 1..N
├── cTopology : CTmcRTH_IndanTopology — #TOPOLOGY + #LINK_LIST of step N
│ ├── pcParam -> cParam (pointer, not owning)
│ └── cBlockList : CTmcRTH_BlockList -> block -> block -> ... -> empty
├── cOut : CTmcRTH_IndanOutput — #OUTPUT of step N
│ └── cFieldDistr : CFieldIntegrated (copy of the step parameters)
└── cError : CTmcLibError
Life cycle. The kernel creates CTmcRTH_Indan together with the document. For each step of the sweep it
calls ReadData(file, N); then it reads the parameters and the block list through getters, builds the node
grid, calls GetOutput()->GetFieldIntegrated().InitAllFile(...), on every time step —
Integrate(...), and after the computation — PutSmatrix() (or PutSmatrixZero() if the step failed).
The temporary preprocessor file is deleted on the next SetTplFileName and in the destructor.
Threads. Task-file parsing runs in the kernel's reading thread, integration and writing of .s in the computation
thread. The classes are not thread-safe; the kernel does not call them from two threads at once.
Errors. Exceptions are not used. Each class holds a CTmcLibError; methods check
IsError() at the start and do nothing if an error is already set. The error text is in English,
with a quotation of the offending task-file line in curly braces; the kernel shows it in the status bar
and in the console.
Reading the task file
The order of work of CTmcRTH_Indan::ReadData(csFileName, nStepNum):
SetTplFileName. Resets the data, checks that the file opens, computes the task folder (the full path up to the last separator). The name of the temporary file is<task file>~$Prepr$~<process number>; the process number is needed so that two simultaneous runs of the same task file do not interfere with each other. On Windows the path of the task file and of the temporary file must be shorter than 260 characters (otherwise a clear error is given; if it does not fit with the number, the number is not added).- Preprocessor.
MainPreprcallsMainPrepr1of the PREPR library (lib-prepr): macros and#includeare expanded, the result is written to the temporary file. - Number of steps.
GetNStepMaxpasses through the file once: it checks that#STEP/#END_STEPare paired, counts the steps and for eachSMATRIXfile collects the set of frequencies (frequencies are compared after normalisation with%.12g). More than 99 frequencies per.sfile is an error: an S-matrix file holds at mostFREQ_MAX_NUM - 1= 99 frequencies. - The step number is checked: from 1 to the number of steps.
- Sections.
ReadParamSection→ReadTopologySection→ReadLinkListSection→ReadOutputSection. Each section is searched for anew:FindStep(N)opens the temporary file from the beginning and positions itself after the N-th#STEPlabel,FindSectionsearches for the section start label up to#END_STEP,GetLineSectionreturns lines up to the section end label.
Line-by-line reading (GetLine):
- empty lines and comment lines (starting with
!) are skipped; - leading spaces are removed, a run of spaces/tabs is compressed into one character; the first gap
after a keyword always becomes a space — keywords are compared together with it
(
"BLOCK ","FREQ ","RECT_STAT "); #EOFends reading; end of file without#EOFis the errorMissing #EOF;- a line longer than
CTMCRTH_INDAN_LINELEN - 2= 19998 characters is an error (a long comment is skipped entirely).
Parameters within lines are separated by ;. The separator is searched for only outside the brackets {}, (), []
(Search_1Param), so a semicolon is allowed inside expressions and in [name]. Values are
expressions of the expr library: numbers, #define variables, functions.
Parameters: the #PARM section
| Keyword | Meaning | Stored as (SI) |
|---|---|---|
LONG_UNIT m\|cm\|mm; |
length unit (default mm) | rLongUnit, metres per unit |
TIME_UNIT s\|ms\|mks\|ns\|ps; |
time unit (default s) | rTimeUnit |
FREQ_UNIT Hz\|kHz\|MHz\|GHz; |
frequency unit (default GHz) | rFreqUnit |
ANGLE_UNIT radian\|gradus; |
angle unit (default radian); also switches the trigonometry of expressions | rAngleUnit |
B_UNIT, N_UNIT |
parsed, not applied by the kernels (see below) | — |
FREQ F; |
operating frequency | rFreq, Hz |
DELTA d; |
grid step | rDelta, m; also the time step rt |
TIME Tmin; Tmax; |
computation interval | rTmin, rTmax, s |
X_MIN, X_MAX, Y_MIN, Y_MAX |
region boundaries | rXmin … rYmax, m |
HEIGHT, DELTA_T_MECHANICAL |
parsed, do not affect the computation | rHeight, rDeltaTMechanical |
A value is converted to SI immediately on reading with the current unit, so the unit lines must
come earlier in the section than the quantities. Parameters accumulate over steps: for step N the
#PARM sections of steps 1, 2, …, N are read; step 1 is mandatory, later steps may have no such section.
Time step of the Rt-grid (theory):
The number of time steps is nGetTmax() .
Checks in IsCorrectly: , , , ,
and , where is the free-space wavelength.
Aligning the region to the grid
After the checks, IsCorrectly computes the number of nodes once and moves the right and top boundaries
onto a reserve column/row of nodes:
The same applies to Y. Nodes are numbered , , the node coordinate is
. The X_MAX/Y_MAX values from the task file are saved in rXmaxUser/rYmaxUser;
a new boundary or a new DELTA in a later step resets nXGrid/nYGrid, and the grid
is recomputed. The blocks of the task file must lie on nodes, and the boundaries must be multiples of the step
(grid rules).
Node indices and the TmcIdx type
The global node index is . On large grids it exceeds , so all indices
and node array sizes have the type TmcIdx (ptrdiff_t: 64 bits in the win64 build). The kernels reject
a grid for which (with a margin for the number of values per node) does not fit into TMC_IDX_MAX.
Coordinate conversion (CTmcRTH_IndanParam):
| Method | Result |
|---|---|
CalcnNodeGlobal(x, y) |
index of the nearest node; a point outside the region is clamped to the boundary; a point closer than half a step to the left/right edge goes to the outermost column |
CalcnNodeGlobalFM(x, y) |
the same, but the strip at the left/right edge is 1.5 steps wide, and a point in it belongs to the second column from the edge |
CalcnNodeGlobalNorm(x, y) |
node index, or −1 if the point is closer than two steps to the boundary |
CalcX(n), CalcY(n) |
node coordinates, m |
IsnInRegion(x, y) |
the point is no more than half a step beyond the region boundary |
In the .eps distribution files the node index is still stored as a 4-byte int (the format has not changed):
reading and writing — TmcReadIdx32/TmcWriteIdx32.
Topology and block placement
The blocks of the #TOPOLOGY section are described in local coordinates. The #LINK_LIST section assembles
the device: the line
T n; X0; Y0;
moves the origin of the local coordinates of block n to the point (X0, Y0) of the region (units LONG_UNIT).
Each block must be placed by exactly one line. Inside the list this is visible from the sign of the number:
after #TOPOLOGY the block number is stored with a minus sign, and SetLink makes it positive;
a repeated T line for the same block is an error, and an unplaced block is the error BLOCK n is absent
in #LINK_LIST section.
The side of each port is also determined here (ports):
INPUT_X(port along the Y axis) — left, if X0 is within one step ofXminor in the left half of the region; right (CTMCRTH_BLCKNTYPE_INPXRIGHT), if within one step ofXmaxor in the right half;INPUT_Y(port along the X axis) — bottom (CTMCRTH_BLCKNTYPE_INPYBOT) or top — in the same way by Y0.
X0/Y0 outside the region is an error with a hint of the allowed values.
Topology blocks
The block text passed to CTmcRTH_BlockList::Add:
BLOCK n;
<PRIMITIVE> <parameter 1>; <parameter 2>; ...;
[L x; y; — only for polygons]
END_B
The number is n >= 1. The primitive is determined by the beginning of the second line; labels are compared in full with
the trailing space, so RECT_STAT_N is not taken for RECT_STAT.
The first parameter is the value of the block or one of the words that set the type (nType, codes from tmcgrviw.h):
| First parameter | nType |
Meaning |
|---|---|---|
| expression | 0 (EPS) |
dielectric: an expression for eps (or N, B, Y, sigma for plasma blocks) |
METAL |
101 | metal |
MAGNETIC |
107 | magnetic wall |
ABSORBER |
100 | absorber |
| (ports) | 102…105 | port on the left, right, top, bottom |
The macro _MODEL_RTE__ in tmcgrviw.h would swap the words METAL and MAGNETIC, but it is not
defined in the build: METAL always gives type 101 in both kernels. What these types mean in the X kernel — see
duality of the walls. The first parameter may start with
[name] — a flag for writing the distribution to a .eps file; this prefix is parsed by the kernel.
Primitives and their parameters
| Primitive | Parameters after the first | Where stored |
|---|---|---|
RECT_STAT |
Xmin; Xmax; Ymin; Ymax; (LONG_UNIT, min < max) |
dXmin…dYmax, m |
CIRCLE_STAT |
Rmin; Rmax; FImin; FImax; (0 <= Rmin < Rmax, 0 <= FImin < FImax <= 2*pi, angles in ANGLE_UNIT) |
dXmin/dXmax — radii, m; dYmin/dYmax — angles, rad |
POLYGON_STAT |
vertex lines L x; y;, at least three |
dX[], dY[], nXY |
FILE <name>; |
not read by the library (the file name is the first parameter) | csEpsExpr; .eps is appended to a name without extension, the task folder is prepended to a relative path |
INPUT_X |
Ymin; Ymax; Tmin; Tmax; [Amp]; [Faza]; [W]; |
dXmin/dXmax — limits along Y, m; dYmin/dYmax — time, s; csVx, csVy, csW |
INPUT_Y |
Xmin; Xmax; Tmin; Tmax; [Amp]; [Faza]; [W]; |
the same, limits along X |
RECT_MOVE, CIRCLE_MOVE, POLYGON_MOVE |
as for the static ones, plus velocities Vx; Vy; W etc. |
csVx, csVy, csW — velocities |
The optional tail of the static primitives (mu; Dz; Hx; Hy; Ro; Sigma;, for the circle also the outer
Dz and conductivity) is stored as text; parsing simply ends at the first missing ;.
The kernels do not use these fields.
Plasma variants (X kernel)
| Suffix | Primitives | Quantity | Unit |
|---|---|---|---|
_N |
RECT_STAT_N, CIRCLE_STAT_N, POLYGON_STAT_N, FILE_N |
electron density N | m^-3 (theory) |
_B |
RECT_STAT_B, CIRCLE_STAT_B, POLYGON_STAT_B, FILE_B |
magnetic flux density B of the biasing field | T (theory) |
_Y |
RECT_STAT_Y, CIRCLE_STAT_Y, POLYGON_STAT_Y, FILE_Y |
losses (grid conductance Y) | — (theory) |
_S |
RECT_STAT_S, CIRCLE_STAT_S, POLYGON_STAT_S |
conductivity sigma | S/m |
For _N, _B, _Y, _S only an expression is allowed as the first parameter (not METAL and the like).
*_STAT_S is parsed by the same code as *_STAT_Y, but keeps the _S label — the conversion of sigma
is done by the kernel. FILE_N, FILE_B, FILE_Y keep their label so that the kernel routes the values of
the file to N, B or Y. The units of the plasma quantities are fixed (units):
the N_UNIT/B_UNIT lines have no effect on them.
Ports
The eight port parameters (the port signal):
| No. | Parameter | Parsing |
|---|---|---|
| 1 | type: empty or METAL — the H10 wave of a waveguide, MAGNETIC — a plane wave |
any other word is an error |
| 2, 3 | port limits along the side | LONG_UNIT, min < max |
| 4, 5 | radio-pulse time Tmin, Tmax | TIME_UNIT, Tmin < Tmax |
| 6 | Amp — an expression of t, f or [file] |
[file] — incident wave from a .sig file (theory) |
| 7 | Faza — an expression of t, f (in ANGLE_UNIT) |
mandatory if Amp is given |
| 8 | W — eps increment in the port cross-section | eps = 1 + W > 0; the variables t and f are forbidden (theory) |
The ban on t/f in W is checked by TmcExprUsesTorF: a one-letter name t or f not followed by (;
numbers with an exponent (1.5e-3) are skipped entirely.
Saving and loading the list
Save writes the list as text between #BlockListBegin and #BlockListEnd: for each block five lines
(primitive, first parameter, Vx, Vy, W), the line dX0 dXmax dXmin dY0 dYmax dYmin nBlock nMemory nType nXY
and nXY vertex lines. Load reads this format. The expressions mu, Dz, Hx, Hy and the force parameters are not
saved.
Output files: the #OUTPUT section
| Line | Action |
|---|---|
FILE name; |
base name (a dot in the file name is forbidden): .t — signals at the ports, .ex, .ey, .hz — field, .tt — topology, .s — S-matrix, and also .em, .ef, .q, .ix, .iy; mandatory |
TOPOLOGY |
write the topology |
FIELDS |
write the fields .ex, .ey, .hz |
SMATRIX file; F; [Tmin; Tmax;] |
S-matrix at frequency F over the window Tmin..Tmax; a name without extension gets .s |
FIELD_DISTRIBUTION name; F; Tmin; Tmax; |
RP, quadratures in files |
FIELD_DISTRIBUTION_M name; F; Tmin; Tmax; |
RP, quadratures in memory |
The task folder is prepended to relative names. Checks when reading a step
(CTmcRTH_Indan::ReadOutputSection):
- single-frequency computation: the
Tmin; Tmaxwindow ofSMATRIXis mandatory (Tmin in the steady state), and theSMATRIXfrequency must coincide with theFREQof the step (relative tolerance ) — the S-matrix is computed atFREQ; - computation with an incident wave from a file (
[name]in the Amp of a port): the default window is the whole interval0..Tmax, the frequency is not checked.
PutSmatrix after a step: a .t file with a multi-frequency header is processed by CTmcWideband
(all tones in a single pass, theory), otherwise by CTmcTtoS at a single
frequency (S-matrix from signals). The error and the warning
are stored in csSMatrixError/csSMatrixWarning. If a step was computed with an error, the kernel calls
PutSmatrixZero: a zero S-matrix at the SMATRIX frequency is written to .s (the number of ports equals the number of
port blocks), so that the faulty sweep point is visible immediately.
Integrating the field for the RP
CFieldIntegrated builds the source data for the RP: the amplitude and phase of the field harmonic near the boundary
of the region and a set of equivalent radiators along a closed contour
(near-field contour). The far-field RP itself is computed by the
TMC_DN program (tmc-dn) from the .DAT file.
Files (base name from FIELD_DISTRIBUTION[_M]):
| File | Contents |
|---|---|
.COS, .SIN |
quadratures C and S over the grid (file mode only) |
.AMP, .FAZ |
amplitude and phase over the grid (except in strip mode) |
.DAT |
equivalent radiators for TMC_DN; with several tones — <name>_<F>MHz.DAT for each tone |
Format of .COS/.SIN/.AMP/.FAZ: a text header of the lines #TMC_GraphicsOutputFieldFile FormVer2.0 2000,
#TMCGROFLD_nT, _Time, _Delta, _Xmin, _Ymin, _Accuracy (bytes per value), _LongUnit,
_TimeUnit, _nX, _nY (separated by CR LF), then nY lines of nodes: CR LF and nX binary _real values.
Storage modes:
| Mode | Set by | Memory | Speed |
|---|---|---|---|
| file | FIELD_DISTRIBUTION |
— | on every time step the .COS/.SIN files are read and rewritten value by value — very slow |
| memory, whole region | FIELD_DISTRIBUTION_M |
_real values |
fast |
| memory, strips | FIELD_DISTRIBUTION_M on a large grid or with several tones |
nBorderSize per tone |
fast |
The node value in the kernel array is prUNode1[n*nNodeStep]: stride 2 for the H kernel (default), 6 for the X kernel
(SetNodeStep(6)). The code calls the accumulated quantity Ez; it is the value of the kernel grid node.
Accumulating the quadratures
On every time step Integrate(t, n, prUNode1):
- outside the window nothing is done;
- inside the window, the following is added to the quadratures of each stored node
- on the first step with the window is closed and the amplitude and phase are built
(the phase is divided by the ANGLE_UNIT multiplier), then .DAT is written.
When #OUTPUT is read, the end of the window is rounded up to a whole number of periods of the frequency F:
(in the code — (int)(...*F + 0.9999)).
Therefore the window may end later than written in the task file; if it ends after the end of the
TIME computation, the kernel reports the error "DN files are not written" (IsWindowOpen()).
With several tones of the incident wave (SetFreqList, called by the kernel for a port with a .sig file)
the quadratures of each tone are accumulated in their own slice of the arrays
[k*nBorderSize, (k+1)*nBorderSize), and .DAT is written for each tone. A multi-frequency RP requires
FIELD_DISTRIBUTION_M — with FIELD_DISTRIBUTION the kernel reports an error.
Strip mode at the contour
The RP is built from the contour, not from the whole region, so on a large grid there is no point in storing
the quadratures of all nodes (theory). Strip mode is enabled
(SetBorderModeIfNeeded) if:
- the environment variable
TMC_FORCE_BORDER=1is set (to test the mode on small task files); - there is more than one tone;
- or the grid is at least 32×32 nodes and four arrays over the whole region,
sizeof(_real)bytes, would occupy more than a quarter of the free physical memory.
The contour in node indices is extended by one node outwards: nBX0..nBX1, nBY0..nBY1. Four strips
3 nodes thick are stored (one node on each side of the contour line — as many as are needed for the field differences):
| Range in the array | Strip |
|---|---|
[0, 3W) |
bottom: rows nBY0..nBY0+2, all columns nBX0..nBX1 |
[3W, 6W) |
top: rows nBY1-2..nBY1 |
[6W, 6W+3Hm) |
left: columns nBX0..nBX0+2, rows between the bottom and the top |
[6W+3Hm, 6W+6Hm) |
right: columns nBX1-2..nBX1 |
Here W = nBX1-nBX0+1, Hm is the height of the side strips between the bottom and the top, nBorderSize = 6W + 6Hm;
no node is stored twice. BorderSlot(ix, iy) returns the position of the node in the array or −1. In strip
mode the .AMP/.FAZ files are not written: the amplitude and phase are computed directly in memory (MakeAmpFazFromMemory).
The .DAT radiator file
The integration contour is a rectangle 10 grid steps from the edges of the region
(SetDirectionalPatternParamDefault; the code offers no other way to set the contour), regardless of
the geometry of the task file. The check IsDirectionalPatternDataCorrect requires at least 9 steps to the edges.
How to place the radiating structure relative to the contour — see the theory.
The contour points are spaced by the step , midway between nodes. At each point:
- Ez is the mean of the complex values of the two neighbouring nodes along the side;
- the tangential component of H is obtained from the difference of Ez along the normal to the side (across one step):
the phase is shifted by ; for vertical sides this is Hy, for horizontal ones Hx;
- if a point fails the check on the phase relation (cos(fH - fEz), the sign of the condition depends on the side),
its Ez and H amplitudes are zeroed; then the phases change sign.
Each point gives three records — Ez with the multiplier "1.", Hy with the multiplier "cos(f)" and Hx with the multiplier "sin(f)" — with the radiation sector of its side: right , top , left , bottom (the limits are shifted by 0.001°). The amplitudes are multiplied by
File format:
Frequence = <F in GHz> Ghz;
N = <number of records>;
1.
1 X = <mm>; Y = <mm>; Amplitude = <A*k>; Faza = <degrees>; FiMin = <degrees>; FiMax = <degrees>; 1.
2 X = ...; ...; cos(f)
3 X = ...; ...; sin(f)
...
The relation to directivity, aperture efficiency and arrays is described on the theory page (RP).
Types and constants
typerth.h sets the computation precision: _PREC_DOUBLE → _real = double (8 bytes; the size is written to
the field files and checked on reading), the node value _ELEM_VAL_RTH = _real. Constants: C0___ — c,
m/s; MU0___, EPS0___ — mu0, eps0; PI___; ELECTRON_Q___, ELECTRON_M___ — the charge and mass of
the electron for the plasma model of the X kernel. The rest of the file consists of prototypes of functions implemented in the kernel
(pl_glfun.cpp): the status bar (PutTrace, PutStatistics), sound signals, the point-in-triangle
check IsPointInTr, the thread functions ReadDataGlobal, RunStepGlobal, RunAllGlobal.
SetAutoStartRun*, IsAutoStartRun, RunStepGlobalOneTacts are declared but not implemented.
TAMIC limits and labels
tmclimit.h is a TAMIC legacy. The Qt6 version uses only FREQ_MAX_NUM = 100 (at most 99 frequencies
in a .s file), MAX_INPUT_NUM = 20 (ports in the S-matrix) and MAX_WINDOW_NUM; the other macros are not
used. label/rth.h contains label strings: MAIN_LABEL and TWP_LABEL are written by the SFILE95 library
into the header of the .s file, COPYRIGHT_TITLE and TITLE_STR are used by SFILE95. The label texts are part of
the format and are not changed.
Unused parts
| What | Status |
|---|---|
CTmcRTH_Input, CTmcRTH_InputNode |
compiled but not used: there are no public filling methods; the port nodes are built by the kernels |
CTmcRTH_Indan::WriteFileForMaple |
auxiliary export of the parameters of the "roller — stator" model to Maple; not called by the kernels |
| optional mu, Dz, Hx, Hy, Ro, Sigma etc. of blocks | parsed and stored as text, the kernels do not read them |
RECT_MOVE, CIRCLE_MOVE, POLYGON_MOVE |
parsed; the velocity fields coincide with the port signal fields (csVx, csVy, csW) |
HEIGHT, DELTA_T_MECHANICAL |
parsed, do not affect the computation |
B_UNIT, N_UNIT |
parsed, not applied by the kernels |
CalcnNodeGlobalNorm |
not called |
libs/tmcindan/stdafx.cpp |
not in the list of library files |
include/indan/* |
old copies of headers; nobody includes indan/...; the active ones are in include/ and in the kernel folders |
Pitfalls
- Order of
#PARMlines. Units are applied to values on reading:DELTA 0.1;beforeLONG_UNIT m;will be read in millimetres (the default unit). - Long path (Windows). The path to the task file and to the temporary
~$Prepr$~file must be shorter than 260 characters. - Long line. A task-file line longer than 19998 characters after the preprocessor is an error.
- RP window beyond the computation. The window
Tmaxis rounded up to a whole number of periods; if it goes beyondTIME, the RP files are not written (kernel error). SMATRIXfrequency ≠FREQ. In a single-frequency computation this is an error: the S-matrix is computed atFREQ.- More than 99 frequencies in one
.s. An error even before the computation; the sweep has to be split into several files. - File mode of the RP (
FIELD_DISTRIBUTION) rereads and rewrites the quadrature files one number at a time on every time step — on large grids this is very slow; useFIELD_DISTRIBUTION_M. - RP tones.
SetFreqListsilently discards tones beyond 99, and ignores a list longer than 2047 characters entirely (the RP is then built at a single frequency). N_UNITwrites the name and the multiplier into the fields of the B unit (csBUnit,rBUnit). This does not affect the computation, since neither unit is applied by the kernels.ANGLE_UNIT gradusand the RP. The phase in.FAZis stored inANGLE_UNITunits, while building.DATsubstitutes it intocos/sinand converts it to degrees as if it were radians — with degrees the phases of the radiators are wrong.- Checking the
.AMP/.FAZheaders (ReadParamFromFile) does not notice different time units: the condition comparesdTimeUnitAwith itself.