Библиотека TMCIndan — API-документация

Пакет TMC Suite. Статическая библиотека — чтение входного файла-шаблона расчёта (.tpl), хранение топологии планарной структуры (блоков-примитивов), параметров расчёта, секции вывода, а также интегрирование поля во времени и экспорт в диаграмму направленности. Язык документации: русский. Все сигнатуры приведены по исходникам из src/libs/TMCIndan/ и общим заголовкам из src/Include/.


1. Назначение библиотеки

TMCIndan — статическая библиотека (StaticLibrary), которую линкуют счётные ядра PlanarRT_H и PlanarRT_X (см. CLAUDE.md, раздел «Зависимости библиотек»). Её задача — превратить текстовый входной файл расчёта (.tpl) в объектную модель расчётной задачи:

  • запуск препроцессора PREPR над .tpl (создание временного развёрнутого файла);
  • разбор секций входного файла: параметры (#PARM), топология (#TOPOLOGY), список связей блоков (#LINK_LIST), вывод (#OUTPUT), шаги (#STEP);
  • хранение топологии в виде односвязного списка блоков-примитивов (прямоугольники, окружности, многоугольники, файлы распределения eps, входы/возбуждения), каждый со своим выражением диэлектрической проницаемости, магнитной проницаемости, потерь и т.п.;
  • хранение глобальных параметров расчёта (единицы измерения, сетка Delta, границы области Xmin..Ymax, частота, время, высота);
  • хранение настроек вывода (имена выходных файлов, флаги вывода S-матрицы, поля, топологии);
  • интегрирование поля по времени (накопление амплитуды и фазы Ez) и экспорт в файл диаграммы направленности.

Имя «Indan» (наведённые токи / «индан-блоки») и часть прикладной семантики относятся к научной модели проекта. Математику расчётов править нельзя (см. CLAUDE.md). Здесь документируется программный интерфейс, а не физический смысл формул.


2. Расположение исходников и состав сборки

Исходники: src/libs/TMCIndan/. Заголовки: src/Include/ (подключаются как <TmcRTH_*.h>). Проект сборки — TMCIndan.vcxproj (тип StaticLibrary, конфигурации Win32/x64).

В сборку входят 8 файлов .cpp:

Файл .cpp Класс / содержимое Заголовок
TmcRTH_Indan.cpp CTmcRTH_Indan — главный фасад: открытие .tpl, запуск PREPR, чтение секций по шагам TmcRTH_Indan.h
TmcRTH_IndanParam.cpp CTmcRTH_IndanParam — глобальные параметры расчёта, единицы измерения, сетка узлов TmcRTH_IndanParam.h
TmcRTH_IndanTopology.cpp CTmcRTH_IndanTopology — обёртка над списком блоков и параметрами TmcRTH_IndanTopology.h
TmcRTH_BolckList.cpp CTmcRTH_BlockList — односвязный список блоков-примитивов топологии TmcRTH_BolckList.h
TmcRTH_IndanOutput.cpp CTmcRTH_IndanOutput — настройки и имена файлов вывода TmcRTH_IndanOutput.h
FieldIntegrated.cpp CFieldIntegrated — интегрирование поля по времени, экспорт в диаграмму направленности FieldIntegrated.h
TmcRTH_Input.cpp CTmcRTH_Input — узлы возбуждения (вход), внутренний класс TmcRTH_Input.h
TmcRTH_InputNode.cpp CTmcRTH_InputNode — один узел возбуждения, внутренний класс TmcRTH_InputNode.h

3. Базовые типы и зависимости

Библиотека опирается на общие заголовки и типы:

Заголовок Что даёт
typerth.h Тип _real (float или double в зависимости от макроса _PREC_FLOAT/_PREC_DOUBLE); _ELEM_VAL_RTH (= _real); физические константы C0___, MU0___, EPS0___, PI___; макросы возбуждения электрона ELECTRON_Q___, ELECTRON_M___
TmcLibError.h Класс CTmcLibError — хранение и передача сообщения об ошибке (методы PutErrorMessage, IsError, Clear, GetErrorMessage)
Tmcgrviw.h Строковые имена типов блоков (CTMCRTH_INDANBLCK_*) и числовые коды типов (CTMCRTH_BLCKNTYPE_*) — общий заголовок, править нельзя
MFC (CString, CWnd) Строки и базовый класс окна
PREPR (prepr1.h) Препроцессор .tpl через функцию-обёртку MainPrepr()

_real в текущей сборке = floattyperth.h активен #define _PREC_FLOAT).

Тип значения узла _ELEM_VAL_RTH

_ELEM_VAL_RTH — тип хранимого значения напряжения в узле. По умолчанию _ELEM_VAL_RTH_REAL равен _real. Альтернатива _ELEM_VAL_RTH_INT (целочисленное представление с множителем 2^20) в текущей сборке не активна.


4. Свободные (нечленские) функции

void MainPrepr( CString csTplFileNamePrepr, CString csTplFileName, CString csCurrentPath, CTmcLibError &cError )

Объявлена в: TmcRTH_Indan.h. Что делает: обёртка над препроцессором PREPR. Запускает развёртывание входного шаблона csTplFileName (директивы #define/#include, удаление комментариев) и записывает результат во временный файл csTplFileNamePrepr.

Параметр Тип Назначение
csTplFileNamePrepr CString имя выходного (развёрнутого) временного файла
csTplFileName CString имя исходного .tpl-шаблона
csCurrentPath CString текущий каталог (для разрешения #include)
cError CTmcLibError& приёмник ошибок (out)

Ошибки: сообщение об ошибке кладётся в cError.

Функции управления глобальным шагом DELTA_T (объявлены в TmcRTH_IndanParam.h)

Глобальные функции работы с механическим шагом по времени (флаг и значение хранятся глобально, вне класса):

Функция Назначение
void SetDeltaT( double dDeltaT1 ) задать значение DELTA_T (число)
void SetDeltaT( char *lpszDeltaT ) задать DELTA_T из строки
double GetDeltaT( void ) получить текущее значение DELTA_T
BOOL IsDeltaTDefine( void ) определён ли DELTA_T
void SwitchDeltaT( void ) переключить флаг определённости DELTA_T

5. Класс CTmcRTH_Indan — главный фасад чтения .tpl

Назначение: верхнеуровневый интерфейс библиотеки. Открывает .tpl-файл, прогоняет его через PREPR в временный файл, ищет и читает секции (#PARM, #TOPOLOGY, #LINK_LIST, #OUTPUT) для заданного шага (#STEP), отдаёт наружу параметры, топологию и настройки вывода. Заголовок: src/Include/TmcRTH_Indan.h Зависит от: TmcLibError.h, TmcRTH_IndanParam.h, TmcRTH_IndanOutput.h, TmcRTH_IndanTopology.h, PREPR.

Важные константы (макросы) заголовка

Макрос Значение Назначение
CTMCRTH_INDANSBUF 30000 размер буфера для строковых операций
CTMCRTH_INDANPREPRFNA "~$Prepr$~" суффикс имени временного файла после препроцессора
CTMCRTH_INDAN_LINELEN 20000 максимальная длина читаемой строки
CTMCRTH_INDANMET_PROGRAM "#TMC_RT_H" маркер программы в начале файла
CTMCRTH_INDANMET_EOF "#EOF" маркер конца файла
CTMCRTH_INDANMET_STEP / _ENDSTEP "#STEP" / "#END_STEP" границы секции шага
CTMCRTH_INDANMET_PARAM / _ENDPARAM "#PARM" / "#END_PARM" границы секции параметров
CTMCRTH_INDANMET_TOPOLOGY / _ENDTOPOLOGY "#TOPOLOGY" / "#END_TOPOLOGY" границы секции топологии
CTMCRTH_INDANMET_LINKLIST / _ENDLINK "#LINK_LIST" / "#END_LINK" границы секции связей
CTMCRTH_INDANMET_OUTPUT / _ENDOUTPUT "#OUTPUT" / "#END_OUTPUT" границы секции вывода
CTMCRTH_INDANMET_BLOCK / _ENDBLOCK "BLOCK " / "END_B" границы описания одного блока
CTMCRTH_INDANMET_LINK "T " маркер строки связи

Поля (приватные)

Поле Тип Назначение
cTopology CTmcRTH_IndanTopology топология (список блоков) текущего шага
cParam CTmcRTH_IndanParam глобальные параметры расчёта
cOut CTmcRTH_IndanOutput настройки вывода
cError CTmcLibError накопитель ошибок
nStep int номер текущего шага
pfPrepr FILE* дескриптор временного (развёрнутого) файла
csCurrentPath CString каталог исходного .tpl
csTplFileName CString имя исходного .tpl
csTplFileNamePrepr CString имя временного файла после PREPR

Конструктор / деструктор

CTmcRTH_Indan();          // обнуляет поля, очищает ошибку
virtual ~CTmcRTH_Indan(); // вызывает DeleteData() (удаляет временный файл)

Публичные методы

void SetTplFileName( CString csFileName ) и void SetTplFileName( char *pszFileName )

Что делает: задаёт имя входного .tpl, проверяет, что файл открывается, определяет текущий каталог и запускает PREPR (создаёт временный развёрнутый файл). Как работает: DeleteData()fopen(csFileName,"r") (проверка) → SetCurrentPath() → формирует csTplFileNamePrepr = имя + CTMCRTH_INDANPREPRFNAMakePreprFile(). Ошибки: «can't open file …», «very long file name …» — в cError.

void ReadData( CString csFileName, int nStepNum )

Что делает: полностью читает данные шага nStepNum из файла csFileName (задаёт имя, находит шаг, читает все секции).

Параметр Тип Назначение
csFileName CString имя .tpl
nStepNum int номер шага (с какого #STEP читать)

void SetStepNumber( int nStep1 )

Что делает: устанавливает номер текущего шага.

void ReadParamSection(), void ReadTopologySection(), void ReadLinkListSection(), void ReadOutputSection()

Что делают: читают соответствующую секцию текущего шага из временного файла. Внутренне находят границы секции по маркерам (FindSection) и передают содержимое в cParam.Read(), cTopology.Read(), cTopology.ReadLink(), cOut.Read().

int GetNStepMax( void ) и int GetNStepMax( CString csFileName )

Что делает: возвращает количество шагов (#STEP) в файле. Перегрузка со строкой предварительно задаёт файл. Возвращает: число шагов.

Геттеры параметров и результатов

Метод Возвращает Смысл
int GetnStep( void ) int номер текущего шага
int GetnBlock( void ) int число блоков в топологии
void GetXYMinMax( double&, double&, double&, double& ) границы области Xmin,Xmax,Ymin,Ymax (out-параметры)
void GetnXnY( int&, int& ) число узлов сетки по X и Y
double dGetDelta( void ) double шаг сетки Delta
double dGetdT( void ) double шаг по времени
double dGetTmin( void ) double начальное время
int nGetTmax( void ) int конечный отсчёт времени
CTmcRTH_IndanParam& GetParam( void ) ссылка объект параметров
CTmcRTH_IndanTopology& GetTopology( void ) ссылка объект топологии
CTmcRTH_IndanOutput* GetOutput( void ) указатель объект вывода
CString GetCurrentPath( void ) CString каталог .tpl
CString GetTopologyFileName( void ) CString имя файла топологии
BOOL IsDataRead( void ) BOOL прочитаны ли данные

Обработка ошибок

Метод Назначение
BOOL IsError( void ) есть ли ошибка
CString GetErrorMessage( void ) текст ошибки

Флаги вывода (делегируются в cOut)

void OnOffSoundEffects(), void OnOffFieldOutput(), void OnOffFieldOutput1(), void OnOffFieldOutputU(), void OnOffSinchronizationFieldOutput() — переключают соответствующие флаги вывода (звук, поле, поле-1, поле-U, синхронный вывод поля).

CTmcLibError WriteFileForMaple( CString csFileName, CString csFileNameData, double dHeight, double dRolikR1, double dRolikR2, double dStatorR1, double dStatorR2, double dMagnMomP ) (+ перегрузка с char*)

Что делает: записывает файл для системы Maple (экспорт геометрии/данных).

Параметр Тип Назначение
csFileName CString/char* имя выходного файла Maple
csFileNameData CString/char* имя файла с данными
dHeight double высота структуры
dRolikR1, dRolikR2 double радиусы «ролика» (внутр./внешн.)
dStatorR1, dStatorR2 double радиусы статора (внутр./внешн.)
dMagnMomP double магнитный момент

Возвращает: CTmcLibError с результатом.

Приватные методы (внутренняя кухня)

MakePreprFile() (запуск PREPR), OpenPreprFile()/ClosePreprFile() (работа с временным файлом), FindSection()/FindSection(char*,char*) (поиск границ секции), FindStep(int) (позиционирование на шаг), CalcNStepMax() (подсчёт шагов), GetLine()/GetLineSection()/GetBlock() (построчное чтение), del_blanks() (удаление пробелов), SetCurrentPath(), DeleteData().


6. Класс CTmcRTH_IndanParam — глобальные параметры расчёта

Назначение: хранит глобальные параметры расчётной области и единицы измерения; пересчитывает узлы сетки (номер узла координаты). Заголовок: src/Include/TmcRTH_IndanParam.h Зависит от: typerth.h, TmcLibError.h.

Единицы измерения (макросы заголовка)

Для каждой величины задана пара «строковый идентификатор + строковое имя единицы + числовой коэффициент перевода в СИ»:

Группа ID Единицы (имя → коэффициент)
Длина LONG_UNIT m→1, cm→0.01, mm→0.001
Время TIME_UNIT s→1, ms→1e-3, mks→1e-6, ns→1e-9, ps→1e-12
Угол ANGLE_UNIT radian→1, gradus→π/180
Частота FREQ_UNIT Hz→1, kHz→1e3, MHz→1e6, GHz→1e9
Магн. индукция B_UNIT Tl→1, mTl→1e-3, mkTl→1e-6
Объёмная концентрация N_UNIT m3→1, cm3→1e-6, mm3→1e-9

Идентификаторы значений: FREQ, DELTA, TIME, X_MIN, X_MAX, Y_MIN, Y_MAX, HEIGHT, DELTA_T_MECHANICAL.

Поля (публичные)

Поле Тип Назначение
rDelta double шаг сетки (Δx = Δy)
rFreq double частота
rHeight double высота структуры
rt double время
rXmin, rXmax, rYmin, rYmax double границы прямоугольной области
rTmin, rTmax double временной интервал
rDeltaTMechanical double механический шаг по времени
csLongUnitcsNUnit CString имена выбранных единиц
rLongUnitrNUnit double коэффициенты перевода единиц в СИ
cError CTmcLibError накопитель ошибок

Методы

void Read( CString &csCh, CTmcLibError &cError1 )

Что делает: разбирает текст секции #PARM и заполняет поля. Внутренне распознаёт идентификаторы и вызывает приватные ReadDelta, ReadFreq, ReadTime, ReadXmin/Xmax/Ymin/Ymax, ReadHeight, ReadDeltaTMechanical, а также Read*Unit.

void IsCorrectly( CTmcLibError &cError1 )

Что делает: проверяет согласованность параметров; пересчитывает rXmax/rYmax так, чтобы они укладывались в целое число шагов Delta (rXmax = rXmin + CalcnX()*rDelta).

int CalcnX( void ) / int CalcnY( void )

Что делает: число узлов сетки по осям. Как работает: nX = (int)((Xmax−Xmin)/Delta)+1 (то же для Y). При |Delta| < FLT_MIN возвращает 0 (защита от деления на ноль). Возвращает: число узлов (int).

int CalcnNodeGlobal( double x, double y )

Что делает: переводит координаты (x,y) в глобальный номер узла сетки. Как работает: точка зажимается в границы области; индекс = iy*nX + ix, где ix, iy — округлённые индексы по Delta (с учётом крайних половин-ячеек).

Параметр Тип Назначение Допустимые значения
x double координата X любое вещественное (зажимается в [Xmin,Xmax])
y double координата Y любое вещественное (зажимается в [Ymin,Ymax])

Возвращает: глобальный номер узла (≥0).

int CalcnNodeGlobalFM( double x, double y )

То же, что CalcnNodeGlobal, но с другим смещением границы (1.5*Delta вместо 0.5*Delta).

int CalcnNodeGlobalNorm( double x, double y )

Что делает: как CalcnNodeGlobal, но если точка ближе 2·Delta к границе области — возвращает −1 (точка не в «нормальной» внутренней зоне). Возвращает: номер узла или −1.

double CalcX( int nNumber ) / double CalcY( int nNumber )

Что делает: обратное преобразование — координата узла по его глобальному номеру. Как работает: nX=(int)((Xmax−Xmin)/Delta)+1; CalcX: остаток nNumber mod nX, координата Xmin+ix*Delta; CalcY: целое nNumber/nX, координата Ymin+iy*Delta.

BOOL IsnInRegion( int n ) / BOOL IsnInRegion( _real x, _real y )

Что делает: проверяет, попадает ли узел (по номеру или по координатам) в сетку [0, nX*nY). Возвращает: TRUE/FALSE.

Геттеры

double dGetDelta(), double dGetdT(), double dGetTmin(), int nGetTmax(), double dGetHeight(), double rGetLongUnit(), CString csGetLongUnit(), void GetXYMinMax(double&,double&,double&,double&).

CTmcRTH_IndanParam& operator=( CTmcRTH_IndanParam& cParam )

Копирующее присваивание (все поля).

Приватные методы

Read*Unit (разбор единиц), Read* (разбор отдельных параметров), Search_1Param() (поиск значения по идентификатору в строке), expr_del_Blanks2() (удаление пробелов в выражении), DeleteData().


7. Класс CTmcRTH_IndanTopology — топология (обёртка над списком блоков)

Назначение: связывает список блоков CTmcRTH_BlockList с параметрами CTmcRTH_IndanParam; читает секцию топологии и секцию связей. Заголовок: src/Include/TmcRTH_IndanTopology.h Зависит от: TmcRTH_BolckList.h, TmcRTH_IndanParam.h.

Поля (приватные)

Поле Тип Назначение
pcParam CTmcRTH_IndanParam* указатель на внешние параметры
cBlockList CTmcRTH_BlockList голова списка блоков

Методы

Метод Что делает
void Read( CString &csCh, CTmcLibError &cError ) разбирает секцию #TOPOLOGY, наполняет список блоков
void ReadLink( CString &csCh, CTmcLibError &cError ) разбирает секцию #LINK_LIST (связи блоков, строки T)
void IsCorrectly( CTmcLibError &cError ) проверка корректности всех блоков
void IsCorrectlyLink( CTmcLibError &cError ) проверка корректности связей
void SetParam( CTmcRTH_IndanParam *pcParam1 ) задать указатель на параметры
CTmcRTH_IndanParam* GetpParam( void ) получить указатель на параметры
CTmcRTH_BlockList* GetBlockList( void ) голова списка блоков
int GetBlockNumber( void ) число блоков
BOOL IsDataRead( void ) прочитаны ли данные
void AddPathForFile( CString &csCurrentPath ) дописать путь каталога к именам файлов в блоках
operator= копирующее присваивание
void DeleteData( void ) очистка

8. Класс CTmcRTH_BlockList — список блоков-примитивов топологии

Назначение: односвязный список «блоков» — геометрических примитивов планарной структуры (прямоугольник, окружность, многоугольник, распределение eps из файла, вход/возбуждение). Каждый узел хранит геометрию, тип и текстовые выражения свойств среды (eps, mu, потери, скорости и т.д.). Читает описание блока из текста, проверяет корректность, умеет сохранять/загружать. Заголовок: src/Include/TmcRTH_BolckList.h Зависит от: TmcLibError.h, typerth.h, TmcRTH_IndanParam.h. Имена и коды типов блоков берутся из Tmcgrviw.h.

Типы блоков (строковые имена, из Tmcgrviw.h)

Группа Макрос → строка
Прямоугольники RECT_STAT, RECT_STAT_N, RECT_STAT_B, RECT_STAT_Y, RECT_MOVE
Окружности CIRCLE_STAT, CIRCLE_STAT_N, CIRCLE_STAT_B, CIRCLE_STAT_Y, CIRCLE_MOVE
Многоугольники POLYGON_STAT, POLYGON_STAT_N, POLYGON_STAT_B, POLYGON_STAT_Y, POLYGON_MOVE, точка многоугольника L
Из файла FILE, FILE_N, FILE_B, FILE_Y
Входы INPUT_X, INPUT_Y
Подтипы среды MAGNETIC, METAL, ABSORBER

Суффиксы: _STAT — статический блок, _N/_B/_Y — варианты задания (см. реализацию Read*StatN/B), _MOVE — движущийся блок (есть скорости Vx,Vy,W).

Числовые коды типа nType (из Tmcgrviw.h)

Код (макрос) Значение Смысл
CTMCRTH_BLCKNTYPE_EPS 0 диэлектрик (eps по выражению)
CTMCRTH_BLCKNTYPE_ABSORBER 100 поглотитель
CTMCRTH_BLCKNTYPE_METAL 101 металл
CTMCRTH_BLCKNTYPE_INPXLEFT 102 вход X слева >
CTMCRTH_BLCKNTYPE_INPXRIGHT 103 вход X справа <
CTMCRTH_BLCKNTYPE_INPYTOP 104 вход Y сверху V
CTMCRTH_BLCKNTYPE_INPYBOT 105 вход Y снизу ^
CTMCRTH_BLCKNTYPE_MAGNETIC 107 магнитная среда
CTMCRTH_BLCKNTYPE_ABSR_* 1..24 подтипы поглотителя (битовые маски граней)

Константы формата файла распределения eps (.eps)

TMC_RTH_EPSFILE_ID_ (сигнатура), TMC_RTH_EPSFILE_TYPE_, _Delta_, _XMIN_, _YMIN_, _NX_, _NY_, _NPoint_, _NAccur_, _NdFrmt_, _VlFrmt_ — ключи заголовка файла .eps. Также TMC_RTH_BLOCKLISTSAVE_BEGIN/_END — границы блока при сохранении; TMC_RTH_BLOCKLISTLOADBUFSIZE (20000) — размер буфера загрузки.

Поля (приватные)

Поле Тип Назначение
nBlock int номер блока
nType int числовой код типа (см. таблицу nType)
csBlock CString строковое имя типа блока
dX0, dY0 double опорная точка/центр блока
dXmin..dYmax double габаритный прямоугольник блока
dX, dY double* массивы координат вершин (для многоугольника)
nXY int размер массивов вершин
csEpsExpr CString выражение для диэлектрической проницаемости eps
csMuExpr CString выражение для магнитной проницаемости mu
csDzExpr, csDzExprOut CString выражения толщины Dz (вход/выход)
csHxExpr, csHyExpr CString выражения подмагничивающего поля Hx, Hy
csForceRo, csForceSigma, csForceConductivity CString выражения плотности, проводимости (силовая модель)
csFileNameMechanicalFreedomDegree CString имя файла механических степеней свободы
csVx, csVy CString линейная скорость по X/Y (для входа — амплитуда/фаза от t)
csW CString угловая скорость (для входа — eps)
nMemory int служебный счётчик памяти
pcNextBlockList CTmcRTH_BlockList* указатель на следующий блок
pszBufForReadTopology[20000] char[] буфер чтения топологии

Методы (публичные)

void Add( CString &csCh, CTmcLibError &cError, CTmcRTH_IndanParam *pcParam )

Что делает: разбирает текст одного блока csCh и добавляет новый узел в конец списка.

Параметр Тип Назначение
csCh CString& текст описания блока
cError CTmcLibError& приёмник ошибок
pcParam CTmcRTH_IndanParam* параметры (единицы, сетка) для пересчёта координат

void Add( CTmcRTH_BlockList &csCh )

Что делает: добавляет копию готового блока в конец списка (рекурсивно идёт до хвоста).

CTmcRTH_BlockList* FindBlock( int nBlock1 )

Что делает: ищет блок по номеру. Возвращает: указатель на блок или NULL.

CTmcRTH_BlockList* GetNext( void )

Возвращает: следующий блок списка (или NULL).

void SetLink( int iBuf, double x0, double y0, CTmcLibError &cError )

Что делает: задаёт связь блока с номером iBuf и его опорные координаты x0,y0.

void IsCorrectly( CTmcLibError &cError ) / void IsCorrectlyLink( CTmcLibError &cError )

Что делает: проверка геометрии/типа блока и корректности связей соответственно.

BOOL Save( CString &csBuffer ) / BOOL Save1( CString &csBuffer )

Что делает: сериализует список (Save1 — вариант формата) в строковый буфер. Возвращает: успех.

void Load( FILE **fp, CTmcLibError &cError )

Что делает: загружает список блоков из открытого файла.

void AddPathForFile( CString &csPath )

Что делает: дописывает путь каталога к именам файлов-распределений (.eps) в блоках типа FILE.

Сеттеры/геттеры

Геометрия: SetX0/SetY0/GetX0/GetY0, SetXmin/SetXmax/SetYmin/SetYmax + соответствующие Get*, double* GetpX(), double* GetpY(), int GetnXY(). Тип и номер: SetnType(int)/GetnType(), SetnBlock(int)/GetnBlock(), SetcsBlock(CString)/GetcsBlock(), GetBlockNumber(). Память: SetnMemory(int)/GetnMemory()/GetnMemoryAll(). Выражения: GetcsEpsExpr(), GetcsMuExpr(), GetcsDzExpr(), GetcsDzExprOut(), GetcsHxExpr(), GetcsHyExpr(), GetcsForceRo(), GetcsForceSigma(), GetcsForceConductivity(), GetcsFileNameMechanicalFreedomDegree(), GetcsVx(), GetcsVy(), GetcsW(). Прочее: operator=, DeleteData(), del_eol(char*).

Приватные методы (разбор конкретных типов)

Семейства ReadFileStat*, ReadRectStat*, ReadCircleStat*, ReadPolygonStat* (с вариантами N/B/_1), ReadRectMove/ReadCircleMove/ReadPolygonMove, ReadInputX/ReadInputY, общий Read(), ReadXY() (чтение пары координат), Search_1Param(), expr_del_Blanks2(), CalcEOL()/SkipEOL(), IsFullName(), AddCurrentPath(), AddFileEpsExtention().

Класс CTMCBlList объявлен другом (friend class CTMCBlList;) — это внешний класс (из вьюверов/ядра), которому открыт доступ к приватным полям.


9. Класс CTmcRTH_IndanOutput — настройки вывода

Назначение: хранит флаги и имена файлов вывода результатов расчёта (S-матрица, поле, топология, распределение поля), а также содержит объект интегрирования поля. Заголовок: src/Include/TmcRTH_IndanOutput.h Зависит от: TmcLibError.h, FieldIntegrated.h.

Идентификаторы секции вывода (макросы)

FILE (CTMCRTH_FILEOUT_ID), TOPOLOGY (_TOPOLOGYOUT_ID), FIELDS (_FIELDSOUT_ID), SMATRIX (_SMATRIXOUT_ID), FIELD_DISTRIBUTION (_FLDSDSTROUT_ID), FIELD_DISTRIBUTION_M (_FLDSDSMROUT_ID).

Поля (публичные)

Поле Тип Назначение
dTmin, dTmax double временной интервал вывода
dFreq double частота
dFreqUnit, dTimeUnit double коэффициенты единиц частоты и времени
bOutSMatrix BOOL выводить S-матрицу
bOutField, bOutField1, bOutFieldU BOOL выводить поле / поле-1 / поле-U
bOutTopology BOOL выводить топологию
bOutFieldSinchronization BOOL синхронный вывод поля
bSoundEffect BOOL звуковые эффекты
csFileName CString базовое имя выходного файла
csFileNameField, …Field1, …Field1Mod, …Field1Faz, …FieldU CString имена файлов поля (значение, модуль, фаза, U)
csFileNameTopology CString файл топологии
csFileNameSMatrix CString файл S-матрицы
csFileNameQ, csFileNameIx, csFileNameIy CString файлы заряда Q и токов Ix, Iy

Методы

Метод Что делает
void Read( CString &csCh, CTmcLibError &cError1 ) разбирает секцию #OUTPUT, заполняет флаги и имена файлов
void IsCorrectly( CTmcLibError &cError1 ) проверка настроек вывода
void AddPath( CString csPath ) дописать путь каталога к именам файлов
void SetFreqAndTimeUnit( double dFr, double dTim ) задать коэффициенты единиц частоты и времени
void PutSmatrix( void ) вывести S-матрицу (запись результата)
BOOL bIsFieldDistribution( void ) включён ли вывод распределения поля
CFieldIntegrated& GetFieldIntegrated( void ) доступ к объекту интегрирования поля
void OnOffSoundEffects(), OnOffFieldOutput(), OnOffFieldOutput1(), OnOffFieldOutputU(), OnOffSinchronizationFieldOutput() переключают соответствующие флаги
operator= копирующее присваивание
void DeleteData( void ) очистка

Приватные методы

ReadSmatrix(), ReadFileName(), ReadTopology(), ReadFields(), ReadFileDistr(), ReadFileDistrInMemory(), IsFullPath(), Search_1Param(), expr_del_Blanks2().


10. Класс CFieldIntegrated — интегрирование поля и диаграмма направленности

Назначение: накапливает (интегрирует) значения поля Ez по времени, вычисляет амплитуду и фазу на заданной частоте, сохраняет результат в файлы и экспортирует в файл диаграммы направленности (по излучателям вдоль границ области). Заголовок: src/Include/FieldIntegrated.h Зависит от: TmcLibError.h, TmcRTH_IndanParam.h.

Поля (приватные, ключевые)

Поле Тип Назначение
nTCurrent int текущий отсчёт времени
dT, dTCurrent double шаг и текущее время
dTmin, dTmax double интервал интегрирования
dFreq double частота интегрирования
dDelta double шаг сетки
dXmin, dYmin double начало координат области
nX, nY int размеры сетки
prAmp, prFaz _real* массивы накопленной амплитуды и фазы
prSin, prCos _real* вспомогательные массивы sin/cos для интегрирования в памяти
bIsIntegretedInMemory BOOL режим интегрирования в памяти
bIsBeginIntegreted BOOL началось ли интегрирование
bIsFieldDistribution BOOL включён вывод распределения поля
cParam CTmcRTH_IndanParam копия параметров
cError CTmcLibError накопитель ошибок
dDirPatXmin..dDirPatYmax double границы диаграммы направленности
csFileDirectPattern, csFileSin, csFileCos, csFileFaza, csFileAmplitude CString имена рабочих файлов

Методы (публичные)

void InitAllFile( int nX1, int nY1, double dDelta1, double dXmin1, double dYmin1, CTmcRTH_IndanParam& cParam1, double dT1 )

Что делает: инициализирует параметры сетки и рабочие файлы перед началом интегрирования.

Параметр Тип Назначение
nX1, nY1 int размеры сетки
dDelta1 double шаг сетки
dXmin1, dYmin1 double начало координат
cParam1 CTmcRTH_IndanParam& параметры расчёта
dT1 double шаг по времени

void Integrate( double dTCurrent1, int nTCurrent1, _real *prUNode1 )

Что делает: добавляет вклад текущего временного слоя поля prUNode1 в накапливаемые амплитуду/фазу.

Параметр Тип Назначение
dTCurrent1 double текущее время
nTCurrent1 int номер текущего отсчёта
prUNode1 _real* массив значений поля по узлам (размер nX*nY)

void ExportToDirectionalPattern( CTmcRTH_IndanParam &cParam1 )

Что делает: экспортирует накопленное поле в файл диаграммы направленности (амплитуда/фаза излучателей вдоль границ Xmin/Xmax/Ymin/Ymax).

Сеттеры/геттеры

SetnX/SetnY/SetnXnY, SetFreq/GetFreq, SetTmin/GetTmin, SetTmax/GetTmax, SetFile(...) (3 перегрузки), SetIntegrateInMemory(), BOOL bIsItegratedInMemory(), BOOL bIsFieldDistr(), CString GetcsDirectPatternFile(), void AddPath(CString), BOOL IsFullPath(), CTmcLibError& GetError(), CString GetErrorMessage(), BOOL IsError(), operator=, void DeleteData().

Приватные методы (внутренняя кухня)

Семейства AddDirectionalPatternFileXmin/Xmax/Ymin/Ymax (+ перегрузки с параметрами излучателя), ReadAmplitudaAndFazaX/Y, ReadAmplitudaAndFazaEz, MakeDirectionalPatternFile*, GetNumberOfEmittersAlongX/Y, IntegrateInMemory(), MakeFileAmplitudeAndFaza[FromMemory](), ReadParamFromFile() / ReadParamFrom1File(...), InitArrayForIntegrate(), InitFile(), SetDirectionalPatternParamDefault(), IsDirectionalPatternDataCorrect().


11. Класс CTmcRTH_Input — узлы возбуждения (вход)

Назначение: описывает «вход» (источник возбуждения) — набор узлов на границе со своим направлением и выражением сигнала. Внутренний вспомогательный класс. Заголовок: src/Include/TmcRTH_Input.h Зависит от: typerth.h, TmcRTH_InputNode.h.

Поля (приватные)

Поле Тип Назначение
pcInputNode CTmcRTH_InputNode* массив узлов входа
rX, rY _real координата входа (X — для типов −5/−6; Y — для −3/−4)
nNode int число узлов входа
nType int направление входа: −3 (X слева >), −4 (X справа <), −5 (Y сверху V), −6 (Y снизу ^)
csExpression CString выражение сигнала возбуждения

Конструктор/деструктор: CTmcRTH_Input(), ~CTmcRTH_Input(). Приватный DeleteData().

Коды nType совпадают с полем nType структуры узла диэлектрика sTmcRTHNodeDielOne (см. счётное ядро).


12. Класс CTmcRTH_InputNode — один узел возбуждения

Назначение: хранит мгновенное состояние одного узла возбуждения. Внутренний вспомогательный класс. Заголовок: src/Include/TmcRTH_InputNode.h Зависит от: typerth.h.

Поля (приватные)

Поле Тип Назначение
rUf _real падающее напряжение (falling voltage)
rUs _real рассеянное напряжение (scattering voltage)
rX, rY _real координаты узла
rT _real текущее время

Конструктор/деструктор: CTmcRTH_InputNode(), ~CTmcRTH_InputNode(). Других публичных методов нет.


13. Типичный сценарий использования

CTmcRTH_Indan cIndan;

// 1. Задать входной .tpl и прогнать препроцессор
cIndan.SetTplFileName( "task.tpl" );
if( cIndan.IsError() ) { /* cIndan.GetErrorMessage() */ }

// 2. Узнать число шагов
int nSteps = cIndan.GetNStepMax();

// 3. Прочитать данные нужного шага
cIndan.ReadData( "task.tpl", 0 );

// 4. Получить параметры, топологию, вывод
CTmcRTH_IndanParam   &p   = cIndan.GetParam();
CTmcRTH_IndanTopology&t   = cIndan.GetTopology();
CTmcRTH_IndanOutput  *out = cIndan.GetOutput();

int nX, nY;  cIndan.GetnXnY( nX, nY );
double delta = cIndan.dGetDelta();

// 5. Обойти блоки топологии
for( CTmcRTH_BlockList *b = t.GetBlockList(); b && b->GetnBlock()!=0; b = b->GetNext() )
{
    int    type    = b->GetnType();      // код типа (eps/metal/absorber/...)
    CString epsExpr = b->GetcsEpsExpr();  // выражение eps
}

The TMCIndan library — API documentation

TMC Suite package. A static library — reading the computation input template file (.tpl), storing the topology of a planar structure (primitive blocks), the computation parameters, the output section, as well as time-integrating the field and exporting it to a radiation pattern. All signatures are taken from the sources in src/libs/TMCIndan/ and the shared headers from src/Include/.


1. Purpose of the library

TMCIndan is a static library (StaticLibrary) linked by the compute kernels PlanarRT_H and PlanarRT_X (see CLAUDE.md, the "Library dependencies" section). Its task is to turn the text computation input file (.tpl) into an object model of the computational task:

  • launching the PREPR preprocessor over the .tpl (creating a temporary expanded file);
  • parsing the sections of the input file: parameters (#PARM), topology (#TOPOLOGY), the block link list (#LINK_LIST), output (#OUTPUT), steps (#STEP);
  • storing the topology as a singly linked list of primitive blocks (rectangles, circles, polygons, eps-distribution files, inputs/excitations), each with its own expression for the permittivity, permeability, losses, etc.;
  • storing the global parameters of the computation (units, the grid Delta, the area boundaries Xmin..Ymax, the frequency, the time, the height);
  • storing the output settings (output file names, flags for outputting the S-matrix, the field, the topology);
  • integrating the field over time (accumulating the amplitude and phase of Ez) and exporting it to a radiation-pattern file.

The name "Indan" (induced currents / "indan blocks") and part of the applied semantics belong to the project's scientific model. The computation math must not be edited (see CLAUDE.md). What is documented here is the programming interface, not the physical meaning of the formulas.


2. Source location and build composition

Sources: src/libs/TMCIndan/. Headers: src/Include/ (included as <TmcRTH_*.h>). The build project is TMCIndan.vcxproj (type StaticLibrary, Win32/x64 configurations).

The build contains 8 .cpp files:

.cpp file Class / contents Header
TmcRTH_Indan.cpp CTmcRTH_Indan — the main facade: opening the .tpl, launching PREPR, reading the sections by step TmcRTH_Indan.h
TmcRTH_IndanParam.cpp CTmcRTH_IndanParam — the global computation parameters, units, grid nodes TmcRTH_IndanParam.h
TmcRTH_IndanTopology.cpp CTmcRTH_IndanTopology — a wrapper over the block list and the parameters TmcRTH_IndanTopology.h
TmcRTH_BolckList.cpp CTmcRTH_BlockList — the singly linked list of primitive topology blocks TmcRTH_BolckList.h
TmcRTH_IndanOutput.cpp CTmcRTH_IndanOutput — the output settings and file names TmcRTH_IndanOutput.h
FieldIntegrated.cpp CFieldIntegrated — time-integration of the field, export to a radiation pattern FieldIntegrated.h
TmcRTH_Input.cpp CTmcRTH_Input — the excitation nodes (input), an internal class TmcRTH_Input.h
TmcRTH_InputNode.cpp CTmcRTH_InputNode — one excitation node, an internal class TmcRTH_InputNode.h

The directory src/Include/Indan/ holds older copies of some of these headers (TmcRTH_Indan.h, TmcRTH_IndanOutput.h, TmcRTH_IndanTopology.h, TmcRTH_Input.h, TmcRTH_InputNode.h, FieldIntegrated.h, plus TmcRTHNodeDiel.h, TmcRTHRectNode.h, Pl_iofor1.h). They are not part of the TMCIndan.vcxproj build: the project includes the headers from ..\..\INCLUDE\. The files TmcRTHNodeDiel.h, TmcRTHRectNode.h, Pl_iofor1.h belong to the compute-kernel implementation (the classes inherit CWnd) and are not described here as part of the library.


3. Base types and dependencies

The library relies on shared headers and types:

Header What it provides
typerth.h The _real type (float or double depending on the _PREC_FLOAT/_PREC_DOUBLE macro); _ELEM_VAL_RTH (= _real); the physical constants C0___, MU0___, EPS0___, PI___; the electron-excitation macros ELECTRON_Q___, ELECTRON_M___
TmcLibError.h The CTmcLibError class — storing and passing an error message (the methods PutErrorMessage, IsError, Clear, GetErrorMessage)
Tmcgrviw.h The string names of the block types (CTMCRTH_INDANBLCK_*) and the numeric type codes (CTMCRTH_BLCKNTYPE_*) — a shared header, must not be edited
MFC (CString, CWnd) Strings and the base window class
PREPR (prepr1.h) The .tpl preprocessor via the wrapper function MainPrepr()

_real in the current build = float (in typerth.h the #define _PREC_FLOAT is active).

The node value type _ELEM_VAL_RTH

_ELEM_VAL_RTH is the type of the stored voltage value at a node. By default _ELEM_VAL_RTH_REAL equals _real. The alternative _ELEM_VAL_RTH_INT (an integer representation with the factor 2^20) is not active in the current build.


4. Free (non-member) functions

void MainPrepr( CString csTplFileNamePrepr, CString csTplFileName, CString csCurrentPath, CTmcLibError &cError )

Declared in: TmcRTH_Indan.h. What it does: a wrapper over the PREPR preprocessor. It launches the expansion of the input template csTplFileName (the #define/#include directives, comment removal) and writes the result into the temporary file csTplFileNamePrepr.

Parameter Type Purpose
csTplFileNamePrepr CString the name of the output (expanded) temporary file
csTplFileName CString the name of the source .tpl template
csCurrentPath CString the current directory (to resolve #include)
cError CTmcLibError& the error receiver (out)

Errors: the error message is placed into cError.

Functions controlling the global step DELTA_T (declared in TmcRTH_IndanParam.h)

Global functions for working with the mechanical time step (the flag and the value are stored globally, outside the class):

Function Purpose
void SetDeltaT( double dDeltaT1 ) set the value of DELTA_T (a number)
void SetDeltaT( char *lpszDeltaT ) set DELTA_T from a string
double GetDeltaT( void ) get the current value of DELTA_T
BOOL IsDeltaTDefine( void ) whether DELTA_T is defined
void SwitchDeltaT( void ) toggle the definiteness flag of DELTA_T

These functions are also declared in typerth.h; their implementation may be in the compute kernel. The purpose of the "mechanical" step relates to the moving-block model (RECT_MOVE, CIRCLE_MOVE).


5. The CTmcRTH_Indan class — the main .tpl reading facade

Purpose: the top-level interface of the library. It opens the .tpl file, runs it through PREPR into a temporary file, finds and reads the sections (#PARM, #TOPOLOGY, #LINK_LIST, #OUTPUT) for a given step (#STEP), and exposes the parameters, topology and output settings. Header: src/Include/TmcRTH_Indan.h Depends on: TmcLibError.h, TmcRTH_IndanParam.h, TmcRTH_IndanOutput.h, TmcRTH_IndanTopology.h, PREPR.

Important header constants (macros)

Macro Value Purpose
CTMCRTH_INDANSBUF 30000 the buffer size for string operations
CTMCRTH_INDANPREPRFNA "~$Prepr$~" the suffix of the temporary file name after the preprocessor
CTMCRTH_INDAN_LINELEN 20000 the maximum length of a read line
CTMCRTH_INDANMET_PROGRAM "#TMC_RT_H" the program marker at the file start
CTMCRTH_INDANMET_EOF "#EOF" the end-of-file marker
CTMCRTH_INDANMET_STEP / _ENDSTEP "#STEP" / "#END_STEP" the step-section boundaries
CTMCRTH_INDANMET_PARAM / _ENDPARAM "#PARM" / "#END_PARM" the parameters-section boundaries
CTMCRTH_INDANMET_TOPOLOGY / _ENDTOPOLOGY "#TOPOLOGY" / "#END_TOPOLOGY" the topology-section boundaries
CTMCRTH_INDANMET_LINKLIST / _ENDLINK "#LINK_LIST" / "#END_LINK" the link-section boundaries
CTMCRTH_INDANMET_OUTPUT / _ENDOUTPUT "#OUTPUT" / "#END_OUTPUT" the output-section boundaries
CTMCRTH_INDANMET_BLOCK / _ENDBLOCK "BLOCK " / "END_B" the boundaries of a single block description
CTMCRTH_INDANMET_LINK "T " the link-line marker

Fields (private)

Field Type Purpose
cTopology CTmcRTH_IndanTopology the topology (block list) of the current step
cParam CTmcRTH_IndanParam the global computation parameters
cOut CTmcRTH_IndanOutput the output settings
cError CTmcLibError the error accumulator
nStep int the current step number
pfPrepr FILE* the handle of the temporary (expanded) file
csCurrentPath CString the directory of the source .tpl
csTplFileName CString the name of the source .tpl
csTplFileNamePrepr CString the name of the temporary file after PREPR

Constructor / destructor

CTmcRTH_Indan();          // zeroes the fields, clears the error
virtual ~CTmcRTH_Indan(); // calls DeleteData() (deletes the temporary file)

Public methods

void SetTplFileName( CString csFileName ) and void SetTplFileName( char *pszFileName )

What it does: sets the input .tpl name, checks that the file can be opened, determines the current directory and launches PREPR (creates the temporary expanded file). How it works: DeleteData()fopen(csFileName,"r") (check) → SetCurrentPath() → forms csTplFileNamePrepr = the name + CTMCRTH_INDANPREPRFNAMakePreprFile(). Errors: "can't open file …", "very long file name …" — in cError.

void ReadData( CString csFileName, int nStepNum )

What it does: fully reads the data of step nStepNum from the file csFileName (sets the name, finds the step, reads all sections).

Parameter Type Purpose
csFileName CString the .tpl name
nStepNum int the step number (from which #STEP to read)

void SetStepNumber( int nStep1 )

What it does: sets the current step number.

void ReadParamSection(), void ReadTopologySection(), void ReadLinkListSection(), void ReadOutputSection()

What they do: read the corresponding section of the current step from the temporary file. Internally they find the section boundaries by markers (FindSection) and pass the contents to cParam.Read(), cTopology.Read(), cTopology.ReadLink(), cOut.Read().

int GetNStepMax( void ) and int GetNStepMax( CString csFileName )

What it does: returns the number of steps (#STEP) in the file. The overload with a string sets the file first. Returns: the number of steps.

Parameter and result getters

Method Returns Meaning
int GetnStep( void ) int the current step number
int GetnBlock( void ) int the number of blocks in the topology
void GetXYMinMax( double&, double&, double&, double& ) the area boundaries Xmin,Xmax,Ymin,Ymax (out parameters)
void GetnXnY( int&, int& ) the number of grid nodes along X and Y
double dGetDelta( void ) double the grid step Delta
double dGetdT( void ) double the time step
double dGetTmin( void ) double the initial time
int nGetTmax( void ) int the final time sample
CTmcRTH_IndanParam& GetParam( void ) reference the parameters object
CTmcRTH_IndanTopology& GetTopology( void ) reference the topology object
CTmcRTH_IndanOutput* GetOutput( void ) pointer the output object
CString GetCurrentPath( void ) CString the .tpl directory
CString GetTopologyFileName( void ) CString the topology file name
BOOL IsDataRead( void ) BOOL whether the data has been read

Error handling

Method Purpose
BOOL IsError( void ) whether there is an error
CString GetErrorMessage( void ) the error text

Output flags (delegated to cOut)

void OnOffSoundEffects(), void OnOffFieldOutput(), void OnOffFieldOutput1(), void OnOffFieldOutputU(), void OnOffSinchronizationFieldOutput() — toggle the corresponding output flags (sound, field, field-1, field-U, synchronous field output).

CTmcLibError WriteFileForMaple( CString csFileName, CString csFileNameData, double dHeight, double dRolikR1, double dRolikR2, double dStatorR1, double dStatorR2, double dMagnMomP ) (+ a char* overload)

What it does: writes a file for the Maple system (export of geometry/data).

Parameter Type Purpose
csFileName CString/char* the Maple output file name
csFileNameData CString/char* the data file name
dHeight double the structure height
dRolikR1, dRolikR2 double the "roller" radii (inner/outer)
dStatorR1, dStatorR2 double the stator radii (inner/outer)
dMagnMomP double the magnetic moment

Returns: a CTmcLibError with the result.

Private methods (internal)

MakePreprFile() (launching PREPR), OpenPreprFile()/ClosePreprFile() (working with the temporary file), FindSection()/FindSection(char*,char*) (finding section boundaries), FindStep(int) (positioning at a step), CalcNStepMax() (counting steps), GetLine()/GetLineSection()/GetBlock() (line-by-line reading), del_blanks() (whitespace removal), SetCurrentPath(), DeleteData().


6. The CTmcRTH_IndanParam class — the global computation parameters

Purpose: stores the global parameters of the computation area and the units; recomputes grid nodes (node number coordinates). Header: src/Include/TmcRTH_IndanParam.h Depends on: typerth.h, TmcLibError.h.

Units (header macros)

For each quantity a triple "string identifier + string unit name + numeric factor to convert to SI" is defined:

Group ID Units (name → factor)
Length LONG_UNIT m→1, cm→0.01, mm→0.001
Time TIME_UNIT s→1, ms→1e-3, mks→1e-6, ns→1e-9, ps→1e-12
Angle ANGLE_UNIT radian→1, gradus→π/180
Frequency FREQ_UNIT Hz→1, kHz→1e3, MHz→1e6, GHz→1e9
Magnetic induction B_UNIT Tl→1, mTl→1e-3, mkTl→1e-6
Volume concentration N_UNIT m3→1, cm3→1e-6, mm3→1e-9

Value identifiers: FREQ, DELTA, TIME, X_MIN, X_MAX, Y_MIN, Y_MAX, HEIGHT, DELTA_T_MECHANICAL.

Fields (public)

Field Type Purpose
rDelta double the grid step (Δx = Δy)
rFreq double the frequency
rHeight double the structure height
rt double the time
rXmin, rXmax, rYmin, rYmax double the boundaries of the rectangular area
rTmin, rTmax double the time interval
rDeltaTMechanical double the mechanical time step
csLongUnitcsNUnit CString the names of the chosen units
rLongUnitrNUnit double the unit-to-SI conversion factors
cError CTmcLibError the error accumulator

Methods

void Read( CString &csCh, CTmcLibError &cError1 )

What it does: parses the text of the #PARM section and fills the fields. Internally it recognizes the identifiers and calls the private ReadDelta, ReadFreq, ReadTime, ReadXmin/Xmax/Ymin/Ymax, ReadHeight, ReadDeltaTMechanical, as well as Read*Unit.

void IsCorrectly( CTmcLibError &cError1 )

What it does: checks the consistency of the parameters; recomputes rXmax/rYmax so that they fit into a whole number of Delta steps (rXmax = rXmin + CalcnX()*rDelta).

int CalcnX( void ) / int CalcnY( void )

What it does: the number of grid nodes along the axes. How it works: nX = (int)((Xmax−Xmin)/Delta)+1 (the same for Y). When |Delta| < FLT_MIN it returns 0 (protection against division by zero). Returns: the number of nodes (int).

int CalcnNodeGlobal( double x, double y )

What it does: converts the coordinates (x,y) into a global grid-node number. How it works: the point is clamped to the area boundaries; the index = iy*nX + ix, where ix, iy are the indices rounded by Delta (accounting for the boundary half-cells).

Parameter Type Purpose Allowed values
x double the X coordinate any real (clamped to [Xmin,Xmax])
y double the Y coordinate any real (clamped to [Ymin,Ymax])

Returns: the global node number (≥0).

int CalcnNodeGlobalFM( double x, double y )

The same as CalcnNodeGlobal, but with a different boundary offset (1.5*Delta instead of 0.5*Delta).

int CalcnNodeGlobalNorm( double x, double y )

What it does: like CalcnNodeGlobal, but if the point is closer than 2·Delta to the area boundary — returns −1 (the point is not in the "normal" interior zone). Returns: the node number or −1.

double CalcX( int nNumber ) / double CalcY( int nNumber )

What it does: the reverse transformation — the node coordinate by its global number. How it works: nX=(int)((Xmax−Xmin)/Delta)+1; CalcX: the remainder nNumber mod nX, the coordinate Xmin+ix*Delta; CalcY: the integer nNumber/nX, the coordinate Ymin+iy*Delta.

BOOL IsnInRegion( int n ) / BOOL IsnInRegion( _real x, _real y )

What it does: checks whether a node (by number or by coordinates) falls within the grid [0, nX*nY). Returns: TRUE/FALSE.

Getters

double dGetDelta(), double dGetdT(), double dGetTmin(), int nGetTmax(), double dGetHeight(), double rGetLongUnit(), CString csGetLongUnit(), void GetXYMinMax(double&,double&,double&,double&).

CTmcRTH_IndanParam& operator=( CTmcRTH_IndanParam& cParam )

Copy assignment (all fields).

Private methods

Read*Unit (parsing units), Read* (parsing individual parameters), Search_1Param() (finding a value by identifier in a line), expr_del_Blanks2() (removing spaces in an expression), DeleteData().


7. The CTmcRTH_IndanTopology class — the topology (a wrapper over the block list)

Purpose: links the block list CTmcRTH_BlockList with the parameters CTmcRTH_IndanParam; reads the topology section and the link section. Header: src/Include/TmcRTH_IndanTopology.h Depends on: TmcRTH_BolckList.h, TmcRTH_IndanParam.h.

Fields (private)

Field Type Purpose
pcParam CTmcRTH_IndanParam* a pointer to the external parameters
cBlockList CTmcRTH_BlockList the head of the block list

Methods

Method What it does
void Read( CString &csCh, CTmcLibError &cError ) parses the #TOPOLOGY section, populates the block list
void ReadLink( CString &csCh, CTmcLibError &cError ) parses the #LINK_LIST section (block links, T lines)
void IsCorrectly( CTmcLibError &cError ) correctness check of all blocks
void IsCorrectlyLink( CTmcLibError &cError ) correctness check of the links
void SetParam( CTmcRTH_IndanParam *pcParam1 ) set the pointer to the parameters
CTmcRTH_IndanParam* GetpParam( void ) get the pointer to the parameters
CTmcRTH_BlockList* GetBlockList( void ) the head of the block list
int GetBlockNumber( void ) the number of blocks
BOOL IsDataRead( void ) whether the data has been read
void AddPathForFile( CString &csCurrentPath ) append the directory path to the file names in the blocks
operator= copy assignment
void DeleteData( void ) cleanup

8. The CTmcRTH_BlockList class — the list of primitive topology blocks

Purpose: a singly linked list of "blocks" — geometric primitives of a planar structure (rectangle, circle, polygon, eps distribution from a file, input/excitation). Each node stores the geometry, the type and the text expressions of the medium properties (eps, mu, losses, velocities, etc.). It reads a block description from text, checks correctness, and can save/load. Header: src/Include/TmcRTH_BolckList.h Depends on: TmcLibError.h, typerth.h, TmcRTH_IndanParam.h. The block-type names and codes are taken from Tmcgrviw.h.

Block types (string names, from Tmcgrviw.h)

Group Macro → string
Rectangles RECT_STAT, RECT_STAT_N, RECT_STAT_B, RECT_STAT_Y, RECT_MOVE
Circles CIRCLE_STAT, CIRCLE_STAT_N, CIRCLE_STAT_B, CIRCLE_STAT_Y, CIRCLE_MOVE
Polygons POLYGON_STAT, POLYGON_STAT_N, POLYGON_STAT_B, POLYGON_STAT_Y, POLYGON_MOVE, the polygon point L
From a file FILE, FILE_N, FILE_B, FILE_Y
Inputs INPUT_X, INPUT_Y
Medium subtypes MAGNETIC, METAL, ABSORBER

Suffixes: _STAT — a static block, _N/_B/_Y — variants of the definition (see the Read*StatN/B implementation), _MOVE — a moving block (has velocities Vx,Vy,W).

Numeric type codes nType (from Tmcgrviw.h)

Code (macro) Value Meaning
CTMCRTH_BLCKNTYPE_EPS 0 a dielectric (eps by expression)
CTMCRTH_BLCKNTYPE_ABSORBER 100 an absorber
CTMCRTH_BLCKNTYPE_METAL 101 metal
CTMCRTH_BLCKNTYPE_INPXLEFT 102 an X input on the left >
CTMCRTH_BLCKNTYPE_INPXRIGHT 103 an X input on the right <
CTMCRTH_BLCKNTYPE_INPYTOP 104 a Y input on the top V
CTMCRTH_BLCKNTYPE_INPYBOT 105 a Y input on the bottom ^
CTMCRTH_BLCKNTYPE_MAGNETIC 107 a magnetic medium
CTMCRTH_BLCKNTYPE_ABSR_* 1..24 absorber subtypes (bit masks of the absorbing sides)

Eps-distribution file format constants (.eps)

TMC_RTH_EPSFILE_ID_ (the signature), TMC_RTH_EPSFILE_TYPE_, _Delta_, _XMIN_, _YMIN_, _NX_, _NY_, _NPoint_, _NAccur_, _NdFrmt_, _VlFrmt_ — the header keys of the .eps file. Also TMC_RTH_BLOCKLISTSAVE_BEGIN/_END — the block boundaries when saving; TMC_RTH_BLOCKLISTLOADBUFSIZE (20000) — the load-buffer size.

Fields (private)

Field Type Purpose
nBlock int the block number
nType int the numeric type code (see the nType table)
csBlock CString the string name of the block type
dX0, dY0 double the reference point/center of the block
dXmin..dYmax double the bounding rectangle of the block
dX, dY double* the arrays of vertex coordinates (for a polygon)
nXY int the size of the vertex arrays
csEpsExpr CString the expression for the permittivity eps
csMuExpr CString the expression for the permeability mu
csDzExpr, csDzExprOut CString the expressions for the thickness Dz (input/output)
csHxExpr, csHyExpr CString the expressions for the magnetizing field Hx, Hy
csForceRo, csForceSigma, csForceConductivity CString the expressions for density, conductivity (the force model)
csFileNameMechanicalFreedomDegree CString the file name of the mechanical degrees of freedom
csVx, csVy CString the linear velocity along X/Y (for an input — the amplitude/phase of t)
csW CString the angular velocity (for an input — eps)
nMemory int a service memory counter
pcNextBlockList CTmcRTH_BlockList* a pointer to the next block
pszBufForReadTopology[20000] char[] the topology-reading buffer

Methods (public)

void Add( CString &csCh, CTmcLibError &cError, CTmcRTH_IndanParam *pcParam )

What it does: parses the text of a single block csCh and adds a new node to the end of the list.

Parameter Type Purpose
csCh CString& the block description text
cError CTmcLibError& the error receiver
pcParam CTmcRTH_IndanParam* the parameters (units, grid) for coordinate recomputation

void Add( CTmcRTH_BlockList &csCh )

What it does: adds a copy of a ready block to the end of the list (recursively going to the tail).

CTmcRTH_BlockList* FindBlock( int nBlock1 )

What it does: finds a block by number. Returns: a pointer to the block or NULL.

CTmcRTH_BlockList* GetNext( void )

Returns: the next block in the list (or NULL).

void SetLink( int iBuf, double x0, double y0, CTmcLibError &cError )

What it does: sets the link of the block numbered iBuf and its reference coordinates x0,y0.

void IsCorrectly( CTmcLibError &cError ) / void IsCorrectlyLink( CTmcLibError &cError )

What it does: checks the geometry/type of the block and the correctness of the links respectively.

BOOL Save( CString &csBuffer ) / BOOL Save1( CString &csBuffer )

What it does: serializes the list (Save1 — a format variant) into a string buffer. Returns: success.

void Load( FILE **fp, CTmcLibError &cError )

What it does: loads the block list from an open file.

void AddPathForFile( CString &csPath )

What it does: appends the directory path to the names of the distribution files (.eps) in blocks of type FILE.

Setters/getters

Geometry: SetX0/SetY0/GetX0/GetY0, SetXmin/SetXmax/SetYmin/SetYmax + the corresponding Get*, double* GetpX(), double* GetpY(), int GetnXY(). Type and number: SetnType(int)/GetnType(), SetnBlock(int)/GetnBlock(), SetcsBlock(CString)/GetcsBlock(), GetBlockNumber(). Memory: SetnMemory(int)/GetnMemory()/GetnMemoryAll(). Expressions: GetcsEpsExpr(), GetcsMuExpr(), GetcsDzExpr(), GetcsDzExprOut(), GetcsHxExpr(), GetcsHyExpr(), GetcsForceRo(), GetcsForceSigma(), GetcsForceConductivity(), GetcsFileNameMechanicalFreedomDegree(), GetcsVx(), GetcsVy(), GetcsW(). Other: operator=, DeleteData(), del_eol(char*).

Private methods (parsing specific types)

The families ReadFileStat*, ReadRectStat*, ReadCircleStat*, ReadPolygonStat* (with the N/B/_1 variants), ReadRectMove/ReadCircleMove/ReadPolygonMove, ReadInputX/ReadInputY, the common Read(), ReadXY() (reading a coordinate pair), Search_1Param(), expr_del_Blanks2(), CalcEOL()/SkipEOL(), IsFullName(), AddCurrentPath(), AddFileEpsExtention().

The class CTMCBlList is declared a friend (friend class CTMCBlList;) — it is an external class (from the viewers/kernel) given access to the private fields.


9. The CTmcRTH_IndanOutput class — the output settings

Purpose: stores the flags and file names for the computation-result output (S-matrix, field, topology, field distribution), and contains the field-integration object. Header: src/Include/TmcRTH_IndanOutput.h Depends on: TmcLibError.h, FieldIntegrated.h.

Output-section identifiers (macros)

FILE (CTMCRTH_FILEOUT_ID), TOPOLOGY (_TOPOLOGYOUT_ID), FIELDS (_FIELDSOUT_ID), SMATRIX (_SMATRIXOUT_ID), FIELD_DISTRIBUTION (_FLDSDSTROUT_ID), FIELD_DISTRIBUTION_M (_FLDSDSMROUT_ID).

Fields (public)

Field Type Purpose
dTmin, dTmax double the output time interval
dFreq double the frequency
dFreqUnit, dTimeUnit double the frequency and time unit factors
bOutSMatrix BOOL output the S-matrix
bOutField, bOutField1, bOutFieldU BOOL output the field / field-1 / field-U
bOutTopology BOOL output the topology
bOutFieldSinchronization BOOL synchronous field output
bSoundEffect BOOL sound effects
csFileName CString the base output file name
csFileNameField, …Field1, …Field1Mod, …Field1Faz, …FieldU CString the field file names (value, magnitude, phase, U)
csFileNameTopology CString the topology file
csFileNameSMatrix CString the S-matrix file
csFileNameQ, csFileNameIx, csFileNameIy CString the charge Q and currents Ix, Iy files

Methods

Method What it does
void Read( CString &csCh, CTmcLibError &cError1 ) parses the #OUTPUT section, fills the flags and file names
void IsCorrectly( CTmcLibError &cError1 ) check the output settings
void AddPath( CString csPath ) append the directory path to the file names
void SetFreqAndTimeUnit( double dFr, double dTim ) set the frequency and time unit factors
void PutSmatrix( void ) output the S-matrix (write the result)
BOOL bIsFieldDistribution( void ) whether field-distribution output is on
CFieldIntegrated& GetFieldIntegrated( void ) access to the field-integration object
void OnOffSoundEffects(), OnOffFieldOutput(), OnOffFieldOutput1(), OnOffFieldOutputU(), OnOffSinchronizationFieldOutput() toggle the corresponding flags
operator= copy assignment
void DeleteData( void ) cleanup

Private methods

ReadSmatrix(), ReadFileName(), ReadTopology(), ReadFields(), ReadFileDistr(), ReadFileDistrInMemory(), IsFullPath(), Search_1Param(), expr_del_Blanks2().


10. The CFieldIntegrated class — field integration and the radiation pattern

Purpose: accumulates (integrates) the field Ez values over time, computes the amplitude and phase at a given frequency, saves the result into files and exports it to a radiation-pattern file (by radiators along the area boundaries). Header: src/Include/FieldIntegrated.h Depends on: TmcLibError.h, TmcRTH_IndanParam.h.

Fields (private, key)

Field Type Purpose
nTCurrent int the current time sample
dT, dTCurrent double the step and the current time
dTmin, dTmax double the integration interval
dFreq double the integration frequency
dDelta double the grid step
dXmin, dYmin double the origin of the area
nX, nY int the grid sizes
prAmp, prFaz _real* the arrays of accumulated amplitude and phase
prSin, prCos _real* auxiliary sin/cos arrays for in-memory integration
bIsIntegretedInMemory BOOL the in-memory integration mode
bIsBeginIntegreted BOOL whether integration has begun
bIsFieldDistribution BOOL whether field-distribution output is on
cParam CTmcRTH_IndanParam a copy of the parameters
cError CTmcLibError the error accumulator
dDirPatXmin..dDirPatYmax double the radiation-pattern boundaries
csFileDirectPattern, csFileSin, csFileCos, csFileFaza, csFileAmplitude CString the working file names

Methods (public)

void InitAllFile( int nX1, int nY1, double dDelta1, double dXmin1, double dYmin1, CTmcRTH_IndanParam& cParam1, double dT1 )

What it does: initializes the grid parameters and the working files before starting integration.

Parameter Type Purpose
nX1, nY1 int the grid sizes
dDelta1 double the grid step
dXmin1, dYmin1 double the origin
cParam1 CTmcRTH_IndanParam& the computation parameters
dT1 double the time step

void Integrate( double dTCurrent1, int nTCurrent1, _real *prUNode1 )

What it does: adds the contribution of the current time layer of the field prUNode1 to the accumulated amplitude/phase.

Parameter Type Purpose
dTCurrent1 double the current time
nTCurrent1 int the current sample number
prUNode1 _real* the array of field values by node (size nX*nY)

void ExportToDirectionalPattern( CTmcRTH_IndanParam &cParam1 )

What it does: exports the accumulated field to a radiation-pattern file (the amplitude/phase of radiators along the boundaries Xmin/Xmax/Ymin/Ymax).

Setters/getters

SetnX/SetnY/SetnXnY, SetFreq/GetFreq, SetTmin/GetTmin, SetTmax/GetTmax, SetFile(...) (3 overloads), SetIntegrateInMemory(), BOOL bIsItegratedInMemory(), BOOL bIsFieldDistr(), CString GetcsDirectPatternFile(), void AddPath(CString), BOOL IsFullPath(), CTmcLibError& GetError(), CString GetErrorMessage(), BOOL IsError(), operator=, void DeleteData().

Private methods (internal)

The families AddDirectionalPatternFileXmin/Xmax/Ymin/Ymax (+ overloads with radiator parameters), ReadAmplitudaAndFazaX/Y, ReadAmplitudaAndFazaEz, MakeDirectionalPatternFile*, GetNumberOfEmittersAlongX/Y, IntegrateInMemory(), MakeFileAmplitudeAndFaza[FromMemory](), ReadParamFromFile() / ReadParamFrom1File(...), InitArrayForIntegrate(), InitFile(), SetDirectionalPatternParamDefault(), IsDirectionalPatternDataCorrect().

The exact physical normalization and integration formulas (sin/cos quadratures, the number of radiators) belong to the scientific model — they must not be changed.


11. The CTmcRTH_Input class — the excitation nodes (input)

Purpose: describes an "input" (an excitation source) — a set of nodes on the boundary with their own direction and signal expression. An internal auxiliary class. Header: src/Include/TmcRTH_Input.h Depends on: typerth.h, TmcRTH_InputNode.h.

Fields (private)

Field Type Purpose
pcInputNode CTmcRTH_InputNode* the array of input nodes
rX, rY _real the input coordinate (X — for types −5/−6; Y — for −3/−4)
nNode int the number of input nodes
nType int the input direction: −3 (X left >), −4 (X right <), −5 (Y top V), −6 (Y bottom ^)
csExpression CString the excitation-signal expression

Constructor/destructor: CTmcRTH_Input(), ~CTmcRTH_Input(). Private DeleteData().

The nType codes coincide with the nType field of the dielectric-node structure sTmcRTHNodeDielOne (see the compute kernel).


12. The CTmcRTH_InputNode class — one excitation node

Purpose: stores the instantaneous state of one excitation node. An internal auxiliary class. Header: src/Include/TmcRTH_InputNode.h Depends on: typerth.h.

Fields (private)

Field Type Purpose
rUf _real the falling voltage
rUs _real the scattering voltage
rX, rY _real the node coordinates
rT _real the current time

Constructor/destructor: CTmcRTH_InputNode(), ~CTmcRTH_InputNode(). There are no other public methods.


13. A typical usage scenario

CTmcRTH_Indan cIndan;

// 1. Set the input .tpl and run the preprocessor
cIndan.SetTplFileName( "task.tpl" );
if( cIndan.IsError() ) { /* cIndan.GetErrorMessage() */ }

// 2. Find out the number of steps
int nSteps = cIndan.GetNStepMax();

// 3. Read the data of the desired step
cIndan.ReadData( "task.tpl", 0 );

// 4. Get the parameters, topology, output
CTmcRTH_IndanParam   &p   = cIndan.GetParam();
CTmcRTH_IndanTopology&t   = cIndan.GetTopology();
CTmcRTH_IndanOutput  *out = cIndan.GetOutput();

int nX, nY;  cIndan.GetnXnY( nX, nY );
double delta = cIndan.dGetDelta();

// 5. Traverse the topology blocks
for( CTmcRTH_BlockList *b = t.GetBlockList(); b && b->GetnBlock()!=0; b = b->GetNext() )
{
    int    type    = b->GetnType();      // the type code (eps/metal/absorber/...)
    CString epsExpr = b->GetcsEpsExpr();  // the eps expression
}