Счётное ядро X: подмагниченная плазма, четыре подтакта и двойственные стенки
Назначение и место в пакете
Ядро X (программа tmc_rtx.exe, PlanarRT_X) считает во временной области двумерные задачи
для волн E-поляризации (необыкновенная волна) в средах с холодной подмагниченной
плазмой (теория, модель плазмы).
Исходники ядра — ветвь кода ядра H: те же классы CTmcRTHRectNode (сетка и цикл во времени)
и CTmcRTHNodeDiel (блоки задания), те же служебные функции pl_iofor/pl_glfun, тот же разбор
задания (TMCIndan) и та же оболочка (оболочка ядер).
Эта страница — дополнение к странице ядра H: здесь описано только то, чем X отличается. Всё, что не упомянуто, работает как в H, по ссылкам на соответствующие разделы.
Главные отличия:
| Ядро H | Ядро X | |
|---|---|---|
| Что хранит узел | напряжение (поле H-задачи) | напряжение = компонента |
| Ячеек на узел | 2 напряжения + 2 коэффициента | 6 напряжений + 6 коэффициентов (96 байт при double) |
| Схема узла | двухслойная (3 временных слоя) | четырёхслойная (5 временных слоёв), см. ниже |
| Подтактов за проход цикла | 2 | 4 |
| Среды | , концентрация , индукция , потери , проводимость | |
| Блоки METAL / MAGNETIC | металл / магнитная стенка | физически магнитная стенка / металл (двойственность) |
| Узлы портов в общем проходе рассеяния | пересчитываются, потом восстанавливаются | исключены (сохранение и восстановление вокруг прохода) |
| Топология | одна таблица eps | четыре таблицы: eps, N, Y, B |
Запись ДН по TMC_AUTO_DN |
есть | нет |
Состав
Файл (src/kernels/planarrt_x/) |
Роль |
|---|---|
tmcrthrectnode.h, tmcrthrectnode.cpp |
CTmcRTHRectNode: массивы узлов (шаг 6), пересчёт eps, N, B, Y, sigma в коэффициенты (SetDielInNodeList), цикл по 4 подтактам, рассеяние (RunScatteringNode*, RunScatteringNode1line*), вывод .t, поля, топологии; функции файла .t (TmcOutT*) |
tmcrthnodediel.h, tmcrthnodediel.cpp |
CTmcRTHNodeDiel: построение узлов блоков, в том числе плазменных (_N, _B, _Y, _S, FILE_N/_B/_Y), EPSFAST, файлы .eps и .sig, возбуждение портов на 4 подтактах (ExciteInputs..ExciteInputs3), защита узлов портов (SaveInputNodes/RestoreInputNodes), граничные условия (RunBlockNode..RunBlockNode3) |
pl_iofor.h, pl_iofor.cpp, pl_glfun.cpp |
побайтно те же, что в ядре H: форматы вывода, ключи запуска, код завершения, функции потоков, строка состояния, звук — см. ядро H |
tmcgpux.h |
перенос цикла во времени на видеокарту — см. Расчёт на видеокарте |
planrt_hdoc.*, planrt_hview.*, диалоги, resource.h |
документ, вид и диалоги ядра — см. оболочку ядер |
Имена классов и файлов у H и X одинаковы (CTmcRTHRectNode, CPlanRT_HDoc …), поэтому ядра
собираются отдельными программами из своих каталогов.
Сборка: макросы X-моды
Цель planarrt_x (src/kernels/PlanarRT_X/qt/CMakeLists.txt) передаёт компилятору шесть имён
макросов X-моды, как проект MFC-версии: ELECTRON_Q___, ELECTRON_M___,
CTMCRTH_INDANBLCK_FILEY, CTMCRTH_INDANBLCK_RECTSTATY, CTMCRTH_INDANBLCK_CIRCSTATY,
CTMCRTH_INDANBLCK_POLYGSTTY. В Qt6-версии все шесть определены и в общих заголовках:
заряд и масса электрона — в typerth.h ( Кл,
кг), ключевые слова блоков ("FILE_Y ", "RECT_STAT_Y " …) —
в tmcgrviw.h; значения берутся из заголовков. В исходниках ядра X условной компиляции по этим
именам нет: они нужны как значения (физические константы в SetDielInNodeList и PutTopology,
ключевые слова в SetBlock).
Структура данных узла
Узлы нумеруются, как в H: (64-битный TmcIdx). Значение узла X-ядра —
компонента (в терминах схемы — «напряжение» узла). На узел приходится 6 ячеек
напряжений и 6 ячеек коэффициентов:
| Ячейка | Содержимое |
|---|---|
prUNode1[6n+0..3] |
четыре последних временных слоя по кругу: на подтакте новое значение пишется в ячейку (там было ) |
prUNode1[6n+4], [6n+5] |
суммы двух прошлых подтактов (см. рассеяние); подтакты 0 и 2 пишут ячейку 5, подтакты 1 и 3 — ячейку 4 |
prYNode[6n+0] |
|
prYNode[6n+1] |
— шлейф узла со знаком: диэлектрик (холостой ход), плазма |
prYNode[6n+2] |
— сеточные потери |
prYNode[6n+3] |
|
prYNode[6n+4] |
|
prYNode[6n+5] |
До перевода в коэффициенты (SetDielInNodeList) ячейки prYNode[6n+0..4] служат
накопителями величин блоков: 0 — , 1 — (м⁻³), 2 — ,
3 — (См/м), 4 — (Тл). Подробно — в разделе блоки плазмы.
InitNodeArray выделяет по элемента с выравниванием на 32 байта и обнуляет все
ячейки; коэффициенты свободного пространства (, ) появляются только после
SetDielInNodeList, который проходит все узлы сетки. Общее число узлов ограничено
TMC_IDX_MAX/8, как в H.
Узел блока (sTmcRTHNodeDielOne) в X хранит падающее напряжение порта отдельно для каждого
подтакта: rU, rU1, rU2, rU3. У поглотителя и магнитной стенки rU — значение
узла, как в H. Поля rU_Cur..rU_Cur3 в расчёте не используются (обнуляются):
узлы порта защищает буфер prInputSave (ниже).
Четыре подтакта
Схема узла с подмагниченной плазмой связывает пять временных слоёв (теория), поэтому один проход цикла — четыре подтакта, и на каждом свои функции. Подтакт пишет ячейку и читает остальные:
| Подтакт | Порты | Рассеяние | Блоки | Пишется | / → | |||
|---|---|---|---|---|---|---|---|---|
| 0 | ExciteInputs |
RunScatteringNode |
RunBlockNode |
0 | 3 | 2 | 1 | 4 / 5 → 5 |
| 1 | ExciteInputs1 |
RunScatteringNode1 |
RunBlockNode1 |
1 | 0 | 3 | 2 | 5 / 4 → 4 |
| 2 | ExciteInputs2 |
RunScatteringNode2 |
RunBlockNode2 |
2 | 1 | 0 | 3 | 4 / 5 → 5 |
| 3 | ExciteInputs3 |
RunScatteringNode3 |
RunBlockNode3 |
3 | 2 | 1 | 0 | 5 / 4 → 4 |
Порядок вызовов одного подтакта (RunKernel1T):
RunExciteInputs*— строка.t(такт, время) и обновление всех портов;RunSaveInputs— запомнить 6 ячеек каждого узла порта;RunScatteringNode*— пересчёт всех внутренних узлов сетки;RunRestoreInputs— вернуть узлам портов их значения;RunBlockNode*— металл, поглотитель, магнитная стенка;PutField(k)— кадр поля из ячейки ;DistributionIntegrated(k)— накопление поля для ДН (накопитель знает шаг 6:SetNodeStep(6));nTCurrent += 1,dTCurrent += τ.
Цикл RunKernel идёт, пока nTCurrent < nTMax, по четыре подтакта; ход счёта выводится каждые
100 подтактов, как в H.
Рассеяние в узле
Для внутренних узлов (строки , столбцы ) функции RunScatteringNode1line*
вычисляют (теория)
где — четыре соседа, = prYNode[6n+k]; новое сохраняется в ячейке 4 или 5.
Это четырёхпараметрический алгоритм для необыкновенной волны: с
, , формула совпадает с выражением
теории, где — шлейф плазмы, — потери.
В узле диэлектрика (, ) формула переходит в
то есть в двухслойную схему ядра H , к обеим частям которой применён множитель (сдвиг на подтакт — ). В точной арифметике решения совпадают.
Узлы краёв области формулой не пересчитываются и остаются нулевыми. В X-ядре это — магнитная стенка, а не металл, как в H (двойственность).
Коэффициенты узла
SetDielInNodeList (после построения всех блоков) переводит величины узла в коэффициенты.
Обозначения: — шаг по времени подтакта, — частота задания,
, — заряд и масса электрона.
- Проводимость. Если : , ячейка 3 обнуляется.
- Узел плазмы — если или . Величины сводятся к одной эквивалентной плазменной частоте (теория):
Знак соответствует выражению алгоритма для необыкновенной волны (теория); прежний вариант с обратным знаком сохранён в исходнике комментарием. При : , , и среда с () — плазма с . 3. Узел диэлектрика (, ): (значения в пределах 0,004 от 4 сдвигаются до 3,996 или 4,004), , , . Индукция в таком узле не используется.
Перед пересчётом выдаются предупреждения (консоль, строка состояния, итог расчёта):
- узлы, где сочетается с : узел считается плазмой, добавка eps верна только на частоте задания; если добавка больше плазменной части, эквивалентная концентрация отрицательна и расчёт расходится;
- узлы, где сочетается с : не используется.
Ошибка «very big Delta*Frequence» — если , как в H. В учебной версии
(_VERSION_EDUC___) узлы с запрещены. Каждые 100 000 узлов проверяется
остановка.
Блоки плазмы
Выражение блока вычисляется так же, как в H (CalcEps: подставляются , , ,
относительно точки привязки), умножается на вес узла (доля ячеек) и прибавляется к своей
ячейке записи узла. Ячейку выбирает EpsFastTypeOffset по ключевому слову
(единицы):
| Блоки | Величина | Единица | Ячейка prYNode[6n+k] |
|---|---|---|---|
RECT_STAT, CIRCLE_STAT, POLYGON_STAT, FILE |
— | 0 | |
RECT_STAT_N, CIRCLE_STAT_N, POLYGON_STAT_N, FILE_N |
концентрация электронов | м⁻³ | 1 |
RECT_STAT_Y, CIRCLE_STAT_Y, POLYGON_STAT_Y, FILE_Y |
сеточные потери | безразмерная | 2 |
RECT_STAT_S, CIRCLE_STAT_S, POLYGON_STAT_S |
проводимость | См/м | 3 |
RECT_STAT_B, CIRCLE_STAT_B, POLYGON_STAT_B, FILE_B |
индукция | Тл | 4 |
Геометрия, веса узлов и правила сложения — как у диэлектрика H
(блоки H). Вклады разных блоков в одну ячейку складываются, поэтому
, , задаются отдельными блоками, перекрывающими друг друга; в каждом узле величины
затем пересчитываются вместе (коэффициенты). Блок (_S) нужен, чтобы
одно и то же затухание получалось на любой сетке: зависит от шага.
Стационарные блоки всех вариантов строятся через EPSFAST с шагом записи 6 и
ячейкой из таблицы; подвижные (*_MOVE) — прежним кодом в ячейку 0.
Блоки задания
SetBlock выбирает построитель так же, как в H (таблица), с
добавлением плазменных вариантов:
| Тип | RECT | CIRCLE | POLYGON | FILE |
|---|---|---|---|---|
| диэлектрик и плазма | SetStatEpsFast или SetRect (STAT, _N, _B, _Y, _S, MOVE) |
SetStatEpsFast или SetCirc |
SetStatEpsFast или SetPoly |
SetRectFile (FILE, FILE_N, FILE_B, FILE_Y) |
| металл, поглотитель, магнитная стенка, вход | как в H |
Дальше — та же доводка, что в H: проверка, что узлы и соседи узлов порта лежат в сетке,
удаление повторов, коды узлов, занесение значения в ячейку (SetYLineForDiel), профиль порта,
освобождение массива узлов стационарного блока.
Быстрое построение EPSFAST
Как в H (тот же код, те же порог, потоки и переменные
TMC_EPS_FAST, TMC_EPS_THREADS, TMC_EPS_SMALL), но вклад узла идёт в
prYNode[6n + k], = EpsFastTypeOffset().
Файлы распределения
Формат и поиск файла — как в H. Блок RECT_STAT* с выражением
[имя]… записывает файл; в строке #TopologyPrimitiv стоит ключевое слово блока
(RECT_STAT, RECT_STAT_N, RECT_STAT_B, RECT_STAT_Y …). При чтении проверяется тип:
| Блок | Принимает файл типа | Значения попадают в ячейку |
|---|---|---|
FILE |
RECT_STAT |
0 () |
FILE_N |
RECT_STAT_N или RECT_STAT |
1 () |
FILE_B |
RECT_STAT_B или RECT_STAT |
4 () |
FILE_Y |
RECT_STAT_Y или RECT_STAT |
2 () |
Файл другого типа — ошибка с указанием, что в файле и что нужно блоку. Блока FILE_S нет.
Двойственность стенок
Значение узла X-ядра — , поэтому граничные условия блоков в физическом смысле меняются местами (теория):
| Блок задания | Что делает код | Физически для волн E |
|---|---|---|
METAL |
в узлах контура (RunBlockNode*) |
— магнитная стенка |
MAGNETIC |
узел с нагрузкой (холостой ход), | металл |
| край области | узлы не пересчитываются, | магнитная стенка |
порт METAL (по умолчанию) |
крайние узлы апертуры равны 0, профиль | порт между магнитными стенками |
порт MAGNETIC |
постоянный профиль, крайние узлы — половинные | плоская волна между металлическими стенками |
Для металла, касающегося подмагниченной плазмы, в теории граничное условие модифицированной
схемы меняется; в коде такого особого условия нет — блок MAGNETIC всегда обычный узел
холостого хода.
Металл
RunBlockNode..RunBlockNode3 блока METAL обнуляют ячейку текущего подтакта узлов контура.
Построение контура (прямоугольник, ступенчатая ломаная многоугольника, кольцевой сектор) — как в
H.
Поглотитель и магнитная стенка
Построение блоков, коды соседства и таблица схем узлов — те же, что в H. Узел контура пересчитывается двухслойной схемой H-ядра поверх результата общего прохода:
(для стороны контура; углы — с долями шлейфа 0,75 и 0,25), где на подтакте соседи и
берутся из ячейки , — из rU, а шлейф — из ячейки 1
(prYNode[6n+1]; ячейка 0 в X — множитель ). В конце подтакта rU получает ячейку .
Ячейки плазмы , , узла не учитываются.
Нагрузка поглотителя — SetAbsorberAdmitance с , то есть поглотитель согласован с
вакуумом при нормальном падении (теория):
, , . В вакууме X-поглотитель
совпадает с поглотителем H. Магнитная стенка — тот же узел с (физически металл).
Порты
Параметры входа, подготовка (SetInp*, CalculateYForInput, SetInputAdmitance,
SetYForInput), профиль основной волны, сигнал и отражённая волна — как в
H (теория). W —
среды в сечении входа (теория); для шлейф порта
совпадает с узла эквивалентной плазмы при , поэтому порт
согласуется и со средой .
Отличия X:
- четыре функции
ExciteInputs..ExciteInputs3, по одной на подтакт; узел порта пересчитывается двухслойной схемой H (без плазменных слагаемых):
где — падающее напряжение, запомненное два подтакта назад (rU2, rU3,
rU, rU1 для подтактов 0, 1, 2, 3);
- у узла позади порта (если порт не на краю области) обнуляются ячейки 0..3;
- восстановления из rU_Cur нет — его заменяет защита узлов порта (ниже).
Узлы порта и общий проход
После обновления портов RunSaveInputs копирует все 6 ячеек каждого узла порта в буфер блока
prInputSave, а после общего прохода рассеяния RunRestoreInputs возвращает их. Поэтому
значения узлов порта задаёт только порт: в кадре поля и в накоплении ДН они такие, какими их
вычислил порт (в H — значение после рассеяния, см. подводные камни H).
Соседи порта при рассеянии читают уже обновлённые значения порта. На видеокарте сохранение
выполняется на процессоре, восстановление — на карте (Restore в tmcgpux.h).
Падающая волна из файла
Как в H: файл .sig, строка #FREQ, линейная интерполяция, фаза
не используется.
Вывод
| Что | Отличие от H |
|---|---|
.t |
тот же формат (ниже); строка на каждый из 4 подтактов |
| файл поля | значения из ячейки текущего подтакта prUNode1[6n+k] |
| топология | четыре таблицы (ниже) |
.s, ДН |
после цикла — матрица рассеяния; файлы ДН — только по команде меню (TMC_AUTO_DN не поддерживается) |
Файл .t
Формат, держание файла открытым и данные портов PutPortInfo — как в H.
Файл топологии
PutTopology пишет заголовок (как в H) и четыре таблицы по строк из значений
(double или текст по формату поля), восстанавливая величины из коэффициентов узла:
| Таблица | Значение |
|---|---|
| eps | при ; при (при это ) |
| N, м⁻³ | 0 в узле диэлектрика; в узле плазмы , , |
| Y | как есть (уже с пересчитанной ) |
| B, Тл | 0 в узле диэлектрика; (отрицательное — заменяется наименьшим числом), |
В узле плазмы с таблица N показывает эквивалентную концентрацию (вместе с вкладом ).
Жизненный цикл шага
Как в H: ReadData → RunStep → InitKernel → RunKernel.
Подготовка
Как в H, с двумя отличиями: накопителю ДН задаётся шаг узла 6
(SetNodeStep(6)), массивы — по 6 ячеек на узел; пересчёт величин в коэффициенты —
SetDielInNodeList.
Цикл во времени
См. четыре подтакта. После цикла: проверка окна ДН (окно позже конца расчёта —
ошибка) и матрица рассеяния (PutSmatrix); автоматической записи ДН нет.
Потоки и остановка
Как в H.
Расчёт на видеокарте
RunKernel1TGpu выполняет те же четыре подтакта: на каждом — копирование окон вокруг портов с
карты (PortsDown), возбуждение портов и RunSaveInputs на процессоре, возврат окон
(PortsUp), затем на карте рассеяние (Pass(k)), восстановление узлов портов (Restore) и
блоки (Blocks(k)). Вся сетка копируется только для вывода поля и в окне ДН. Подробности —
Расчёт на видеокарте.
Замер времени и режимы запуска
Замер времени (/Time) — как в H; имя ядра в отчёте —
«PlanarRT_X (tmc_rtx.exe)», файл отчёта <tpl>.timing_X_<win32|win64>.txt.
Ключи запуска
/Ar, /Arb, /d, /Time и коды завершения — как в H
(pl_iofor.cpp у ядер одинаков).
Точность
Точность X-схемы (численная дисперсия, шаг сетки относительно длины волны в плазме) — в теории.
Типичные ошибки и подводные камни
- METAL в X — магнитная стенка, MAGNETIC — металл, край области — тоже магнитная стенка
(двойственность). Канал с металлическими (для волн E) стенками задаётся блоками
MAGNETIC. - Подмагниченная плазма у блока
MAGNETIC. Особое граничное условие металла для модифицированной схемы в коде не реализовано. - Поглотитель согласован с вакуумом при нормальном падении. Его узел учитывает только шлейф ; плазма под поглотителем и угол падения не учитываются.
- и в одном узле — узел считается плазмой; если добавка eps больше плазменной части, расчёт расходится (выдаётся предупреждение). Диэлектрик и плазму нужно ставить в разные узлы.
- без плазмы не действует (предупреждение).
- — сеточная безразмерная величина: одно и то же на разных сетках даёт разное
затухание; в физических единицах — блоки
*_STAT_S(, См/м). - Узел порта — диэлектрический: порт не учитывает и потери; W должно совпадать с среды, в которой стоит вход.
- Число подтактов, не кратное 4: цикл идёт четвёрками, поэтому выполняется до трёх
подтактов сверх
nTMax. - Память: 12 чисел на узел (96 байт при
double) — втрое больше, чем в H. - Файлы ДН пишутся только по команде меню; переменная
TMC_AUTO_DNв X не действует. - Блок FILE не читает файл
RECT_STAT_N(и наоборот, FILE_N не читает файлRECT_STAT_B): тип файла должен соответствовать величине. - Остальное — как в H (поглотитель и порты у края, около 4, окно ДН, синхронный вывод поля).
Compute kernel X: magnetized plasma, four sub-steps and dual walls
Purpose and place in the package
Kernel X (the program tmc_rtx.exe, PlanarRT_X) solves two-dimensional time-domain problems
for E-polarization waves (the extraordinary wave) in media with cold magnetized
plasma (theory, plasma model).
The kernel sources are a branch of the kernel H code: the same classes CTmcRTHRectNode (grid and time loop)
and CTmcRTHNodeDiel (task file blocks), the same service functions pl_iofor/pl_glfun, the same task file
parsing (TMCIndan) and the same shell (kernel shell).
This page is an addition to the kernel H page: it describes only how X differs. Everything not mentioned works as in H, via links to the corresponding sections.
Main differences:
| Kernel H | Kernel X | |
|---|---|---|
| What a node stores | voltage (the field of the H problem) | voltage = the component |
| Cells per node | 2 voltages + 2 coefficients | 6 voltages + 6 coefficients (96 bytes with double) |
| Node scheme | two-layer (3 time layers) | four-layer (5 time layers), see below |
| Sub-steps per loop pass | 2 | 4 |
| Media | , electron density , magnetic flux density , losses , conductivity | |
| METAL / MAGNETIC blocks | metal / magnetic wall | physically magnetic wall / metal (duality) |
| Port nodes in the common scattering pass | recomputed, then restored | excluded (saved and restored around the pass) |
| Topology | one eps table | four tables: eps, N, Y, B |
Writing the RP via TMC_AUTO_DN |
yes | no |
Contents
File (src/kernels/planarrt_x/) |
Role |
|---|---|
tmcrthrectnode.h, tmcrthrectnode.cpp |
CTmcRTHRectNode: node arrays (step 6), conversion of eps, N, B, Y, sigma into coefficients (SetDielInNodeList), loop over 4 sub-steps, scattering (RunScatteringNode*, RunScatteringNode1line*), output of .t, fields, topology; .t file functions (TmcOutT*) |
tmcrthnodediel.h, tmcrthnodediel.cpp |
CTmcRTHNodeDiel: building the nodes of blocks, including plasma ones (_N, _B, _Y, _S, FILE_N/_B/_Y), EPSFAST, .eps and .sig files, port excitation on 4 sub-steps (ExciteInputs..ExciteInputs3), protection of port nodes (SaveInputNodes/RestoreInputNodes), boundary conditions (RunBlockNode..RunBlockNode3) |
pl_iofor.h, pl_iofor.cpp, pl_glfun.cpp |
identical byte for byte to those of kernel H: output formats, launch options, exit code, thread functions, status bar, sound — see kernel H |
tmcgpux.h |
moving the time loop to the GPU — see GPU computing |
planrt_hdoc.*, planrt_hview.*, dialogs, resource.h |
document, view and dialogs of the kernel — see the kernel shell |
The class and file names of H and X are the same (CTmcRTHRectNode, CPlanRT_HDoc …), so the kernels
are built as separate programs from their own directories.
Build: X-mode macros
The planarrt_x target (src/kernels/PlanarRT_X/qt/CMakeLists.txt) passes the compiler six X-mode macro
names, as the MFC version project does: ELECTRON_Q___, ELECTRON_M___,
CTMCRTH_INDANBLCK_FILEY, CTMCRTH_INDANBLCK_RECTSTATY, CTMCRTH_INDANBLCK_CIRCSTATY,
CTMCRTH_INDANBLCK_POLYGSTTY. In the Qt6 version all six are also defined in the common headers:
the electron charge and mass — in typerth.h ( C,
kg), the block keywords ("FILE_Y ", "RECT_STAT_Y " …) —
in tmcgrviw.h; the values are taken from the headers. The kernel X sources have no conditional compilation on these
names: they are needed as values (physical constants in SetDielInNodeList and PutTopology,
keywords in SetBlock).
Node data structure
The nodes are numbered as in H: (64-bit TmcIdx). The value of a kernel X node is
the component (in circuit terms, the node "voltage"). Each node has 6 voltage
cells and 6 coefficient cells:
| Cell | Contents |
|---|---|
prUNode1[6n+0..3] |
the four last time layers of in a ring: on sub-step the new value is written into cell (which held ) |
prUNode1[6n+4], [6n+5] |
the sums of the two previous sub-steps (see scattering); sub-steps 0 and 2 write cell 5, sub-steps 1 and 3 — cell 4 |
prYNode[6n+0] |
|
prYNode[6n+1] |
— the node stub with sign: dielectric (open circuit), plasma |
prYNode[6n+2] |
— grid losses |
prYNode[6n+3] |
|
prYNode[6n+4] |
|
prYNode[6n+5] |
Before conversion into coefficients (SetDielInNodeList), the cells prYNode[6n+0..4] serve as
accumulators of the block quantities: 0 — , 1 — (m⁻³), 2 — ,
3 — (S/m), 4 — (T). Details are in the plasma blocks section.
InitNodeArray allocates elements each, aligned to 32 bytes, and zeroes all
cells; the free-space coefficients (, ) appear only after
SetDielInNodeList, which traverses all grid nodes. The total number of nodes is limited to
TMC_IDX_MAX/8, as in H.
A block node (sTmcRTHNodeDielOne) in X stores the incident voltage of the port separately for each
sub-step: rU, rU1, rU2, rU3. For an absorber and a magnetic wall rU is the value
of the node, as in H. The fields rU_Cur..rU_Cur3 are not used in the computation (they are zeroed):
the port nodes are protected by the prInputSave buffer (below).
Four sub-steps
The node scheme with magnetized plasma couples five time layers (theory), so one loop pass is four sub-steps, each with its own functions. Sub-step writes cell and reads the others:
| Sub-step | Ports | Scattering | Blocks | Written | / → | |||
|---|---|---|---|---|---|---|---|---|
| 0 | ExciteInputs |
RunScatteringNode |
RunBlockNode |
0 | 3 | 2 | 1 | 4 / 5 → 5 |
| 1 | ExciteInputs1 |
RunScatteringNode1 |
RunBlockNode1 |
1 | 0 | 3 | 2 | 5 / 4 → 4 |
| 2 | ExciteInputs2 |
RunScatteringNode2 |
RunBlockNode2 |
2 | 1 | 0 | 3 | 4 / 5 → 5 |
| 3 | ExciteInputs3 |
RunScatteringNode3 |
RunBlockNode3 |
3 | 2 | 1 | 0 | 5 / 4 → 4 |
Order of calls within one sub-step (RunKernel1T):
RunExciteInputs*— a.tline (time step, time) and update of all ports;RunSaveInputs— save the 6 cells of each port node;RunScatteringNode*— recompute all inner grid nodes;RunRestoreInputs— give the port nodes back their values;RunBlockNode*— metal, absorber, magnetic wall;PutField(k)— a field frame from cell ;DistributionIntegrated(k)— field accumulation for the RP (the accumulator knows the step 6:SetNodeStep(6));nTCurrent += 1,dTCurrent += τ.
The RunKernel loop runs while nTCurrent < nTMax, four sub-steps at a time; progress is output every
100 sub-steps, as in H.
Scattering at a node
For the inner nodes (rows , columns ) the functions RunScatteringNode1line*
compute (theory)
where are the four neighbors, = prYNode[6n+k]; the new is stored in cell 4 or 5.
This is the four-parameter algorithm for the extraordinary wave: with
, , the formula coincides with the expression
of the theory, where is the plasma stub and is the losses.
At a dielectric node (, ) the formula becomes
that is, the two-layer scheme of kernel H with the multiplier applied to both sides (a shift by one sub-step is ). In exact arithmetic the solutions coincide.
The nodes at the edges of the region are not recomputed by the formula and remain zero. In the X kernel this is — a magnetic wall, not metal as in H (duality).
Node coefficients
SetDielInNodeList (after all blocks have been built) converts the node quantities into coefficients.
Notation: is the time step of a sub-step, is the task frequency,
, are the electron charge and mass.
- Conductivity. If : , cell 3 is zeroed.
- Plasma node — if or . The quantities are reduced to a single equivalent plasma frequency (theory):
The sign of corresponds to the expression of the algorithm for the extraordinary wave (theory); the former variant with the opposite sign is kept in the source as a comment. At : , , and a medium with () is a plasma with . 3. Dielectric node (, ): (values of within 0.004 of 4 are shifted to 3.996 or 4.004), , , . The magnetic flux density is not used at such a node.
Before the conversion, warnings are issued (console, status bar, computation result):
- nodes where is combined with : the node is treated as plasma, the eps addition is correct only at the task frequency; if the addition is larger than the plasma part, the equivalent density is negative and the computation diverges;
- nodes where is combined with : is not used.
The error "very big Delta*Frequence" — if , as in H. In the educational version
(_VERSION_EDUC___) nodes with are forbidden. Every 100,000 nodes a stop request
is checked.
Plasma blocks
The block expression is evaluated as in H (CalcEps: , , , are substituted
relative to the anchor point), multiplied by the node weight (fraction of cells) and added to its
record cell of the node. The cell is chosen by EpsFastTypeOffset from the keyword
(units):
| Blocks | Quantity | Unit | Cell prYNode[6n+k] |
|---|---|---|---|
RECT_STAT, CIRCLE_STAT, POLYGON_STAT, FILE |
— | 0 | |
RECT_STAT_N, CIRCLE_STAT_N, POLYGON_STAT_N, FILE_N |
electron density | m⁻³ | 1 |
RECT_STAT_Y, CIRCLE_STAT_Y, POLYGON_STAT_Y, FILE_Y |
grid losses | dimensionless | 2 |
RECT_STAT_S, CIRCLE_STAT_S, POLYGON_STAT_S |
conductivity | S/m | 3 |
RECT_STAT_B, CIRCLE_STAT_B, POLYGON_STAT_B, FILE_B |
magnetic flux density | T | 4 |
Geometry, node weights and summation rules are as for the H dielectric
(H blocks). The contributions of different blocks to the same cell add up, so
, , are specified by separate, mutually overlapping blocks; at each node the quantities
are then converted together (coefficients). The block (_S) is needed so that
the same attenuation is obtained on any grid: depends on the step.
Stationary blocks of all variants are built through EPSFAST with a record step of 6 and
the cell from the table; moving ones (*_MOVE) — by the former code into cell 0.
Task file blocks
SetBlock chooses the builder as in H (table), with
the plasma variants added:
| Type | RECT | CIRCLE | POLYGON | FILE |
|---|---|---|---|---|
| dielectric and plasma | SetStatEpsFast or SetRect (STAT, _N, _B, _Y, _S, MOVE) |
SetStatEpsFast or SetCirc |
SetStatEpsFast or SetPoly |
SetRectFile (FILE, FILE_N, FILE_B, FILE_Y) |
| metal, absorber, magnetic wall, port | as in H |
Then comes the same finishing as in H: checking that the nodes and the neighbors of the port nodes lie within the grid,
removing duplicates, node codes, entering the value into the cell (SetYLineForDiel), the port profile,
freeing the node array of a stationary block.
Fast construction EPSFAST
As in H (the same code, the same threshold, threads and variables
TMC_EPS_FAST, TMC_EPS_THREADS, TMC_EPS_SMALL), but the node contribution goes to
prYNode[6n + k], = EpsFastTypeOffset().
Distribution files
Format and file lookup — as in H. A RECT_STAT* block with the expression
[name]… writes a file; the #TopologyPrimitiv line holds the block keyword
(RECT_STAT, RECT_STAT_N, RECT_STAT_B, RECT_STAT_Y …). On reading, the type is checked:
| Block | Accepts a file of type | The values go into cell |
|---|---|---|
FILE |
RECT_STAT |
0 () |
FILE_N |
RECT_STAT_N or RECT_STAT |
1 () |
FILE_B |
RECT_STAT_B or RECT_STAT |
4 () |
FILE_Y |
RECT_STAT_Y or RECT_STAT |
2 () |
A file of another type is an error stating what is in the file and what the block needs. There is no FILE_S block.
Duality of walls
The value of a kernel X node is , so the boundary conditions of the blocks swap roles in the physical sense (theory):
| Task file block | What the code does | Physically for E waves |
|---|---|---|
METAL |
at the contour nodes (RunBlockNode*) |
— magnetic wall |
MAGNETIC |
node with load (open circuit), | metal |
| edge of the region | nodes are not recomputed, | magnetic wall |
METAL port (default) |
the end nodes of the aperture are 0, profile | port between magnetic walls |
MAGNETIC port |
constant profile, the end nodes are half | plane wave between metal walls |
For metal in contact with magnetized plasma, the theory modifies the boundary condition of the
modified scheme; the code has no such special condition — the MAGNETIC block is always an ordinary
open-circuit node.
Metal
RunBlockNode..RunBlockNode3 of a METAL block zero the cell of the current sub-step at the contour nodes.
The contour construction (rectangle, staircase polyline of a polygon, annular sector) is as in
H.
Absorber and magnetic wall
Block construction, neighborhood codes and the table of node circuits are the same as in H. A contour node is recomputed by the two-layer scheme of the H kernel on top of the result of the common pass:
(for a side of the contour; corners use stub fractions of 0.75 and 0.25), where on sub-step the neighbors and
are taken from cell , — from rU, and the stub — from cell 1
(prYNode[6n+1]; cell 0 in X is the multiplier ). At the end of the sub-step rU receives cell .
The plasma cells , , of the node are not taken into account.
The absorber load is SetAbsorberAdmitance with , that is, the absorber is matched to
vacuum at normal incidence (theory):
, , . In vacuum the X absorber
coincides with the H absorber. The magnetic wall is the same node with (physically metal).
Ports
The port parameters, preparation (SetInp*, CalculateYForInput, SetInputAdmitance,
SetYForInput), the profile of the fundamental wave, the signal and the reflected wave are as in
H (theory). W is the
of the medium in the port cross-section (theory); for the port stub
coincides with of an equivalent plasma node at , so the port
is matched to a medium with as well.
Differences of X:
- four functions
ExciteInputs..ExciteInputs3, one per sub-step; a port node is recomputed by the two-layer H scheme (without the plasma terms):
where is the incident voltage saved two sub-steps earlier (rU2, rU3,
rU, rU1 for sub-steps 0, 1, 2, 3);
- at the node behind the port (if the port is not at the edge of the region) cells 0..3 are zeroed;
- there is no restoring from rU_Cur — it is replaced by the protection of port nodes (below).
Port nodes and the common pass
After the ports are updated, RunSaveInputs copies all 6 cells of each port node into the block buffer
prInputSave, and after the common scattering pass RunRestoreInputs returns them. Therefore
the values of the port nodes are set only by the port: in the field frame and in the RP accumulation they are as
computed by the port (in H — the value after scattering, see H pitfalls).
The neighbors of the port read the already updated port values during scattering. On the GPU, saving
is done on the CPU and restoring on the card (Restore in tmcgpux.h).
Incident wave from a file
As in H: the .sig file, the #FREQ line, linear interpolation, the phase
is not used.
Output
| What | Difference from H |
|---|---|
.t |
the same format (below); a line for each of the 4 sub-steps |
| field file | the values from the cell of the current sub-step prUNode1[6n+k] |
| topology | four tables (below) |
.s, RP |
after the loop — the scattering matrix; RP files — only on a menu command (TMC_AUTO_DN is not supported) |
The .t file
The format, keeping the file open and the port data PutPortInfo are as in H.
Topology file
PutTopology writes a header (as in H) and four tables of rows of values
(double or text in the field format), recovering the quantities from the node coefficients:
| Table | Value |
|---|---|
| eps | for ; for (at this is ) |
| N, m⁻³ | 0 at a dielectric node; at a plasma node , , |
| Y | as is (already with the converted ) |
| B, T | 0 at a dielectric node; (a negative value is replaced with the smallest number), |
At a plasma node with the N table shows the equivalent density (including the contribution of ).
Life cycle of a step
As in H: ReadData → RunStep → InitKernel → RunKernel.
Preparation
As in H, with two differences: the RP accumulator is given the node step 6
(SetNodeStep(6)), the arrays have 6 cells per node; conversion of the quantities into coefficients —
SetDielInNodeList.
Time loop
See four sub-steps. After the loop: a check of the RP window (a window later than the end of the computation is
an error) and the scattering matrix (PutSmatrix); there is no automatic writing of the RP.
Threads and stopping
As in H.
GPU computing
RunKernel1TGpu performs the same four sub-steps: on each — copying the windows around the ports from
the card (PortsDown), port excitation and RunSaveInputs on the CPU, returning the windows
(PortsUp), then on the card the scattering (Pass(k)), restoring the port nodes (Restore) and the
blocks (Blocks(k)). The whole grid is copied only for field output and within the RP window. Details —
GPU computing.
Timing and launch modes
Timing (/Time) — as in H; the kernel name in the report is
"PlanarRT_X (tmc_rtx.exe)", the report file is <tpl>.timing_X_<win32|win64>.txt.
Launch options
/Ar, /Arb, /d, /Time and the exit codes — as in H
(pl_iofor.cpp is the same in both kernels).
Accuracy
The accuracy of the X scheme (numerical dispersion, the grid step relative to the wavelength in plasma) is covered in the theory.
Typical errors and pitfalls
- METAL in X is a magnetic wall, MAGNETIC is metal, and the edge of the region is also a magnetic wall
(duality). A channel with metal (for E waves) walls is specified with
MAGNETICblocks. - Magnetized plasma next to a
MAGNETICblock. The special metal boundary condition for the modified scheme is not implemented in the code. - The absorber is matched to vacuum at normal incidence. Its node takes into account only the stub ; plasma under the absorber and the angle of incidence are not taken into account.
- and at the same node — the node is treated as plasma; if the eps addition is larger than the plasma part, the computation diverges (a warning is issued). Dielectric and plasma must be placed at different nodes.
- without plasma has no effect (a warning).
- is a dimensionless grid quantity: the same on different grids gives different
attenuation; in physical units — the
*_STAT_Sblocks (, S/m). - A port node is a dielectric one: the port does not take and losses into account; W must equal the of the medium in which the port is placed.
- A number of sub-steps not divisible by 4: the loop runs in groups of four, so up to three
sub-steps beyond
nTMaxare performed. - Memory: 12 numbers per node (96 bytes with
double) — three times more than in H. - RP files are written only on a menu command; the
TMC_AUTO_DNvariable has no effect in X. - The FILE block does not read a
RECT_STAT_Nfile (and conversely, FILE_N does not read aRECT_STAT_Bfile): the file type must match the quantity. - Everything else — as in H (absorber and ports at the edge, near 4, the RP window, synchronous field output).