Счётное ядро H: сетка, блоки и расчёт во времени

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

Ядро H (программа tmc_rth.exe, PlanarRT_H) считает во временной области двумерные задачи для волн H-поляризации методом импедансного аналога пространства на Rt-сетке (теория). Оно получает задание .tpl, разобранное библиотекой TMCIndan, строит сетку узлов, заносит в неё диэлектрик, металл, поглотители, магнитные стенки и порты, затем шаг за шагом по времени вычисляет напряжения узлов и записывает:

  • сигналы портов (падающая и отражённая волны) — файл .t, по нему TMCIndan строит матрицу рассеяния .s;
  • кадры поля (напряжения всех узлов) — для FieldView;
  • топологию (полную eps каждого узла);
  • накопленное распределение поля на контуре — для диаграммы направленности (файлы .AMP/.FAZ/.DAT).

Эта страница описывает вычислительную часть ядра: классы CTmcRTHRectNode (сетка и цикл во времени) и CTmcRTHNodeDiel (блоки задания) и служебные функции pl_iofor/pl_glfun. Окно, документ, вид и диалоги ядра описаны на странице оболочки ядер. У ядра X — собственные файлы с теми же именами (src/kernels/planarrt_x): класс и порядок расчёта те же, но узел другой (плазма, четыре подтакта); побайтно совпадают только pl_iofor.* и pl_glfun.cpp. Отличия — на странице kernel-x.

Состав

Файл (src/kernels/planarrt_h/) Роль
tmcrthrectnode.h, tmcrthrectnode.cpp CTmcRTHRectNode: массивы узлов, подготовка шага, цикл по подтактам, рассеяние в узлах, вывод .t, поля, топологии; функции открытого файла .t (TmcOutT*)
tmcrthnodediel.h, tmcrthnodediel.cpp CTmcRTHNodeDiel: построение узлов блока каждого типа, EPSFAST, файлы .eps и .sig, возбуждение портов, граничные условия металла, поглотителя и магнитной стенки
pl_iofor.h, pl_iofor.cpp форматы чисел в .t и в файле поля, ключи запуска /Ar, /Arb, /d, /Time, код завершения процесса, вывод в консоль
pl_glfun.cpp функции рабочих потоков (RunStepGlobal, RunAllGlobal, ReadDataGlobal), вывод в строку состояния, IsPointInTr, звуковые сигналы; объявлены в общем typerth.h
tmcgpuh.h перенос цикла во времени на видеокарту — см. Расчёт на видеокарте
planrt_hdoc.*, planrt_hview.*, tmcdialog*, tmcrth_dialog*, tmcsound*, tmcerrormessage.* документ, вид и диалоги ядра — см. оболочку ядер

Классы и их связи

CPlanRT_HDoc (документ)                        поток интерфейса
 └── cRectNode : CTmcRTHRectNode               расчётный поток (AfxBeginThread)
      ├── cIndan : CTmcRTH_Indan               разбор задания (TMCIndan)
      │     ├── параметры #PARM, блоки #LINK_LIST, вывод #OUTPUT
      │     └── CFieldIntegrated               накопление поля для ДН
      ├── prUNode1[2*nX*nY]                    напряжения узлов
      ├── prYNode [2*nX*nY]                    проводимости узлов
      ├── pcNodeDiel[nDiel] : CTmcRTHNodeDiel  по объекту на блок задания
      │     └── pcNodeDielOne[]                узлы блока (номер узла сетки, роль, состояние)
      ├── m_cTiming : CTmcCalcTiming           замер времени (/Time)
      └── g_cGpuH : CTmcGpuH (статический)      сетка на видеокарте (/GPU)

Объект CTmcRTHRectNode живёт в документе всё время работы окна. Массивы узлов и блоков создаются при подготовке каждого шага #STEP и освобождаются при чтении следующего шага (DeleteData). Оба класса наследуют CWnd только исторически — окон они не создают.

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

Узлы сетки нумеруются построчно: n=iynX+ix, ix=0..nX−1 (ось X), iy=0..nY−1 (ось Y), номер — 64-битный TmcIdx. Шаг сетки Δ одинаков по осям. Для каждого узла хранятся четыре вещественных числа (при double — 32 байта на узел):

Ячейка Содержимое
prUNode1[2n] напряжение узла на чётном подтакте (подтакт 0)
prUNode1[2n+1] напряжение узла на нечётном подтакте (подтакт 1)
prYNode[2n] нормированная проводимость шлейфа узла y5 (со знаком); до перевода в проводимость — накопленная Δε узла
prYNode[2n+1] множитель 2/(4+|y5|)

Каждая ячейка напряжения хранит значение «через такт»: на подтакте 0 в чётную ячейку пишется Uτ вместо Uτ−2, а нечётная содержит Uτ−1; на подтакте 1 — наоборот. Так схема с тремя временными слоями (теория) обходится двумя ячейками на узел. Массивы выделяются с запасом 32 элемента, начало выровнено на 32 байта. Начальное состояние — свободное пространство: U=0, y5=0, 2/(4+y5)=0,5.

Блок хранит свои узлы отдельно, в массиве записей sTmcRTHNodeDielOne:

Поле Смысл
nNodeGlobal номер узла сетки n
nType код узла (см. типы)
rY вес узла: доля ячеек диэлектрика, профиль порта или нагрузка поглотителя
rU, rUo порт: падающее напряжение прошлого чётного/нечётного подтакта; поглотитель — Uτ−2 узла
rU_Cur, rU_Cur1 порт: сохранённые напряжения узла (чётная/нечётная ячейки)

Типы блоков и узлов

Код блока (CTmcRTHNodeDiel::nType) и код узла (sTmcRTHNodeDielOne::nType) берутся из констант CTMCRTH_BLCKNTYPE_* общего заголовка tmcgrviw.h:

Код Константа Блок
0 EPS диэлектрик (RECT_STAT, CIRCLE_STAT, POLYGON_STAT, *_MOVE, FILE)
100 ABSORBER поглотитель
101 METAL металл
102 / 103 INPXLEFT / INPXRIGHT вход слева (волна идёт вправо) / справа
104 / 105 INPYTOP / INPYBOT вход сверху (волна идёт вниз) / снизу
107 MAGNETIC магнитная стенка

Узлы поглотителя и магнитной стенки вместо кода блока получают код соседства ABSR_* (см. поглотитель). Старые комментарии в исходнике со значениями 0, 1, −1 … −6 не соответствуют текущим константам.

Блоки задания

На каждый блок секции #LINK_LIST создаётся объект CTmcRTHNodeDiel; CTmcRTHRectNode::SetDielTopology вызывает для него SetBlock. Тот по типу и ключевому слову примитива выбирает построитель узлов:

Тип RECT CIRCLE POLYGON FILE
диэлектрик SetStatEpsFast или SetRect SetStatEpsFast или SetCirc SetStatEpsFast или SetPoly SetRectFile
металл SetRectMetal SetCircMetal SetPolyMetal —
поглотитель SetRectAbsorber SetCircAbsorber SetPolyAbsorber —
магнитная стенка SetRectMagnetic SetCircMagnetic SetPolyMagnetic —
вход SetInpXLeft, SetInpXRight, SetInpYTop, SetInpYBot

Затем SetBlock проверяет, что все узлы блока (и соседи, которые читает порт) лежат в сетке, удаляет повторяющиеся узлы (DeleteDublicateData), записывает коды узлов (SetnType), прибавляет вклад диэлектрика к prYNode[2n] (SetYLineForDiel), строит профиль порта (SetYForInput) и освобождает массив узлов стационарного диэлектрика: после занесения eps в общий массив он больше не нужен.

Диэлектрик. Значение выражения eps блока — это Δε=ε−1 (в выражение подставляются x,y относительно точки привязки блока X0, Y0 в LONG_UNIT, r=x2+y2 и полярный угол f в ANGLE_UNIT). В узел заносится w·Δε, где вес w — доля четырёх соседних ячеек сетки внутри блока: у прямоугольника 1 внутри, 0,5 на стороне и 0,25 в углу; у круга и многоугольника — по 0,25 за каждую из четырёх диагональных точек (x±Δ, y±Δ), попавшую в фигуру. Вклады блоков складываются, поэтому узел на стыке двух блоков получает среднее по четырём ячейкам, как в теории. Части блока за краем области обрезаются.

Металл — только контур фигуры: стороны прямоугольника; ступенчатая (4-связная) ломаная по сторонам многоугольника; у кольцевого сектора — два радиальных отрезка и две дуги. Внутренние узлы отделены контуром от остальной сетки. Части контура дальше полушага за краем области отбрасываются.

Поглотитель и магнитная стенка — полоса узлов вдоль контура (у прямоугольника — внешний контур и кольцо на шаг внутри, у круга и многоугольника — квадраты 2×2 узла вдоль сторон), см. ниже.

Вход — строка или столбец узлов на координате X0 (вход слева/справа) или Y0 (сверху/снизу); апертура задаётся пределами блока Xmin..Xmax относительно другой координаты привязки и не подходит к краям области ближе 2 шагов. Пределы Ymin..Ymax блока входа — окно возбуждения Tmin..Tmax. См. порты.

Жизненный цикл шага #STEP

  1. Чтение — ReadData(файл, шаг) (из документа): препроцессор, число шагов, выбор шага, секции #PARM, #TOPOLOGY, #LINK_LIST, #OUTPUT через CTmcRTH_Indan. Сетка не строится.
  2. Расчёт — RunStep() в рабочем потоке → RunStep1(): - InitKernel — подготовка (ниже); - RunKernel — цикл во времени, затем матрица рассеяния; - звуковой сигнал конца шага.
  3. Документ после ошибки шага пишет в .s нули (PutSmatrixZero) и переходит к следующему шагу свипа.

RunStep перехватывает исключения (нехватка памяти и др.) и превращает их в ошибку ядра, в конце закрывает файл .t и подводит итог замера времени.

Подготовка

InitKernel выполняет, останавливаясь на первой ошибке:

  1. Открывает файл .t шага и пишет заголовок (DeleteOutputFile), удаляет старые файлы поля и топологии.
  2. Берёт время: число подтактов nTMax = (Tmax − Tmin)/τ, начало Tmin, шаг τ=Δμ0ε0/2=Δ/(c2) (теория).
  3. Проверяет область: не меньше 10 шагов по каждой оси, размеры сетки nX, nY > 1, общее число узлов не больше TMC_IDX_MAX/8.
  4. Готовит накопитель поля для ДН (CFieldIntegrated::InitAllFile).
  5. Выделяет prUNode1, prYNode (InitNodeArray).
  6. Создаёт и строит блоки (InitDielArray → SetDielTopology), переводит Δε узлов в проводимости (SetDielInNodeList), пишет топологию.
  7. Дописывает в заголовок .t данные портов (PutPortInfo).

Если сетка уже построена (повторный запуск после Stop), InitKernel ничего не делает и расчёт продолжается с прерванного такта.

Проводимости шлейфов

После построения всех блоков в prYNode[2n] лежит Δε узла. SetDielInNodeList переводит её в нормированную проводимость шлейфа (теория):

y5={4Δε,Δε≥0 (шлейф холостого хода),[2pt]Δε(k0Δ)22,Δε<0 (шлейф короткого замыкания),k0=2πfc,(1)

и записывает prYNode[2n] = y_5, prYNode[2n+1] = 2/(4 + |y_5|). Значения Δε, отличающиеся от 4 меньше чем на 0,004, сдвигаются до 3,996 или 4,004. Для Δε<0 проводимость зависит от частоты задания f (среда описывается на одной частоте, теория). Если ωτ/2>π/3 — ошибка «very big Delta*Frequence»: шаг сетки слишком крупный для частоты. Обратный пересчёт (ε=y5/4+1 или ε=y5/k+1) выполняет PutTopology при записи топологии.

Цикл во времени

RunKernel крутит цикл, пока номер подтакта nTCurrent меньше nTMax. Один проход — два подтакта (RunKernel1T); на каждом подтакте выполняется:

Шаг Функция Что делает
1 RunExciteInputs / RunExciteInputs1 начинает строку .t (такт, время), обновляет узлы всех портов и пишет их Up, Uo
2 RunScatteringNode / RunScatteringNode1 рассеяние во всех внутренних узлах сетки
3 RunBlockNode / RunBlockNode1 граничные условия блоков: металл, поглотитель, магнитная стенка
4 PutField кадр поля (если включён вывод поля)
5 DistributionIntegrated накопление поля для ДН (в окне ДН)
6 nTCurrent += 1, dTCurrent += τ

На подтакте 0 новые значения пишутся в чётные ячейки и читаются из нечётных, на подтакте 1 — наоборот. Каждые 100 подтактов в строку состояния выводятся номер такта, модельное время и прошедшее время. После цикла RunKernel проверяет, что окно ДН закончилось внутри расчёта (иначе файлы ДН не будут записаны — это ошибка), строит матрицу рассеяния (PutSmatrix) и, если задана переменная окружения TMC_AUTO_DN=1, сразу записывает файлы ДН.

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

RunScatteringNode обходит строки 1..nY−2 и столбцы 1..nX−2 (внутренние узлы) и для каждого узла вычисляет (теория, обмен волнами):

U0τ=24+|y5|(U1τ−1+U2τ−1+U3τ−1+U4τ−1+y5U0τ−1)−U0τ−2,(2)

где U1..U4 — соседние узлы слева, справа, снизу, сверху. В коде (RunScatteringNode1line) это одна строка на узел: U[2n] = Y[2n+1]*(U[2n-1] + U[2n+3] + U[2n+1-2nX] + U[2n+1+2nX] + Y[2n]*U[2n+1]) - U[2n]; узлы строки обрабатываются парами. Обмен волнами между узлами отдельной операцией не выполняется: он заложен в формулу через напряжения соседей прошлого подтакта.

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

Металл

RunBlockNode блока металла после рассеяния записывает U=0 во все узлы его контура (условие КЗ, теория). Наклонные и криволинейные стенки аппроксимируются ступенчатой ломаной из узлов (теория).

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

Обе границы строятся одинаково и отличаются только нагрузкой узлов контура: у поглотителя — проводимость согласованной нагрузки y (SetAbsorberAdmitance), у магнитной стенки y=0 (холостой ход, теория).

Код соседства. Для каждого узла блока SetAbsorberNodeType взводит бит, если соседний узел тоже принадлежит блоку: 0001 — левый (n−1), 0010 — верхний (n+nX), 0100 — правый (n+1), 1000 — нижний (n−nX). У прямоугольника коды контура задаются сразу при построении. По коду RunBlockNode выбирает схему узла с потерями (теория):

Код Положение узла Линии Шлейф Нагрузка
три соседа (0111, 1011, 1101, 1110) сторона контура наружу — полная, вдоль контура — половинные, внутрь — нет y5/2 y
два смежных (0011, 0110, 1001, 1100) внешний угол наружу — полные, вдоль — половинные 3y5/4 y/2
1111_1..1111_4 внутренний угол (нет одного диагонального соседа) две половинные y5/4 3y/2
1111, 0000 внутри блока, без соседей — — U=0
один сосед или два противоположных — — — ошибка «Bad Absorber or Magnetic Type»

Например, для стороны контура с внешним соседом Uo и соседями вдоль контура Ua, Ub:

Uτ=22+|y5′|+y(Uoτ−1+12(Uaτ−1+Ubτ−1)+y5′Uτ−1+yUτ−2)−Uτ−2,y5′=y5/2.(3)

Значение Uτ−2 узла хранится в rU: общий проход рассеяния успевает переписать ячейку раньше, чем выполняется граничное условие.

Нагрузка поглотителя подбирается по дисперсионному уравнению сетки для плоской волны, падающей по нормали:

y=sinβsina,cosβ=(2+|yW|2)cosa−1−yW2,a=ωτ=2πΔfc.(4)

У блоков поглотителя yW=0 — поглотитель согласован со свободным пространством.

Прямоугольный поглотитель не подходит к краям области ближе 1 шага слева и снизу и 2 шагов справа и сверху; его размер — не меньше 2 шагов. Магнитный прямоугольник ставит узлы через CalcnNodeGlobalFM и у края области добавляет к коду бит стороны края, чтобы стенка продолжалась до края; для круга и многоугольника то же делает SetMagneticPolygonType.

Порты

Вход — блок INPUT_X/INPUT_Y с параметрами: апертура, окно Tmin..Tmax, амплитуда Amp, фаза Faza, W (Δε среды порта), тип боковых стенок METAL или MAGNETIC. Подробно о трансформаторе возбуждения и поглощения — в теории.

Подготовка (SetInp*):

y1=sinβsina,cosβ=(2+|yW|2)cosa−yW2−cosπΔb,(5)

где b — ширина апертуры. Если |cosβ|>1, частота ниже отсечки порта — ошибка. У порта MAGNETIC — формула нагрузки поглотителя (плоская волна) с yW порта; - профиль основной волны (SetYForInput): у порта со стенками-металлом ri=Unsin(πi/(N−1)), у порта MAGNETIC ri=Un, где Un=1/(y1∑ipi2Δ2) и pi — ненормированный профиль (теория).

На каждом подтакте (ExciteInputs, ExciteInputs1):

  1. Сигнал a(t)=Amp(t,f)·sin(ωt+φ), φ=−Faza (в радианах; минус — задержка), или значение из файла .sig; вне окна Tmin..Tmax a=0 (теория).
  2. Восстанавливаются сохранённые напряжения узлов порта (rU_Cur, rU_Cur1): общий проход рассеяния мог их переписать.
  3. Если порт стоит не на краю области, узел позади порта обнуляется (обе ячейки).
  4. Новое напряжение узла апертуры (сосед внутрь области Uin, соседи вдоль апертуры Ua, Ub):
Uτ=22+y1+|yW|/2(12Uaτ−1+Uinτ−1+12Ubτ−1+yW2Uτ−1+y1(Uτ−2+riaτ−riaτ−2))−Uτ−2.(6)

У крайних узлов порта MAGNETIC все линии, шлейф и нагрузка вдвое меньше, а отсутствующий сосед вдоль апертуры равен 0; у порта со стенками-металлом крайние узлы не пересчитываются. 5. Новые напряжения сохраняются. 6. Отражённая волна — проекция на профиль: Uo=∑iri(Ui−ria)/∑iri2; в .t пишутся номер блока, Up=a(t) и Uo.

Падающая волна из файла

Если амплитуда порта задана как [имя], сигнал берётся из файла имя.sig (теория):

  • без точки в имени добавляется .sig, без пути — папка задания;
  • две колонки: время в TIME_UNIT задания и значение; строки, начинающиеся с ! или #, пропускаются; время должно строго возрастать, точек не меньше двух;
  • строка #FREQ f1 f2 ... (в FREQ_UNIT) — список частот многочастотного сигнала; он передаётся накопителю ДН (по паре квадратур на частоту, нужен FIELD_DISTRIBUTION_M) и записывается в заголовок .t в герцах для последующей обработки (теория);
  • между точками — линейная интерполяция, вне диапазона файла — 0; окно Tmin..Tmax порта тоже действует;
  • фаза порта с файлом не используется — если она задана, выводится предупреждение.

Быстрое построение блоков EPSFAST

Стационарные диэлектрические блоки RECT_STAT, CIRCLE_STAT, POLYGON_STAT (и их варианты _N/_B/_Y) строятся функцией SetStatEpsFast, которая даёт в prYNode те же числа бит в бит, что прежний путь SetRect/SetCirc/SetPoly + SetYLineForDiel, но:

  1. выражение без x,y,r,f вычисляется один раз на блок;
  2. вклад сразу прибавляется к prYNode, массив узлов блока (десятки байт на узел) не строится;
  3. узлы обходятся по строкам — подряд в памяти;
  4. выражение с x,y,r,f без = считается в нескольких потоках, у каждого свой контекст интерпретатора выражений; потоки берут по 8 строк (EPSFAST_CHUNK) и не пишут в одну ячейку (узлы блока на сетке различны — это проверяется заранее);
  5. выражение с = (переменные переходят от узла к узлу) считается в одном потоке в исходном порядке узлов.

Порог. Если в описанном прямоугольнике блока меньше 1000 узлов (EPSFAST_SMALL, переменная TMC_EPS_SMALL), счёт идёт в одном потоке. Число потоков — TMC_EPS_THREADS или число процессоров минус один на каждые восемь (ядра оставляются системе), не больше 64; потоки работают с пониженным приоритетом.

При любом нестандартном случае (повтор узлов сетки, нет узлов, очень большой блок) SetStatEpsFast возвращает FALSE и блок строится прежним кодом с прежними сообщениями. При ошибке выражения в каком-либо узле повторно ищется первый ошибочный узел в исходном порядке, чтобы сообщение было тем же. TMC_EPS_FAST=0 выключает EPSFAST для всех блоков.

Файлы распределения eps

Запись. Если выражение eps блока RECT_STAT начинается с [имя], распределение блока записывается в файл имя.eps (папка задания, если путь не полный) — SaveFileRect:

  • текстовый заголовок, строки с CR LF: метка #TamicRTH_planar_DistributionDielectricPermeability_File_V2.00 2000, #TopologyPrimitiv RECT_STAT, #dDelta (м), #Xmin, #Ymin (м, локальные координаты блока), #nX, #nY, #nPoint, #nAccuracy (4 или 8 байт), #sNodeFormat NULL, #sValueFormat NULL;
  • затем для каждого узла (строки снизу вверх, в строке слева направо) — значение «вес × Δε» типа _real и 4-байтовый локальный номер узла j+inX.

Чтение — блок FILE (SetRectFile): файл ищется как задан, затем в папке задания и с расширением .eps. Проверяются метки, тип RECT_STAT, совпадение шага сетки с заданием (до 10−5), точность 4 или 8 байт. Узлы ставятся на сетку с учётом X0, Y0; не попавшие в область пропускаются. Значение из файла уже содержит вес и прибавляется к prYNode[2n] как есть.

Вывод

Что Когда Формат
.t — сигналы портов каждый подтакт текст, см. ниже
файл поля каждый подтакт, если включён вывод поля заголовок (такт, время, шаг, Xmin, Ymin, точность, единицы, nX, nY) + напряжения всех узлов: _real в двоичном виде или текст по формату
файл топологии при подготовке шага и по команде меню заголовок + полная eps каждого узла (double или текст)
.s, ДН после цикла строит TMCIndan (lib-tmcindan)

При синхронном выводе поля ядро перед записью кадра ждёт, пока программа просмотра прочитает прошлый: после записи ядро снимает у файла атрибут ARCHIVE, FieldView после чтения взводит его. Ожидание — до 25 с (500 × 50 мс); если FieldView не ответил, дальше ядро не ждёт, пока он снова не начнёт читать. При автозапуске (/Ar, /Arb, /d) не ждёт. Форматы файлов — на странице форматов.

Файл .t

Заголовок: метка, имя файла, частота задания (Гц), число входов (−2); после построения блоков PutPortInfo дописывает признак многочастотного сигнала, список частот из #FREQ (Гц) и по строке на порт: номер блока, шаг сетки (м), апертура (м), частота согласования (Гц), признак файла .sig. Далее на каждом подтакте — строка: номер такта, время (с), затем у каждого порта «номер блока, Up, Uo» (форматы — pl_iofor).

Файл открыт всё время шага с запретом записи для других программ (TmcOutTOpen, _SH_DENYWR): второе ядро с тем же именем FILE получит понятную ошибку, а не смешает строки. Занятый файл ждут до 20 с. После Stop файл закрывается и при продолжении открывается на дозапись. Перед построением матрицы рассеяния буфер сбрасывается на диск.

Потоки и остановка

  • Чтение задания и расчёт идут в рабочем потоке, запущенном документом (ReadDataGlobal, RunStepGlobal, RunAllGlobal в pl_glfun.cpp); интерфейс остаётся в главном потоке.
  • Признак bIsReadData означает «объект занят». Stop() (из интерфейса) снимает его и не ждёт. Его проверяют цикл во времени (каждый подтакт), построение блоков (каждый узел через pbIsStop), EPSFAST (каждая строка), перевод в проводимости (каждые 100 000 узлов) и ожидание FieldView. Повторный RunStep() продолжает шаг с прерванного такта.
  • Классы не потокобезопасны; одновременно с расчётом интерфейс читает только флаги и результаты через документ. Таблица открытых файлов .t защищена мьютексом.
  • Рабочие потоки EPSFAST существуют только внутри SetStatEpsFast.

Расчёт на видеокарте

При ключе /GPU (только win64) RunKernel переносит сетку на видеокарту (g_cGpuH.Begin) и вместо RunKernel1T вызывает RunKernel1TGpu: на карте выполняются рассеяние и граничные условия металла, поглотителя и магнитной стенки, а порты и весь вывод остаются на процессоре. Перед возбуждением порта узлы вокруг него копируются с карты и обратно; всю сетку копируют только для вывода поля и в окне ДН. Результат совпадает с расчётом на процессоре бит в бит. Подробности — Расчёт на видеокарте и теория.

Замер времени (/Time)

CTmcRTHRectNode::m_cTiming (tmccalctiming.h) накапливает такты QPC по этапам: освобождение памяти, препроцессор, чтение задания, открытие файлов, накопитель ДН, выделение массивов, геометрия блоков, запись и чтение файлов .eps, перевод в проводимости, топология, возбуждение портов, рассеяние, граничные условия блоков, запись поля и сигналов, накопление ДН, строка состояния, матрица рассеяния, звук. Счётчики блоков подключаются через SetTimingCounters / SetTimingEpsCounters. С ключом /Time в конце «Run all» отчёт записывается рядом с заданием (<tpl>.timing_<H|X>_<win32|win64>.txt); тот же отчёт доступен из окна статистики.

Режимы запуска

Ключи командной строки (Set_CommandLine_Flags; также с -, регистр не важен, ключ — отдельное слово вне кавычек):

Ключ Режим
/Ar автозапуск всех шагов, сообщения и итог в консоль, без ожидания FieldView, окно закрывается в конце
/Arb то же + пакетный режим: без звука
/d то же + демонстрационный режим: после каждого кадра поля открывается его просмотр
/Time отчёт о времени расчёта

Код завершения процесса (TMC_EXIT_*): 0 — все шаги посчитаны, 1 — ошибка задания, 2 — ошибка расчёта шага, 3 — остановлено или окно закрыто до конца. При автозапуске до окончания расчёта код равен 3.

Типичные ошибки и подводные камни

  • В выражении eps H-ядра задаётся Δε=ε−1, а не ε: ядро заносит значение выражения как есть, а при записи топологии прибавляет 1.
  • Край области — металл. Узлы на краю не пересчитываются; открытую границу нужно задавать поглотителем.
  • Поглотитель согласован только со свободным пространством при нормальном падении: его нагрузка считается с yW=0, диэлектрик под поглотителем не учитывается.
  • Порт ниже отсечки (ширина апертуры меньше половины длины волны в среде порта) — ошибка «Frequency … is below cutoff of port»; порт из меньше чем 3 узлов — ошибка.
  • Значения Δε около 4 (в пределах 0,004) сдвигаются до 3,996/4,004; то же для W порта.
  • Окно ДН позже конца расчёта — ошибка шага: файлы ДН не будут записаны.
  • Нечётное число подтактов: цикл идёт парами подтактов, поэтому при нечётном nTMax выполняется на один подтакт больше.
  • Большие поглотители и магнитные стенки сложной формы строятся медленно: удаление повторов и расстановка кодов соседства перебирают все пары узлов блока (O(N2)).
  • Файл .eps хранит номер узла в 4 байтах: блок RECT_STAT с записью в файл — не больше INT_MAX узлов; шаг сетки при чтении должен совпадать с заданием.
  • Порт внутри области. Общий проход рассеяния обновляет и узлы порта, если порт стоит не на краю; перед следующим обновлением порта значения восстанавливаются, но в кадре поля и в накоплении ДН на этом подтакте в узлах порта оказывается значение после рассеяния.
  • Синхронный вывод поля без FieldView замедляет расчёт: до 25 с ожидания на первом кадре.

Compute kernel H: grid, blocks and time-domain computation

Purpose and place in the package

Kernel H (the program tmc_rth.exe, PlanarRT_H) solves two-dimensional time-domain problems for H-polarization waves by the impedance analogue of space method on an Rt-grid (theory). It receives a .tpl task file parsed by the TMCIndan library, builds the grid of nodes, places dielectric, metal, absorbers, magnetic walls and ports into it, then computes the node voltages time step by time step and writes:

  • port signals (incident and reflected waves) — the .t file, from which TMCIndan builds the scattering matrix .s;
  • field frames (the voltages of all nodes) — for FieldView;
  • the topology (the full eps of each node);
  • the accumulated field distribution on a contour — for the radiation pattern (files .AMP/.FAZ/.DAT).

This page describes the computational part of the kernel: the classes CTmcRTHRectNode (grid and time loop) and CTmcRTHNodeDiel (task file blocks) and the service functions pl_iofor/pl_glfun. The window, document, view and dialogs of the kernel are described on the kernel shell page. Kernel X has its own files with the same names (src/kernels/planarrt_x): the class and the order of computation are the same, but the node is different (plasma, four sub-steps); only pl_iofor.* and pl_glfun.cpp are identical byte for byte. The differences are on the kernel-x page.

Contents

File (src/kernels/planarrt_h/) Role
tmcrthrectnode.h, tmcrthrectnode.cpp CTmcRTHRectNode: node arrays, step preparation, sub-step loop, scattering at the nodes, output of .t, fields, topology; functions of the open .t file (TmcOutT*)
tmcrthnodediel.h, tmcrthnodediel.cpp CTmcRTHNodeDiel: building the nodes of a block of each type, EPSFAST, .eps and .sig files, port excitation, boundary conditions of metal, absorber and magnetic wall
pl_iofor.h, pl_iofor.cpp number formats in .t and in the field file, launch options /Ar, /Arb, /d, /Time, process exit code, console output
pl_glfun.cpp worker thread functions (RunStepGlobal, RunAllGlobal, ReadDataGlobal), status bar output, IsPointInTr, sound signals; declared in the common typerth.h
tmcgpuh.h moving the time loop to the GPU — see GPU computing
planrt_hdoc.*, planrt_hview.*, tmcdialog*, tmcrth_dialog*, tmcsound*, tmcerrormessage.* document, view and dialogs of the kernel — see the kernel shell

Classes and their relations

CPlanRT_HDoc (document)                        interface thread
 └── cRectNode : CTmcRTHRectNode               computation thread (AfxBeginThread)
      ├── cIndan : CTmcRTH_Indan               task file parsing (TMCIndan)
      │     ├── parameters #PARM, blocks #LINK_LIST, output #OUTPUT
      │     └── CFieldIntegrated               field accumulation for the RP
      ├── prUNode1[2*nX*nY]                    node voltages
      ├── prYNode [2*nX*nY]                    node conductances
      ├── pcNodeDiel[nDiel] : CTmcRTHNodeDiel  one object per task file block
      │     └── pcNodeDielOne[]                block nodes (grid node number, role, state)
      ├── m_cTiming : CTmcCalcTiming           timing (/Time)
      └── g_cGpuH : CTmcGpuH (static)           grid on the GPU (/GPU)

The CTmcRTHRectNode object lives in the document for the whole lifetime of the window. The node and block arrays are created when each #STEP step is prepared and freed when the next step is read (DeleteData). Both classes inherit CWnd only for historical reasons — they create no windows.

Node data structure

The grid nodes are numbered row by row: n=iynX+ix, ix=0..nX−1 (X axis), iy=0..nY−1 (Y axis); the number is a 64-bit TmcIdx. The grid step Δ is the same along both axes. For each node four real numbers are stored (with double — 32 bytes per node):

Cell Contents
prUNode1[2n] node voltage on the even sub-step (sub-step 0)
prUNode1[2n+1] node voltage on the odd sub-step (sub-step 1)
prYNode[2n] normalized stub conductance of the node y5 (signed); before conversion to a conductance — the accumulated Δε of the node
prYNode[2n+1] the multiplier 2/(4+|y5|)

Each voltage cell stores a value "every other time step": on sub-step 0 the even cell receives Uτ in place of Uτ−2, while the odd one contains Uτ−1; on sub-step 1 it is the other way round. In this way the scheme with three time layers (theory) gets by with two cells per node. The arrays are allocated with a margin of 32 elements, the start is aligned to 32 bytes. The initial state is free space: U=0, y5=0, 2/(4+y5)=0,5.

A block stores its nodes separately, in an array of sTmcRTHNodeDielOne records:

Field Meaning
nNodeGlobal grid node number n
nType node code (see types)
rY node weight: fraction of dielectric cells, port profile or absorber load
rU, rUo port: incident voltage of the previous even/odd sub-step; absorber — Uτ−2 of the node
rU_Cur, rU_Cur1 port: saved node voltages (even/odd cells)

Block and node types

The block code (CTmcRTHNodeDiel::nType) and the node code (sTmcRTHNodeDielOne::nType) are taken from the constants CTMCRTH_BLCKNTYPE_* of the common header tmcgrviw.h:

Code Constant Block
0 EPS dielectric (RECT_STAT, CIRCLE_STAT, POLYGON_STAT, *_MOVE, FILE)
100 ABSORBER absorber
101 METAL metal
102 / 103 INPXLEFT / INPXRIGHT port on the left (the wave travels to the right) / on the right
104 / 105 INPYTOP / INPYBOT port at the top (the wave travels downward) / at the bottom
107 MAGNETIC magnetic wall

Nodes of an absorber and a magnetic wall get a neighborhood code ABSR_* instead of the block code (see absorber). Old comments in the source with the values 0, 1, −1 … −6 do not correspond to the current constants.

Task file blocks

For each block of the #LINK_LIST section a CTmcRTHNodeDiel object is created; CTmcRTHRectNode::SetDielTopology calls SetBlock for it. That function chooses the node builder by the type and the primitive keyword:

Type RECT CIRCLE POLYGON FILE
dielectric SetStatEpsFast or SetRect SetStatEpsFast or SetCirc SetStatEpsFast or SetPoly SetRectFile
metal SetRectMetal SetCircMetal SetPolyMetal —
absorber SetRectAbsorber SetCircAbsorber SetPolyAbsorber —
magnetic wall SetRectMagnetic SetCircMagnetic SetPolyMagnetic —
port SetInpXLeft, SetInpXRight, SetInpYTop, SetInpYBot

Then SetBlock checks that all nodes of the block (and the neighbors read by a port) lie within the grid, removes duplicate nodes (DeleteDublicateData), writes the node codes (SetnType), adds the dielectric contribution to prYNode[2n] (SetYLineForDiel), builds the port profile (SetYForInput) and frees the node array of a stationary dielectric: once the eps has been entered into the common array, it is no longer needed.

Dielectric. The value of the block's eps expression is Δε=ε−1 (the expression receives x,y relative to the block anchor point X0, Y0 in LONG_UNIT, r=x2+y2 and the polar angle f in ANGLE_UNIT). The node receives w·Δε, where the weight w is the fraction of the four neighboring grid cells inside the block: for a rectangle 1 inside, 0.5 on a side and 0.25 at a corner; for a circle and a polygon — 0.25 for each of the four diagonal points (x±Δ, y±Δ) that falls inside the shape. The contributions of blocks add up, so a node at the junction of two blocks gets the average over the four cells, as in the theory. Parts of a block beyond the edge of the region are clipped.

Metal — only the contour of the shape: the sides of a rectangle; a staircase (4-connected) polyline along the sides of a polygon; for an annular sector — two radial segments and two arcs. The inner nodes are separated from the rest of the grid by the contour. Parts of the contour more than half a step beyond the edge of the region are discarded.

Absorber and magnetic wall — a band of nodes along the contour (for a rectangle — the outer contour and a ring one step inside, for a circle and a polygon — 2×2 node squares along the sides), see below.

Port — a row or column of nodes at the coordinate X0 (port on the left/right) or Y0 (top/bottom); the aperture is given by the block limits Xmin..Xmax relative to the other anchor coordinate and must not come closer than 2 steps to the edges of the region. The limits Ymin..Ymax of a port block are the excitation window Tmin..Tmax. See ports.

Life cycle of a #STEP step

  1. Reading — ReadData(file, step) (from the document): preprocessor, number of steps, step selection, the #PARM, #TOPOLOGY, #LINK_LIST, #OUTPUT sections through CTmcRTH_Indan. The grid is not built.
  2. Computation — RunStep() in the worker thread → RunStep1(): - InitKernel — preparation (below); - RunKernel — the time loop, then the scattering matrix; - the end-of-step sound signal.
  3. After a step error the document writes zeros to .s (PutSmatrixZero) and goes on to the next step of the sweep.

RunStep catches exceptions (out of memory and others) and turns them into a kernel error; at the end it closes the .t file and totals the timing.

Preparation

InitKernel performs the following, stopping at the first error:

  1. Opens the .t file of the step and writes the header (DeleteOutputFile), deletes old field and topology files.
  2. Takes the time: the number of sub-steps nTMax = (Tmax − Tmin)/τ, the start Tmin, the step τ=Δμ0ε0/2=Δ/(c2) (theory).
  3. Checks the region: at least 10 steps along each axis, grid sizes nX, nY > 1, the total number of nodes not more than TMC_IDX_MAX/8.
  4. Prepares the field accumulator for the RP (CFieldIntegrated::InitAllFile).
  5. Allocates prUNode1, prYNode (InitNodeArray).
  6. Creates and builds the blocks (InitDielArray → SetDielTopology), converts the Δε of the nodes into conductances (SetDielInNodeList), writes the topology.
  7. Appends the port data to the .t header (PutPortInfo).

If the grid has already been built (a repeated run after Stop), InitKernel does nothing and the computation continues from the interrupted time step.

Stub conductances

After all blocks have been built, prYNode[2n] holds the Δε of the node. SetDielInNodeList converts it into the normalized stub conductance (theory):

y5={4Δε,Δε≥0 (open-circuited stub),[2pt]Δε(k0Δ)22,Δε<0 (short-circuited stub),k0=2πfc,(1)

and writes prYNode[2n] = y_5, prYNode[2n+1] = 2/(4 + |y_5|). Values of Δε that differ from 4 by less than 0.004 are shifted to 3.996 or 4.004. For Δε<0 the conductance depends on the task frequency f (the medium is described at a single frequency, theory). If ωτ/2>π/3 — the error "very big Delta*Frequence": the grid step is too coarse for the frequency. The inverse conversion (ε=y5/4+1 or ε=y5/k+1) is performed by PutTopology when the topology is written.

Time loop

RunKernel runs the loop while the sub-step number nTCurrent is less than nTMax. One pass is two sub-steps (RunKernel1T); on each sub-step the following is performed:

Step Function What it does
1 RunExciteInputs / RunExciteInputs1 starts a .t line (time step, time), updates the nodes of all ports and writes their Up, Uo
2 RunScatteringNode / RunScatteringNode1 scattering at all inner grid nodes
3 RunBlockNode / RunBlockNode1 boundary conditions of the blocks: metal, absorber, magnetic wall
4 PutField a field frame (if field output is enabled)
5 DistributionIntegrated field accumulation for the RP (within the RP window)
6 nTCurrent += 1, dTCurrent += τ

On sub-step 0 the new values are written to the even cells and read from the odd ones, on sub-step 1 — the other way round. Every 100 sub-steps the time step number, the model time and the elapsed time are output to the status bar. After the loop RunKernel checks that the RP window ended within the computation (otherwise the RP files would not be written — this is an error), builds the scattering matrix (PutSmatrix) and, if the environment variable TMC_AUTO_DN=1 is set, immediately writes the RP files.

Scattering at a node

RunScatteringNode traverses rows 1..nY−2 and columns 1..nX−2 (the inner nodes) and for each node computes (theory, wave exchange):

U0τ=24+|y5|(U1τ−1+U2τ−1+U3τ−1+U4τ−1+y5U0τ−1)−U0τ−2,(2)

where U1..U4 are the neighboring nodes on the left, right, bottom and top. In the code (RunScatteringNode1line) this is one line per node: U[2n] = Y[2n+1]*(U[2n-1] + U[2n+3] + U[2n+1-2nX] + U[2n+1+2nX] + Y[2n]*U[2n+1]) - U[2n]; the nodes of a row are processed in pairs. Wave exchange between nodes is not performed as a separate operation: it is built into the formula through the neighbors' voltages of the previous sub-step.

The nodes at the edges of the region are not recomputed by the formula and remain zero — a short-circuit condition (metal) acts at the edge of the region unless a port or an absorber is placed there.

Metal

After scattering, RunBlockNode of a metal block writes U=0 to all nodes of its contour (short-circuit condition, theory). Inclined and curved walls are approximated by a staircase polyline of nodes (theory).

Absorber and magnetic wall

Both boundaries are built the same way and differ only in the load of the contour nodes: for an absorber — the conductance of a matched load y (SetAbsorberAdmitance), for a magnetic wall y=0 (open circuit, theory).

Neighborhood code. For each node of the block SetAbsorberNodeType sets a bit if the neighboring node also belongs to the block: 0001 — left (n−1), 0010 — top (n+nX), 0100 — right (n+1), 1000 — bottom (n−nX). For a rectangle the contour codes are set directly during construction. By the code, RunBlockNode chooses the circuit of the lossy node (theory):

Code Node position Lines Stub Load
three neighbors (0111, 1011, 1101, 1110) side of the contour outward — full, along the contour — half, inward — none y5/2 y
two adjacent (0011, 0110, 1001, 1100) outer corner outward — full, along — half 3y5/4 y/2
1111_1..1111_4 inner corner (one diagonal neighbor missing) two half lines y5/4 3y/2
1111, 0000 inside the block, no neighbors — — U=0
one neighbor or two opposite ones — — — error "Bad Absorber or Magnetic Type"

For example, for a side of the contour with the outer neighbor Uo and the neighbors along the contour Ua, Ub:

Uτ=22+|y5′|+y(Uoτ−1+12(Uaτ−1+Ubτ−1)+y5′Uτ−1+yUτ−2)−Uτ−2,y5′=y5/2.(3)

The value Uτ−2 of the node is stored in rU: the common scattering pass overwrites the cell before the boundary condition is applied.

The absorber load is chosen from the dispersion equation of the grid for a plane wave at normal incidence:

y=sinβsina,cosβ=(2+|yW|2)cosa−1−yW2,a=ωτ=2πΔfc.(4)

For absorber blocks yW=0 — the absorber is matched to free space.

A rectangular absorber must not come closer than 1 step to the edges of the region on the left and bottom and 2 steps on the right and top; its size is at least 2 steps. A magnetic rectangle places its nodes through CalcnNodeGlobalFM and at the edge of the region adds the bit of the edge side to the code, so that the wall continues up to the edge; for a circle and a polygon the same is done by SetMagneticPolygonType.

Ports

A port is an INPUT_X/INPUT_Y block with the parameters: aperture, window Tmin..Tmax, amplitude Amp, phase Faza, W (Δε of the port medium), type of the side walls METAL or MAGNETIC. The excitation and absorption transformer is described in detail in the theory.

Preparation (SetInp*):

  • the stub of the port medium yW (CalculateYForInput) — from W by the same rule as the dielectric conductance (theory);
  • the load matched to the fundamental wave (SetInputAdmitance):
y1=sinβsina,cosβ=(2+|yW|2)cosa−yW2−cosπΔb,(5)

where b is the aperture width. If |cosβ|>1, the frequency is below the port cutoff — an error. For a MAGNETIC port — the absorber load formula (plane wave) with the yW of the port; - the profile of the fundamental wave (SetYForInput): for a port with metal walls ri=Unsin(πi/(N−1)), for a MAGNETIC port ri=Un, where Un=1/(y1∑ipi2Δ2) and pi is the unnormalized profile (theory).

On every sub-step (ExciteInputs, ExciteInputs1):

  1. The signal a(t)=Amp(t,f)·sin(ωt+φ), φ=−Faza (in radians; minus means delay), or the value from the .sig file; outside the window Tmin..Tmax a=0 (theory).
  2. The saved voltages of the port nodes are restored (rU_Cur, rU_Cur1): the common scattering pass may have overwritten them.
  3. If the port is not at the edge of the region, the node behind the port is zeroed (both cells).
  4. The new voltage of an aperture node (the neighbor toward the inside of the region Uin, the neighbors along the aperture Ua, Ub):
Uτ=22+y1+|yW|/2(12Uaτ−1+Uinτ−1+12Ubτ−1+yW2Uτ−1+y1(Uτ−2+riaτ−riaτ−2))−Uτ−2.(6)

For the end nodes of a MAGNETIC port all lines, the stub and the load are halved, and the missing neighbor along the aperture equals 0; for a port with metal walls the end nodes are not recomputed. 5. The new voltages are saved. 6. The reflected wave is the projection onto the profile: Uo=∑iri(Ui−ria)/∑iri2; the block number, Up=a(t) and Uo are written to .t.

Incident wave from a file

If the port amplitude is given as [name], the signal is taken from the file name.sig (theory):

  • without a dot in the name .sig is appended, without a path — the task file folder is used;
  • two columns: time in the TIME_UNIT of the task file and the value; lines starting with ! or # are skipped; the time must be strictly increasing, there must be at least two points;
  • the line #FREQ f1 f2 ... (in FREQ_UNIT) is the list of frequencies of a multi-frequency signal; it is passed to the RP accumulator (one pair of quadratures per frequency, FIELD_DISTRIBUTION_M is required) and written to the .t header in hertz for subsequent processing (theory);
  • between the points — linear interpolation, outside the file range — 0; the port window Tmin..Tmax also applies;
  • the port phase is not used with a file — if it is given, a warning is output.

Fast block construction EPSFAST

Stationary dielectric blocks RECT_STAT, CIRCLE_STAT, POLYGON_STAT (and their variants _N/_B/_Y) are built by the function SetStatEpsFast, which yields in prYNode the same numbers bit for bit as the former path SetRect/SetCirc/SetPoly + SetYLineForDiel, but:

  1. an expression without x,y,r,f is evaluated once per block;
  2. the contribution is added to prYNode immediately, the node array of the block (tens of bytes per node) is not built;
  3. the nodes are traversed row by row — contiguously in memory;
  4. an expression with x,y,r,f without = is evaluated in several threads, each with its own context of the expression interpreter; the threads take 8 rows at a time (EPSFAST_CHUNK) and never write to the same cell (the block nodes on the grid are distinct — this is checked in advance);
  5. an expression with = (variables carry over from node to node) is evaluated in one thread in the original node order.

Threshold. If the bounding rectangle of the block contains fewer than 1000 nodes (EPSFAST_SMALL, variable TMC_EPS_SMALL), the computation runs in one thread. The number of threads is TMC_EPS_THREADS or the number of processors minus one for every eight (cores are left to the system), at most 64; the threads run at reduced priority.

In any non-standard case (repeated grid nodes, no nodes, a very large block) SetStatEpsFast returns FALSE and the block is built by the former code with the former messages. On an expression error at some node, the first erroneous node in the original order is searched for again, so that the message is the same. TMC_EPS_FAST=0 disables EPSFAST for all blocks.

Eps distribution files

Writing. If the eps expression of a RECT_STAT block starts with [name], the distribution of the block is written to the file name.eps (the task file folder if the path is not full) — SaveFileRect:

  • a text header, lines with CR LF: the tag #TamicRTH_planar_DistributionDielectricPermeability_File_V2.00 2000, #TopologyPrimitiv RECT_STAT, #dDelta (m), #Xmin, #Ymin (m, local coordinates of the block), #nX, #nY, #nPoint, #nAccuracy (4 or 8 bytes), #sNodeFormat NULL, #sValueFormat NULL;
  • then for each node (rows from bottom to top, within a row from left to right) — the value "weight × Δε" of type _real and the 4-byte local node number j+inX.

Reading — the FILE block (SetRectFile): the file is looked up as given, then in the task file folder and with the .eps extension. The tags, the RECT_STAT type, the agreement of the grid step with the task file (to 10−5) and the precision of 4 or 8 bytes are checked. The nodes are placed on the grid taking X0, Y0 into account; those that do not fall into the region are skipped. The value from the file already contains the weight and is added to prYNode[2n] as is.

Output

What When Format
.t — port signals every sub-step text, see below
field file every sub-step, if field output is enabled header (time step, time, step, Xmin, Ymin, precision, units, nX, nY) + voltages of all nodes: _real in binary form or text by format
topology file when the step is prepared and on a menu command header + full eps of each node (double or text)
.s, RP after the loop built by TMCIndan (lib-tmcindan)

With synchronous field output the kernel, before writing a frame, waits until the viewer has read the previous one: after writing, the kernel clears the ARCHIVE attribute of the file, and FieldView sets it after reading. The wait is up to 25 s (500 × 50 ms); if FieldView has not responded, the kernel no longer waits until it starts reading again. On autorun (/Ar, /Arb, /d) it does not wait. File formats are on the formats page.

The .t file

Header: tag, file name, task frequency (Hz), number of ports (−2); after the blocks are built, PutPortInfo appends the multi-frequency signal flag, the list of frequencies from #FREQ (Hz) and one line per port: block number, grid step (m), aperture (m), matching frequency (Hz), .sig file flag. Then, on every sub-step, a line: time step number, time (s), then for each port "block number, Up, Uo" (formats — pl_iofor).

The file is kept open for the whole step with writing denied to other programs (TmcOutTOpen, _SH_DENYWR): a second kernel with the same FILE name gets a clear error instead of mixing lines. A busy file is waited for up to 20 s. After Stop the file is closed and, when continuing, reopened for appending. Before the scattering matrix is built, the buffer is flushed to disk.

Threads and stopping

  • Reading the task file and the computation run in a worker thread started by the document (ReadDataGlobal, RunStepGlobal, RunAllGlobal in pl_glfun.cpp); the interface stays in the main thread.
  • The flag bIsReadData means "the object is busy". Stop() (from the interface) clears it and does not wait. It is checked by the time loop (every sub-step), block construction (every node through pbIsStop), EPSFAST (every row), the conversion to conductances (every 100,000 nodes) and the wait for FieldView. A repeated RunStep() continues the step from the interrupted time step.
  • The classes are not thread-safe; while a computation runs, the interface reads only the flags and the results through the document. The table of open .t files is protected by a mutex.
  • The EPSFAST worker threads exist only inside SetStatEpsFast.

GPU computing

With the /GPU option (win64 only) RunKernel moves the grid to the GPU (g_cGpuH.Begin) and calls RunKernel1TGpu instead of RunKernel1T: the card performs the scattering and the boundary conditions of metal, absorber and magnetic wall, while the ports and all output stay on the CPU. Before a port is excited, the nodes around it are copied from the card and back; the whole grid is copied only for field output and within the RP window. The result coincides with the CPU computation bit for bit. Details — GPU computing and theory.

Timing (/Time)

CTmcRTHRectNode::m_cTiming (tmccalctiming.h) accumulates QPC ticks by stages: freeing memory, preprocessor, reading the task file, opening files, RP accumulator, allocating arrays, block geometry, writing and reading .eps files, conversion to conductances, topology, port excitation, scattering, block boundary conditions, writing the field and signals, RP accumulation, status bar, scattering matrix, sound. Block counters are connected through SetTimingCounters / SetTimingEpsCounters. With the /Time option, at the end of "Run all" the report is written next to the task file (<tpl>.timing_<H|X>_<win32|win64>.txt); the same report is available from the statistics window.

Launch modes

Command-line options (Set_CommandLine_Flags; also with -, case-insensitive, an option is a separate word outside quotes):

Option Mode
/Ar autorun of all steps, messages and the result to the console, without waiting for FieldView, the window closes at the end
/Arb the same + batch mode: no sound
/d the same + demonstration mode: after each field frame its viewer is opened
/Time report on the computation time

Process exit code (TMC_EXIT_*): 0 — all steps computed, 1 — task file error, 2 — step computation error, 3 — stopped or the window was closed before the end. On autorun, until the computation ends, the code equals 3.

Typical errors and pitfalls

  • The eps expression of the H kernel specifies Δε=ε−1, not ε: the kernel enters the value of the expression as is, and adds 1 when writing the topology.
  • The edge of the region is metal. The nodes at the edge are not recomputed; an open boundary must be specified with an absorber.
  • The absorber is matched only to free space at normal incidence: its load is computed with yW=0, a dielectric under the absorber is not taken into account.
  • A port below cutoff (aperture width less than half the wavelength in the port medium) — the error "Frequency … is below cutoff of port"; a port of fewer than 3 nodes — an error.
  • Values of Δε near 4 (within 0.004) are shifted to 3.996/4.004; the same applies to the port W.
  • An RP window later than the end of the computation is a step error: the RP files will not be written.
  • An odd number of sub-steps: the loop runs in pairs of sub-steps, so with an odd nTMax one extra sub-step is performed.
  • Large absorbers and magnetic walls of complex shape are built slowly: removing duplicates and assigning neighborhood codes iterate over all pairs of block nodes (O(N2)).
  • The .eps file stores the node number in 4 bytes: a RECT_STAT block written to a file — at most INT_MAX nodes; when reading, the grid step must match the task file.
  • A port inside the region. The common scattering pass also updates the port nodes if the port is not at the edge; the values are restored before the next port update, but the field frame and the RP accumulation on that sub-step contain the post-scattering value at the port nodes.
  • Synchronous field output without FieldView slows down the computation: up to 25 s of waiting on the first frame.