Программа TMCROS — API-документация

Пакет TMC Suite. Вьювер временны́х характеристик (сигналов во временно́й области) и инструмент преобразования «время → матрица рассеяния» (Time-to-Scattering). Язык документации: русский. Все сигнатуры приведены по исходникам из src/viewers/Tmcrtout/ и общим заголовкам из src/Include/.


1. Назначение программы

TMCROS (выходной EXE — TMCROS.exe, проект TMCROS.vcxproj) — графический просмотрщик результатов электродинамического расчёта во временно́й области: строит 2D-графики временны́х сигналов многополюсника, считанных из выходных файлов сигнала (.t — Rt-Signal), и умеет на их основе вычислять матрицу рассеяния на заданных частотах (преобразование «время → S-матрица», подсистема TtoS).

Программа построена по той же схеме MFC Document/View (приложение типа MDI), что и родственный частотный вьювер TMCGROUT, и разделяет с ним большую часть исходных файлов и модель данных. Ключевые отличия TMCROS:

  • ось X — время (n, с, мс, мкс, нс, пс), а не частота;
  • ось Y — временно́й сигнал и производные от него величины (амплитудная огибающая, КСВН/потери/фаза, вычисляемые по огибающей);
  • данные читаются из файлов сигнала .t (а не из S-файлов): функция read_RT_output_signal в CTMCGROUTDoc;
  • документ имеет расширение .tos и сигнатуру #TMCGROTS (у TMCGROUT — .soc / #TMCGROUT);
  • добавлена подсистема Time-to-Scattering: классы CTmcSMatrix, CTmcTtoS и диалог CDialogTtoS, преобразующие набор временны́х сигналов в один S-файл (.s) на заданных частотах (пункт меню «To S-matrix»);
  • в виде заведён второй буфер точек tmcgrwin1 (рабочая копия для отрисовки, см. §8).

TMCROS позиционируется как временно́й (промежуточный) вьювер: он показывает сигналы и готовит из них S-матрицу, которую затем смотрят в TMCGROUT.

Совпадение имён файлов с TMCGROUT. Файлы TMCGROUT.cpp/.h, MainFrm, ChildFrm, TMCGROUTDoc, TMCGROUTView, TMCGROUTDIALOGView, DialogDoc, TmcGroutColorGraphDialog, TmcGrParColTypWid, TMCGrExpression называются так же, как в TMCGROUT (исторически TMCROS сделан копированием проекта TMCGROUT), но содержат другую логику в части временны́х данных и TtoS. Ниже то, что действительно идентично TMCGROUT, описано кратко со ссылкой; отличия документированы полно.


2. Состав проекта

В сборку TMCROS.vcxproj входят следующие файлы (по <ClCompile>/<ClInclude>):

Файл Класс / содержимое Назначение (кратко)
TMCGROUT.cpp/.h CTMCGROUTApp Класс приложения; InitInstance; диалог «О программе». Отличие от TMCGROUT — ключ реестра TMCROS
MainFrm.cpp/.h CMainFrame Главное MDI-окно (тулбар, статусбар). Аналогично TMCGROUT
ChildFrm.cpp/.h CChildFrame Дочернее MDI-окно. Аналогично TMCGROUT
TMCGROUTDoc.cpp/.h CTMCGROUTDoc Документ: чтение/запись .tos, чтение временны́х сигналов .t, параметры графиков
TMCGROUTView.cpp/.h CTMCGROUTView Вид: отрисовка временны́х графиков, мышь, меню; пункт «To S-matrix»
TMCGROUTDIALOGView.cpp/.h CTMCGROUTDIALOGView Диалог параметров графика (единицы времени, тип Y, пределы, точки)
DialogDoc.cpp/.h CDialogDoc Диалог-таблица содержимого документа (до 20 графиков)
DialogTtoS.cpp/.h CDialogTtoS TtoS-диалог: список .t-сигналов, частоты, экспорт в S-файл
TmcSMatrix.cpp (+ src/Include/TmcSMatrix.h) CTmcSMatrix TtoS-ядро: чтение .t, восстановление S-матрицы из временно́го сигнала, запись .s
TmcTtoS.cpp (+ src/Include/TmcTtoS.h) CTmcTtoS TtoS-обёртка: один вызов «файл .t → файл .s»
TmcGroutColorGraphDialog.cpp/.h CTmcGroutColorGraphDialog Диалог цвета/типа/толщины 16 линий. Аналогично TMCGROUT
TmcGrParColTypWid.cpp/.h CTmcGrParColTypWid Диалог параметров одной линии. Аналогично TMCGROUT
TMCGrExpression.cpp (+ src/Include/TMCGrExpression.h) CTMCGrExpression Графики-выражения над несколькими файлами. Аналогично TMCGROUT
StdAfx.cpp/.h Прекомпилированный заголовок MFC
resource.h, TMCGROUT.rc Ресурсы (меню, диалоги, иконки, тулбар)

Файл TmcGrParColTypWid1.cpp/.h (класс CTmcGrParColTypWid1) физически лежит в каталоге, но не включён в TMCROS.vcxproj (отсутствует в <ClCompile>/<ClInclude>) — в сборке не участвует. См. §9.5.

Зависимости и настройки сборки (TMCROS.vcxproj): - UseOfMfc = Static, CharacterSet = MultiByte, PlatformToolset = v145; конфигурации Win32 и x64 (Debug/Release); - линковка с библиотеками пакета: SFILE95 (sfile95.lib — запись S-матрицы save_S_matrix_element), complex (complex.lib), exprint (exprint.lib — вычисление выражений); - выходной каталог из build\ExeOutput.propsdist\<platform>\bin; - общие заголовки из src/Include/: tmcgrviw.h, proc_s.h, s_file.h, typedef.h, complex1.h, TmcSMatrix.h, TmcTtoS.h, TMCGrExpression.h.


3. Общие структуры данных (заголовок Tmcgrviw.h)

TMCROS использует те же структуры модели данных, что и TMCGROUT (TMC_GR_DOC1, TMC_GR_DOC, TMC_GR_VIEW, TMC_GR_WINDOW, TMC_GR_TYPE_X/Y). Полное описание полей — см. tmcgrout.md, §3. Здесь зафиксированы отличия в трактовке полей и константы типов, специфичные для временно́го вьювера.

3.1. Отличие трактовки полей TMC_GR_DOC1

В TMCROS поля структуры графика читаются из файла сигнала .t, поэтому их физический смысл другой:

Поле Тип Трактовка в TMCROS
pFreq double* Массив отсчётов времени (а не частот): значения времени из .t-файла
pSmatr _complex* Массив значений сигнала: pSmatr[j].xотсчёт временно́го сигнала для выбранного входа/моды (мнимая часть .y не используется)
dFreq double Частота (Гц), считанная из строки #TMC_GROTS_Freq … файла .t; используется при восстановлении фазы/амплитуды и в TtoS
nInp1, nMod1 int Номер входа и моды (столбца сигнала) в .t-файле; нормируются в read_RT_output_signal (in1≥1, mod1∈{0,1})
nInp2, nMod2 int Второй адрес; в read_RT_output_signal принудительно in2=1, mod2∈{0,1}
szFileName char* Полный путь к .t-файлу сигнала

Остальные поля (nPoint, szGrapName, szGrapPodp, LineColor/Type/Width, piPoint[10], PointColor/Type/Width, OutFlag, LastWriteTime, pcExpr) — как в TMCGROUT.

3.2. Константы типа оси X (время) — TMC_GROTS_TYPE_*

Константа Значение Смысл (ось X)
TMC_GROTS_TYPE_nT 0 Время в отсчётах (номер точки)
TMC_GROTS_TYPE_ps 1 Время, пс (×1e−12)
TMC_GROTS_TYPE_ns 2 Время, нс (×1e−9)
TMC_GROTS_TYPE_mks 3 Время, мкс (×1e−6)
TMC_GROTS_TYPE_ms 4 Время, мс (×1e−3)
TMC_GROTS_TYPE_s 5 Время, с (×1)

3.3. Константы типа оси Y — TMC_GROTS_TYPE_*

Константа Значение Смысл (ось Y)
TMC_GROTS_TYPE_FULL 0 Сигнал — отсчёт сигнала как есть (pSmatr[j].x)
TMC_GROTS_TYPE_AMPL 1 Амплитуда (огибающая |S|, восстановленная по локальным экстремумам сигнала)
TMC_GROTS_TYPE_PHAS_R 2 Фаза, радианы
TMC_GROTS_TYPE_PHAS_G 3 Фаза, градусы
TMC_GROTS_TYPE_WSVR 4 КСВН (по амплитудной огибающей)
TMC_GROTS_TYPE_LDB 5 Потери, дБ (−20·lg|огибающая|)
TMC_GROTS_TYPE_PHASD 6 «Дельта-фаза» (приращение фазы)

Массив типов в CTMCGROUTView (gr_typY) предъявляет пользователю 7 пунктов: Signal, Amplitude, WSVR, L dB, Phase in radian, Phase in gradus, Delta Phase (плюс терминатор). Назначение/корректность пунктов PHAS_R, PHAS_G, PHASD для временно́го сигнала требует уточнения (см. §13).

3.4. Константы файла/документа — TMC_GROTS_*

Константа Значение Смысл
TMC_GROTS_DOCFILE_ID "#TMCGROTS" Сигнатура файла документа .tos и имя секции в реестре HKCU
TMC_GROTS_DOCFILE_XAXIESFORMAT "#TMCGROTS_X_AXIES_FORMAT" Ключ формата оси X
TMC_GROTS_DOCFILE_YAXIESFORMAT "#TMCGROTS_Y_AXIES_FORMAT" Ключ формата оси Y
TMC_GROTS_DOCFILE_POINTSIZE "#TMCGROTS_POINTSIZE" Ключ размера маркера точки
TMC_GROTS_DOCFILE_ANGLE_TETA "#TMCGROTS_ANGLE_TETA" Ключ (угол θ) — в TMCROS, по-видимому, не задействован
TMC_GROTS_FILEOUT_ID "#TMC_GraphicsOutputSignalFile FormVer2.0 2000 " Сигнатура файла сигнала .t
TMC_GROTS_FLOUTFreq_ID "#TMC_GROTS_Freq " Префикс строки с частотой в .t-файле
TMC_GROTS_FLOUTInpNum_ID "#TMC_GROTS_InpNum " Префикс строки с числом входов в .t-файле

Прочие константы (TMC_GROUT_MAXSTRING_BUF, TMC_GROUT_POINT_TYPE, TMC_VIEW_XSIZE/YSIZE, TMC_VIEW_SIZEMODE, идентификаторы окна TMC_GROUT_DOCFILE_ID_INIWND / …_INIWNDVWPRT) — общие с TMCGROUT.


4. Класс CTMCGROUTApp

Назначение: класс приложения MFC. Идентичен TMCGROUT по структуре (см. tmcgrout.md, §4), с единственным отличием:

  • InitInstance() вызывает SetRegistryKey("TMCROS") (а не "TMCGROUT") — настройки и список последних файлов (MRU) хранятся в HKCU\…\TMCROS.

Остальное: AfxOleInit(), Enable3dControls()/Static, LoadStdProfileSettings(9), регистрация CMultiDocTemplate (CTMCGROUTDoc+CChildFrame+CTMCGROUTView, ресурс IDR_TMCGROTYPE), автооткрытие первого существующего файла из MRU при пустой командной строке, восстановление положения окна из профиля (#INIWND), показ окна SW_RESTORE. Заголовок: TMCGROUT.h · Базовый класс: CWinApp · Глобальный объект: CTMCGROUTApp theApp; Вложенный класс CAboutDlgTMCGROUT.cpp) — диалог «О программе».


5. Класс CMainFrame

Идентичен TMCGROUT (см. tmcgrout.md, §5). Главное MDI-окно с тулбаром и статусбаром из 2 панелей; OnCreate, PreCreateWindow (WS_MAXIMIZE), OnDestroy (сохранение позиции окна в реестр под #INIWND). Заголовок: MainFrm.h · Базовый класс: CMDIFrameWnd.


6. Класс CChildFrame

Идентичен TMCGROUT (см. tmcgrout.md, §6). Дочернее MDI-окно, по умолчанию развёрнуто (WS_MAXIMIZE). Заголовок: ChildFrm.h · Базовый класс: CMDIChildWnd.


7. Класс CTMCGROUTDoc — документ

Назначение: модель данных документа: читает/пишет .tos-файл, загружает временны́е сигналы из .t-файлов, хранит параметры графиков и оформления. Заголовок: TMCGROUTDoc.h · Базовый класс: CDocument · Зависит от: Tmcgrviw.h, proc_s.h, SFILE95.

Структура класса (поля и большинство методов) совпадает с TMCGROUT (см. tmcgrout.md, §7). Ниже — отличия, специфичные для временно́го вьювера.

7.1. Дополнительное поле

Поле Тип Назначение
dFreq double Частота (Гц), считанная из последнего обработанного .t-файла (поле-«черновик», используется внутри read_RT_output_signal)

Прочие поля (grdoc, sGrDoc[16], bLossPoint, цвета scBackgoundColor/scGridColor/scAxiesColor/scTextColor/scPointColor, lfInitial, csEditorName, error[300], piProcInfo) — как в TMCGROUT. Примечание: в TMCROS-версии заголовка отсутствуют поля dXAxiesUserUnit/csXAxiesUserName (пользовательская единица оси X не предусмотрена — ось X всегда время).

7.2. Чтение данных — ключевое отличие

Вместо чтения S-файлов через read_S_matrix_element (как в TMCGROUT) TMCROS читает временно́й сигнал собственной функцией:

void read_RT_output_signal(int *in1, int *mod1, int *in2, int *mod2, char *filename, _complex **sss, double **f1, int *nPoint, double *dFr)

Что делает: читает файл сигнала .t и заполняет массив времени *f1 и массив отсчётов сигнала *sss. Как работает: 1. нормирует адрес: *in1≥1, *mod1∈{0,1}, *in2=1, *mod2∈{0,1}; 2. первый проход — считает число строк данных (строки, начинающиеся с пробела) → nPoint; параллельно ищет строку #TMC_GROTS_Freq … и читает из неё частоту в *dFr (по умолчанию 1e10); 3. выделяет память sss[n], f1[n]; 4. второй проход — по каждой строке данных: f1[i] = gets_f1(ch) (время), sss[i].x = gets_sss(ch, in1, mod1) (отсчёт сигнала для входа in1, компонента mod1).

Параметр Тип Назначение
in1, mod1, in2, mod2 int* Адрес входа/моды (на входе нормируются)
filename char* Путь к .t-файлу
sss _complex** Выход: массив отсчётов сигнала (.x)
f1 double** Выход: массив времени
nPoint int* Выход: число точек (0 — ошибка/файл не открыт)
dFr double* Выход: частота из файла

Ошибки: при невозможности открыть файл или пустых данных *nPoint=0; вызывающий ReadGraph1 пишет в подпись Error_when_read_<имя>.

Вспомогательные методы парсинга .t-строки

Метод Назначение
double gets_f1(char *ch) Читает время из строки: sscanf(ch,"%d%lg",&i,&r1) → возвращает r1 (второе число строки)
double gets_sss(char *ch, int in1, int mod1) Возвращает отсчёт сигнала для входа in1: пропускает поля до нужного входа (skip_ntdt_itd), затем sscanf "%d%lg%lg"; при mod1==0r1, при mod1==1r2
int skip_ntdt_itd(char *ch, int in1) Возвращает смещение в строке до данных входа in1 (пропускает номер точки, время и (in1−1) троек чисел предыдущих входов)
int skip_blank(char *ch) / int skip_number(char *ch) Пропуск пробелов/числа (как в TMCGROUT)

void ReadGraph1(int nGr, char *szFileName, int *nPoint, double **pFreq, _complex **pSmatr)

Отличие от TMCGROUT: формирует абсолютный путь файла относительно каталога документа и вызывает read_RT_output_signal (а не read_S_matrix_element). При *nPoint<=0 пишет Error_when_read_<имя> в szGrapPodp.

void ReadGraph1Expession(int nGr, char *szExpression)

Аналогично TMCGROUT, но переменные-«файлы» в выражении — это .t-сигналы (читаются через ReadGraph1read_RT_output_signal). Проверяет совпадение временны́х сеток (IsFreqCorrect).

7.3. Имя и формат документа — отличия

Метод Отличие от TMCGROUT
void SFileNameToDatFileName(char *ch) Формирует имя документа с расширением .tos (если такой уже есть — .$os), а не .soc/.$OC
BOOL IsDocFileName(char *ch) Проверяет, что первая строка файла = сигнатура #TMCGROTS
void MakeDocFileName(void) Формирует имя .tos-документа
WriteDocFile() / ReadGraphParameters() / SetOneReadGraphParameters() Пишут/читают секцию #TMCGROTS (в т. ч. в реестр HKCU\…\#TMCGROTS); типы осей трактуются как время/сигнал

7.4. Остальные методы

Совпадают с TMCGROUT (см. tmcgrout.md, §7): ReadDocFile, ReadGraphParameters, ReadGraphParametersDefault, WriteDocFile, AddGraphicsInDoc, IsDataModific, SetGraphColor, RunExeFile, DocFileNewData, DocFileDelData, ReadNGraph, ReadGraph, ReadInputModeFromFileName (если присутствует), SetOneReadGraphParameters, SetDefaultLineColorWidthType, MakeRelatPathSFile, CalcNDirInPathName, SelectDirName, LastWriteTime, del_bl2, del_bl3, put_error_messege, CreatProc.

Инверсная семантика WriteDocFile() (возврат FALSE при успехе, TRUE при ошибке) — как в TMCGROUT, требует подтверждения (см. §13).


8. Класс CTMCGROUTView — вид

Назначение: отрисовка временны́х графиков, интерактив (мышь, меню, масштаб, печать) и запуск TtoS-диалога. Заголовок: TMCGROUTView.h · Базовый класс: CScrollView · Зависит от: Tmcgrviw.h, complex1.h, DialogTtoS.h.

Структура совпадает с TMCGROUT (см. tmcgrout.md, §8); ниже — отличия.

8.1. Дополнительные поля

Поле Тип Назначение
tmcgrwin1 TMC_GR_WINDOW Второй буфер графиков — рабочая копия точек для отрисовки. Инициализируется по умолчанию (тип X=nT, тип Y=FULL, вьюпорт 2000..TMC_VIEW_*SIZE); в ReadDocFileW пересоздаётся под число графиков, копирует nPointDraw/координаты из tmcgrwin; используется в OnDrawGraph1/2/3
gr_typX TMC_GR_TYPE_X* Массив из 7 типов оси X: Time n, Time sec, Time msec, Time mksec, Time nsec, Time psec + терминатор
gr_typY TMC_GR_TYPE_Y* Массив из 8 типов оси Y: Signal, Amplitude, WSVR, L dB, Phase in radian, Phase in gradus, Delta Phase + терминатор

Точное назначение второго буфера tmcgrwin1 (почему отрисовка идёт по копии, а не напрямую по tmcgrwin) требует уточнения (см. §13). По коду OnDrawGraph1/2/3 рисуют именно из tmcgrwin1.

8.2. Подготовка данных к рисованию — отличия

void PrepareDoubleGraph(void)

Что делает: заполняет вещественные точки pPoint[j] для каждого видимого графика, исходя из временны́х типов осей. Как работает: - X = время: pFreq[j], делённое на множитель единицы (GetXAxiesUnit: с→1, мс→1e3, мкс→1e6, нс→1e9, пс→1e12; для nT — номер точки); - Y — по nYType: - TMC_GROTS_TYPE_FULL — отсчёт сигнала pSmatr[j].x как есть; - TMC_GROTS_TYPE_AMPL — амплитудная огибающая r14, восстановленная по локальным экстремумам сигнала (отслеживание тройки соседних отсчётов r11,r12,r13 и смены знака производной); - TMC_GROTS_TYPE_WSVR(1+s)/(1−s) по огибающей s (с защитой |s|≈1); - TMC_GROTS_TYPE_LDB−20·lg(огибающая); - TMC_GROTS_TYPE_PHAS_R / PHAS_G — фаза (рад/град), оцениваемая по моментам смены знака сигнала и частоте dFreq; - для графиков-выражений значение берётся из методов CTMCGrExpression (GetExpressionValueL/K/SM). - параллельно ищет мин/макс X и Y; при включённом авто-масштабе (nAFlagX/nAFlagY) задаёт пределы окна; вызывает PutStatistics1().

void PrepareLogGraph(void)

Переводит вещественные точки в логические (DoublXCordToLX/Y), считает nPointDraw, прижимает точки вне [Xmin,Xmax]. После — копирует результат в tmcgrwin1 (пересоздавая его массив под число графиков и nPointDraw).

double GetXAxiesUnit(void)

Возвращает множитель текущей единицы времени: с→1, мс→1e3, мкс→1e6, нс→1e9, пс→1e12 (для nT обрабатывается отдельно). Это отличается от частотного GetXAxiesUnit в TMCGROUT.

8.3. Отрисовка — отличия

  • OnDrawGraph(CDC*) делает 3 прохода (OnDrawGraph1/2/3), но рисует из tmcgrwin1 (а не tmcgrwin).
  • OnDraw: фон → (при ошибке — текст и выход) → рамка zoom → сетка → оси → графики → OnDrawMouseScrol. При первом вызове (FlagResizeInit) подгоняет вьюпорт (OnViewResizectrlr).
  • onDrowAxies/onDrawGrid/OnDrawLine/OnDrawPoint/OnDrawBackground/OnDrawMouseResize/VTextOut/SetRectOutXY/IvalidateRectView — как в TMCGROUT.

8.4. Новая команда меню — TtoS

afx_msg void OnEditTosmatrix() (команда ID_EDIT_TOSMATRIX, пункт «To S-matrix»)

Что делает: открывает диалог CDialogTtoS для преобразования временны́х сигналов документа в S-файл. Как работает: 1. передаёт диалогу имя документа (m_DocFileName = GetPathName()) и текущие пределы по времени (m_dTmin/m_dTmax = tmcgrwin.sGrWin.Xmin/Xmax); 2. по tmcgrwin.nXType задаёт множитель единицы времени dlg.dTUnit и подпись m_csTimeUnit (ps/ns/mks/ms/s; default — единица, пределы 0..1); 3. для каждого из ≤20 графиков копирует в диалог имя файла-сигнала (m_SFileName_<k>), флаг вывода (m_OutGrFlag_<k>) и частоту (m_dXValue<k> = psGraph[k].dFreq); 4. показывает диалог; экспорт выполняется внутри диалога (OnExportCharacteristics/OnOK).

8.5. Прочие обработчики

Команды масштаба, мыши, цветов, шрифта, редактора, файла, авто-масштаба, прокрутки Home/End, таймер (перечитывание при изменении файлов) — как в TMCGROUT (см. tmcgrout.md, §8). Команда выбора «пользовательской единицы X» в TMCROS отсутствует (ось X — всегда время). Глобальные функции PutTrace/PutStatistics (запись в статусбар) — см. §11.


9. Диалоги

9.1. CTMCGROUTDIALOGView — параметры графика

Заголовок: TMCGROUTDIALOGView.h · Базовый класс: CDialog · Ресурс: IDD_DIALOG1. Структурно как в TMCGROUT (см. tmcgrout.md, §9.1): пределы X/Y, авто-масштаб, тип X (радиогруппа единиц времени), тип Y (Signal/Amplitude/…), флаг и размер точек, форматы подписей, имя документа. Отличие — радиогруппа X соответствует единицам времени, а не частоты.

9.2. CDialogDoc — таблица графиков документа

Заголовок: DialogDoc.h · Базовый класс: CDialog · Ресурс: IDD_DIALOG2. Назначение: редактирование содержимого документа в виде таблицы на 20 строк (имя графика, имя файла, входы/моды np1/mod1, флаг вывода). Совпадает с TMCGROUT, но: - содержит дополнительное поле double dTUnit — множитель единицы времени; - семантика входа/моды относится к столбцам временно́го сигнала, а не S-матрицы.

Поля: m_DocFileName; по 20 шт. m_GraphName*, m_SFileName_*, m_np1_*, m_mod1_*, m_OutGrFlag_*; m_AddCharacteristicsFlag (BOOL — нажата «добавить»); dTUnit. Методы: OnAddCharacteristics() — выставляет m_AddCharacteristicsFlag и закрывает диалог; OnNotify (переопределён).

Поля m_np2_*/m_mod2_* в TMCROS-версии DialogDoc.h отсутствуют (в отличие от описания в TMCGROUT) — задаётся только первый адрес np1/mod1.

9.3. CDialogTtoS — преобразование «время → S-матрица» (НОВЫЙ, только в TMCROS)

Заголовок: DialogTtoS.h · Базовый класс: CDialog · Ресурс: IDD_DIALOG3 · Реализация: DialogTtoS.cpp. Назначение: собрать до 20 файлов сигнала .t, задать для каждого частоту, диапазон времени [Tmin,Tmax] и единицу времени, и экспортировать результат — восстановленную S-матрицу — в один S-файл .s.

Поля (DDX): | Поле | Тип | Назначение | |------|-----|-----------| | m_DocFileName | CString | Имя файла документа (для построения путей) | | dTUnit | double | Множитель единицы времени (задаётся из вида) | | m_SFileName | CString | Имя выходного S-файла (.s); по умолчанию <документ>.s | | m_SFileName_1..20 | CString | Имена входных .t-файлов сигнала (до 20) | | m_OutGrFlag_1..20 | BOOL | Флаг «обрабатывать этот файл» | | m_dXValue1..20 | double | Частота (Гц) для соответствующего .t-файла | | m_dTmin, m_dTmax | double | Диапазон времени (в текущих единицах) | | m_csTimeUnit | CString | Подпись единицы времени (ps/ns/mks/ms/s) | | m_dXmin, m_dDx | double | Начальная частота и шаг для авто-заполнения частот (по умолчанию 1e10 и 1e8) | | m_csError | CString | Текст последней ошибки преобразования |

Методы: - INT_PTR DoModal() — перед показом достраивает абсолютные пути: имя выходного .s = <документ без расширения>.s, а каждое непустое m_SFileName_<k> приводит к виду <каталог документа>\<имя>; - void OnChangeSfilename() — выбор имени выходного .s-файла через CFileDialog (фильтр «Tamic S-matrix», маска *.s); - void OnAddCharacteristics() — выбор входного .t-файла (CFileDialog, «Tamic Rt-Signal», маска *.t) и запись его в первую свободную ячейку m_SFileName_1..20; - void OnChangeSfiledelet() — удаляет файл с именем m_SFileName с диска (remove); - void OnExportFillxvalue() — заполняет m_dXValue1..20 арифметической прогрессией: m_dXmin, +m_dDx, +2·m_dDx, …; - void OnExportCharacteristics()главное действие: для каждого k, у которого m_OutGrFlag_k и непустое имя, вызывает CTmcTtoS::TtoS(m_SFileName_k, m_SFileName, m_dTmin*dTUnit, m_dTmax*dTUnit, m_dXValue_k); при ошибке пишет её в m_csError и прерывается; - void OnOK() — вызывает OnExportCharacteristics(), затем CDialog::OnOK().

Ошибки/особенности: входные сигналы конвертируются по очереди в один выходной S-файл (каждый вызов TtoS дописывает строку матрицы — см. CTmcSMatrix::Save); при первой же ошибке экспорт останавливается.

9.4. CTmcGroutColorGraphDialog, CTmcGrParColTypWid

Идентичны TMCGROUT (см. tmcgrout.md, §9.3 и §9.4): настройка цвета/типа/толщины 16 линий и одной линии соответственно. Заголовки TmcGroutColorGraphDialog.h, TmcGrParColTypWid.h.

9.5. CTmcGrParColTypWid1 (НЕ в сборке)

Заголовок: TmcGrParColTypWid1.h · Базовый класс: CDialog · Ресурс: IDD_DIALOGGRLINECOLORTYPEWIDTH1. Пустой диалог-заготовка (нет полей и обработчиков, только DoDataExchange). Не включён в TMCROS.vcxproj и в сборке не участвует — оставлен в каталоге как артефакт.

Назначение CTmcGrParColTypWid1 неясно; вероятно, неиспользуемый дубль CTmcGrParColTypWid (см. §13).


10. Подсистема Time-to-Scattering (TtoS)

Преобразование набора временны́х сигналов в матрицу рассеяния на заданной частоте. Идея: по двум соседним отсчётам гармонического сигнала s(t)=A·sin(ωt+φ) восстанавливаются амплитуда A и фаза φ (комплексное S), усреднённые по всем парам точек диапазона; возбуждённый вход определяет строку S-матрицы.

10.1. Класс CTmcTtoS — обёртка «файл .t → файл .s»

Заголовок: src/Include/TmcTtoS.h · Реализация: TmcTtoS.cpp · Зависит от: TmcSMatrix.h, tmcgrviw.h.

Поля (private): | Поле | Тип | Назначение | |------|-----|-----------| | cSMatrix | CTmcSMatrix | Рабочее ядро преобразования | | csSFileName | CString | Имя выходного .s | | csTFileName | CString | Имя входного .t | | csError | CString | Текст ошибки (по умолчанию "No error") | | dTmin, dTmax | double | Диапазон времени (секунды) | | dFreq | double | Частота (Гц), на которой восстанавливается S | | bIsError | BOOL | Флаг ошибки |

Методы: | Метод | Что делает | |-------|-----------| | void TtoS(CString csTfn, CString csSfn, double dTmin1, double dTmax1, double dFreq1) | Главный публичный вызов: сохраняет параметры и выполняет TtoS() | | void TtoS(void) (private) | MakeSmatrixFromFileT()SaveSmatrixToFileS() | | void MakeSmatrixFromFileT(void) | Читает .t (cSMatrix.ReadTFile) и строит S-матрицу (cSMatrix.MakeSmatrix); ошибки ядра переносит в csError | | void SaveSmatrixToFileS(void) | Сохраняет результат в .s (cSMatrix.Save(csSFileName, dFreq)) | | BOOL IsError(void) | Флаг ошибки | | CString& GetErrorMessage(void) | Текст ошибки | | void DeleteData(void) (private) | Сброс полей и cSMatrix.DeleteData() |

10.2. Класс CTmcSMatrix — ядро восстановления S из сигнала

Заголовок: src/Include/TmcSMatrix.h · Реализация: TmcSMatrix.cpp · Зависит от: typedef.h (_complex), proc_s.h, s_file.h (SFILE95 — save_S_matrix_element).

Поля (private): | Поле | Тип | Назначение | |------|-----|-----------| | csTFileName, csSFileName | CString | Имена входного .t и выходного .s | | csError | CString | Текст ошибки | | dTmin, dTmax | double | Диапазон времени | | dFreq | double | Частота восстановления (Гц) | | bIsError | BOOL | Флаг ошибки | | pcSmatrix | _complex* | Восстановленная строка S-матрицы (nInput элементов) | | pdTsignal | double* | Отсчёты сигнала всех входов (nPoint*nInput*2) | | pdTime | double* | Отсчёты времени (nPoint) | | nInput | int | Число входов (столбцов сигнала) | | nPoint | int | Число точек времени в диапазоне | | nLineInSMatrix | int | Индекс возбуждённого входа = номер строки S-матрицы (−1 — не определён) |

Публичные методы: | Метод | Что делает | |-------|-----------| | void ReadTFile(CString csTFile, double dTmin1, double dTmax1) / void ReadTFile(void) (private) | Читает .t: проверяет Tmax>Tmin, считает nPoint (CalcNPoint) и nInput (CalcNInput), выделяет массивы (AllocTArray), читает данные (ReadTArray) | | void MakeSmatrix(void) | Восстанавливает S: AllocSArray()TtoS()SetnLineInSMatrix() | | void Save(CString csSFileName1, double dFreq1) / void Save(CString csSFileName1) / void Save(void) (private) | Записывает строку S-матрицы в .s через save_S_matrix_element(nLineInSMatrix+1, …, pcSmatrix, dFreq, nInput) | | BOOL IsError(void) / CString& GetErrorMessage(void) | Флаг и текст ошибки | | void DeleteData(void) | Освобождение массивов и сброс полей |

Приватные методы (алгоритм): | Метод | Назначение | |-------|-----------| | int CalcNPoint(void) | Считает число строк данных в диапазоне [Tmin,Tmax]; параллельно читает частоту из #TMC_GROTS_Freq; требует >5 точек | | int CalcNInput(void) | По первой строке данных определяет число входов: (чисел_в_строке − 2)/3 | | double gets_f1(char *ch) | Читает время из строки (sscanf "%d%lg") | | int gets_nNumbersInLine(char *ch) | Считает число «слов»-чисел в строке | | void AllocTArray(void) | Выделяет pdTsignal[nPoint*nInput*2], pdTime[nPoint] | | void ReadTArray(void) | Читает отсчёты сигнала всех входов в диапазоне времени (readTsignal/readTsignalOne) | | void readTsignal(double **pdTsign, char *ch) / int readTsignalOne(…) | Разбор одной строки: пропуск номера и времени, затем по nInput пар (Re/Im сигнала) | | int skip_blank(char*) / int skip_number(char*) | Пропуск пробелов/числа | | void AllocSArray(void) | Выделяет pcSmatrix[nInput], инициализирует FLT_MAX | | void TtoS(void) | По всем входам вызывает TtoSOneInput | | void TtoSOneInput(int n) | Усредняет комплексное S входа n по всем парам соседних точек (TtoSOneInputOnePoint) | | BOOL TtoSOneInputOnePoint(_complex *acc, double s1, double t1, double s2, double t2) | По паре (s,t) решает систему для A и φ гармоники A·sin(ωt+φ) на частоте dFreq; прибавляет A·(cosφ, sinφ) к аккумулятору. Возвращает TRUE, если вклад учтён | | void SetnLineInSMatrix(void) | Находит единственный возбуждённый вход → nLineInSMatrix; ошибка, если возбуждённых не один | | BOOL IsInputExcite(int n) | TRUE, если у входа n есть ненулевые отсчёты (вход возбуждён) | | void PutErrorMessage(char *ch) | Устанавливает bIsError и текст ошибки |

Формат файла сигнала .t (по коду парсинга): строки данных начинаются с пробела и содержат номер_точки время [для каждого входа: номер Re Im] …; служебная строка #TMC_GROTS_Freq <частота> задаёт частоту; сигнатура файла — #TMC_GraphicsOutputSignalFile FormVer2.0 2000.

Математика восстановления S из сигнала (TtoSOneInputOnePoint, усреднение, критерий возбуждённого входа) — научный алгоритм; не изменять без согласования. Физический смысл отдельных порогов (10*DBL_MIN, ветви выбора dsin/dcos) требует уточнения (см. §13).

10.3. Известные дефекты в TtoS-коде (для сведения)

В CTmcSMatrix::CalcNPoint() и CalcNInput() при ошибке открытия файла вызывается sprintf("Can't open file {%s}", csTFileName); без буфера-приёмника (первый аргумент — формат, а не буфер). Это ошибочный вызов (потенциальный сбой). Отмечено как дефект кода — см. §13.


11. Класс CTMCGrExpression — графики-выражения

Идентичен TMCGROUT (см. tmcgrout.md, §10). Разбирает выражение над несколькими файлами ([имя]-переменные), вычисляет значение в точке через exprint (i1nte_atof_1). В TMCROS «файлы-переменные» — это .t-сигналы, а методы GetExpressionValue* применяются к восстановленным из сигнала величинам. Заголовок: src/Include/TMCGrExpression.h · Реализация: TMCGrExpression.cpp.


12. Глобальные функции (в TMCGROUTView.cpp)

Как в TMCGROUT (см. tmcgrout.md, §11). Объявлены в TMCGROUTView.h: void PutTrace(CString), void PutTrace(char*), void PutStatistics(CString), void PutStatistics(char*) — вывод в панели 0 и 1 строки состояния.


The TMCROS program — API documentation

TMC Suite package. A viewer of time characteristics (time-domain signals) and a "time → scattering matrix" transformation tool (Time-to-Scattering). All signatures are taken from the sources in src/viewers/Tmcrtout/ and the shared headers from src/Include/.


1. Purpose of the program

TMCROS (the output EXE — TMCROS.exe, the TMCROS.vcxproj project) is a graphical viewer of electrodynamic-computation results in the time domain: it builds 2D graphs of time signals of a multiport read from signal output files (.t — Rt-Signal), and can compute from them a scattering matrix at given frequencies (the "time → S-matrix" transform, the TtoS subsystem).

The program is built on the same MFC Document/View scheme (an MDI application) as the related frequency viewer TMCGROUT, and shares most of its source files and data model. The key differences of TMCROS:

  • the X axis is time (n, s, ms, µs, ns, ps), not frequency;
  • the Y axis is the time signal and quantities derived from it (the amplitude envelope, VSWR/losses/phase computed from the envelope);
  • the data is read from signal files .t (not from S-files): the read_RT_output_signal function in CTMCGROUTDoc;
  • the document has the extension .tos and the signature #TMCGROTS (TMCGROUT has .soc / #TMCGROUT);
  • a Time-to-Scattering subsystem is added: the classes CTmcSMatrix, CTmcTtoS and the dialog CDialogTtoS, which convert a set of time signals into one S-file (.s) at given frequencies (the "To S-matrix" menu item);
  • a second point buffer tmcgrwin1 is introduced in the view (a working copy for drawing, see §8).

TMCROS is positioned as a time (intermediate) viewer: it shows the signals and prepares an S-matrix from them, which is then viewed in TMCGROUT.

Coincidence of file names with TMCGROUT. The files TMCGROUT.cpp/.h, MainFrm, ChildFrm, TMCGROUTDoc, TMCGROUTView, TMCGROUTDIALOGView, DialogDoc, TmcGroutColorGraphDialog, TmcGrParColTypWid, TMCGrExpression are named the same as in TMCGROUT (historically TMCROS was made by copying the TMCGROUT project), but they contain different logic in the time-data and TtoS parts. Below, what is truly identical to TMCGROUT is described briefly with a reference; the differences are documented in full.


2. Project composition

The TMCROS.vcxproj build contains the following files (by <ClCompile>/<ClInclude>):

File Class / contents Purpose (briefly)
TMCGROUT.cpp/.h CTMCGROUTApp The application class; InitInstance; the "About" dialog. The difference from TMCGROUT — the registry key TMCROS
MainFrm.cpp/.h CMainFrame The main MDI window (toolbar, status bar). Like TMCGROUT
ChildFrm.cpp/.h CChildFrame The child MDI window. Like TMCGROUT
TMCGROUTDoc.cpp/.h CTMCGROUTDoc The document: reading/writing .tos, reading time signals .t, the graph parameters
TMCGROUTView.cpp/.h CTMCGROUTView The view: drawing time graphs, mouse, menu; the "To S-matrix" item
TMCGROUTDIALOGView.cpp/.h CTMCGROUTDIALOGView The graph-parameters dialog (time units, Y type, limits, points)
DialogDoc.cpp/.h CDialogDoc The document-contents table dialog (up to 20 graphs)
DialogTtoS.cpp/.h CDialogTtoS The TtoS dialog: the list of .t signals, frequencies, export to an S-file
TmcSMatrix.cpp (+ src/Include/TmcSMatrix.h) CTmcSMatrix The TtoS core: reading .t, reconstructing the S-matrix from a time signal, writing .s
TmcTtoS.cpp (+ src/Include/TmcTtoS.h) CTmcTtoS The TtoS wrapper: one call "file .t → file .s"
TmcGroutColorGraphDialog.cpp/.h CTmcGroutColorGraphDialog The color/type/width dialog for 16 lines. Like TMCGROUT
TmcGrParColTypWid.cpp/.h CTmcGrParColTypWid The single-line parameters dialog. Like TMCGROUT
TMCGrExpression.cpp (+ src/Include/TMCGrExpression.h) CTMCGrExpression Expression graphs over several files. Like TMCGROUT
StdAfx.cpp/.h The MFC precompiled header
resource.h, TMCGROUT.rc Resources (menus, dialogs, icons, toolbar)

The file TmcGrParColTypWid1.cpp/.h (the class CTmcGrParColTypWid1) physically lies in the directory but is not included in TMCROS.vcxproj (absent from <ClCompile>/<ClInclude>) — it does not take part in the build. See §9.5.

Dependencies and build settings (TMCROS.vcxproj): - UseOfMfc = Static, CharacterSet = MultiByte, PlatformToolset = v145; the Win32 and x64 configurations (Debug/Release); - linking with the package libraries: SFILE95 (sfile95.lib — writing the S-matrix save_S_matrix_element), complex (complex.lib), exprint (exprint.lib — expression evaluation); - the output directory from build\ExeOutput.propsdist\<platform>\bin; - the shared headers from src/Include/: tmcgrviw.h, proc_s.h, s_file.h, typedef.h, complex1.h, TmcSMatrix.h, TmcTtoS.h, TMCGrExpression.h.


3. Common data structures (the Tmcgrviw.h header)

TMCROS uses the same data-model structures as TMCGROUT (TMC_GR_DOC1, TMC_GR_DOC, TMC_GR_VIEW, TMC_GR_WINDOW, TMC_GR_TYPE_X/Y). For the full field description, see tmcgrout.md, §3. Here the differences in field interpretation and the type constants specific to the time viewer are recorded.

3.1. Difference in the interpretation of the TMC_GR_DOC1 fields

In TMCROS the graph-structure fields are read from a signal file .t, so their physical meaning is different:

Field Type Interpretation in TMCROS
pFreq double* The array of time samples (not frequencies): the time values from the .t file
pSmatr _complex* The array of signal values: pSmatr[j].x is the time-signal sample for the chosen input/mode (the imaginary part .y is not used)
dFreq double The frequency (Hz) read from the line #TMC_GROTS_Freq … of the .t file; used when reconstructing the phase/amplitude and in TtoS
nInp1, nMod1 int The input and mode number (signal column) in the .t file; normalized in read_RT_output_signal (in1≥1, mod1∈{0,1})
nInp2, nMod2 int The second address; in read_RT_output_signal forced to in2=1, mod2∈{0,1}
szFileName char* The full path to the .t signal file

The other fields (nPoint, szGrapName, szGrapPodp, LineColor/Type/Width, piPoint[10], PointColor/Type/Width, OutFlag, LastWriteTime, pcExpr) — as in TMCGROUT.

3.2. X-axis type constants (time) — TMC_GROTS_TYPE_*

Constant Value Meaning (X axis)
TMC_GROTS_TYPE_nT 0 Time in samples (the point number)
TMC_GROTS_TYPE_ps 1 Time, ps (×1e−12)
TMC_GROTS_TYPE_ns 2 Time, ns (×1e−9)
TMC_GROTS_TYPE_mks 3 Time, µs (×1e−6)
TMC_GROTS_TYPE_ms 4 Time, ms (×1e−3)
TMC_GROTS_TYPE_s 5 Time, s (×1)

3.3. Y-axis type constants — TMC_GROTS_TYPE_*

Constant Value Meaning (Y axis)
TMC_GROTS_TYPE_FULL 0 Signal — the signal sample as is (pSmatr[j].x)
TMC_GROTS_TYPE_AMPL 1 Amplitude (the envelope |S|, reconstructed from the local extrema of the signal)
TMC_GROTS_TYPE_PHAS_R 2 Phase, radians
TMC_GROTS_TYPE_PHAS_G 3 Phase, degrees
TMC_GROTS_TYPE_WSVR 4 VSWR (from the amplitude envelope)
TMC_GROTS_TYPE_LDB 5 Losses, dB (−20·lg|envelope|)
TMC_GROTS_TYPE_PHASD 6 "Delta phase" (a phase increment)

The type array in CTMCGROUTView (gr_typY) presents 7 items to the user: Signal, Amplitude, WSVR, L dB, Phase in radian, Phase in gradus, Delta Phase (plus a terminator).

3.4. File/document constants — TMC_GROTS_*

Constant Value Meaning
TMC_GROTS_DOCFILE_ID "#TMCGROTS" The signature of the .tos document file and the section name in the registry HKCU
TMC_GROTS_DOCFILE_XAXIESFORMAT "#TMCGROTS_X_AXIES_FORMAT" The X-axis format key
TMC_GROTS_DOCFILE_YAXIESFORMAT "#TMCGROTS_Y_AXIES_FORMAT" The Y-axis format key
TMC_GROTS_DOCFILE_POINTSIZE "#TMCGROTS_POINTSIZE" The point-marker size key
TMC_GROTS_DOCFILE_ANGLE_TETA "#TMCGROTS_ANGLE_TETA" A key (the angle θ) — apparently unused in TMCROS
TMC_GROTS_FILEOUT_ID "#TMC_GraphicsOutputSignalFile FormVer2.0 2000 " The signature of the .t signal file
TMC_GROTS_FLOUTFreq_ID "#TMC_GROTS_Freq " The prefix of the frequency line in the .t file
TMC_GROTS_FLOUTInpNum_ID "#TMC_GROTS_InpNum " The prefix of the input-count line in the .t file

The other constants (TMC_GROUT_MAXSTRING_BUF, TMC_GROUT_POINT_TYPE, TMC_VIEW_XSIZE/YSIZE, TMC_VIEW_SIZEMODE, the window identifiers TMC_GROUT_DOCFILE_ID_INIWND / …_INIWNDVWPRT) — shared with TMCGROUT.


4. The CTMCGROUTApp class

Purpose: the MFC application class. Identical to TMCGROUT in structure (see tmcgrout.md, §4), with a single difference:

  • InitInstance() calls SetRegistryKey("TMCROS") (not "TMCGROUT") — the settings and the recent-files list (MRU) are stored in HKCU\…\TMCROS.

The rest: AfxOleInit(), Enable3dControls()/Static, LoadStdProfileSettings(9), registering CMultiDocTemplate (CTMCGROUTDoc+CChildFrame+CTMCGROUTView, the resource IDR_TMCGROTYPE), auto-opening the first existing file from the MRU when the command line is empty, restoring the window position from the profile (#INIWND), showing the window SW_RESTORE. Header: TMCGROUT.h · Base class: CWinApp · Global object: CTMCGROUTApp theApp; The nested class CAboutDlg (in TMCGROUT.cpp) — the "About" dialog.


5. The CMainFrame class

Identical to TMCGROUT (see tmcgrout.md, §5). The main MDI window with a toolbar and a 2-panel status bar; OnCreate, PreCreateWindow (WS_MAXIMIZE), OnDestroy (saving the window position to the registry under #INIWND). Header: MainFrm.h · Base class: CMDIFrameWnd.


6. The CChildFrame class

Identical to TMCGROUT (see tmcgrout.md, §6). The child MDI window, maximized by default (WS_MAXIMIZE). Header: ChildFrm.h · Base class: CMDIChildWnd.


7. The CTMCGROUTDoc class — the document

Purpose: the document data model: reads/writes the .tos file, loads time signals from .t files, stores the graph and appearance parameters. Header: TMCGROUTDoc.h · Base class: CDocument · Depends on: Tmcgrviw.h, proc_s.h, SFILE95.

The class structure (the fields and most methods) coincides with TMCGROUT (see tmcgrout.md, §7). Below are the differences specific to the time viewer.

7.1. An additional field

Field Type Purpose
dFreq double The frequency (Hz) read from the last processed .t file (a "draft" field, used inside read_RT_output_signal)

The other fields (grdoc, sGrDoc[16], bLossPoint, the colors scBackgoundColor/scGridColor/scAxiesColor/scTextColor/scPointColor, lfInitial, csEditorName, error[300], piProcInfo) — as in TMCGROUT. Note: the TMCROS version of the header lacks the fields dXAxiesUserUnit/csXAxiesUserName (a custom X-axis unit is not provided — the X axis is always time).

7.2. Reading data — the key difference

Instead of reading S-files via read_S_matrix_element (as in TMCGROUT), TMCROS reads a time signal with its own function:

void read_RT_output_signal(int *in1, int *mod1, int *in2, int *mod2, char *filename, _complex **sss, double **f1, int *nPoint, double *dFr)

What it does: reads the .t signal file and fills the time array *f1 and the signal-sample array *sss. How it works: 1. normalizes the address: *in1≥1, *mod1∈{0,1}, *in2=1, *mod2∈{0,1}; 2. the first pass — counts the number of data lines (lines starting with a space) → nPoint; in parallel it finds the #TMC_GROTS_Freq … line and reads the frequency into *dFr (by default 1e10); 3. allocates the memory sss[n], f1[n]; 4. the second pass — for each data line: f1[i] = gets_f1(ch) (the time), sss[i].x = gets_sss(ch, in1, mod1) (the signal sample for input in1, component mod1).

Parameter Type Purpose
in1, mod1, in2, mod2 int* The input/mode address (normalized on input)
filename char* The path to the .t file
sss _complex** Output: the array of signal samples (.x)
f1 double** Output: the time array
nPoint int* Output: the number of points (0 — error/file not opened)
dFr double* Output: the frequency from the file

Errors: if the file cannot be opened or the data is empty, *nPoint=0; the calling ReadGraph1 writes Error_when_read_<name> into the caption.

Auxiliary methods for parsing a .t line

Method Purpose
double gets_f1(char *ch) Reads the time from a line: sscanf(ch,"%d%lg",&i,&r1) → returns r1 (the second number of the line)
double gets_sss(char *ch, int in1, int mod1) Returns the signal sample for input in1: skips the fields up to the desired input (skip_ntdt_itd), then sscanf "%d%lg%lg"; for mod1==0r1, for mod1==1r2
int skip_ntdt_itd(char *ch, int in1) Returns the offset in the line up to the data of input in1 (skips the point number, the time and (in1−1) triples of the previous inputs' numbers)
int skip_blank(char *ch) / int skip_number(char *ch) Skipping spaces/a number (as in TMCGROUT)

void ReadGraph1(int nGr, char *szFileName, int *nPoint, double **pFreq, _complex **pSmatr)

Difference from TMCGROUT: forms the absolute file path relative to the document directory and calls read_RT_output_signal (not read_S_matrix_element). When *nPoint<=0 it writes Error_when_read_<name> into szGrapPodp.

void ReadGraph1Expession(int nGr, char *szExpression)

Like TMCGROUT, but the "file" variables in the expression are .t signals (read via ReadGraph1read_RT_output_signal). Checks that the time grids coincide (IsFreqCorrect).

7.3. Document name and format — differences

Method Difference from TMCGROUT
void SFileNameToDatFileName(char *ch) Forms the document name with the extension .tos (if one already exists — .$os), not .soc/.$OC
BOOL IsDocFileName(char *ch) Checks that the first line of the file = the signature #TMCGROTS
void MakeDocFileName(void) Forms the .tos document name
WriteDocFile() / ReadGraphParameters() / SetOneReadGraphParameters() Write/read the #TMCGROTS section (including into the registry HKCU\…\#TMCGROTS); the axis types are interpreted as time/signal

7.4. The other methods

They coincide with TMCGROUT (see tmcgrout.md, §7): ReadDocFile, ReadGraphParameters, ReadGraphParametersDefault, WriteDocFile, AddGraphicsInDoc, IsDataModific, SetGraphColor, RunExeFile, DocFileNewData, DocFileDelData, ReadNGraph, ReadGraph, ReadInputModeFromFileName (if present), SetOneReadGraphParameters, SetDefaultLineColorWidthType, MakeRelatPathSFile, CalcNDirInPathName, SelectDirName, LastWriteTime, del_bl2, del_bl3, put_error_messege, CreatProc.


8. The CTMCGROUTView class — the view

Purpose: drawing the time graphs, interaction (mouse, menu, scaling, printing) and launching the TtoS dialog. Header: TMCGROUTView.h · Base class: CScrollView · Depends on: Tmcgrviw.h, complex1.h, DialogTtoS.h.

The structure coincides with TMCGROUT (see tmcgrout.md, §8); below are the differences.

8.1. Additional fields

Field Type Purpose
tmcgrwin1 TMC_GR_WINDOW The second graph buffer — a working copy of the points for drawing. Initialized with defaults (X type=nT, Y type=FULL, viewport 2000..TMC_VIEW_*SIZE); in ReadDocFileW re-created for the number of graphs, copies nPointDraw/coordinates from tmcgrwin; used in OnDrawGraph1/2/3
gr_typX TMC_GR_TYPE_X* An array of 7 X-axis types: Time n, Time sec, Time msec, Time mksec, Time nsec, Time psec + a terminator
gr_typY TMC_GR_TYPE_Y* An array of 8 Y-axis types: Signal, Amplitude, WSVR, L dB, Phase in radian, Phase in gradus, Delta Phase + a terminator

8.2. Preparing the data for drawing — differences

void PrepareDoubleGraph(void)

What it does: fills the real points pPoint[j] for each visible graph, based on the time axis types. How it works: - X = time: pFreq[j], divided by the unit multiplier (GetXAxiesUnit: s→1, ms→1e3, µs→1e6, ns→1e9, ps→1e12; for nT — the point number); - Y — by nYType: - TMC_GROTS_TYPE_FULL — the signal sample pSmatr[j].x as is; - TMC_GROTS_TYPE_AMPL — the amplitude envelope r14, reconstructed from the local extrema of the signal (tracking a triple of adjacent samples r11,r12,r13 and the sign change of the derivative); - TMC_GROTS_TYPE_WSVR(1+s)/(1−s) from the envelope s (with protection for |s|≈1); - TMC_GROTS_TYPE_LDB−20·lg(envelope); - TMC_GROTS_TYPE_PHAS_R / PHAS_G — the phase (rad/deg), estimated from the moments of the signal's sign change and the frequency dFreq; - for expression graphs the value is taken from the CTMCGrExpression methods (GetExpressionValueL/K/SM). - in parallel it finds the X and Y min/max; with auto-scale on (nAFlagX/nAFlagY) it sets the window limits; it calls PutStatistics1().

The algorithm for reconstructing the envelope and phase from a time signal is scientific logic. The TMC_GR_TYPE_SFD branch is commented out in the code.

void PrepareLogGraph(void)

Converts the real points into logical ones (DoublXCordToLX/Y), counts nPointDraw, snaps points outside [Xmin,Xmax]. Afterwards it copies the result into tmcgrwin1 (re-creating its array for the number of graphs and nPointDraw).

double GetXAxiesUnit(void)

Returns the multiplier of the current time unit: s→1, ms→1e3, µs→1e6, ns→1e9, ps→1e12 (for nT it is handled separately). This differs from the frequency GetXAxiesUnit in TMCGROUT.

8.3. Drawing — differences

  • OnDrawGraph(CDC*) makes 3 passes (OnDrawGraph1/2/3), but draws from tmcgrwin1 (not tmcgrwin).
  • OnDraw: background → (on error — the text and exit) → zoom frame → grid → axes → graphs → OnDrawMouseScrol. On the first call (FlagResizeInit) it fits the viewport (OnViewResizectrlr).
  • onDrowAxies/onDrawGrid/OnDrawLine/OnDrawPoint/OnDrawBackground/OnDrawMouseResize/VTextOut/SetRectOutXY/IvalidateRectView — as in TMCGROUT.

8.4. A new menu command — TtoS

afx_msg void OnEditTosmatrix() (the command ID_EDIT_TOSMATRIX, the "To S-matrix" item)

What it does: opens the CDialogTtoS dialog to convert the document's time signals into an S-file. How it works: 1. passes the document name (m_DocFileName = GetPathName()) and the current time limits (m_dTmin/m_dTmax = tmcgrwin.sGrWin.Xmin/Xmax) to the dialog; 2. by tmcgrwin.nXType sets the time-unit multiplier dlg.dTUnit and the label m_csTimeUnit (ps/ns/mks/ms/s; default — the unit, limits 0..1); 3. for each of the ≤20 graphs copies into the dialog the signal-file name (m_SFileName_<k>), the output flag (m_OutGrFlag_<k>) and the frequency (m_dXValue<k> = psGraph[k].dFreq); 4. shows the dialog; the export is performed inside the dialog (OnExportCharacteristics/OnOK).

8.5. Other handlers

The commands for scaling, mouse, colors, font, editor, file, auto-scale, Home/End scrolling, the timer (re-reading on file change) — as in TMCGROUT (see tmcgrout.md, §8). The "custom X unit" selection command is absent in TMCROS (the X axis is always time). The global functions PutTrace/PutStatistics (writing to the status bar) — see §11.


9. Dialogs

9.1. CTMCGROUTDIALOGView — the graph parameters

Header: TMCGROUTDIALOGView.h · Base class: CDialog · Resource: IDD_DIALOG1. Structurally as in TMCGROUT (see tmcgrout.md, §9.1): X/Y limits, auto-scale, X type (the time unit radio group), Y type (Signal/Amplitude/…), the point flag and size, the label formats, the document name. The difference — the X radio group corresponds to time units, not frequency.

9.2. CDialogDoc — the document graph table

Header: DialogDoc.h · Base class: CDialog · Resource: IDD_DIALOG2. Purpose: editing the document contents as a table of 20 rows (graph name, file name, inputs/modes np1/mod1, the output flag). Coincides with TMCGROUT, but: - contains an additional field double dTUnit — the time-unit multiplier; - the input/mode semantics refer to the columns of the time signal, not the S-matrix.

Fields: m_DocFileName; 20 each of m_GraphName*, m_SFileName_*, m_np1_*, m_mod1_*, m_OutGrFlag_*; m_AddCharacteristicsFlag (BOOL — "add" pressed); dTUnit. Methods: OnAddCharacteristics() — sets m_AddCharacteristicsFlag and closes the dialog; OnNotify (overridden).

The fields m_np2_*/m_mod2_* are absent from the TMCROS version of DialogDoc.h (unlike the TMCGROUT description) — only the first address np1/mod1 is set.

9.3. CDialogTtoS — the "time → S-matrix" transform (NEW, only in TMCROS)

Header: DialogTtoS.h · Base class: CDialog · Resource: IDD_DIALOG3 · Implementation: DialogTtoS.cpp. Purpose: to gather up to 20 signal files .t, set for each a frequency, a time range [Tmin,Tmax] and a time unit, and export the result — the reconstructed S-matrix — into a single S-file .s.

Fields (DDX): | Field | Type | Purpose | |-------|------|---------| | m_DocFileName | CString | The document file name (for building paths) | | dTUnit | double | The time-unit multiplier (set from the view) | | m_SFileName | CString | The name of the output S-file (.s); by default <document>.s | | m_SFileName_1..20 | CString | The names of the input .t signal files (up to 20) | | m_OutGrFlag_1..20 | BOOL | The "process this file" flag | | m_dXValue1..20 | double | The frequency (Hz) for the corresponding .t file | | m_dTmin, m_dTmax | double | The time range (in the current units) | | m_csTimeUnit | CString | The time-unit label (ps/ns/mks/ms/s) | | m_dXmin, m_dDx | double | The start frequency and step for auto-filling the frequencies (by default 1e10 and 1e8) | | m_csError | CString | The text of the last conversion error |

Methods: - INT_PTR DoModal() — before showing it builds the absolute paths: the output .s name = <document without extension>.s, and each non-empty m_SFileName_<k> is reduced to the form <document directory>\<name>; - void OnChangeSfilename() — choosing the output .s-file name via CFileDialog (the "Tamic S-matrix" filter, mask *.s); - void OnAddCharacteristics() — choosing an input .t file (CFileDialog, "Tamic Rt-Signal", mask *.t) and writing it into the first free cell m_SFileName_1..20; - void OnChangeSfiledelet() — deletes the file named m_SFileName from disk (remove); - void OnExportFillxvalue() — fills m_dXValue1..20 with an arithmetic progression: m_dXmin, +m_dDx, +2·m_dDx, …; - void OnExportCharacteristics()the main action: for each k that has m_OutGrFlag_k and a non-empty name, calls CTmcTtoS::TtoS(m_SFileName_k, m_SFileName, m_dTmin*dTUnit, m_dTmax*dTUnit, m_dXValue_k); on error writes it into m_csError and stops; - void OnOK() — calls OnExportCharacteristics(), then CDialog::OnOK().

Errors/features: the input signals are converted in turn into one output S-file (each TtoS call appends a matrix row — see CTmcSMatrix::Save); the export stops at the first error.

9.4. CTmcGroutColorGraphDialog, CTmcGrParColTypWid

Identical to TMCGROUT (see tmcgrout.md, §9.3 and §9.4): setting the color/type/width of 16 lines and of a single line respectively. Headers TmcGroutColorGraphDialog.h, TmcGrParColTypWid.h.

9.5. CTmcGrParColTypWid1 (NOT in the build)

Header: TmcGrParColTypWid1.h · Base class: CDialog · Resource: IDD_DIALOGGRLINECOLORTYPEWIDTH1. An empty dialog stub (no fields or handlers, only DoDataExchange). Not included in TMCROS.vcxproj and does not take part in the build — left in the directory as an artifact.


10. The Time-to-Scattering (TtoS) subsystem

The conversion of a set of time signals into a scattering matrix at a given frequency. The idea: from two adjacent samples of the harmonic signal s(t)=A·sin(ωt+φ) the amplitude A and phase φ (the complex S) are reconstructed, averaged over all pairs of points in the range; the excited input determines the row of the S-matrix.

10.1. The CTmcTtoS class — the "file .t → file .s" wrapper

Header: src/Include/TmcTtoS.h · Implementation: TmcTtoS.cpp · Depends on: TmcSMatrix.h, tmcgrviw.h.

Fields (private): | Field | Type | Purpose | |-------|------|---------| | cSMatrix | CTmcSMatrix | The working conversion core | | csSFileName | CString | The output .s name | | csTFileName | CString | The input .t name | | csError | CString | The error text (by default "No error") | | dTmin, dTmax | double | The time range (seconds) | | dFreq | double | The frequency (Hz) at which S is reconstructed | | bIsError | BOOL | The error flag |

Methods: | Method | What it does | |--------|--------------| | void TtoS(CString csTfn, CString csSfn, double dTmin1, double dTmax1, double dFreq1) | The main public call: saves the parameters and performs TtoS() | | void TtoS(void) (private) | MakeSmatrixFromFileT()SaveSmatrixToFileS() | | void MakeSmatrixFromFileT(void) | Reads the .t (cSMatrix.ReadTFile) and builds the S-matrix (cSMatrix.MakeSmatrix); transfers the core errors into csError | | void SaveSmatrixToFileS(void) | Saves the result into the .s (cSMatrix.Save(csSFileName, dFreq)) | | BOOL IsError(void) | The error flag | | CString& GetErrorMessage(void) | The error text | | void DeleteData(void) (private) | Reset of the fields and cSMatrix.DeleteData() |

10.2. The CTmcSMatrix class — the core of reconstructing S from a signal

Header: src/Include/TmcSMatrix.h · Implementation: TmcSMatrix.cpp · Depends on: typedef.h (_complex), proc_s.h, s_file.h (SFILE95 — save_S_matrix_element).

Fields (private): | Field | Type | Purpose | |-------|------|---------| | csTFileName, csSFileName | CString | The names of the input .t and the output .s | | csError | CString | The error text | | dTmin, dTmax | double | The time range | | dFreq | double | The reconstruction frequency (Hz) | | bIsError | BOOL | The error flag | | pcSmatrix | _complex* | The reconstructed row of the S-matrix (nInput elements) | | pdTsignal | double* | The signal samples of all inputs (nPoint*nInput*2) | | pdTime | double* | The time samples (nPoint) | | nInput | int | The number of inputs (signal columns) | | nPoint | int | The number of time points in the range | | nLineInSMatrix | int | The index of the excited input = the S-matrix row number (−1 — undefined) |

Public methods: | Method | What it does | |--------|--------------| | void ReadTFile(CString csTFile, double dTmin1, double dTmax1) / void ReadTFile(void) (private) | Reads the .t: checks Tmax>Tmin, counts nPoint (CalcNPoint) and nInput (CalcNInput), allocates the arrays (AllocTArray), reads the data (ReadTArray) | | void MakeSmatrix(void) | Reconstructs S: AllocSArray()TtoS()SetnLineInSMatrix() | | void Save(CString csSFileName1, double dFreq1) / void Save(CString csSFileName1) / void Save(void) (private) | Writes the S-matrix row into the .s via save_S_matrix_element(nLineInSMatrix+1, …, pcSmatrix, dFreq, nInput) | | BOOL IsError(void) / CString& GetErrorMessage(void) | The error flag and text | | void DeleteData(void) | Freeing the arrays and resetting the fields |

Private methods (the algorithm): | Method | Purpose | |--------|---------| | int CalcNPoint(void) | Counts the number of data lines in the range [Tmin,Tmax]; in parallel reads the frequency from #TMC_GROTS_Freq; requires >5 points | | int CalcNInput(void) | From the first data line determines the number of inputs: (numbers_in_line − 2)/3 | | double gets_f1(char *ch) | Reads the time from a line (sscanf "%d%lg") | | int gets_nNumbersInLine(char *ch) | Counts the number of "word" numbers in a line | | void AllocTArray(void) | Allocates pdTsignal[nPoint*nInput*2], pdTime[nPoint] | | void ReadTArray(void) | Reads the signal samples of all inputs in the time range (readTsignal/readTsignalOne) | | void readTsignal(double **pdTsign, char *ch) / int readTsignalOne(…) | Parsing one line: skipping the number and time, then nInput pairs (Re/Im of the signal) | | int skip_blank(char*) / int skip_number(char*) | Skipping spaces/a number | | void AllocSArray(void) | Allocates pcSmatrix[nInput], initializes with FLT_MAX | | void TtoS(void) | For all inputs calls TtoSOneInput | | void TtoSOneInput(int n) | Averages the complex S of input n over all pairs of adjacent points (TtoSOneInputOnePoint) | | BOOL TtoSOneInputOnePoint(_complex *acc, double s1, double t1, double s2, double t2) | From a pair (s,t) solves the system for A and φ of the harmonic A·sin(ωt+φ) at the frequency dFreq; adds A·(cosφ, sinφ) to the accumulator. Returns TRUE if the contribution was taken into account | | void SetnLineInSMatrix(void) | Finds the single excited input → nLineInSMatrix; an error if not exactly one is excited | | BOOL IsInputExcite(int n) | TRUE if input n has non-zero samples (the input is excited) | | void PutErrorMessage(char *ch) | Sets bIsError and the error text |

The .t signal file format (by the parsing code): the data lines start with a space and contain point_number time [for each input: number Re Im] …; the service line #TMC_GROTS_Freq <frequency> sets the frequency; the file signature is #TMC_GraphicsOutputSignalFile FormVer2.0 2000.

The math of reconstructing S from a signal (TtoSOneInputOnePoint, the averaging, the excited-input criterion) is a scientific algorithm; do not change it without agreement.

10.3. Known defects in the TtoS code (for reference)

In CTmcSMatrix::CalcNPoint() and CalcNInput(), on a file-open error the call sprintf("Can't open file {%s}", csTFileName); is made without a receiving buffer (the first argument is the format, not a buffer). This is an erroneous call (a potential failure). It is noted as a code defect.


11. The CTMCGrExpression class — expression graphs

Identical to TMCGROUT (see tmcgrout.md, §10). Parses an expression over several files ([name] variables), computes the value at a point via exprint (i1nte_atof_1). In TMCROS the "file variables" are .t signals, and the GetExpressionValue* methods are applied to the quantities reconstructed from the signal. Header: src/Include/TMCGrExpression.h · Implementation: TMCGrExpression.cpp.


12. Global functions (in TMCGROUTView.cpp)

As in TMCGROUT (see tmcgrout.md, §11). Declared in TMCGROUTView.h: void PutTrace(CString), void PutTrace(char*), void PutStatistics(CString), void PutStatistics(char*) — output into panels 0 and 1 of the status bar.