Вьювер TMC_DN — диаграммы направленности, КНД и КИП

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

TMC_DN (tmc_dn.exe) строит диаграмму направленности (ДН) в дальней зоне по набору излучателей на плоскости и считает коэффициент направленного действия (КНД) и коэффициент использования поверхности (КИП). Исходные данные — файл излучателей .DAT. Обычно его пишет счётное ядро PlanarRT_H или PlanarRT_X: библиотека TMCIndan интегрирует поле на замкнутом контуре в ближней зоне и превращает каждую точку контура в три эквивалентных излучателя (файл .DAT). TMC_DN суммирует поля этих излучателей с учётом набега фазы в каждом направлении — это и есть переход ближнее поле → дальняя зона (теория). Тот же файл можно написать вручную — тогда это обычная антенная решётка (решётки).

Кроме просмотра ДН, программа умеет:

Программа выросла из вьювера TMCGROUT (через копию TMCROS), поэтому документ и вид называются CTMCGROUTDoc/CTMCGROUTView, а окно графика, оси, сетка, стили линий, кривые-выражения устроены так же (общее для вьюверов). Отличия: строка документа ссылается на файл .DAT, «данные графика» — рассчитанная ДН, ось X — угол, расчёт идёт в отдельном потоке под окном прогресса.

Программа собрана из трёх слоёв:

  • src/viewers/dianapr — расчётная часть: решётка c2DArray, излучатель cIzl;
  • src/viewers/dianapgr — код Windows-версии вьювера: документ, вид, диалоги; он обращается к классам MFC, которые реализует слой совместимости на Qt 6;
  • src/viewers/DiaNapGr/qt — Qt-оболочка: точка входа, главное окно, потокобезопасный виджет-хозяин вида, разметка диалогов, тестовые программы.

Состав

Файл Роль
src/viewers/dianapr/c2darray.h/.cpp c2DArray — решётка: чтение .DAT, сумма полей, нормировка, КНД, КИП, кэш ДН, девиации
src/viewers/dianapr/cizl.h/.cpp cIzl — один излучатель: координаты, амплитуда, фаза, сектор, собственная ДН
src/viewers/dianapr/stdafx.h общий заголовок расчётной части (stdio.h)
src/viewers/dianapgr/tmcgroutdoc.h/.cpp CTMCGROUTDoc — документ .dop: список ДН, массив решёток, расчёт ДН каждого графика
src/viewers/dianapgr/tmcgroutview.h/.cpp CTMCGROUTView — вид: поток расчёта, подготовка и рисование ДН, легенда с КНД/КИП, мышь, команды меню; функции строки состояния PutTrace, PutStatistics; флаг g_lTmcDnCalcRunning
src/viewers/dianapgr/threadcalcdirpat.h/.cpp CThreadCalcDirPat — окно прогресса расчёта (IDD_READDATA_THREAD)
src/viewers/dianapgr/cdeviation.h/.cpp cDeviation — окно девиаций распределения (IDD_DIALOGMAKEDEVIAT)
src/viewers/dianapgr/deviatdirpat.h/.cpp CDeviatDirPat — окно ДН с отклонениями (IDD_DIALOGCALCDEVIAT)
src/viewers/dianapgr/dialogdoc.h/.cpp окно Characteristics (IDD_DIALOG2): 20 строк ДН, признаки показа и Reduce, кнопки девиаций
src/viewers/dianapgr/tmcgroutdialogview.h/.cpp окно Viewport (IDD_DIALOG1): диапазоны, радианы/градусы, линейно/дБ, нормировка
src/viewers/dianapgr/tmcgroutcolorgraphdialog.h/.cpp, tmcgrparcoltypwid.h/.cpp окна 16 стилей линий и стиля одной линии (как у TMCGROUT)
src/viewers/dianapgr/tmcgrexpression.cpp CTMCGrExpression — кривая-выражение (объявление — в общем tmcgrexpression.h)
src/viewers/dianapgr/dialogttos.h/.cpp, tmcsmatrix.cpp, tmcttos.cpp наследие TMCROS: окно To S-matrix и пересчёт .t -> .s (ниже)
src/viewers/dianapgr/mainfrm.h/.cpp CMainFrame — в Qt6-версии только носитель строки состояния
src/viewers/dianapgr/tmcgrout.h, stdafx.h, resource.h класс приложения MFC (не создаётся), общий заголовок, номера ресурсов
apps/tmc_dn/main.cpp точка входа
apps/tmc_dn/mainwindow.h/.cpp MainWindow — меню, панель, строка состояния (StatusBarHost), окна документов (MDI)
apps/tmc_dn/dnviewwidget.h/.cpp DnViewWidget — виджет-хозяин вида, принимающий вызовы из потока расчёта
apps/tmc_dn/dialogs/*.ui, dialog_registry.cpp разметка диалогов, порождённая из ресурса Windows-версии (диалоги из .rc)
apps/tmc_dn/testtools/* тестовые программы (ниже)

Сборка (apps/tmc_dn/CMakeLists.txt): tmc_dn_core (решётка, документ, выражения, TtoS — без Qt-интерфейса), tmc_dn_view (вид, рамка, диалоги), tmc_dn_gui (главное окно, разметка, пиктограммы), программа tmc_dn и тестовые tmc_dn_doccheck, tmc_dn_shot, tmc_dn_uitest. Модулям dianapr при сборке подставляется заголовок tmc_mfc_doc.h слоя совместимости (в нём CString и функции времени записи файла). Вне сборки — наследие.

Ключевые классы и их связи

MainWindow ─┬─ TmcDocumentWindow ×N ─┬─ CTMCGROUTDoc ─┬─ TMC_GR_DOC_DN grdoc ── TMC_GR_DOC1_DN[nGraph]
            │                        │                └─ c2DArray pcDirectionalPattern[nGraph] ── cIzl[N]
            │                        ├─ CTMCGROUTView ── tmcgrwin (все точки), tmcgrwin1 (прореженные)
            │                        ├─ DnViewWidget (виджет-хозяин вида)
            │                        └─ QMdiSubWindow
            └─ CMainFrame m_frame + StatusBarHost (строка состояния для PutTrace/PutStatistics)
  • Решётка c2DArray — вся физика модуля: читает .DAT, хранит излучатели, сетку углов графика и ДН (модуль и фаза), считает КНД и КИП. Ошибки не бросаются: флаг IsError() и текст GetError().
  • Документ хранит то, что пишется в .dop (список графиков, оси, цвета, шрифт, стили линий), и массив решёток — по одной на график. После расчёта ДН графика i её углы лежат в grdoc.psGraph[i].pFreq (радианы), нормированная амплитуда — в pSmatr[].x (имена полей остались от графиков S-параметров).
  • Вид переводит ДН в величины осей и рисует; запускает расчёт и следит за изменением файлов.

Документ и его файл

Путь документа задаётся при открытии; перед каждым чтением MakeDocFileName решает, что это:

Путь Что происходит
пустой (File > New) путь = заголовок окна (TMCRTOS1 …); создаётся файл с одной меткой #TMCGROTS
файл не существует ошибка документа file not found …
первая строка начинается с #TMCGROTS это документ, читается как есть
любой другой файл (обычно .DAT) путь меняется на то же имя с расширением .dop; если .dop уже есть — .$op. Создаётся документ с одной строкой <имя.DAT> <имя.DAT> 1 1 1 1 1

Ошибка документа хранится в CTMCGROUTDoc::error; при ней вид выводит Error : <текст>. Ошибка отдельной ДН не останавливает чтение: её подпись становится Error_when_read_<файл>:_<текст ошибки решётки>, КНД в легенде не выводится.

Файл документа .dop

Текстовый файл того же устройства, что .soc у TMCGROUT: первая строка #TMCGROTS, строки параметров #метка значение (точки, тип осей, диапазоны, редактор, шрифт, цвета, 16 стилей линий; единиц пользователя оси X у TMC_DN нет), комментарии !, затем строки графиков:

<файл .DAT или {выражение}> <подпись> <показ> <вход1> <мода1> <вход2> <мода2>
Поле Смысл в TMC_DN
файл путь к .DAT; без : и без начального \\ — относительно папки документа
подпись текст легенды; без пробелов
показ 1 — ДН рисуется, 0 — скрыта
вход1, вход2 приводятся к 1; на расчёт не влияют
мода1 признак Reduce: 1 — учитывать секторы излучения, 0 — нет (больше 1 приводится к 1)
мода2 приводится к 0..1; на расчёт не влияет

Параметры по умолчанию для новых документов хранятся в настройках программы (раздел и ключ #TMCGROTS, строки разделены байтом 0x01), как у TMCGROUT (настройки). Тип оси X (#nXType): 0 — радианы, 1 — градусы. Тип оси Y (#nYType) — см. оси.

Слежение за изменениями

Таймер вида (каждые 10 с) вызывает IsDataModific: сравнивает время записи файла документа и файлов .DAT показываемых ДН с запомненным. Если что-то изменилось и расчёт не идёт, вид сбрасывает bIsDataCalculate и запускает полный пересчёт (ReadDocFileW). Так ДН обновляется сама, когда ядро перезаписало .DAT. Двойной щелчок по окну тоже проверяет файлы, но после первого расчёта сам ничего не пересчитывает (обновление делает таймер).

Входной файл излучателей .DAT

c2DArray::ReadData читает файл формата, который пишет ядро (формат, теория):

Frequence = <F, ГГц> Ghz;
N = <число излучателей>;
<выражение общей ДН элемента, обычно 1.>
1   X = <мм>; Y = <мм>; Amplitude = <A>; Faza = <градусы> degree; FiMin = <градусы> degree; FiMax = <градусы> degree; <ДН излучателя>
...
  • Строка излучателя — 8 полей или 5 полей (без сектора и ДН излучателя; тогда сектор −180…180°, излучатель изотропный). Строка из 5 полей должна кончаться degree;. Номер в начале строки не проверяется.
  • Внутри объекта координаты переводятся в метры, фаза и углы сектора — в радианы, частота — в Гц.
  • Проверки: N ≥ 1; N не больше размера файла / 32 + 1 (защита от выделения памяти по ошибочному N); все числа конечны; длина пути не больше 800 символов.
  • Третья строка хранится вместе с переводом строки — см. подводные камни.

Модель решётки

Решётка — N излучателей cIzl на плоскости XY. Излучатель i задан полярными координатами (ri,αi) (из X, Y), комплексной амплитудой Aiejψi, сектором излучения [φmin,i,φmax,i] и собственной ДН gi(φ). Общая для всех ДН элемента r1(φ) — третья строка файла. Угол φ отсчитывается от оси X против часовой стрелки, радианы.

ДН излучателя

cIzl::dGetDirectionalPatternEmitter возвращает gi(φ):

Последнее поле строки gi(φ)
пусто 1 (сектор не проверяется)
1. 1
cos(f) cosφ (ядро так помечает касательное H вертикальных сторон)
sin(f) sinφ (касательное H горизонтальных сторон)
другое выражение от f значение выражения библиотекой Expr, f = угол в радианах

Вне сектора $g_i = $ FLT_MIN (практически 0). Вклад излучателя — GetdAmplituda(φ) =Aigi(φ).

Секторы излучения и признак Reduce

Ядро задаёт каждой точке контура сектор своей стороны (правая −90…90°, верхняя 0…180°, левая 90…270°, нижняя 180…360°): эквивалентный источник на стороне контура излучает только наружу. bIsAngleInDiapazon проверяет попадание дважды — с углами, приведёнными к (−π,π], и к (0,2π], — поэтому правильно обрабатываются секторы, пересекающие и 0°, и 180°.

Признак Reduce (мода 1 строки документа, флажок в окне Characteristics) включает секторы. При Reduce = 0 (bIsReduceElMagnAnalysis = FALSE) все секторы заменяются на −180…180°: каждый излучатель излучает во все стороны, собственные ДН gi сохраняются. В легенде такая ДН подписана - <подпись>, с секторами — -<подпись>;.

Поле решётки в дальней зоне

В направлении φ поле решётки — когерентная сумма полей излучателей с набегом фазы по разности хода (дальняя зона):

F(φ)=r1(φ)∑i=1NAigi(φ)exp(j[ψi+kricos(φ−αi)]),k=2πFc,(1)

c=299792458 м/с. CalculateRealDN и CalculateImageDN дают Re и Im суммы (без r1); CalculateDiagrNapr умножает на r1(φ) и хранит |F| (pdRealDN) и \argF (pdImageDN, радианы; несмотря на имена массивов). Множитель e−jkρ/ρ цилиндрической волны для всех направлений одинаков и опущен: ДН — функция только угла. Для файла от ядра это и есть пересчёт поля с контура в ближней зоне в дальнюю зону: точки контура — эквивалентные источники (Ez с g=1 и касательное H с g=cosφ или sinφ), фазы и амплитуды которых ядро уже привело (контур).

Сетка углов графика

ДН для рисования считается на сетке из nAngle точек:

Решётка Сетка
N ≤ 400 после чтения 400 точек 0…π; затем документ перестраивает её на диапазон оси X (ResizeAngle(Xmin, Xmax), градусы переводятся в радианы)
N > 400 1000 точек −π…π; ResizeAngle после первого расчёта ничего не делает

Когда пользователь меняет диапазон X (рамка мышью, Zoom ±X, сдвиг, Home/End, Auto X, Resize window), вид вызывает ReadDocFileW_1 -> CTMCGROUTDoc::ReadDocFile_1 -> для каждого графика ReadGraph1_CangeAngle: решётка пересчитывает ДН на новой сетке того же размера, файлы не читаются, нормировка прежняя. Это выполняется в главном потоке без окна прогресса. У большой решётки ДН остаётся на сетке −π…π, а окно просто показывает её часть.

Нормировка, КНД и КИП

NormirovkaDiagrNapr выполняется один раз после расчёта (флаг IsNormirovka) на мелкой сетке по полному кругу [0,2π), отдельной от сетки графика. Число точек

n=max(nmin, ⌈64kRmax+1⌉),16≤n≤4000000,(2)

где nmin = 1000 (nPointForNormir), Rmax — наибольшее удаление излучателя от начала координат: 64 точки на радиан набега фазы, чтобы не пропустить узкий главный лепесток. Интегралы — методом прямоугольников с шагом Δφ=2π/n.

КНД

Коэффициент направленного действия двумерной задачи (теория):

D=2πmaxφ|F(φ)|2∫02π|F(φ)|2dφ.(3)

GetKnd — в разах, GetKnd_dB — 10lgD. Нулевая или нечисловая ДН — ошибка Directional pattern is identically zero or not a finite number. КНД считается одинаково для любого N.

КИП

Для решётки из N ≤ 400 излучателей (теория):

КИП=DD0,(4)

где D0 — КНД опорной решётки той же геометрии: все амплитуды 1, фазы 0, без ДН излучателей, без секторов и без общей ДН элемента (CalculateRealDN_ForKip, CalculateImageDN_ForKip). Для N > 400 опорная решётка не считается, а в поле dKip кладётся излучённая мощность ∫02π|F|2dφ (условные единицы); в легенде и листинге она подписана Emitted Power. Признак — IsCalculateKip(), который возвращает TRUE именно для больших решёток (имя обратно смыслу).

Большие решётки и нормирующий множитель

Решётка dMax Нормированная ДН
N ≤ 400 1,001·max|F| на мелкой сетке |F|/dMax, максимум около 0,999
N > 400 max|F| на сетке графика |F|/dMax, максимум ровно 1

Документ получает нормированную амплитуду; вид при необходимости умножает её обратно на GetdMax() (оси). Большая решётка отличается ещё и сеткой (сетка углов) и кэшем (ниже). В файле от ядра три записи на каждую точку контура, поэтому решётка «большая» уже при контуре длиннее 133 точек.

Поток расчёта

Полный расчёт одного графика (CTMCGROUTDoc::ReadGraph1 -> read_RT_output_signal):

  1. Номера входов и мод приводятся к допустимым; мода 1 = 0 выключает секторы.
  2. c2DArray::CalculateDiagrNapr(<файл.DAT>, <файл.DAT>~~tempDia):
  3. ReadData — чтение .DAT, создание излучателей, имена временных файлов;
  4. сумма полей на сетке графика (поле решётки) или чтение из кэша;
  5. NormirovkaDiagrNapr — КНД, КИП, dMax, нормировка;
  6. WriteData — листинг <файл.DAT>~~tempDia0|1 (излучатели, КНД, КИП, точки ДН) и кэш.
  7. ResizeAngle на диапазон оси X документа.
  8. Копирование углов и нормированной амплитуды в массивы графика; частота первой решётки — в dFreq документа (строка состояния Pattern; Freq=… GHz).

Ошибка на любом шаге оставляет у графика 0 точек и подпись Error_when_read_… с причиной.

Временные файлы и кэш

Рядом с .DAT программа пишет:

Файл Содержимое Срок жизни
<.DAT>~~tempDia0, …1 листинг: излучатели, КНД, КИП/мощность, точки ДН (угол, модуль, фаза в градусах) удаляется при уничтожении решётки (пересчёт, закрытие окна)
<.DAT>_Temp0, …1 кэш ДН: угол (градусы), ненормированный модуль, нормированный модуль, фаза (градусы) при N < 400 удаляется вместе с решёткой, при N ≥ 400 остаётся
<.DAT>_Temp0.chk, …1.chk подпись кэша: версия формата, размер и время .DAT, N, частота при N ≥ 400

Цифра в имени — признак Reduce. При N ≥ 400 перед расчётом IsDirectPatSaveInFile проверяет: кэш есть, он не старше .DAT и подпись совпадает. Тогда ДН на сетке графика читается из кэша, а нормировка, КНД и КИП всё равно считаются заново (на мелкой сетке). Негодный кэш удаляется и ДН считается заново. Папка только для чтения — не ошибка: листинг и кэш просто не пишутся.

Поток и окно прогресса

Расчёт всех ДН документа может занимать минуты, поэтому вид выполняет его в отдельном потоке:

  1. ReadDocFileW (если ДН ещё не посчитаны и расчёт не идёт) ставит глобальный флаг g_lTmcDnCalcRunning = 1, запоминает время и запускает AfxBeginThread(ReadDocFileW_Thread1).
  2. Главный поток показывает модальное окно CThreadCalcDirPat. Его таймер (100 мс) читает номер считаемого графика nGraphCurrent и ход цикла c2DArray::iN и обновляет поля: номер ДН, число ДН, число излучателей, проценты, прошедшее время.
  3. Поток: ReadDocFileW_Thread -> CTMCGROUTDoc::ReadDocFile (все графики), выделение массивов точек вида, bIsDataCalculate = TRUE, подготовка рисунка; затем флаг сбрасывается в 0.
  4. Таймер окна видит 0 и закрывает окно; вид перерисовывается уже с ДН.

Пока флаг не 0: OnDraw выводит «Please wait ... Data calculate», команды Characteristics и Add characteristics ничего не делают, пересчёт на новом диапазоне X не выполняется, таймер не проверяет файлы, кнопка Hide и крестик окна прогресса не действуют. Закрытие окна документа во время расчёта ждёт конца потока (OnDestroy).

Код Windows-версии в конце расчёта зовёт RedrawWindow и пишет строку состояния прямо из потока расчёта. В Qt это допустимо только из главного потока, поэтому:

  • DnViewWidget (виджет-хозяин вида) из чужого потока не рисует сам, а ставит перерисовку в очередь событий главного потока; окно сообщения из потока показывается без ожидания ответа;
  • StatusBarHost (хозяин строки состояния рамки) передаёт текст в главное окно тоже через очередь событий.

Порядок и результат вычислений от этого не меняются — откладывается только показ.

Величины по осям

Ось Значения Подпись
X, nXType = 0 угол, радианы Angle radian
X, nXType = 1 угол, градусы Angle degree
Y, TMC_GROTS_TYPE_FULL (0) |F| = нормированная амплитуда · dMax Pattern
Y, TMC_GROTS_TYPE_AMPL (1) 20lg|F|, дБ Pattern dB
Y, TMC_GROTS_TYPE_PHAS_R (2) нормированная амплитуда Pattern
Y, TMC_GROTS_TYPE_PHAS_G (3) нормированная амплитуда в дБ Pattern dB

В окне Viewport ось X выбирается переключателем Radian/Degree, ось Y — переключателем Pattern/Pattern dB и флажком Normirovka (+2). Константы взяты из таблицы TMCROS (TMC_GROTS_TYPE_nT = 0 для радиан, TMC_GROTS_TYPE_ps = 1 для градусов). Типы КСВ и L (дБ) остались в таблице от прежних вьюверов и из окна не выбираются. Автодиапазон Y считается только по точкам, видимым по X; включённый автодиапазон X — это −π…π (−180…180°).

Рисование

Устройство то же, что у TMCGROUT: координаты MM_HIMETRIC, сетка 10 × 10, оси со стрелками, стили линий. Отличие — прореживание: PrepareLogGraph строит набор tmcgrwin1, в который попадают только точки в диапазоне X, а из подряд идущих точек с одинаковой экранной высотой — только крайние. Линии и маркеры рисуются по tmcgrwin1; при включённом прореживании маркеров рисуется каждая (n/20+1)-я точка.

Легенда

Строка легенды справа от графика: образец линии, подпись и, если ДН посчитана без ошибки, Knd = <дБ>dB; Kip = <разы>; или для большой решётки Knd = <дБ>dB; Emitted Power = <…>;.

Кривые-выражения

Строка графика вида {формула с [файл.DAT] ...} разбирается так же, как у TMCGROUT: для каждого файла считается ДН (ReadGraph1), сетки углов должны совпадать. Переменная f выражения — угол точки (радианы). В формулу вместо каждого [файл] подставляется GetExpressionValueK: (1+|a|)/(1−|a|), где a — значение массива ДН этого файла, — см. подводные камни.

Девиации распределения

Окно Make Distribution Deviation (cDeviation, кнопка окна Characteristics) создаёт новый .DAT из исходного, задавая каждому излучателю независимое равномерно распределённое отклонение (теория):

A′=A(1+ξAδA/100),ψ′=ψ+ξψδψ,x′=x+ξxδx,y′=y+ξyδy,ξ∈[−1,1],(5)

где δA — проценты, δψ — градусы, δx,δy — мм (по умолчанию амплитуда и фаза — 10, координаты — 0). Расчёт — c2DArray::MakeDeviation, запись — SaveData (формат .DAT с секторами, без КНД). Файл пишется сразу после выбора пути «To» и повторно по OK. Полученный файл открывается как обычная ДН.

ДН с отклонениями и требуемая ДН

Окно Calculate Directional Pattern Deviation (CDeviatDirPat) сравнивает ДН решётки с требуемой:

  1. первая решётка читает .DAT (секторы учитываются);
  2. вторая читает файл требуемой ДН .opt — строки «угол_в_градусах значение» (строки, где не прочитались два числа, пропускаются; точек не меньше 2) — и берёт из него сетку углов (OptimizationInit);
  3. во вторую переносятся частота, выражение общей ДН элемента, излучатели и их секторы;
  4. SaveDeviationDirectionalPattern считает и нормирует ДН на этой сетке и пишет .dev: строка !Degree AmplitudeDirectPatternRequired AmplitudeDirectPattern, затем по строке на угол — угол (градусы), требуемая и рассчитанная нормированная ДН через табуляцию.

Для N > 400 нормировка — на максимум в точках .opt. Функция GetOptimPurposeFunction (сумма |Fнорм−Fтреб| по точкам) для подбора амплитуд и фаз в пакете не вызывается.

Время → S-матрица (наследие)

В каталоге dianapgr лежат копии подсистемы TtoS вьювера TMCROS: окно To S-matrix (CDialogTtoS), CTmcTtoS, CTmcSMatrix — вариант без многочастотной обработки. Код собирается (tmc_dn_core, tmc_dn_view), обработчик OnEditTosmatrix есть в карте сообщений вида, но пункта меню в Qt6-версии TMC_DN нет, поэтому пользователю окно недоступно. Устройство описано у TMCROS: время → S, окно To S-matrix.

Команды меню

Меню и панель повторяют ресурсы Windows-версии (IDR_TMCGROTYPE, IDR_MAINFRAME). Команду выполняет карта сообщений вида; печать главное окно выполняет само. Отличия от TMCGROUT:

Команда Обработчик Что делает в TMC_DN
File > Open MainWindow::onOpenDocument фильтр *.dat *.dop *.$op
File > Save As OnFileSaveAs пересчитывает относительные пути; окно предлагает расширение .tos
Edit > Characteristics OnEditDocument 20 строк ДН с флажками показа и Reduce, кнопки девиаций; после OK — полный пересчёт
Edit > Add characteristics OnEditAddcharacteristics выбор *.dat, строка <имя> <имя> 1 1 1 1 1, пересчёт, окно Characteristics
View > Viewport OnEditGraphicsparameters радианы/градусы, Pattern/Pattern dB, Normirovka
View > Redraw data OnViewGraphics полный пересчёт всех ДН
Zoom ±X, рамка мышью, Translate X, Home, End, Auto X, Resize window OnViewZoomZoomxp … новый диапазон X и пересчёт ДН малых решёток (ReadDocFileW_1); Home — левая граница 0, End — правая граница π (180°), ширина прежняя
Config > Color > Graphics OnConfigColorGraphics после OK — полный пересчёт

Остальные команды (Zoom ±, ±Y, Auto Y, цвета, шрифт, редактор) — как у TMCGROUT.

Qt-оболочка

main.cpp: безопасный поиск DLL, QApplication с именем TMC_DN, имя настроек CWinApp::SetAppName("TMC_DN"), оформление, главное окно; первый аргумент командной строки — файл документа или .DAT. MainWindow::openDocument проверяет, что файл есть и путь представим в кодовой странице Windows, создаёт документ, вид и DnViewWidget, задаёт фон по цвету документа и вызывает initialUpdate — в нём OnInitialUpdate вида запускает расчёт. Рамка CMainFrame с хозяином строки состояния StatusBarHost становится главным окном приложения слоя совместимости, чтобы PutTrace/PutStatistics писали в строку состояния окна (левая ячейка — координаты под мышью, правая — Pattern; Freq=<ГГц> GHz).

Тестовые программы

Не входят в поставку.

Программа Что делает
tmc_dn_doccheck <документ> [--dump] открывает документ кодом программы (с расчётом ДН) и печатает параметры осей, графики, N, КНД, КИП/мощность, dMax, первые точки; --dump — строки файла с видимыми CR/LF/TAB. Создаёт рядом временные файлы (а для .DAT — документ .dop) — запускать на копии
tmc_dn_shot <файл.png> [документ] [ширина] [высота], --dialogs [папка] снимок главного окна (через 1 с после открытия) или всех диалогов в PNG
tmc_dn_uitest <документ> [секунд на шаг] нажимает все команды, меняет размер окна, щёлкает по графику; зависание — код 2 и стек, захваченная мышь — код 3 (не Windows)

testtools/crashtrace.h печатает при падении стек и поток (главный или расчёта).

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

  • Индикатор хода считает проценты как iN/10, то есть рассчитан на сетку из 1000 углов (большая решётка). У малой решётки полоса доходит до 40%. Время нормировки на мелкой сетке (для большого контура — основная часть расчёта) в индикаторе не отражается.
  • Большая решётка (N > 400, почти всегда файл от ядра): КИП не считается — в легенде Emitted Power; ДН всегда на сетке −π…π из 1000 точек; смена диапазона X её не пересчитывает, а только обрезает.
  • Кривые-выражения: в формулу подставляется (1+|a|)/(1−|a|) от нормированной амплитуды, а мнимая часть элементов массива ДН не задаётся (read_RT_output_signal) — результат выражения не является ДН.
  • Третья строка .DAT читается вместе с переводом строки, поэтому сравнение с 1. не срабатывает и выражение общей ДН элемента вычисляется в каждой точке (на результат не влияет, только на время). Угол для него печатается в строку с 6 значащими цифрами.
  • Фазы излучателей TMC_DN берёт из .DAT как есть. При ANGLE_UNIT gradus в задании ядро пишет неверные фазы излучателей (дефект библиотеки TMCIndan), и ДН получается неверной; см. накопление квадратур.
  • Двойной щелчок не пересчитывает изменившиеся файлы после первого расчёта; новые данные подхватывает таймер (до 10 с).
  • Save As предлагает расширение .tos (наследие TMCROS) — для документа TMC_DN нужно указать .dop.
  • Метка документа #TMCGROTS та же, что у документов TMCROS: файл TMCROS, открытый в TMC_DN, читается как документ ДН, и его строки принимаются за имена .DAT.
  • Отклонения (MakeDeviation) строятся генератором rand() без начального значения: при каждом запуске программы последовательность одна и та же.
  • c2DArray::GetIzl/SetIzl проверяют индекс как i > nIzl и пропускают i == nIzl.
  • Рядом с .DAT появляются листинг и кэш (временные файлы); при N ≥ 400 кэш и его подпись остаются и после закрытия программы.

Файлы вне сборки

dianapgr/childfrm.h/.cpp (дочернее окно MDI MFC), dianapgr/tmcgrout.cpp (приложение MFC), dianapgr/stdafx.cpp, dianapgr/tmcgrparcoltypwid1.h/.cpp (пустая заготовка окна), dianapr/dianapr.cpp (консольная программа расчёта ДН по .DAT — тот же расчёт делает c2DArray::CalculateDiagrNapr), dianapr/stdafx.cpp. Оставлены для сверки с MFC-версией (наследие).

TMC_DN viewer — radiation patterns, directivity and aperture efficiency

Purpose and place in the package

TMC_DN (tmc_dn.exe) builds the far-field radiation pattern (RP) of a set of radiators on a plane and computes the directivity (D) and the aperture efficiency. The input data is the radiator file .DAT. It is usually written by the PlanarRT_H or PlanarRT_X compute kernel: the TMCIndan library integrates the field on a closed near-field contour and turns each contour point into three equivalent radiators (the .DAT file). TMC_DN sums the fields of these radiators taking into account the phase delay in each direction — this is the transition from the near field to the far field (theory). The same file can be written by hand — it is then an ordinary antenna array (arrays).

Besides viewing the RP, the program can:

  • build an array with random deviations of the amplitudes, phases and coordinates of the radiators (distribution deviations);
  • compute the RP of an array on the angle grid of a required RP and write their comparison (RP with deviations, theory).

The program grew out of the TMCGROUT viewer (via a copy of TMCROS), so the document and the view are called CTMCGROUTDoc/CTMCGROUTView, and the plot window, axes, grid, line styles and expression curves work the same way (common to the viewers). Differences: a document line refers to a .DAT file, the "plot data" is the computed RP, the X axis is the angle, and the computation runs in a separate thread under a progress window.

The program is built from three layers:

  • src/viewers/dianapr — the computational part: the array c2DArray, the radiator cIzl;
  • src/viewers/dianapgr — the code of the Windows version of the viewer: document, view, dialogs; it uses MFC classes, which the compatibility layer implements on Qt 6;
  • src/viewers/DiaNapGr/qt — the Qt shell: entry point, main window, a thread-safe view host widget, dialog layouts, test programs.

Contents

File Role
src/viewers/dianapr/c2darray.h/.cpp c2DArray — the array: reading .DAT, sum of fields, normalisation, directivity, aperture efficiency, RP cache, deviations
src/viewers/dianapr/cizl.h/.cpp cIzl — a single radiator: coordinates, amplitude, phase, sector, element pattern
src/viewers/dianapr/stdafx.h common header of the computational part (stdio.h)
src/viewers/dianapgr/tmcgroutdoc.h/.cpp CTMCGROUTDoc — the .dop document: list of RPs, array of arrays, RP computation for each plot
src/viewers/dianapgr/tmcgroutview.h/.cpp CTMCGROUTView — the view: computation thread, preparation and drawing of the RP, legend with directivity/aperture efficiency, mouse, menu commands; the status-bar functions PutTrace, PutStatistics; the flag g_lTmcDnCalcRunning
src/viewers/dianapgr/threadcalcdirpat.h/.cpp CThreadCalcDirPat — computation progress window (IDD_READDATA_THREAD)
src/viewers/dianapgr/cdeviation.h/.cpp cDeviation — distribution deviation dialog (IDD_DIALOGMAKEDEVIAT)
src/viewers/dianapgr/deviatdirpat.h/.cpp CDeviatDirPat — dialog of the RP with deviations (IDD_DIALOGCALCDEVIAT)
src/viewers/dianapgr/dialogdoc.h/.cpp the Characteristics dialog (IDD_DIALOG2): 20 RP rows, display and Reduce flags, deviation buttons
src/viewers/dianapgr/tmcgroutdialogview.h/.cpp the Viewport dialog (IDD_DIALOG1): ranges, radians/degrees, linear/dB, normalisation
src/viewers/dianapgr/tmcgroutcolorgraphdialog.h/.cpp, tmcgrparcoltypwid.h/.cpp dialogs for the 16 line styles and for the style of one line (as in TMCGROUT)
src/viewers/dianapgr/tmcgrexpression.cpp CTMCGrExpression — an expression curve (declaration — in the shared tmcgrexpression.h)
src/viewers/dianapgr/dialogttos.h/.cpp, tmcsmatrix.cpp, tmcttos.cpp TMCROS legacy: the To S-matrix dialog and the .t -> .s conversion (below)
src/viewers/dianapgr/mainfrm.h/.cpp CMainFrame — in the Qt6 version only a carrier of the status bar
src/viewers/dianapgr/tmcgrout.h, stdafx.h, resource.h the MFC application class (not created), common header, resource IDs
apps/tmc_dn/main.cpp entry point
apps/tmc_dn/mainwindow.h/.cpp MainWindow — menu, toolbar, status bar (StatusBarHost), document windows (MDI)
apps/tmc_dn/dnviewwidget.h/.cpp DnViewWidget — view host widget that accepts calls from the computation thread
apps/tmc_dn/dialogs/*.ui, dialog_registry.cpp dialog layouts generated from the resource of the Windows version (dialogs from .rc)
apps/tmc_dn/testtools/* test programs (below)

Build (apps/tmc_dn/CMakeLists.txt): tmc_dn_core (array, document, expressions, TtoS — without the Qt interface), tmc_dn_view (view, frame, dialogs), tmc_dn_gui (main window, layouts, icons), the program tmc_dn and the test programs tmc_dn_doccheck, tmc_dn_shot, tmc_dn_uitest. The dianapr modules are given the header tmc_mfc_doc.h of the compatibility layer at build time (it contains CString and the file-modification-time functions). Outside the build — legacy.

Key classes and their relations

MainWindow ─┬─ TmcDocumentWindow ×N ─┬─ CTMCGROUTDoc ─┬─ TMC_GR_DOC_DN grdoc ── TMC_GR_DOC1_DN[nGraph]
            │                        │                └─ c2DArray pcDirectionalPattern[nGraph] ── cIzl[N]
            │                        ├─ CTMCGROUTView ── tmcgrwin (all points), tmcgrwin1 (thinned)
            │                        ├─ DnViewWidget (view host widget)
            │                        └─ QMdiSubWindow
            └─ CMainFrame m_frame + StatusBarHost (status bar for PutTrace/PutStatistics)
  • The array c2DArray holds all the physics of the module: it reads .DAT, stores the radiators, the angle grid of the plot and the RP (magnitude and phase), and computes the directivity and the aperture efficiency. No exceptions are thrown: there is the flag IsError() and the text GetError().
  • The document stores what is written to .dop (list of plots, axes, colours, font, line styles) and an array of arrays — one per plot. After the RP of plot i has been computed, its angles are in grdoc.psGraph[i].pFreq (radians), and the normalised amplitude in pSmatr[].x (the field names are left over from the S-parameter plots).
  • The view converts the RP into axis quantities and draws it; it starts the computation and watches for file changes.

The document and its file

The document path is set on opening; before each read MakeDocFileName decides what it is:

Path What happens
empty (File > New) path = window title (TMCRTOS1 …); a file with the single label #TMCGROTS is created
the file does not exist document error file not found …
the first line starts with #TMCGROTS it is a document and is read as is
any other file (usually .DAT) the path is changed to the same name with the .dop extension; if .dop already exists — .$op. A document with one line <name.DAT> <name.DAT> 1 1 1 1 1 is created

The document error is stored in CTMCGROUTDoc::error; when there is one, the view prints Error : <text>. An error in an individual RP does not stop reading: its label becomes Error_when_read_<file>:_<array error text>, and the directivity is not shown in the legend.

The .dop document file

A text file with the same structure as .soc of TMCGROUT: the first line #TMCGROTS, parameter lines #label value (points, axis type, ranges, editor, font, colours, 16 line styles; TMC_DN has no user units of the X axis), ! comments, then the plot lines:

<.DAT file or {expression}> <label> <display> <port1> <mode1> <port2> <mode2>
Field Meaning in TMC_DN
file path to .DAT; without : and without a leading \\ — relative to the document folder
label legend text; without spaces
display 1 — the RP is drawn, 0 — hidden
port1, port2 clamped to 1; do not affect the computation
mode1 the Reduce flag: 1 — take the radiation sectors into account, 0 — do not (values greater than 1 are clamped to 1)
mode2 clamped to 0..1; does not affect the computation

The default parameters for new documents are stored in the program settings (section and key #TMCGROTS, lines separated by the byte 0x01), as in TMCGROUT (settings). X-axis type (#nXType): 0 — radians, 1 — degrees. Y-axis type (#nYType) — see axes.

Watching for changes

The view timer (every 10 s) calls IsDataModific: it compares the modification time of the document file and of the .DAT files of the displayed RPs with the remembered ones. If something has changed and no computation is running, the view resets bIsDataCalculate and starts a full recomputation (ReadDocFileW). This way the RP updates by itself when the kernel has rewritten .DAT. A double click on the window also checks the files, but after the first computation it does not recompute anything by itself (the update is done by the timer).

Input radiator file .DAT

c2DArray::ReadData reads a file in the format written by the kernel (format, theory):

Frequence = <F, GHz> Ghz;
N = <number of radiators>;
<expression of the common element pattern, usually 1.>
1   X = <mm>; Y = <mm>; Amplitude = <A>; Faza = <degrees> degree; FiMin = <degrees> degree; FiMax = <degrees> degree; <radiator pattern>
...
  • A radiator line has 8 fields or 5 fields (without the sector and the radiator pattern; then the sector is −180…180° and the radiator is isotropic). A 5-field line must end with degree;. The number at the beginning of the line is not checked.
  • Inside the object the coordinates are converted to metres, the phase and the sector angles to radians, the frequency to Hz.
  • Checks: N ≥ 1; N not greater than the file size / 32 + 1 (protection against allocating memory for an erroneous N); all numbers are finite; the path length is at most 800 characters.
  • The third line is stored together with its line feed — see pitfalls.

The array model

The array is N radiators cIzl on the XY plane. Radiator i is defined by polar coordinates (ri,αi) (from X, Y), a complex amplitude Aiejψi, a radiation sector [φmin,i,φmax,i] and its own pattern gi(φ). The element pattern common to all radiators r1(φ) is the third line of the file. The angle φ is measured from the X axis counterclockwise, in radians.

Radiator pattern

cIzl::dGetDirectionalPatternEmitter returns gi(φ):

Last field of the line gi(φ)
empty 1 (the sector is not checked)
1. 1
cos(f) cosφ (the kernel marks the tangential H of vertical sides this way)
sin(f) sinφ (tangential H of horizontal sides)
another expression of f the value of the expression via the Expr library, f = angle in radians

Outside the sector $g_i = $ FLT_MIN (practically 0). The contribution of a radiator is GetdAmplituda(φ) =Aigi(φ).

Radiation sectors and the Reduce flag

The kernel gives each contour point the sector of its side (right −90…90°, top 0…180°, left 90…270°, bottom 180…360°): an equivalent source on a side of the contour radiates only outwards. bIsAngleInDiapazon checks membership twice — with angles reduced to (−π,π] and to (0,2π] — so sectors that cross both 0° and 180° are handled correctly.

The Reduce flag (mode 1 of the document line, a check box in the Characteristics dialog) enables the sectors. With Reduce = 0 (bIsReduceElMagnAnalysis = FALSE) all sectors are replaced by −180…180°: every radiator radiates in all directions, the element patterns gi are kept. In the legend such an RP is labelled - <label>, with sectors — -<label>;.

Far field of the array

In the direction φ the field of the array is the coherent sum of the radiator fields with the phase delay due to the path difference (far field):

F(φ)=r1(φ)∑i=1NAigi(φ)exp(j[ψi+kricos(φ−αi)]),k=2πFc,(1)

c=299792458 m/s. CalculateRealDN and CalculateImageDN give Re and Im of the sum (without r1); CalculateDiagrNapr multiplies by r1(φ) and stores |F| (pdRealDN) and \argF (pdImageDN, radians; despite the array names). The cylindrical-wave factor e−jkρ/ρ is the same for all directions and is omitted: the RP is a function of the angle only. For a file from the kernel this is exactly the transformation of the field from the near-field contour to the far field: the contour points are equivalent sources (Ez with g=1 and tangential H with g=cosφ or sinφ) whose phases and amplitudes the kernel has already prepared (contour).

Angle grid of the plot

The RP for drawing is computed on a grid of nAngle points:

Array Grid
N ≤ 400 after reading, 400 points 0…π; then the document rebuilds it for the X-axis range (ResizeAngle(Xmin, Xmax), degrees are converted to radians)
N > 400 1000 points −π…π; ResizeAngle does nothing after the first computation

When the user changes the X range (a frame drawn with the mouse, Zoom ±X, shift, Home/End, Auto X, Resize window), the view calls ReadDocFileW_1 -> CTMCGROUTDoc::ReadDocFile_1 -> for each plot ReadGraph1_CangeAngle: the array recomputes the RP on a new grid of the same size, files are not read, the normalisation stays the same. This is done in the main thread without a progress window. For a large array the RP remains on the −π…π grid, and the window simply shows part of it.

Normalisation, directivity and aperture efficiency

NormirovkaDiagrNapr is performed once after the computation (flag IsNormirovka) on a fine grid over the full circle [0,2π), separate from the plot grid. The number of points is

n=max(nmin, ⌈64kRmax+1⌉),16≤n≤4000000,(2)

where nmin = 1000 (nPointForNormir), Rmax is the largest distance of a radiator from the origin: 64 points per radian of phase delay, so as not to miss a narrow main lobe. The integrals are computed by the rectangle method with step Δφ=2π/n.

Directivity

Directivity of the two-dimensional problem (theory):

D=2πmaxφ|F(φ)|2∫02π|F(φ)|2dφ.(3)

GetKnd returns it as a ratio, GetKnd_dB as 10lgD. A zero or non-numeric RP is the error Directional pattern is identically zero or not a finite number. The directivity is computed the same way for any N.

Aperture efficiency

For an array of N ≤ 400 radiators (theory):

aperture efficiency=DD0,(4)

where D0 is the directivity of a reference array with the same geometry: all amplitudes 1, phases 0, without radiator patterns, without sectors and without the common element pattern (CalculateRealDN_ForKip, CalculateImageDN_ForKip). For N > 400 the reference array is not computed, and the radiated power ∫02π|F|2dφ (arbitrary units) is put into the field dKip; in the legend and the listing it is labelled Emitted Power. The indicator is IsCalculateKip(), which returns TRUE precisely for large arrays (the name is the opposite of its meaning).

Large arrays and the normalising factor

Array dMax Normalised RP
N ≤ 400 1,001·max|F| on the fine grid |F|/dMax, maximum about 0.999
N > 400 max|F| on the plot grid |F|/dMax, maximum exactly 1

The document receives the normalised amplitude; the view multiplies it back by GetdMax() when needed (axes). A large array also differs in its grid (angle grid) and in its cache (below). A file from the kernel has three records per contour point, so the array is "large" already for a contour longer than 133 points.

Computation flow

Full computation of one plot (CTMCGROUTDoc::ReadGraph1 -> read_RT_output_signal):

  1. The port and mode numbers are clamped to allowed values; mode 1 = 0 disables the sectors.
  2. c2DArray::CalculateDiagrNapr(<file.DAT>, <file.DAT>~~tempDia):
  3. ReadData — reading .DAT, creating the radiators, names of the temporary files;
  4. sum of the fields on the plot grid (array field) or reading from the cache;
  5. NormirovkaDiagrNapr — directivity, aperture efficiency, dMax, normalisation;
  6. WriteData — the listing <file.DAT>~~tempDia0|1 (radiators, directivity, aperture efficiency, RP points) and the cache.
  7. ResizeAngle to the X-axis range of the document.
  8. Copying the angles and the normalised amplitude into the plot arrays; the frequency of the first array goes into dFreq of the document (status bar Pattern; Freq=… GHz).

An error at any step leaves the plot with 0 points and the label Error_when_read_… with the cause.

Temporary files and the cache

Next to .DAT the program writes:

File Contents Lifetime
<.DAT>~~tempDia0, …1 listing: radiators, directivity, aperture efficiency/power, RP points (angle, magnitude, phase in degrees) deleted when the array is destroyed (recomputation, closing the window)
<.DAT>_Temp0, …1 RP cache: angle (degrees), unnormalised magnitude, normalised magnitude, phase (degrees) for N < 400 deleted together with the array, for N ≥ 400 kept
<.DAT>_Temp0.chk, …1.chk cache signature: format version, size and time of .DAT, N, frequency for N ≥ 400

The digit in the name is the Reduce flag. For N ≥ 400, before the computation IsDirectPatSaveInFile checks that the cache exists, is not older than .DAT and its signature matches. Then the RP on the plot grid is read from the cache, while the normalisation, directivity and aperture efficiency are computed anew anyway (on the fine grid). An unusable cache is deleted and the RP is computed anew. A read-only folder is not an error: the listing and the cache are simply not written.

The thread and the progress window

Computing all RPs of a document may take minutes, so the view performs it in a separate thread:

  1. ReadDocFileW (if the RPs have not been computed yet and no computation is running) sets the global flag g_lTmcDnCalcRunning = 1, remembers the time and starts AfxBeginThread(ReadDocFileW_Thread1).
  2. The main thread shows the modal window CThreadCalcDirPat. Its timer (100 ms) reads the number of the plot being computed nGraphCurrent and the loop progress c2DArray::iN and updates the fields: RP number, number of RPs, number of radiators, percent, elapsed time.
  3. The thread: ReadDocFileW_Thread -> CTMCGROUTDoc::ReadDocFile (all plots), allocation of the view point arrays, bIsDataCalculate = TRUE, preparation of the drawing; then the flag is reset to 0.
  4. The window timer sees 0 and closes the window; the view is redrawn with the RP.

While the flag is not 0: OnDraw prints "Please wait ... Data calculate", the Characteristics and Add characteristics commands do nothing, recomputation for a new X range is not performed, the timer does not check files, and the Hide button and the close button of the progress window have no effect. Closing the document window during the computation waits for the end of the thread (OnDestroy).

The code of the Windows version calls RedrawWindow at the end of the computation and writes the status bar directly from the computation thread. In Qt this is allowed only from the main thread, therefore:

  • DnViewWidget (the view host widget) does not draw by itself when called from another thread, but queues a repaint in the event queue of the main thread; a message box from the thread is shown without waiting for an answer;
  • StatusBarHost (the host of the frame's status bar) also passes the text to the main window through the event queue.

The order and the result of the computations do not change — only the display is deferred.

Axis quantities

Axis Values Label
X, nXType = 0 angle, radians Angle radian
X, nXType = 1 angle, degrees Angle degree
Y, TMC_GROTS_TYPE_FULL (0) |F| = normalised amplitude · dMax Pattern
Y, TMC_GROTS_TYPE_AMPL (1) 20lg|F|, dB Pattern dB
Y, TMC_GROTS_TYPE_PHAS_R (2) normalised amplitude Pattern
Y, TMC_GROTS_TYPE_PHAS_G (3) normalised amplitude in dB Pattern dB

In the Viewport dialog the X axis is chosen with the Radian/Degree radio buttons, the Y axis with the Pattern/Pattern dB radio buttons and the Normirovka check box (+2). The constants are taken from the TMCROS table (TMC_GROTS_TYPE_nT = 0 for radians, TMC_GROTS_TYPE_ps = 1 for degrees). The VSWR and L (dB) types remain in the table from the earlier viewers and cannot be selected in the dialog. The Y auto-range is computed only over the points visible along X; the enabled X auto-range is −π…π (−180…180°).

Drawing

The structure is the same as in TMCGROUT: MM_HIMETRIC coordinates, a 10 × 10 grid, axes with arrows, line styles. The difference is thinning: PrepareLogGraph builds the set tmcgrwin1, which includes only the points within the X range, and of consecutive points with the same on-screen height — only the outermost ones. Lines and markers are drawn from tmcgrwin1; when marker thinning is enabled, every (n/20+1)-th point is drawn.

Legend

A legend line to the right of the plot: a line sample, the label and, if the RP has been computed without an error, Knd = <dB>dB; Kip = <ratio>; or for a large array Knd = <dB>dB; Emitted Power = <…>;.

Expression curves

A plot line of the form {formula with [file.DAT] ...} is parsed in the same way as in TMCGROUT: the RP is computed for each file (ReadGraph1), and the angle grids must coincide. The variable f of the expression is the angle of the point (radians). Into the formula, in place of each [file], GetExpressionValueK is substituted: (1+|a|)/(1−|a|), where a is the value of the RP array of that file — see pitfalls.

Distribution deviations

The Make Distribution Deviation dialog (cDeviation, a button of the Characteristics dialog) creates a new .DAT from the source one, giving each radiator an independent uniformly distributed deviation (theory):

A′=A(1+ξAδA/100),ψ′=ψ+ξψδψ,x′=x+ξxδx,y′=y+ξyδy,ξ∈[−1,1],(5)

where δA is in percent, δψ in degrees, δx,δy in mm (by default the amplitude and phase are 10, the coordinates 0). The computation is c2DArray::MakeDeviation, writing is SaveData (the .DAT format with sectors, without directivity). The file is written immediately after the "To" path is chosen and again on OK. The resulting file is opened as an ordinary RP.

RP with deviations and the required RP

The Calculate Directional Pattern Deviation dialog (CDeviatDirPat) compares the RP of an array with the required one:

  1. the first array reads .DAT (sectors are taken into account);
  2. the second reads the required-RP file .opt — lines "angle_in_degrees value" (lines where two numbers could not be read are skipped; at least 2 points) — and takes the angle grid from it (OptimizationInit);
  3. the frequency, the expression of the common element pattern, the radiators and their sectors are transferred to the second one;
  4. SaveDeviationDirectionalPattern computes and normalises the RP on this grid and writes .dev: the line !Degree AmplitudeDirectPatternRequired AmplitudeDirectPattern, then one line per angle — the angle (degrees), the required and the computed normalised RP separated by tabs.

For N > 400 the normalisation is to the maximum at the .opt points. The function GetOptimPurposeFunction (the sum of |Fnorm−Freq| over the points) for fitting amplitudes and phases is not called in the package.

Time → S-matrix (legacy)

The dianapgr directory contains copies of the TtoS subsystem of the TMCROS viewer: the To S-matrix dialog (CDialogTtoS), CTmcTtoS, CTmcSMatrix — a variant without multi-frequency processing. The code is built (tmc_dn_core, tmc_dn_view), the handler OnEditTosmatrix is in the message map of the view, but there is no menu item in the Qt6 version of TMC_DN, so the dialog is not available to the user. Its structure is described for TMCROS: time → S, the To S-matrix dialog.

Menu commands

The menu and the toolbar repeat the resources of the Windows version (IDR_TMCGROTYPE, IDR_MAINFRAME). A command is executed by the message map of the view; printing is done by the main window itself. Differences from TMCGROUT:

Command Handler What it does in TMC_DN
File > Open MainWindow::onOpenDocument filter *.dat *.dop *.$op
File > Save As OnFileSaveAs recomputes relative paths; the dialog suggests the .tos extension
Edit > Characteristics OnEditDocument 20 RP rows with display and Reduce check boxes, deviation buttons; after OK — full recomputation
Edit > Add characteristics OnEditAddcharacteristics choice of *.dat, the line <name> <name> 1 1 1 1 1, recomputation, the Characteristics dialog
View > Viewport OnEditGraphicsparameters radians/degrees, Pattern/Pattern dB, Normirovka
View > Redraw data OnViewGraphics full recomputation of all RPs
Zoom ±X, mouse frame, Translate X, Home, End, Auto X, Resize window OnViewZoomZoomxp … new X range and recomputation of the RP of small arrays (ReadDocFileW_1); Home — left limit 0, End — right limit π (180°), the width is kept
Config > Color > Graphics OnConfigColorGraphics after OK — full recomputation

The other commands (Zoom ±, ±Y, Auto Y, colours, font, editor) are as in TMCGROUT.

Qt shell

main.cpp: safe DLL search, QApplication named TMC_DN, the settings name CWinApp::SetAppName("TMC_DN"), the theme, the main window; the first command-line argument is a document file or a .DAT. MainWindow::openDocument checks that the file exists and that the path can be represented in the Windows code page, creates the document, the view and DnViewWidget, sets the background from the document colour and calls initialUpdate — in it OnInitialUpdate of the view starts the computation. The CMainFrame frame with the status-bar host StatusBarHost becomes the main window of the compatibility-layer application, so that PutTrace/PutStatistics write to the status bar of the window (left pane — coordinates under the mouse, right pane — Pattern; Freq=<GHz> GHz).

Test programs

Not part of the distribution.

Program What it does
tmc_dn_doccheck <document> [--dump] opens the document with the program code (computing the RP) and prints the axis parameters, the plots, N, directivity, aperture efficiency/power, dMax, the first points; --dump — the file lines with visible CR/LF/TAB. Creates temporary files next to it (and for a .DAT — a .dop document) — run it on a copy
tmc_dn_shot <file.png> [document] [width] [height], --dialogs [folder] a snapshot of the main window (1 s after opening) or of all dialogs as PNG
tmc_dn_uitest <document> [seconds per step] presses all commands, resizes the window, clicks on the plot; a hang — code 2 and the stack, a grabbed mouse — code 3 (not Windows)

testtools/crashtrace.h prints the stack and the thread (main or computation) on a crash.

Typical errors and pitfalls

  • The progress indicator computes the percentage as iN/10, i.e. it is designed for a grid of 1000 angles (a large array). For a small array the bar reaches 40%. The time of the normalisation on the fine grid (for a large contour — the main part of the computation) is not reflected in the indicator.
  • A large array (N > 400, almost always a file from the kernel): the aperture efficiency is not computed — the legend shows Emitted Power; the RP is always on the −π…π grid of 1000 points; changing the X range does not recompute it but only crops it.
  • Expression curves: (1+|a|)/(1−|a|) of the normalised amplitude is substituted into the formula, and the imaginary part of the RP array elements is not set (read_RT_output_signal) — the result of the expression is not an RP.
  • The third line of .DAT is read together with the line feed, so the comparison with 1. does not succeed and the expression of the common element pattern is evaluated at every point (this does not affect the result, only the time). The angle for it is printed into the string with 6 significant digits.
  • Radiator phases are taken by TMC_DN from .DAT as they are. With ANGLE_UNIT gradus in the task file the kernel writes wrong radiator phases (a defect of the TMCIndan library), and the RP comes out wrong; see accumulating the quadratures.
  • A double click does not recompute changed files after the first computation; new data are picked up by the timer (within 10 s).
  • Save As suggests the .tos extension (a TMCROS legacy) — for a TMC_DN document you have to specify .dop.
  • The document label #TMCGROTS is the same as for TMCROS documents: a TMCROS file opened in TMC_DN is read as an RP document, and its lines are taken for .DAT names.
  • Deviations (MakeDeviation) are generated by rand() without a seed: every time the program is started, the sequence is the same.
  • c2DArray::GetIzl/SetIzl check the index as i > nIzl and let i == nIzl through.
  • A listing and a cache appear next to .DAT (temporary files); for N ≥ 400 the cache and its signature remain even after the program is closed.

Files outside the build

dianapgr/childfrm.h/.cpp (MFC MDI child window), dianapgr/tmcgrout.cpp (the MFC application), dianapgr/stdafx.cpp, dianapgr/tmcgrparcoltypwid1.h/.cpp (an empty dialog stub), dianapr/dianapr.cpp (a console program computing the RP from .DAT — the same computation is done by c2DArray::CalculateDiagrNapr), dianapr/stdafx.cpp. They are kept for comparison with the MFC version (legacy).