Программа TMC_DN — API-документация
Пакет TMC Suite. Вьювер диаграмм направленности (ДН) антенных решёток: расчёт и построение диаграммы направленности по описанию решётки излучателей, а также расчёт КНД/КИП, отклонений ДН и преобразование «время → S-матрица». Язык документации: русский. Все сигнатуры приведены по исходникам из
src/viewers/DiaNapGr/, ядру расчёта ДН изsrc/viewers/DiaNapr/(c2DArray,cIzl) и общим заголовкам изsrc/Include/.
1. Назначение программы
TMC_DN (исходники — папка src/viewers/DiaNapGr/, выходной EXE — TMC_DN.exe) — графический просмотрщик и калькулятор диаграмм направленности антенных решёток.
Программа построена на той же кодовой базе MFC Document/View (MDI), что и TMCGROUT (классы CTMCGROUTApp, CMainFrame, CChildFrame, CTMCGROUTDoc, CTMCGROUTView имеют те же имена), но расширена для работы с диаграммами направленности:
- читает текстовые файлы
.datс описанием антенной решётки (частота, число излучателей, координаты/амплитуды/фазы каждого излучателя, выражение ДН одного элемента); - по этому описанию рассчитывает диаграмму направленности решётки (когерентное суммирование полей излучателей по углу) — класс
c2DArray; - вычисляет интегральные характеристики: КНД (коэффициент направленного действия,
Knd, в разах и дБ) и КИП (коэффициент использования поверхности,Kip); - строит 2D-график ДН (как и TMCGROUT строит частотные характеристики), показывает КНД/КИП в строке состояния;
- считает ДН в фоновом потоке с прогресс-окном (классы
CThreadCalcDirPat, функцияReadDocFileW_Thread1) — расчёт большой решётки длительный; - умеет вносить случайные отклонения (девиации) в параметры излучателей (
cDeviation,c2DArray::MakeDeviation) и считать ДН отклонённой решётки относительно требуемой ДН (CDeviatDirPat,c2DArray::OptimizationInit/SaveDeviationDirectionalPattern); - содержит утилиту преобразования временно́го сигнала в S-матрицу (
CDialogTtoS,CTmcTtoS,CTmcSMatrix) — общий с TMCROS код.
Всё, что относится к рисованию, осям, цветам, масштабированию, формату документа — устроено так же, как в TMCGROUT (см. tmcgrout.md, разделы 3, 7–9, 11–12). Ниже подробно документируются именно отличия и дополнения TMC_DN, а общая часть приводится со ссылками.
2. Состав проекта
В сборку TMC_DN.vcxproj входят файлы из src/viewers/DiaNapGr/ плюс ядро расчёта ДН из src/viewers/DiaNapr/:
| Файл | Класс / содержимое | Назначение (кратко) |
|---|---|---|
TMCGROUT.cpp/.h |
CTMCGROUTApp |
Класс приложения, InitInstance; ключ реестра — "TMC_DN" |
MainFrm.cpp/.h |
CMainFrame |
Главное MDI-окно (тулбар, статусбар) |
ChildFrm.cpp/.h |
CChildFrame |
Дочернее MDI-окно документа |
TMCGROUTDoc.cpp/.h |
CTMCGROUTDoc |
Документ: чтение/запись, загрузка данных; + массив ДН pcDirectionalPattern |
TMCGROUTView.cpp/.h |
CTMCGROUTView |
Вид: отрисовка, мышь, меню; + фоновый расчёт ДН |
TMCGROUTDIALOGView.cpp/.h |
CTMCGROUTDIALOGView |
Диалог параметров графика |
DialogDoc.cpp/.h |
CDialogDoc |
Диалог-таблица документа; + кнопки девиаций (DN) |
TmcGroutColorGraphDialog.cpp/.h |
CTmcGroutColorGraphDialog |
Цвета/тип/толщина 16 линий |
TmcGrParColTypWid.cpp/.h |
CTmcGrParColTypWid |
Параметры одной линии |
TmcGrParColTypWid1.cpp/.h |
CTmcGrParColTypWid1 |
Пустой диалог-заготовка (см. §10) |
TMCGrExpression.cpp |
CTMCGrExpression |
Графики-выражения (заголовок общий) |
cDeviation.cpp/.h |
cDeviation |
Диалог внесения случайных отклонений в решётку |
DeviatDirPat.cpp/.h |
CDeviatDirPat |
Диалог расчёта ДН отклонённой решётки vs. требуемой |
ThreadCalcDirPat.cpp/.h |
CThreadCalcDirPat |
Прогресс-окно фонового расчёта ДН |
DialogTtoS.cpp/.h |
CDialogTtoS |
Диалог «время → S-матрица» (общий с TMCROS) |
TmcTtoS.cpp |
CTmcTtoS |
Логика преобразования T→S (заголовок общий) |
TmcSMatrix.cpp |
CTmcSMatrix |
Сборка S-матрицы из временно́го сигнала (заголовок общий) |
..\DiaNapr\c2DArray.cpp/.h |
c2DArray |
Ядро: модель антенной решётки и расчёт ДН |
..\DiaNapr\cIzl.cpp/.h |
cIzl |
Один излучатель решётки |
StdAfx.cpp/.h |
— | Прекомпилированный заголовок MFC |
resource.h, TMCGROUT.rc |
— | Ресурсы |
Жирным выделены файлы и классы, специфичные для TMC_DN (отсутствуют в TMCGROUT). Класс
c2DArrayподключается через относительный путь..\DiaNapr\c2DArray.h.
Зависимости: MFC; общие заголовки src/Include/ (Tmcgrviw.h, Proc_s.h, complex1.h, typedef.h, expr.h, TmcTtoS.h, TmcSMatrix.h, TMCGrExpression.h); библиотеки пакета: SFILE95, complex, exprint (i1nte_atof_1, expr_set_angle, expr_get_error из expr.h — вычисление выражения ДН элемента).
3. Архитектура расчёта ДН (отличие от TMCGROUT)
В TMCGROUT график i берётся из S-файла. В TMC_DN добавлен параллельный массив объектов ДН:
// поле CTMCGROUTDoc
c2DArray * pcDirectionalPattern; // массив [grdoc.nGraph] — по объекту ДН на каждый график
int nGraphCurrent; // индекс ДН, которая считается прямо сейчас
Поток данных:
.dat (описание решётки)
│ c2DArray::ReadData → cIzl[] (читает излучатели)
▼
c2DArray::CalculateDiagrNapr (считает pdRealDN[], pdImageDN[] по углам)
│ + NormirovkaDiagrNapr (КНД/КИП, нормировка)
▼
CTMCGROUTView (рисует как обычный график; масштаб амплитуды × GetdMax)
Расчёт запускается в отдельном потоке ReadDocFileW_Thread1 (через AfxBeginThread), а модальное окно CThreadCalcDirPat показывает прогресс по полю c2DArray::iN (текущий угол) и nGraphCurrent (текущая ДН из общего числа).
4. Класс c2DArray — модель антенной решётки и расчёт ДН
Назначение: хранит описание антенной решётки (набор излучателей cIzl), рассчитывает её диаграмму направленности по углу, считает КНД/КИП, читает/пишет файлы .dat, поддерживает девиации и сравнение с требуемой ДН.
Заголовок: src/viewers/DiaNapr/c2DArray.h
Реализация: src/viewers/DiaNapr/c2DArray.cpp
Зависит от: cIzl.h, windows.h, typedef.h, expr.h (exprint — i1nte_atof_1), стандартная математика.
Физическая модель (как работает расчёт)
Поле решётки в направлении dAngle (плоская задача, угол в радианах) — когерентная сумма по всем излучателям:
Re = Σ aᵢ·cos( φᵢ + (2π·f·cᵢ/c₀)·cos(dAngle − αᵢ) )
Im = Σ aᵢ·sin( φᵢ + (2π·f·cᵢ/c₀)·cos(dAngle − αᵢ) )
где для излучателя i: aᵢ — амплитуда (с учётом собственной ДН элемента и углового диапазона), φᵢ — фаза, (xᵢ,yᵢ) — координаты, cᵢ=√(xᵢ²+yᵢ²) — расстояние от начала координат, αᵢ=atan2(yᵢ,xᵢ), f — частота (Гц), c₀ = 299792458 м/с — скорость света. Амплитуда ДН в точке: |поле| = √(Re²+Im²), фаза: atan2(Im,Re).
Это научный код расчёта. Формулы НЕ изменять без разрешения автора.
Поля (private, основные)
| Поле | Тип | Назначение |
|---|---|---|
pcIzl |
cIzl* |
Массив излучателей решётки, длина nIzl |
nIzl |
int |
Число излучателей |
dFreq |
double |
Рабочая частота, Гц (в файле задаётся в ГГц) |
szOneExpression |
char[1000] |
Выражение ДН одного элемента (текст, вычисляется exprint; "1." — изотропный) |
nAngle |
int |
Число угловых точек ДН (по умолчанию 400; 1000 для больших решёток) |
pdAngle |
double* |
Массив углов (рад), длина nAngle |
pdRealDN |
double* |
Амплитуда ДН по углам (после нормировки — в [0..1]) |
pdImageDN |
double* |
Фаза ДН по углам (рад) |
pdRequiredDN |
double* |
Требуемая ДН (для режима сравнения/девиаций) |
dKnd |
double |
КНД (раз) |
dKip |
double |
КИП (раз) |
dMax |
double |
Максимум амплитуды ДН (масштабный множитель) |
iN |
int (public) |
Текущий обрабатываемый угол — индикатор прогресса для потока |
bIsReduceElMagnAnalysis |
BOOL (public) |
Учитывать угловой диапазон FiMin..FiMax каждого элемента |
bIsError |
BOOL |
Флаг ошибки |
szError |
char[1000] |
Текст последней ошибки |
nMaxTemporary |
int |
Порог «большой решётки» (400): сверх него ДН кэшируется во временный файл |
nPointForNormir |
int |
Число точек для интегрирования при нормировке/КНД (по умолчанию 1000) |
Конструктор / деструктор
c2DArray()
Инициализирует поля (нет излучателей, nAngle=400, изотропный элемент "1."), выделяет угловые массивы (InitAngle), задаёт режим углов exprint в радианах (expr_set_angle(EXPR_RADIAN)).
~c2DArray()
Удаляет временный и выходной файлы (если создавались), освобождает все массивы (DeleteAngle, DeleteData).
Публичные методы — расчёт и доступ к ДН
void CalculateDiagrNapr(char *szInputFileName, char *szOutputFileName)
Что делает: полный цикл «из файла в файл»: читает решётку (ReadData), считает ДН (CalculateDiagrNapr()), записывает результат (WriteData).
| Параметр | Тип | Назначение |
|---|---|---|
szInputFileName |
char* |
Путь к .dat-файлу с описанием решётки |
szOutputFileName |
char* |
Путь к выходному файлу ДН |
void CalculateDiagrNapr(void)
Что делает: рассчитывает ДН для уже загруженной решётки.
Как работает: для каждого угла pdAngle[iN] вычисляет Re/Im (CalculateRealDN/CalculateImageDN), при изотропном элементе (szOneExpression=="1.") — напрямую, иначе домножает на значение выражения элемента (через i1nte_atof_1); пишет амплитуду в pdRealDN, фазу в pdImageDN; затем нормирует (NormirovkaDiagrNapr). Для больших решёток, если есть актуальный кэш, читает его (ReadDataFromTempFile). Поле iN обновляется по ходу — его читает прогресс-окно.
Ошибки: при ошибке вычисления выражения ставит bIsError=TRUE, текст из expr_get_error().
int GetnAngle(void) — число угловых точек ДН.
double GetdAngle(int i) — угол i-й точки (рад); 0.0 при выходе за границы/ошибке.
double GetdAmplitudeDiagrNapr(int i) — амплитуда ДН в i-й точке; 0.0 при ошибке.
double GetdMax(void) — максимум амплитуды ДН (масштабный множитель dMax).
double GetKnd(void) / double GetKnd_dB(void) — КНД в разах / в дБ (10·lg(Knd)).
double GetKip(void) / double GetKip_dB(void) — КИП в разах / в дБ.
int GetnIzl(void) — число излучателей.
double GetdFreqGHz(void) — частота в ГГц.
BOOL IsCalculateKip(void) — TRUE, если решётка «большая» (nIzl > nMaxTemporary) — тогда вместо КИП считается «излучённая мощность».
BOOL IsError(void) / char* GetError(void) — флаг и текст ошибки.
void ResizeAngle(double dAngleMin, double dAngleMax)
Перестраивает сетку углов на диапазон [dAngleMin, dAngleMax] (рад), пересчитывает ДН и перезаписывает выходной файл.
Публичные методы — ввод/вывод и редактирование решётки
void ReadData(char *szFileName1)
Загружает решётку из .dat. Формат: строка Frequence = … Ghz;, строка N = …; (число излучателей), строка-выражение ДН элемента, далее по строке на излучатель: i X = … mm; Y = … mm; Amplitude = …; Faza = … degree; [FiMin = … degree; FiMax = … degree; выражение]. Координаты переводятся в метры, фазы и углы — в радианы.
void SaveData(char *pszFile)
Сохраняет только описание решётки (без рассчитанной ДН) в файл pszFile.
void SaveDeviationDirectionalPattern(char *pszFileName)
Считает ДН и пишет файл из трёх колонок: угол (град) · требуемая ДН · рассчитанная ДН — для сравнения отклонённой решётки с эталоном.
void GetIzl(int i, double *dXmm, double *dYmm, double *dAmpl, double *dFazaDegree)
Возвращает параметры излучателя i: координаты (мм), амплитуду, фазу (град).
void SetIzl(int i, double dXcoord_mm, double dYcoord_mm, double dAmplitud, double dFaza_gradus)
Задаёт параметры излучателя i.
double GetRealIzl(int i) / double GetImageIzl(int i)
Re/Im комплексного возбуждения излучателя i: a·cos(φ) / a·sin(φ).
void SetdFrequence(double dFrequenceGHz) — задаёт частоту (вход в ГГц, хранится в Гц).
void SetOneExpression(char *ch) / void SetszOneExpression(char *ch) / char* GetOneExpression(void)
Задать/получить текст выражения ДН элемента. (SetOneExpression дополнительно проверяет длину; SetszOneExpression — без проверки.)
char* GetOneExpression(void) — текущее выражение элемента.
void SetNPointForNormirovka(int nPoint) — число точек интегрирования при нормировке.
Публичные методы — девиации и оптимизация
void MakeDeviation(char *szSourceFile, char *szDistinationFile, double dXmm, double dYmm, double dAmplProcent, double dFazaDegree)
Что делает: читает решётку из szSourceFile, вносит случайные отклонения в каждый излучатель (координаты ±dXmm/dYmm мм, амплитуда ±dAmplProcent %, фаза ±dFazaDegree град — равномерное распределение через GetRnd), сохраняет результат в szDistinationFile.
void OptimizationInit(char *szFileRequiDirPat, int nIzl1)
Читает файл требуемой ДН (две колонки: угол в градусах, амплитуда) в pdRequiredDN, выделяет решётку на nIzl1 излучателей. Используется в CDeviatDirPat.
double GetOptimPurposeFunction(void)
Целевая функция оптимизации: пересчитывает ДН и возвращает сумму модулей отклонений Σ|pdRealDN[i] − pdRequiredDN[i]|.
Ключевые приватные методы
| Метод | Назначение |
|---|---|
double CalculateRealDN(double dAngle) / CalculateImageDN(double dAngle) |
Re/Im поля решётки в направлении dAngle (формулы — см. «Физическая модель») |
double CalculateRealDN_ForKip(double) / CalculateImageDN_ForKip(double) |
То же, но с единичными амплитудами и нулевой фазой (для расчёта КИП) |
void NormirovkaDiagrNapr(void) |
Нормировка ДН на максимум; интегрирование для КНД и КИП |
void InitAngle(void) / DeleteAngle(void) |
Выделить/освободить угловые массивы; равномерная сетка 0..π (или −π..π для большой решётки) |
void InitData(void) |
Выделить массив pcIzl[nIzl], обнулить ДН |
void ReadData(void) / WriteData(void) |
Внутренние чтение/запись (работают по szFileName/szFileNameOut) |
double GetRnd(double dMedium, double dDelta) |
Равномерное случайное число в [dMedium−dDelta, dMedium+dDelta] |
BOOL IsDirectPatSaveInFile(void) / WriteTemporaryFile(void) / ReadDataFromTempFile(void) |
Кэш ДН во временном файле для больших решёток (сравнение времён записи) |
FILETIME LastWriteTime(char *szFileName) |
Время последней записи файла |
5. Класс cIzl — один излучатель решётки
Назначение: хранит параметры одного излучателя антенной решётки и вычисляет его собственную (элементную) диаграмму направленности.
Заголовок: src/viewers/DiaNapr/cIzl.h
Реализация: src/viewers/DiaNapr/cIzl.cpp
Зависит от: typedef.h, expr.h (exprint).
Поля (private)
| Поле | Тип | Назначение |
|---|---|---|
dAmplituda |
double |
Амплитуда возбуждения |
dFaza |
double |
Фаза возбуждения (рад) |
dXcoordinata, dYcoordinata |
double |
Координаты излучателя (м) |
dFimin, dFimax |
double |
Угловой диапазон видимости элемента (рад) |
csEmitterDirectPat |
CString |
Текст выражения собственной ДН элемента |
nTypeEmitterDirectPat |
int |
Тип ДН элемента: ALL(0)/SIN(1)/COS(2)/ARB(−1) |
Константы типа ДН элемента (cIzl.h)
| Константа | Значение | Смысл |
|---|---|---|
TMC_IZL_DIRPATTYPE_ALL |
0 | Изотропный ("1.") |
TMC_IZL_DIRPATTYPE_SIN |
1 | sin(f) |
TMC_IZL_DIRPATTYPE_COS |
2 | cos(f) |
TMC_IZL_DIRPATTYPE_ARB |
−1 | Произвольное выражение (через exprint) |
Методы
double GetdAmplituda(double dAngle)
Что делает: амплитуда элемента в направлении dAngle с учётом собственной ДН: dGetDirectionalPatternEmitter(dAngle) · dAmplituda. Если амплитуда ≈ 0 — возвращает 0.
double dGetDirectionalPatternEmitter(double dAngle)
Что делает: значение собственной ДН элемента в направлении dAngle.
Как работает: если угол вне [Fimin,Fimax] — FLT_MIN; для ALL→1, SIN→sin(dAngle), COS→cos(dAngle); для произвольного — подставляет угол f и вычисляет выражение через i1nte_atof_1.
BOOL bIsAngleInDiapazon(double dAngle)
TRUE, если угол попадает в диапазон видимости [Fimin,Fimax] (с приведением углов к двум формам через dAnglePrived/dAnglePrived1).
Сеттеры/геттеры
SetdAmplituda/GetdAmplituda, SetdFaza/GetdFaza, SetdXcoordinata/GetdXcoordinata, SetdYcoordinata/GetdYcoordinata, SetdFimin/GetdFimin, SetdFimax/GetdFimax, SetcsEmitterDirectPat/GetcsEmitterDirectPat (две перегрузки сеттера — для char* и CString&; при установке распознаётся тип ДН элемента).
cIzl& operator=(cIzl& cIzl1)
Полное копирование всех полей излучателя.
Приватные void dAnglePrived(double& dAngle) / dAnglePrived1(double& dAngle)
Приведение угла к диапазону (−π,π] и (0,2π] соответственно (через atan2(sin,cos)).
6. Дополнения в CTMCGROUTDoc (отличия от TMCGROUT)
Документ TMC_DN — это CTMCGROUTDoc (заголовок TMCGROUTDoc.h), как в TMCGROUT (см. tmcgrout.md, раздел 7), но с добавлениями для ДН:
Дополнительные поля
| Поле | Тип | Назначение |
|---|---|---|
pcDirectionalPattern |
c2DArray* |
Массив объектов ДН (по одному на график документа) |
nGraphCurrent |
int |
Индекс ДН, рассчитываемой в данный момент (для прогресс-окна) |
Дополнительные структуры (в TMCGROUTDoc.h)
Объявлены DN-варианты структур графика/документа (с суффиксом _DN): TMC_GR_DOC1_DN и TMC_GR_DOC_DN. Они повторяют TMC_GR_DOC1/TMC_GR_DOC (см. tmcgrout.md, раздел 3), добавляя поле bIsReduceElMagnAnalysis (учитывать угловой диапазон элементов). Поле grdoc документа имеет тип TMC_GR_DOC_DN.
Остальное (чтение/запись .soc, параметры графиков и оформления, цвета, шрифт) — идентично TMCGROUT.
7. Дополнения в CTMCGROUTView (фоновый расчёт ДН)
Вид TMC_DN — CTMCGROUTView (заголовок TMCGROUTView.h), общая отрисовка/мышь/меню — как в TMCGROUT (см. tmcgrout.md, раздел 8). Отличия:
Дополнительное поле
| Поле | Тип | Назначение |
|---|---|---|
ltime_start |
time_t |
Момент старта расчёта ДН (для отсчёта времени в прогресс-окне) |
void ReadDocFileW_Thread(void)
Что делает: перечитывает документ и пересоздаёт буферы точек из фонового потока; в конце выставляет bIsDataCalculate=TRUE, пересчитывает и перерисовывает график. Запускается функцией-обёрткой потока:
UINT ReadDocFileW_Thread1( LPVOID pParam ); // (CTMCGROUTView*)pParam -> ReadDocFileW_Thread()
void OnEditTosmatrix()
Команда меню — открывает диалог CDialogTtoS («время → S-матрица»).
Отрисовка амплитуды ДН
В OnDrawGraph*/PrepareDoubleGraph амплитуда точки масштабируется на максимум ДН: pSmatr[j].x · pcDirectionalPattern[i].GetdMax(). В строке состояния (PutStatistics1) выводятся КНД и КИП (или «Emitted Power» для больших решёток).
void OnDestroy()
Перед закрытием дожидается завершения фонового расчёта: пока bIsDataCalculate==FALSE, повторно показывает прогресс-окно CThreadCalcDirPat.
8. Класс CThreadCalcDirPat — прогресс-окно расчёта ДН
Назначение: модальное окно с двумя прогресс-барами, показывающее ход фонового расчёта диаграмм направленности.
Заголовок: ThreadCalcDirPat.h · Базовый класс: CDialog · Ресурс: IDD_READDATA_THREAD.
Поля (DDX)
| Поле | Тип | Назначение |
|---|---|---|
pCView |
void* |
Указатель на CTMCGROUTView (источник прогресса) |
m_Progress |
CProgressCtrl |
Прогресс текущей ДН |
m_ProgressAll |
CProgressCtrl |
Прогресс по всем ДН документа |
m_csStatistics, m_csStatisticsAll |
CString |
Процент готовности (текущая / общая) |
m_CurrentDirPat, m_NAllDirPat |
int |
Номер текущей ДН / общее число ДН |
m_nEmitters |
int |
Число излучателей текущей ДН |
m_csElapsTime |
CString |
Прошедшее время (сек / мм:сс / чч:мм:сс) |
Методы
BOOL OnInitDialog()
Запускает таймер обновления (100 мс).
void OnTimer(UINT_PTR nIDEvent)
По таймеру читает прогресс из c2DArray::iN текущей ДН и nGraphCurrent документа, обновляет проценты, прогресс-бары, число излучателей и таймер. Когда последняя ДН досчитана (или ошибка) — закрывает диалог (EndDialog(0)).
INT_PTR DoModal()
Запоминает время старта (ltime_start) и показывает диалог.
9. Диалоги девиаций (специфичны для TMC_DN)
9.1. Класс cDeviation — внесение случайных отклонений
Заголовок: cDeviation.h · Базовый класс: CDialog · Ресурс: IDD_DIALOGMAKEDEVIAT.
Назначение: взять файл-источник решётки и создать файл с случайно отклонёнными параметрами излучателей.
Поля (DDX): m_csFileFrom (исходный .dat), m_csFileTo (выходной .dat), m_dXdev/m_dYdev (разброс координат, мм), m_dAmpDev (разброс амплитуды, %), m_dFazaDev (разброс фазы, град).
Методы:
- OnButtonsource() — выбор исходного файла;
- OnButtondistination() — выбор выходного файла и вызов MakeDeviation();
- OnOK() — выполнить девиацию и закрыть;
- BOOL MakeDeviation(void) (private) — вызывает c2DArray::MakeDeviation(...); при ошибке показывает сообщение.
9.2. Класс CDeviatDirPat — ДН отклонённой решётки vs. требуемой
Заголовок: DeviatDirPat.h · Базовый класс: CDialog · Ресурс: IDD_DIALOGCALCDEVIAT.
Назначение: рассчитать ДН для распределения амплитуд/фаз и сохранить её рядом с требуемой ДН (файл сравнения .dev).
Поля (DDX): m_csDistrAmplFaza (файл .dat распределения амплитуд/фаз), m_csRequireDirPat (файл .opt требуемой ДН), m_csFileDevDirPat (выходной .dev).
Методы:
- OnButtondistramplfaza() / OnButtonrequrdirectpattern() / OnButtondeviatdirpattern() — выбор файлов (последняя кнопка запускает расчёт);
- OnOK() — выполнить расчёт и закрыть;
- BOOL CalculateDeviationDirectionalPattern(void) (private) — читает распределение (c2DArray::ReadData), инициализирует требуемую ДН (OptimizationInit), переносит излучатели (GetIzl/SetIzl), сохраняет сравнение (SaveDeviationDirectionalPattern).
9.3. Дополнения в CDialogDoc
Диалог-таблица документа CDialogDoc (см. tmcgrout.md, §9.2) в TMC_DN получает две дополнительные кнопки:
- OnAddMakedeviation() — открывает диалог cDeviation;
- OnAddMakedeviation2() — открывает диалог CDeviatDirPat.
Также CDialogDoc содержит поле dTUnit (double) и подключает cDeviation.h.
10. Утилита «время → S-матрица» и прочие классы
10.1. CDialogTtoS, CTmcTtoS, CTmcSMatrix
Эта подсистема общая с TMCROS и подробно описана в tmcros.md. Кратко:
CTmcSMatrix(TmcSMatrix.h,TmcSMatrix.cpp) — читает файл временно́го сигнала.t, строит из него элементы S-матрицы (ReadTFile,MakeSmatrix,Save).CTmcTtoS(TmcTtoS.h,TmcTtoS.cpp) — высокоуровневая обёртка:TtoS(csTfn, csSfn, dTmin, dTmax, dFreq)выполняет полный цикл «файл сигнала → S-файл» черезCTmcSMatrix.CDialogTtoS(DialogTtoS.h,DialogTtoS.cpp, ресурсIDD_DIALOG3) — диалог настройки преобразования (имя S-файла, окно времениTmin..Tmax, частота, до 20 точек X), вызывается изCTMCGROUTView::OnEditTosmatrix.
10.2. CTmcGrParColTypWid1
Заголовок: TmcGrParColTypWid1.h · Ресурс: IDD_DIALOGGRLINECOLORTYPEWIDTH1.
Пустой диалог-заготовка (нет полей и обработчиков). Назначение неясно — вероятно, мёртвый код/дубль CTmcGrParColTypWid (то же замечание есть в TMCROS).
10.3. Общие с TMCGROUT классы
CTMCGROUTApp, CMainFrame, CChildFrame, CTMCGROUTDIALOGView, CTmcGroutColorGraphDialog, CTmcGrParColTypWid, CTMCGrExpression, глобальные PutTrace/PutStatistics — см. tmcgrout.md, разделы 4–6, 9–11. Единственное отличие приложения — ключ реестра "TMC_DN" вместо "TMCGROUT" в InitInstance.
The TMC_DN program — API documentation
TMC Suite package. A viewer of radiation patterns (RP) of antenna arrays: computation and building of the radiation pattern from a description of the radiator array, as well as computation of directivity/aperture efficiency, pattern deviations, and the "time → S-matrix" transform. All signatures are taken from the sources in
src/viewers/DiaNapGr/, the RP computation core fromsrc/viewers/DiaNapr/(c2DArray,cIzl) and the shared headers fromsrc/Include/.
1. Purpose of the program
TMC_DN (sources — the folder src/viewers/DiaNapGr/, the output EXE — TMC_DN.exe)
is a graphical viewer and calculator of radiation patterns of antenna arrays.
The program is built on the same MFC Document/View (MDI) codebase as TMCGROUT (the
classes CTMCGROUTApp, CMainFrame, CChildFrame, CTMCGROUTDoc, CTMCGROUTView have
the same names), but is extended to work with radiation patterns:
- reads text
.datfiles with a description of the antenna array (the frequency, the number of radiators, the coordinates/amplitudes/phases of each radiator, the pattern expression of a single element); - from this description computes the radiation pattern of the array (coherent
summation of the radiators' fields over the angle) — the
c2DArrayclass; - computes the integral characteristics: the directivity (
Knd, in ratio and dB) and the aperture efficiency (Kip); - builds a 2D graph of the pattern (as TMCGROUT builds frequency responses), shows the directivity/aperture efficiency in the status bar;
- computes the pattern in a background thread with a progress window (the classes
CThreadCalcDirPat, the functionReadDocFileW_Thread1) — computing a large array is lengthy; - can introduce random deviations into the radiator parameters (
cDeviation,c2DArray::MakeDeviation) and compute the pattern of a deviated array relative to the required pattern (CDeviatDirPat,c2DArray::OptimizationInit/SaveDeviationDirectionalPattern); - contains a utility for converting a time signal into an S-matrix (
CDialogTtoS,CTmcTtoS,CTmcSMatrix) — code shared with TMCROS.
Everything related to drawing, axes, colors, scaling, the document format is arranged
the same way as in TMCGROUT (see tmcgrout.md, sections 3, 7–9, 11–12).
Below, precisely the differences and additions of TMC_DN are documented in detail,
while the common part is given with references.
2. Project composition
The TMC_DN.vcxproj build contains files from src/viewers/DiaNapGr/ plus the RP
computation core from src/viewers/DiaNapr/:
| File | Class / contents | Purpose (briefly) |
|---|---|---|
TMCGROUT.cpp/.h |
CTMCGROUTApp |
The application class, InitInstance; the registry key — "TMC_DN" |
MainFrm.cpp/.h |
CMainFrame |
The main MDI window (toolbar, status bar) |
ChildFrm.cpp/.h |
CChildFrame |
The child MDI document window |
TMCGROUTDoc.cpp/.h |
CTMCGROUTDoc |
The document: reading/writing, loading data; + the RP array pcDirectionalPattern |
TMCGROUTView.cpp/.h |
CTMCGROUTView |
The view: drawing, mouse, menu; + background RP computation |
TMCGROUTDIALOGView.cpp/.h |
CTMCGROUTDIALOGView |
The graph-parameters dialog |
DialogDoc.cpp/.h |
CDialogDoc |
The document table dialog; + deviation buttons (DN) |
TmcGroutColorGraphDialog.cpp/.h |
CTmcGroutColorGraphDialog |
Color/type/width of 16 lines |
TmcGrParColTypWid.cpp/.h |
CTmcGrParColTypWid |
The single-line parameters |
TmcGrParColTypWid1.cpp/.h |
CTmcGrParColTypWid1 |
An empty dialog stub (see §10) |
TMCGrExpression.cpp |
CTMCGrExpression |
Expression graphs (the header is shared) |
cDeviation.cpp/.h |
cDeviation |
The dialog for introducing random deviations into the array |
DeviatDirPat.cpp/.h |
CDeviatDirPat |
The dialog for computing the pattern of a deviated array vs. the required one |
ThreadCalcDirPat.cpp/.h |
CThreadCalcDirPat |
The progress window of the background RP computation |
DialogTtoS.cpp/.h |
CDialogTtoS |
The "time → S-matrix" dialog (shared with TMCROS) |
TmcTtoS.cpp |
CTmcTtoS |
The T→S conversion logic (the header is shared) |
TmcSMatrix.cpp |
CTmcSMatrix |
Assembling the S-matrix from a time signal (the header is shared) |
..\DiaNapr\c2DArray.cpp/.h |
c2DArray |
The core: the antenna-array model and RP computation |
..\DiaNapr\cIzl.cpp/.h |
cIzl |
One array radiator |
StdAfx.cpp/.h |
— | The MFC precompiled header |
resource.h, TMCGROUT.rc |
— | Resources |
The bold entries mark the files and classes specific to TMC_DN (absent from TMCGROUT). The
c2DArrayclass is included via the relative path..\DiaNapr\c2DArray.h.
Dependencies: MFC; the shared headers src/Include/ (Tmcgrviw.h, Proc_s.h,
complex1.h, typedef.h, expr.h, TmcTtoS.h, TmcSMatrix.h, TMCGrExpression.h);
the package libraries: SFILE95, complex, exprint (i1nte_atof_1,
expr_set_angle, expr_get_error from expr.h — evaluating the element pattern
expression).
3. The RP computation architecture (difference from TMCGROUT)
In TMCGROUT graph i is taken from an S-file. In TMC_DN a parallel array of RP
objects is added:
// a field of CTMCGROUTDoc
c2DArray * pcDirectionalPattern; // an array [grdoc.nGraph] — one RP object per graph
int nGraphCurrent; // the index of the RP being computed right now
The data flow:
.dat (array description)
│ c2DArray::ReadData → cIzl[] (reads the radiators)
▼
c2DArray::CalculateDiagrNapr (computes pdRealDN[], pdImageDN[] by angle)
│ + NormirovkaDiagrNapr (directivity/aperture efficiency, normalization)
▼
CTMCGROUTView (draws it as an ordinary graph; the amplitude scale × GetdMax)
The computation is launched in a separate thread ReadDocFileW_Thread1 (via
AfxBeginThread), and the modal window CThreadCalcDirPat shows the progress by the
field c2DArray::iN (the current angle) and nGraphCurrent (the current RP out of the
total).
4. The c2DArray class — the antenna-array model and RP computation
Purpose: stores the description of the antenna array (a set of cIzl radiators),
computes its radiation pattern by angle, computes the directivity/aperture efficiency,
reads/writes .dat files, supports deviations and comparison with the required pattern.
Header: src/viewers/DiaNapr/c2DArray.h
Implementation: src/viewers/DiaNapr/c2DArray.cpp
Depends on: cIzl.h, windows.h, typedef.h, expr.h (exprint — i1nte_atof_1),
standard math.
The physical model (how the computation works)
The array field in the direction dAngle (a planar problem, the angle in radians) is a
coherent sum over all radiators:
Re = Σ aᵢ·cos( φᵢ + (2π·f·cᵢ/c₀)·cos(dAngle − αᵢ) )
Im = Σ aᵢ·sin( φᵢ + (2π·f·cᵢ/c₀)·cos(dAngle − αᵢ) )
where for radiator i: aᵢ is the amplitude (accounting for the element's own pattern
and the angular range), φᵢ is the phase, (xᵢ,yᵢ) are the coordinates,
cᵢ=√(xᵢ²+yᵢ²) is the distance from the origin, αᵢ=atan2(yᵢ,xᵢ), f is the frequency
(Hz), c₀ = 299792458 m/s is the speed of light. The pattern amplitude at a point:
|field| = √(Re²+Im²), the phase: atan2(Im,Re).
This is scientific computation code. Do NOT change the formulas without the author's permission.
Fields (private, main)
| Field | Type | Purpose |
|---|---|---|
pcIzl |
cIzl* |
The array of the array's radiators, length nIzl |
nIzl |
int |
The number of radiators |
dFreq |
double |
The operating frequency, Hz (set in GHz in the file) |
szOneExpression |
char[1000] |
The pattern expression of a single element (text, evaluated by exprint; "1." — isotropic) |
nAngle |
int |
The number of angular points of the pattern (400 by default; 1000 for large arrays) |
pdAngle |
double* |
The array of angles (rad), length nAngle |
pdRealDN |
double* |
The pattern amplitude by angle (after normalization — in [0..1]) |
pdImageDN |
double* |
The pattern phase by angle (rad) |
pdRequiredDN |
double* |
The required pattern (for the comparison/deviation mode) |
dKnd |
double |
The directivity (ratio) |
dKip |
double |
The aperture efficiency (ratio) |
dMax |
double |
The maximum of the pattern amplitude (the scale factor) |
iN |
int (public) |
The currently processed angle — a progress indicator for the thread |
bIsReduceElMagnAnalysis |
BOOL (public) |
Whether to account for the FiMin..FiMax angular range of each element |
bIsError |
BOOL |
The error flag |
szError |
char[1000] |
The text of the last error |
nMaxTemporary |
int |
The "large array" threshold (400): above it the pattern is cached to a temporary file |
nPointForNormir |
int |
The number of points for integration during normalization/directivity (1000 by default) |
Constructor / destructor
c2DArray()
Initializes the fields (no radiators, nAngle=400, the isotropic element "1."),
allocates the angular arrays (InitAngle), sets the exprint angle mode to radians
(expr_set_angle(EXPR_RADIAN)).
~c2DArray()
Deletes the temporary and output files (if they were created), frees all the arrays
(DeleteAngle, DeleteData).
Public methods — computation and RP access
void CalculateDiagrNapr(char *szInputFileName, char *szOutputFileName)
What it does: the full "file to file" cycle: reads the array (ReadData), computes
the pattern (CalculateDiagrNapr()), writes the result (WriteData).
| Parameter | Type | Purpose |
|---|---|---|
szInputFileName |
char* |
The path to the .dat file with the array description |
szOutputFileName |
char* |
The path to the output pattern file |
void CalculateDiagrNapr(void)
What it does: computes the pattern for an already-loaded array.
How it works: for each angle pdAngle[iN] computes Re/Im
(CalculateRealDN/CalculateImageDN), for an isotropic element
(szOneExpression=="1.") — directly, otherwise multiplies by the element-expression
value (via i1nte_atof_1); writes the amplitude into pdRealDN, the phase into
pdImageDN; then normalizes (NormirovkaDiagrNapr). For large arrays, if there is an
up-to-date cache, it reads it (ReadDataFromTempFile). The field iN is updated as it
goes — the progress window reads it.
Errors: on an expression-evaluation error it sets bIsError=TRUE, the text from
expr_get_error().
int GetnAngle(void) — the number of angular points of the pattern.
double GetdAngle(int i) — the angle of the i-th point (rad); 0.0 on out of bounds/error.
double GetdAmplitudeDiagrNapr(int i) — the pattern amplitude at the i-th point; 0.0 on error.
double GetdMax(void) — the maximum of the pattern amplitude (the scale factor dMax).
double GetKnd(void) / double GetKnd_dB(void) — the directivity in ratio / in dB (10·lg(Knd)).
double GetKip(void) / double GetKip_dB(void) — the aperture efficiency in ratio / in dB.
int GetnIzl(void) — the number of radiators.
double GetdFreqGHz(void) — the frequency in GHz.
BOOL IsCalculateKip(void) — TRUE if the array is "large" (nIzl > nMaxTemporary) — then "emitted power" is computed instead of the aperture efficiency.
BOOL IsError(void) / char* GetError(void) — the error flag and text.
void ResizeAngle(double dAngleMin, double dAngleMax)
Rebuilds the angle grid to the range [dAngleMin, dAngleMax] (rad), recomputes the
pattern and rewrites the output file.
Public methods — array I/O and editing
void ReadData(char *szFileName1)
Loads the array from a .dat. Format: the line Frequence = … Ghz;, the line N = …;
(the number of radiators), the element-pattern expression line, then one line per
radiator: i X = … mm; Y = … mm; Amplitude = …; Faza = … degree; [FiMin = … degree;
FiMax = … degree; expression]. The coordinates are converted to meters, the phases and
angles to radians.
void SaveData(char *pszFile)
Saves only the array description (without the computed pattern) into the file pszFile.
void SaveDeviationDirectionalPattern(char *pszFileName)
Computes the pattern and writes a three-column file: angle (deg) · required pattern · computed pattern — for comparing a deviated array with the reference.
void GetIzl(int i, double *dXmm, double *dYmm, double *dAmpl, double *dFazaDegree)
Returns the parameters of radiator i: the coordinates (mm), the amplitude, the phase
(deg).
void SetIzl(int i, double dXcoord_mm, double dYcoord_mm, double dAmplitud, double dFaza_gradus)
Sets the parameters of radiator i.
double GetRealIzl(int i) / double GetImageIzl(int i)
The Re/Im of the complex excitation of radiator i: a·cos(φ) / a·sin(φ).
void SetdFrequence(double dFrequenceGHz) — sets the frequency (input in GHz, stored in Hz).
void SetOneExpression(char *ch) / void SetszOneExpression(char *ch) / char* GetOneExpression(void)
Set/get the element pattern expression text. (SetOneExpression additionally checks the
length; SetszOneExpression — without a check.)
char* GetOneExpression(void) — the current element expression.
void SetNPointForNormirovka(int nPoint) — the number of integration points during normalization.
Public methods — deviations and optimization
void MakeDeviation(char *szSourceFile, char *szDistinationFile, double dXmm, double dYmm, double dAmplProcent, double dFazaDegree)
What it does: reads the array from szSourceFile, introduces random deviations
into each radiator (coordinates ±dXmm/dYmm mm, amplitude ±dAmplProcent %, phase
±dFazaDegree deg — a uniform distribution via GetRnd), saves the result into
szDistinationFile.
void OptimizationInit(char *szFileRequiDirPat, int nIzl1)
Reads the required pattern file (two columns: angle in degrees, amplitude) into
pdRequiredDN, allocates the array for nIzl1 radiators. Used in CDeviatDirPat.
double GetOptimPurposeFunction(void)
The optimization objective function: recomputes the pattern and returns the sum of the
absolute deviations Σ|pdRealDN[i] − pdRequiredDN[i]|.
Key private methods
| Method | Purpose |
|---|---|
double CalculateRealDN(double dAngle) / CalculateImageDN(double dAngle) |
The Re/Im of the array field in the direction dAngle (the formulas — see "The physical model") |
double CalculateRealDN_ForKip(double) / CalculateImageDN_ForKip(double) |
The same, but with unit amplitudes and zero phase (for computing the aperture efficiency) |
void NormirovkaDiagrNapr(void) |
Normalization of the pattern to the maximum; integration for the directivity and aperture efficiency |
void InitAngle(void) / DeleteAngle(void) |
Allocate/free the angular arrays; a uniform grid 0..π (or −π..π for a large array) |
void InitData(void) |
Allocate the array pcIzl[nIzl], zero the pattern |
void ReadData(void) / WriteData(void) |
Internal reading/writing (operate on szFileName/szFileNameOut) |
double GetRnd(double dMedium, double dDelta) |
A uniform random number in [dMedium−dDelta, dMedium+dDelta] |
BOOL IsDirectPatSaveInFile(void) / WriteTemporaryFile(void) / ReadDataFromTempFile(void) |
The pattern cache in a temporary file for large arrays (comparison of write times) |
FILETIME LastWriteTime(char *szFileName) |
The last write time of a file |
5. The cIzl class — one array radiator
Purpose: stores the parameters of one antenna-array radiator and computes its own
(element) radiation pattern.
Header: src/viewers/DiaNapr/cIzl.h
Implementation: src/viewers/DiaNapr/cIzl.cpp
Depends on: typedef.h, expr.h (exprint).
Fields (private)
| Field | Type | Purpose |
|---|---|---|
dAmplituda |
double |
The excitation amplitude |
dFaza |
double |
The excitation phase (rad) |
dXcoordinata, dYcoordinata |
double |
The radiator coordinates (m) |
dFimin, dFimax |
double |
The angular visibility range of the element (rad) |
csEmitterDirectPat |
CString |
The text of the element's own pattern expression |
nTypeEmitterDirectPat |
int |
The element pattern type: ALL(0)/SIN(1)/COS(2)/ARB(−1) |
Element pattern type constants (cIzl.h)
| Constant | Value | Meaning |
|---|---|---|
TMC_IZL_DIRPATTYPE_ALL |
0 | Isotropic ("1.") |
TMC_IZL_DIRPATTYPE_SIN |
1 | sin(f) |
TMC_IZL_DIRPATTYPE_COS |
2 | cos(f) |
TMC_IZL_DIRPATTYPE_ARB |
−1 | An arbitrary expression (via exprint) |
Methods
double GetdAmplituda(double dAngle)
What it does: the element amplitude in the direction dAngle accounting for its own
pattern: dGetDirectionalPatternEmitter(dAngle) · dAmplituda. If the amplitude ≈ 0 —
returns 0.
double dGetDirectionalPatternEmitter(double dAngle)
What it does: the value of the element's own pattern in the direction dAngle.
How it works: if the angle is outside [Fimin,Fimax] — FLT_MIN; for ALL→1,
SIN→sin(dAngle), COS→cos(dAngle); for an arbitrary one — substitutes the angle f
and evaluates the expression via i1nte_atof_1.
BOOL bIsAngleInDiapazon(double dAngle)
TRUE if the angle falls into the visibility range [Fimin,Fimax] (with reduction of the
angles to two forms via dAnglePrived/dAnglePrived1).
Setters/getters
SetdAmplituda/GetdAmplituda, SetdFaza/GetdFaza, SetdXcoordinata/GetdXcoordinata,
SetdYcoordinata/GetdYcoordinata, SetdFimin/GetdFimin, SetdFimax/GetdFimax,
SetcsEmitterDirectPat/GetcsEmitterDirectPat (two setter overloads — for char* and
CString&; on setting, the element pattern type is recognized).
cIzl& operator=(cIzl& cIzl1)
Full copying of all the radiator fields.
Private void dAnglePrived(double& dAngle) / dAnglePrived1(double& dAngle)
Reduction of the angle to the range (−π,π] and (0,2π] respectively (via
atan2(sin,cos)).
6. Additions in CTMCGROUTDoc (differences from TMCGROUT)
The TMC_DN document is CTMCGROUTDoc (the header TMCGROUTDoc.h), as in TMCGROUT (see
tmcgrout.md, section 7), but with additions for the pattern:
Additional fields
| Field | Type | Purpose |
|---|---|---|
pcDirectionalPattern |
c2DArray* |
The array of RP objects (one per document graph) |
nGraphCurrent |
int |
The index of the RP being computed at the moment (for the progress window) |
Additional structures (in TMCGROUTDoc.h)
DN variants of the graph/document structures (with the _DN suffix) are declared:
TMC_GR_DOC1_DN and TMC_GR_DOC_DN. They repeat TMC_GR_DOC1/TMC_GR_DOC (see
tmcgrout.md, section 3), adding the field bIsReduceElMagnAnalysis
(whether to account for the elements' angular range). The document field grdoc has the
type TMC_GR_DOC_DN.
The rest (reading/writing .soc, the graph and appearance parameters, colors, font) — is
identical to TMCGROUT.
7. Additions in CTMCGROUTView (background RP computation)
The TMC_DN view is CTMCGROUTView (the header TMCGROUTView.h), the common
drawing/mouse/menu — as in TMCGROUT (see tmcgrout.md, section 8). The
differences:
An additional field
| Field | Type | Purpose |
|---|---|---|
ltime_start |
time_t |
The moment the RP computation started (for the time counter in the progress window) |
void ReadDocFileW_Thread(void)
What it does: re-reads the document and re-creates the point buffers from the
background thread; at the end it sets bIsDataCalculate=TRUE, recomputes and redraws
the graph. It is launched by the thread wrapper function:
UINT ReadDocFileW_Thread1( LPVOID pParam ); // (CTMCGROUTView*)pParam -> ReadDocFileW_Thread()
void OnEditTosmatrix()
A menu command — opens the CDialogTtoS dialog ("time → S-matrix").
Drawing the RP amplitude
In OnDrawGraph*/PrepareDoubleGraph the point amplitude is scaled to the pattern
maximum: pSmatr[j].x · pcDirectionalPattern[i].GetdMax(). In the status bar
(PutStatistics1) the directivity and aperture efficiency are output (or "Emitted
Power" for large arrays).
void OnDestroy()
Before closing it waits for completion of the background computation: while
bIsDataCalculate==FALSE, it re-shows the progress window CThreadCalcDirPat.
8. The CThreadCalcDirPat class — the RP computation progress window
Purpose: a modal window with two progress bars, showing the course of the background
computation of the radiation patterns.
Header: ThreadCalcDirPat.h · Base class: CDialog · Resource:
IDD_READDATA_THREAD.
Fields (DDX)
| Field | Type | Purpose |
|---|---|---|
pCView |
void* |
A pointer to CTMCGROUTView (the progress source) |
m_Progress |
CProgressCtrl |
The progress of the current RP |
m_ProgressAll |
CProgressCtrl |
The progress across all RPs of the document |
m_csStatistics, m_csStatisticsAll |
CString |
The readiness percentage (current / total) |
m_CurrentDirPat, m_NAllDirPat |
int |
The current RP number / the total number of RPs |
m_nEmitters |
int |
The number of radiators of the current RP |
m_csElapsTime |
CString |
The elapsed time (sec / mm:ss / hh:mm:ss) |
Methods
BOOL OnInitDialog()
Starts the update timer (100 ms).
void OnTimer(UINT_PTR nIDEvent)
By the timer reads the progress from c2DArray::iN of the current RP and nGraphCurrent
of the document, updates the percentages, progress bars, the number of radiators and the
timer. When the last RP is computed (or on error) — closes the dialog (EndDialog(0)).
INT_PTR DoModal()
Remembers the start time (ltime_start) and shows the dialog.
9. Deviation dialogs (specific to TMC_DN)
9.1. The cDeviation class — introducing random deviations
Header: cDeviation.h · Base class: CDialog · Resource:
IDD_DIALOGMAKEDEVIAT.
Purpose: to take a source array file and create a file with randomly deviated
radiator parameters.
Fields (DDX): m_csFileFrom (the source .dat), m_csFileTo (the output .dat),
m_dXdev/m_dYdev (the coordinate spread, mm), m_dAmpDev (the amplitude spread, %),
m_dFazaDev (the phase spread, deg).
Methods:
- OnButtonsource() — choosing the source file;
- OnButtondistination() — choosing the output file and calling MakeDeviation();
- OnOK() — perform the deviation and close;
- BOOL MakeDeviation(void) (private) — calls c2DArray::MakeDeviation(...); on error
shows a message.
9.2. The CDeviatDirPat class — the pattern of a deviated array vs. the required one
Header: DeviatDirPat.h · Base class: CDialog · Resource:
IDD_DIALOGCALCDEVIAT.
Purpose: to compute the pattern for an amplitude/phase distribution and save it next
to the required pattern (the comparison file .dev).
Fields (DDX): m_csDistrAmplFaza (the .dat amplitude/phase distribution file),
m_csRequireDirPat (the .opt required-pattern file), m_csFileDevDirPat (the output
.dev).
Methods:
- OnButtondistramplfaza() / OnButtonrequrdirectpattern() / OnButtondeviatdirpattern()
— choosing the files (the last button launches the computation);
- OnOK() — perform the computation and close;
- BOOL CalculateDeviationDirectionalPattern(void) (private) — reads the distribution
(c2DArray::ReadData), initializes the required pattern (OptimizationInit), transfers
the radiators (GetIzl/SetIzl), saves the comparison
(SaveDeviationDirectionalPattern).
9.3. Additions in CDialogDoc
The document table dialog CDialogDoc (see tmcgrout.md, §9.2) in TMC_DN
gets two additional buttons:
- OnAddMakedeviation() — opens the cDeviation dialog;
- OnAddMakedeviation2() — opens the CDeviatDirPat dialog.
CDialogDoc also contains the field dTUnit (double) and includes cDeviation.h.
10. The "time → S-matrix" utility and other classes
10.1. CDialogTtoS, CTmcTtoS, CTmcSMatrix
This subsystem is shared with TMCROS and described in detail in
tmcros.md. In brief:
CTmcSMatrix(TmcSMatrix.h,TmcSMatrix.cpp) — reads a.ttime-signal file, builds S-matrix elements from it (ReadTFile,MakeSmatrix,Save).CTmcTtoS(TmcTtoS.h,TmcTtoS.cpp) — a high-level wrapper:TtoS(csTfn, csSfn, dTmin, dTmax, dFreq)performs the full "signal file → S-file" cycle viaCTmcSMatrix.CDialogTtoS(DialogTtoS.h,DialogTtoS.cpp, the resourceIDD_DIALOG3) — the conversion-settings dialog (the S-file name, the time windowTmin..Tmax, the frequency, up to 20 X points), called fromCTMCGROUTView::OnEditTosmatrix.
10.2. CTmcGrParColTypWid1
Header: TmcGrParColTypWid1.h · Resource: IDD_DIALOGGRLINECOLORTYPEWIDTH1.
An empty dialog stub (no fields or handlers). The purpose is unclear — likely dead
code / a duplicate of CTmcGrParColTypWid (the same note is in TMCROS).
10.3. Classes shared with TMCGROUT
CTMCGROUTApp, CMainFrame, CChildFrame, CTMCGROUTDIALOGView,
CTmcGroutColorGraphDialog, CTmcGrParColTypWid, CTMCGrExpression, the global
PutTrace/PutStatistics — see tmcgrout.md, sections 4–6, 9–11. The
only application difference — the registry key "TMC_DN" instead of "TMCGROUT" in
InitInstance.