Счётное ядро X: подмагниченная плазма, четыре подтакта и двойственные стенки

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

Ядро X (программа tmc_rtx.exe, PlanarRT_X) считает во временной области двумерные задачи для волн E-поляризации (необыкновенная волна) в средах с холодной подмагниченной плазмой (теория, модель плазмы). Исходники ядра — ветвь кода ядра H: те же классы CTmcRTHRectNode (сетка и цикл во времени) и CTmcRTHNodeDiel (блоки задания), те же служебные функции pl_iofor/pl_glfun, тот же разбор задания (TMCIndan) и та же оболочка (оболочка ядер).

Эта страница — дополнение к странице ядра H: здесь описано только то, чем X отличается. Всё, что не упомянуто, работает как в H, по ссылкам на соответствующие разделы.

Главные отличия:

Ядро H Ядро X
Что хранит узел напряжение (поле H-задачи) напряжение = компонента Hz
Ячеек на узел 2 напряжения + 2 коэффициента 6 напряжений + 6 коэффициентов (96 байт при double)
Схема узла двухслойная (3 временных слоя) четырёхслойная (5 временных слоёв), см. ниже
Подтактов за проход цикла 2 4
Среды Δε Δε, концентрация N, индукция B, потери Y, проводимость σ
Блоки 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 (e=1,602176565·10−19 Кл, m=9,10938356·10−31 кг), ключевые слова блоков ("FILE_Y ", "RECT_STAT_Y " …) — в tmcgrviw.h; значения берутся из заголовков. В исходниках ядра X условной компиляции по этим именам нет: они нужны как значения (физические константы в SetDielInNodeList и PutTopology, ключевые слова в SetBlock).

Структура данных узла

Узлы нумеруются, как в H: n=iynX+ix (64-битный TmcIdx). Значение узла X-ядра — компонента Hz (в терминах схемы — «напряжение» узла). На узел приходится 6 ячеек напряжений и 6 ячеек коэффициентов:

Ячейка Содержимое
prUNode1[6n+0..3] четыре последних временных слоя U по кругу: на подтакте k новое значение Uτ пишется в ячейку k (там было Uτ−4)
prUNode1[6n+4], [6n+5] суммы R двух прошлых подтактов (см. рассеяние); подтакты 0 и 2 пишут ячейку 5, подтакты 1 и 3 — ячейку 4
prYNode[6n+0] Y0=2/(4+|Y1|+Y2+Y3/2)
prYNode[6n+1] Y1 — шлейф узла y5 со знаком: >0 диэлектрик (холостой ход), <0 плазма
prYNode[6n+2] Y2 — сеточные потери y
prYNode[6n+3] Y3=2y6y7/(y6+y7)
prYNode[6n+4] Y4=2(y7−y6)/(y6+y7)
prYNode[6n+5] Y5=Y3Y4/4

До перевода в коэффициенты (SetDielInNodeList) ячейки prYNode[6n+0..4] служат накопителями величин блоков: 0 — Δε, 1 — N (м⁻³), 2 — Y, 3 — σ (См/м), 4 — B (Тл). Подробно — в разделе блоки плазмы.

InitNodeArray выделяет по 6nXnY+32 элемента с выравниванием на 32 байта и обнуляет все ячейки; коэффициенты свободного пространства (Y0=0,5, Y4=−2) появляются только после SetDielInNodeList, который проходит все узлы сетки. Общее число узлов ограничено TMC_IDX_MAX/8, как в H.

Узел блока (sTmcRTHNodeDielOne) в X хранит падающее напряжение порта отдельно для каждого подтакта: rU, rU1, rU2, rU3. У поглотителя и магнитной стенки rU — значение Uτ−2 узла, как в H. Поля rU_Cur..rU_Cur3 в расчёте не используются (обнуляются): узлы порта защищает буфер prInputSave (ниже).

Четыре подтакта

Схема узла с подмагниченной плазмой связывает пять временных слоёв (теория), поэтому один проход цикла — четыре подтакта, и на каждом свои функции. Подтакт k пишет ячейку k и читает остальные:

Подтакт Порты Рассеяние Блоки Пишется Uτ−1 Uτ−2 Uτ−3 Rτ−1 / Rτ−2 → Rτ
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):

  1. RunExciteInputs* — строка .t (такт, время) и обновление всех портов;
  2. RunSaveInputs — запомнить 6 ячеек каждого узла порта;
  3. RunScatteringNode* — пересчёт всех внутренних узлов сетки;
  4. RunRestoreInputs — вернуть узлам портов их значения;
  5. RunBlockNode* — металл, поглотитель, магнитная стенка;
  6. PutField(k) — кадр поля из ячейки k;
  7. DistributionIntegrated(k) — накопление поля для ДН (накопитель знает шаг 6: SetNodeStep(6));
  8. nTCurrent += 1, dTCurrent += τ.

Цикл RunKernel идёт, пока nTCurrent < nTMax, по четыре подтакта; ход счёта выводится каждые 100 подтактов, как в H.

Рассеяние в узле

Для внутренних узлов (строки 1..nY−2, столбцы 1..nX−2) функции RunScatteringNode1line* вычисляют (теория)

Rτ=∑i=14Uiτ−1+Y1Uτ−1+Y2Uτ−2,(1)
Uτ=−Uτ−4−2Uτ−2+Y4(Uτ−1+Uτ−3)+Y0(Rτ+Rτ−2−Y4Rτ−1+Y3Uτ−2−Y5(Uτ−1+Uτ−3)),(2)

где Ui — четыре соседа, Yk = prYNode[6n+k]; новое Rτ сохраняется в ячейке 4 или 5. Это четырёхпараметрический алгоритм для необыкновенной волны: с Y0=2/YΣ, Y3=2Y67, Y4=2(Y7−Y6)/(Y6+Y7) формула совпадает с выражением теории, где −Y5U — шлейф плазмы, YUτ−2 — потери.

В узле диэлектрика (Y3=Y5=0, Y4=−2) формула переходит в

Uτ+2Uτ−1+2Uτ−2+2Uτ−3+Uτ−4=Y0(Rτ+2Rτ−1+Rτ−2),(3)

то есть в двухслойную схему ядра H Uτ+Uτ−2=Y0Rτ, к обеим частям которой применён множитель (1+z−1)2 (сдвиг на подтакт — z−1). В точной арифметике решения совпадают.

Узлы краёв области формулой не пересчитываются и остаются нулевыми. В X-ядре это Hz=0 — магнитная стенка, а не металл, как в H (двойственность).

Коэффициенты узла

SetDielInNodeList (после построения всех блоков) переводит величины узла в коэффициенты. Обозначения: τ — шаг по времени подтакта, ω=2πf — частота задания, e, m — заряд и масса электрона.

  1. Проводимость. Если σ≠0: Y+=2τσ/ε0, ячейка 3 обнуляется.
  2. Узел плазмы — если Δε<0 или N≠0. Величины сводятся к одной эквивалентной плазменной частоте (теория):
ωp2=Ne2mε0−Δεω2,ωc2=(eBm)2,x=τ2(ωc2+ωp2),(4)
Y1=−τ2ωp4ωc2+ωp2,Y3=8τ2ωc2ωp2(ωc2+ωp2)(4+x),Y4=2(4−x)4+x,Y5=Y3Y44,Y0=24+|Y1|+Y2+Y3/2.(5)

Знак Y4 соответствует выражению алгоритма для необыкновенной волны (теория); прежний вариант с обратным знаком сохранён в исходнике комментарием. При B=0: Y1=−τ2ωp2, Y3=0, и среда с ε<1 (Δε<0) — плазма с ωp2=−Δεω2. 3. Узел диэлектрика (Δε≥0, N=0): Y1=4Δε (значения Δε в пределах 0,004 от 4 сдвигаются до 3,996 или 4,004), Y3=Y5=0, Y4=−2, Y0=2/(4+|Y1|+Y2). Индукция B в таком узле не используется.

Перед пересчётом выдаются предупреждения (консоль, строка состояния, итог расчёта):

  • узлы, где Δε>0 сочетается с N: узел считается плазмой, добавка eps верна только на частоте задания; если добавка больше плазменной части, эквивалентная концентрация отрицательна и расчёт расходится;
  • узлы, где Δε>0 сочетается с B: B не используется.

Ошибка «very big Delta*Frequence» — если ωτ/2>π/3, как в H. В учебной версии (_VERSION_EDUC___) узлы с ε<1 запрещены. Каждые 100 000 узлов проверяется остановка.

Блоки плазмы

Выражение блока вычисляется так же, как в H (CalcEps: подставляются x, y, r, f относительно точки привязки), умножается на вес узла (доля ячеек) и прибавляется к своей ячейке записи узла. Ячейку выбирает EpsFastTypeOffset по ключевому слову (единицы):

Блоки Величина Единица Ячейка prYNode[6n+k]
RECT_STAT, CIRCLE_STAT, POLYGON_STAT, FILE Δε=ε−1 — 0
RECT_STAT_N, CIRCLE_STAT_N, POLYGON_STAT_N, FILE_N концентрация электронов N м⁻³ 1
RECT_STAT_Y, CIRCLE_STAT_Y, POLYGON_STAT_Y, FILE_Y сеточные потери Y безразмерная 2
RECT_STAT_S, CIRCLE_STAT_S, POLYGON_STAT_S проводимость σ См/м 3
RECT_STAT_B, CIRCLE_STAT_B, POLYGON_STAT_B, FILE_B индукция B Тл 4

Геометрия, веса узлов и правила сложения — как у диэлектрика H (блоки H). Вклады разных блоков в одну ячейку складываются, поэтому N, B, Y задаются отдельными блоками, перекрывающими друг друга; в каждом узле величины затем пересчитываются вместе (коэффициенты). Блок σ (_S) нужен, чтобы одно и то же затухание получалось на любой сетке: Y=2τσ/ε0 зависит от шага.

Стационарные блоки всех вариантов строятся через 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], 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 (N)
FILE_B RECT_STAT_B или RECT_STAT 4 (B)
FILE_Y RECT_STAT_Y или RECT_STAT 2 (Y)

Файл другого типа — ошибка с указанием, что в файле и что нужно блоку. Блока FILE_S нет.

Двойственность стенок

Значение узла X-ядра — Hz, поэтому граничные условия блоков в физическом смысле меняются местами (теория):

Блок задания Что делает код Физически для волн E
METAL U=0 в узлах контура (RunBlockNode*) Hz=0 — магнитная стенка
MAGNETIC узел с нагрузкой y=0 (холостой ход), ∂Hz/∂n=0 металл
край области узлы не пересчитываются, U=0 магнитная стенка
порт METAL (по умолчанию) крайние узлы апертуры равны 0, профиль sin порт между магнитными стенками
порт MAGNETIC постоянный профиль, крайние узлы — половинные плоская волна между металлическими стенками

Для металла, касающегося подмагниченной плазмы, в теории граничное условие модифицированной схемы меняется; в коде такого особого условия нет — блок MAGNETIC всегда обычный узел холостого хода.

Металл

RunBlockNode..RunBlockNode3 блока METAL обнуляют ячейку текущего подтакта узлов контура. Построение контура (прямоугольник, ступенчатая ломаная многоугольника, кольцевой сектор) — как в H.

Поглотитель и магнитная стенка

Построение блоков, коды соседства и таблица схем узлов — те же, что в H. Узел контура пересчитывается двухслойной схемой H-ядра поверх результата общего прохода:

Uτ=22+|y5′|+y(Uoτ−1+12(Uaτ−1+Ubτ−1)+y5′Uτ−1+yUτ−2)−Uτ−2(6)

(для стороны контура; углы — с долями шлейфа 0,75 и 0,25), где на подтакте k соседи и Uτ−1 берутся из ячейки k−1, Uτ−2 — из rU, а шлейф y5 — из ячейки 1 (prYNode[6n+1]; ячейка 0 в X — множитель Y0). В конце подтакта rU получает ячейку k−1. Ячейки плазмы Y3, Y4, Y5 узла не учитываются.

Нагрузка поглотителя — SetAbsorberAdmitance с yW=0, то есть поглотитель согласован с вакуумом при нормальном падении (теория): y=sinβ/sina, cosβ=2cosa−1, a=ωτ. В вакууме X-поглотитель совпадает с поглотителем H. Магнитная стенка — тот же узел с y=0 (физически металл).

Порты

Параметры входа, подготовка (SetInp*, CalculateYForInput, SetInputAdmitance, SetYForInput), профиль основной волны, сигнал и отражённая волна — как в H (теория). W — Δε среды в сечении входа (теория); для W<0 шлейф порта yW=W(k0Δ)2/2 совпадает с Y1 узла эквивалентной плазмы при B=0, поэтому порт согласуется и со средой ε<1.

Отличия X:

  • четыре функции ExciteInputs..ExciteInputs3, по одной на подтакт; узел порта пересчитывается двухслойной схемой H (без плазменных слагаемых):
Uτ=22+y1+|yW|/2(12Uaτ−1+Uinτ−1+12Ubτ−1+yW2Uτ−1+y1(Uτ−2+riaτ−riaτ−2))−Uτ−2,(7)

где riaτ−2 — падающее напряжение, запомненное два подтакта назад (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 подтактов
файл поля значения Hz из ячейки текущего подтакта prUNode1[6n+k]
топология четыре таблицы (ниже)
.s, ДН после цикла — матрица рассеяния; файлы ДН — только по команде меню (TMC_AUTO_DN не поддерживается)

Файл .t

Формат, держание файла открытым и данные портов PutPortInfo — как в H.

Файл топологии

PutTopology пишет заголовок (как в H) и четыре таблицы по nY строк из nX значений (double или текст по формату поля), восстанавливая величины из коэффициентов узла:

Таблица Значение
eps Y1/4+1 при Y1≥0; Y1/(ωτ)2+1 при Y1<0 (при B=0 это 1−ωp2/ω2)
N, м⁻³ 0 в узле диэлектрика; в узле плазмы x=4(2−Y4)/(2+Y4), ωp2=|Y1|x/τ2, N=ωp2ε0m/e2
Y Y2 как есть (уже с пересчитанной σ)
B, Тл 0 в узле диэлектрика; ωc2=x/τ2−ωp2 (отрицательное — заменяется наименьшим числом), B=ωcm/e

В узле плазмы с Δε≠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. Особое граничное условие металла для модифицированной схемы в коде не реализовано.
  • Поглотитель согласован с вакуумом при нормальном падении. Его узел учитывает только шлейф y5; плазма под поглотителем и угол падения не учитываются.
  • Δε>0 и N в одном узле — узел считается плазмой; если добавка eps больше плазменной части, расчёт расходится (выдаётся предупреждение). Диэлектрик и плазму нужно ставить в разные узлы.
  • B без плазмы не действует (предупреждение).
  • Y — сеточная безразмерная величина: одно и то же Y на разных сетках даёт разное затухание; в физических единицах — блоки *_STAT_S (σ, См/м).
  • Узел порта — диэлектрический: порт не учитывает B и потери; 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 Hz 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 N, magnetic flux density B, losses Y, 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 (e=1,602176565·10−19 C, m=9,10938356·10−31 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: n=iynX+ix (64-bit TmcIdx). The value of a kernel X node is the Hz 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 U in a ring: on sub-step k the new value Uτ is written into cell k (which held Uτ−4)
prUNode1[6n+4], [6n+5] the sums R 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] Y0=2/(4+|Y1|+Y2+Y3/2)
prYNode[6n+1] Y1 — the node stub y5 with sign: >0 dielectric (open circuit), <0 plasma
prYNode[6n+2] Y2 — grid losses y
prYNode[6n+3] Y3=2y6y7/(y6+y7)
prYNode[6n+4] Y4=2(y7−y6)/(y6+y7)
prYNode[6n+5] Y5=Y3Y4/4

Before conversion into coefficients (SetDielInNodeList), the cells prYNode[6n+0..4] serve as accumulators of the block quantities: 0 — Δε, 1 — N (m⁻³), 2 — Y, 3 — σ (S/m), 4 — B (T). Details are in the plasma blocks section.

InitNodeArray allocates 6nXnY+32 elements each, aligned to 32 bytes, and zeroes all cells; the free-space coefficients (Y0=0,5, Y4=−2) 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 Uτ−2 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 k writes cell k and reads the others:

Sub-step Ports Scattering Blocks Written Uτ−1 Uτ−2 Uτ−3 Rτ−1 / Rτ−2 → Rτ
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):

  1. RunExciteInputs* — a .t line (time step, time) and update of all ports;
  2. RunSaveInputs — save the 6 cells of each port node;
  3. RunScatteringNode* — recompute all inner grid nodes;
  4. RunRestoreInputs — give the port nodes back their values;
  5. RunBlockNode* — metal, absorber, magnetic wall;
  6. PutField(k) — a field frame from cell k;
  7. DistributionIntegrated(k) — field accumulation for the RP (the accumulator knows the step 6: SetNodeStep(6));
  8. 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 1..nY−2, columns 1..nX−2) the functions RunScatteringNode1line* compute (theory)

Rτ=∑i=14Uiτ−1+Y1Uτ−1+Y2Uτ−2,(1)
Uτ=−Uτ−4−2Uτ−2+Y4(Uτ−1+Uτ−3)+Y0(Rτ+Rτ−2−Y4Rτ−1+Y3Uτ−2−Y5(Uτ−1+Uτ−3)),(2)

where Ui are the four neighbors, Yk = prYNode[6n+k]; the new Rτ is stored in cell 4 or 5. This is the four-parameter algorithm for the extraordinary wave: with Y0=2/YΣ, Y3=2Y67, Y4=2(Y7−Y6)/(Y6+Y7) the formula coincides with the expression of the theory, where −Y5U is the plasma stub and YUτ−2 is the losses.

At a dielectric node (Y3=Y5=0, Y4=−2) the formula becomes

Uτ+2Uτ−1+2Uτ−2+2Uτ−3+Uτ−4=Y0(Rτ+2Rτ−1+Rτ−2),(3)

that is, the two-layer scheme of kernel H Uτ+Uτ−2=Y0Rτ with the multiplier (1+z−1)2 applied to both sides (a shift by one sub-step is z−1). 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 Hz=0 — 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, ω=2πf is the task frequency, e, m are the electron charge and mass.

  1. Conductivity. If σ≠0: Y+=2τσ/ε0, cell 3 is zeroed.
  2. Plasma node — if Δε<0 or N≠0. The quantities are reduced to a single equivalent plasma frequency (theory):
ωp2=Ne2mε0−Δεω2,ωc2=(eBm)2,x=τ2(ωc2+ωp2),(4)
Y1=−τ2ωp4ωc2+ωp2,Y3=8τ2ωc2ωp2(ωc2+ωp2)(4+x),Y4=2(4−x)4+x,Y5=Y3Y44,Y0=24+|Y1|+Y2+Y3/2.(5)

The sign of Y4 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 B=0: Y1=−τ2ωp2, Y3=0, and a medium with ε<1 (Δε<0) is a plasma with ωp2=−Δεω2. 3. Dielectric node (Δε≥0, N=0): Y1=4Δε (values of Δε within 0.004 of 4 are shifted to 3.996 or 4.004), Y3=Y5=0, Y4=−2, Y0=2/(4+|Y1|+Y2). The magnetic flux density B is not used at such a node.

Before the conversion, warnings are issued (console, status bar, computation result):

  • nodes where Δε>0 is combined with N: 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 Δε>0 is combined with B: B is not used.

The error "very big Delta*Frequence" — if ωτ/2>π/3, as in H. In the educational version (_VERSION_EDUC___) nodes with ε<1 are forbidden. Every 100,000 nodes a stop request is checked.

Plasma blocks

The block expression is evaluated as in H (CalcEps: x, y, r, f 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 Δε=ε−1 — 0
RECT_STAT_N, CIRCLE_STAT_N, POLYGON_STAT_N, FILE_N electron density N m⁻³ 1
RECT_STAT_Y, CIRCLE_STAT_Y, POLYGON_STAT_Y, FILE_Y grid losses Y 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 B 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 N, B, Y 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: Y=2τσ/ε0 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], 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 (N)
FILE_B RECT_STAT_B or RECT_STAT 4 (B)
FILE_Y RECT_STAT_Y or RECT_STAT 2 (Y)

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 Hz, 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 U=0 at the contour nodes (RunBlockNode*) Hz=0 — magnetic wall
MAGNETIC node with load y=0 (open circuit), ∂Hz/∂n=0 metal
edge of the region nodes are not recomputed, U=0 magnetic wall
METAL port (default) the end nodes of the aperture are 0, sin 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:

Uτ=22+|y5′|+y(Uoτ−1+12(Uaτ−1+Ubτ−1)+y5′Uτ−1+yUτ−2)−Uτ−2(6)

(for a side of the contour; corners use stub fractions of 0.75 and 0.25), where on sub-step k the neighbors and Uτ−1 are taken from cell k−1, Uτ−2 — from rU, and the stub y5 — from cell 1 (prYNode[6n+1]; cell 0 in X is the multiplier Y0). At the end of the sub-step rU receives cell k−1. The plasma cells Y3, Y4, Y5 of the node are not taken into account.

The absorber load is SetAbsorberAdmitance with yW=0, that is, the absorber is matched to vacuum at normal incidence (theory): y=sinβ/sina, cosβ=2cosa−1, a=ωτ. In vacuum the X absorber coincides with the H absorber. The magnetic wall is the same node with y=0 (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 W<0 the port stub yW=W(k0Δ)2/2 coincides with Y1 of an equivalent plasma node at B=0, so the port is matched to a medium with ε<1 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):
Uτ=22+y1+|yW|/2(12Uaτ−1+Uinτ−1+12Ubτ−1+yW2Uτ−1+y1(Uτ−2+riaτ−riaτ−2))−Uτ−2,(7)

where riaτ−2 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 Hz 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 nY rows of nX values (double or text in the field format), recovering the quantities from the node coefficients:

Table Value
eps Y1/4+1 for Y1≥0; Y1/(ωτ)2+1 for Y1<0 (at B=0 this is 1−ωp2/ω2)
N, m⁻³ 0 at a dielectric node; at a plasma node x=4(2−Y4)/(2+Y4), ωp2=|Y1|x/τ2, N=ωp2ε0m/e2
Y Y2 as is (already with the converted σ)
B, T 0 at a dielectric node; ωc2=x/τ2−ωp2 (a negative value is replaced with the smallest number), B=ωcm/e

At a plasma node with Δε≠0 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 MAGNETIC blocks.
  • Magnetized plasma next to a MAGNETIC block. 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 y5; plasma under the absorber and the angle of incidence are not taken into account.
  • Δε>0 and N 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.
  • B without plasma has no effect (a warning).
  • Y is a dimensionless grid quantity: the same Y on different grids gives different attenuation; in physical units — the *_STAT_S blocks (σ, S/m).
  • A port node is a dielectric one: the port does not take B 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 nTMax are 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_DN variable has no effect in X.
  • The FILE block does not read a RECT_STAT_N file (and conversely, FILE_N does not read a RECT_STAT_B file): 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).