Библиотека sfile95 — файлы матриц рассеяния (.s)

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

Библиотека sfile95 (каталог src/libs/sfile95) читает и пишет S-файлы — двоичные файлы .s с матрицей рассеяния многополюсника на наборе частот. Это единственный код пакета, который знает раскладку файла .s: все программы работают с ним только через функции библиотеки.

Кто пользуется библиотекой в Qt6-версии:

Кто Что вызывает Зачем
Счётные ядра PlanarRT_H / PlanarRT_X (через библиотеку TMCIndan и класс CTmcTtoS → CTmcSMatrix) save_S_matrix_element после расчёта с возбуждением одного входа записать столбец S-матрицы на частоте из секции SMATRIX; для шага #STEP, посчитанного с ошибкой, — записать нули
TMCROS (CTmcSMatrix, CTmcWideband) save_S_matrix_element построить .s по временным сигналам, в том числе многочастотный расчёт за один проход
TMC_DN (CTmcSMatrix) save_S_matrix_element то же для программы диаграмм направленности
TMCGROUT (CTMCGROUTDoc) read_S_matrix_element прочитать частотную зависимость одного элемента S-матрицы для графика

Как S-матрица получается из сигналов, описано в теории: S-матрица по временным сигналам, многочастотный расчёт.

Публичные объявления лежат в общих заголовках src/Include: s_file.h (формат и низкоуровневый ввод-вывод), proc_s.h (внешний интерфейс для программ), frqdata.h (таблица частот), ys_proc.h и listing.h (наследие утилит TAMIC). Функции выделения памяти alloc_mem_err, free_mem, free_mem_null объявлены в tmc_lib.h, а определены здесь (s_memf.cpp); ими пользуется и библиотека prepr. Из-за этого prepr и sfile95 зависят друг от друга, и при линковке программ библиотеки собираются в группу (--start-group … --end-group).

Состав

В сборку входят 13 файлов .cpp — ровно те, что в Windows-проекте SFILE95.vcxproj.

Файл Роль
s_file.cpp единственный открытый S-файл процесса: Open_S_file, Close_S_file, read_S, write_S, skip_string
write_s.cpp запись S-матрицы одной частоты save_S_matrix; заголовок, строка сетки, пустые таблицы смещений
sofftbl.cpp update_offset_table — занесение частоты и смещения блока в таблицу
read_s.cpp чтение всех частот read_S_matrix; освобождение Free_S_read, Free_GRID_Index
s_wemt.cpp save_S_matrix_element — запись одного столбца на одной частоте (главный вход для записи)
sadd.cpp S_add — объединение двух S-файлов; Compare_S_ind, Free_S
unite_s.cpp Unite_two_S — слияние частотных точек двух наборов с сортировкой
s_remt.cpp read_S_matrix_element и варианты для форматов TMC, HFSS, CST
frqdata.cpp глобальная таблица частот FREQUENCY и функции доступа
s_memf.cpp alloc_mem_err, free_mem, free_mem_null; заглушки stat_messege, get_comp_file_flag
errors.cpp заглушка put_error_messege(int, ...) и тексты сообщений
s_table.cpp put_S_table — печать матрицы в листинг (наследие, в программах не вызывается)
wrrd_s.cpp make_S_matrix_name, copy_S_matrix (наследие, в программах не вызываются)
_file.h, error2.h локальные заголовки: константы файлового меню DOS, дополнительные коды ошибок

Файлы каталога, не входящие в сборку, перечислены в разделе Наследие TAMIC.

Формат S-файла

S-файл — двоичный, порядок байтов — младший первым (little-endian). Типы полей в сборке: целые поля заголовка и блоков — INT_1 = short, 2 байта; смещения — int, 4 байта; частоты, шаги сетки и элементы матрицы — double, 8 байт (в typedef.h всегда задан _HIGH_ACCURACY, поэтому _real = double). Схема в шапке write_s.cpp написана для типов TAMIC; ниже — фактическая раскладка, которую пишет и читает код.

«Паскалева» строка (PS) — длина INT_1, затем столько байт текста (без завершающего нуля), затем разделитель. Разделитель — значение INT_1 0x0a0d, т. е. байты 0D 0A.

Заголовок

Смещение, байт Длина Содержимое
0 4 метка SMT и байт 0 (SMT_LABEL)
4 4 версия текстом: 102 и байт 0 (SMT_VERSION)
8 2 разделитель
10 2 NS — число PS в заголовке: 7 + 2*extrapol_flag
12 2 разделитель
14 PS MAIN_LABEL — метка программы (для Rt-H: TAMIC-RTH V 2.00)
… PS TWP_LABEL — вторая метка программы
… PS строка сетки (см. ниже)
… PS × 2(extrapol_flag+1) для каждой сетки: имя файла задания .tpl, имя S-файла .s
… PS основная таблица смещений
… PS таблица смещений коэффициентов интерполяции (всегда пустая)

Строка сетки: длина 2 + 24*(extrapol_flag+1), затем extrapol_flag (INT_1, 0..2 — число сеток минус один; в пакете всегда 0), затем для каждой сетки три double delta1, delta2, delta3 — шаги сетки по X, Y, Z, м; затем разделитель. Файлы, которые пишет save_S_matrix_element, содержат одну сетку с нулевыми шагами, имя задания Tamic Output Signal Viewer и имя самого S-файла.

Таблицы смещений

Длина Содержимое
2 (WORD) длина строки таблицы: 2 + 12*NF, где NF — число точек глобальной таблицы частот при создании файла
2 (WORD) число записанных частот
12 × NF записи: частота double, Гц, и смещение int начала блока частоты от начала файла
2 разделитель

Место под все NF записей резервируется при создании файла (write_offset_table пишет нули). При записи частоты номер k функция update_offset_table:

  1. берёт текущую длину файла — это смещение будущего блока;
  2. переходит на начало файла + 14 байт и пропускает PS до нужной таблицы (skip_string: для основной — NS-2 строк, для таблицы интерполяции — NS-1);
  3. пропускает длину таблицы и пишет число записанных частот k+1;
  4. переходит к записи k (12*k байт) и пишет частоту и смещение;
  5. возвращается в конец файла.

Смещение хранится как 4-байтовое целое со знаком: S-файл длиннее 2 ГБ записать нельзя.

Блок одной частоты

Блоки дописываются в конец файла в порядке записи частот.

Длина Содержимое
8 частота, Гц (double)
2 num — число входов, 0..MAX_INPUT_NUM
2 × num число мод на каждом входе
2 dim — размерность матрицы, 1..255 (сумма мод по входам)
2 разделитель
16 × dim² матрица: пары (Re, Im) double, по строкам
2 разделитель

Порядок строк и столбцов матрицы — по входам, внутри входа — по модам. Элемент S(i, j) (i — вход-приёмник, j — возбуждаемый вход; при одной моде на входе) лежит по индексу (i-1)*dim + (j-1). Элементы, которые ещё не записаны, save_S_matrix_element заполняет значением FLT_MAX (обе части).

Таблица частот

Запись многочастотного файла опирается на глобальную таблицу частот (frqdata.cpp) — одну статическую структуру FREQUENCY на процесс:

  • f[] — до FREQ_MAX_NUM = 100 частот, всегда в Гц;
  • max — число точек, num — номер текущей точки;
  • code — текущие единицы (0 — Гц, 1 — кГц, 2 — МГц, 3 — ГГц; по умолчанию 3).

Текущие единицы применяются только на входе и выходе функций с пересчётом: set_frequency(f0, df, nf) и set_frequency_arr принимают частоты в текущих единицах и умножают их на unit[code]; get_frq_f0(1) и get_frq_df(1) возвращают в текущих единицах. Остальные функции работают в Гц.

save_S_matrix берёт частоту и номер точки именно из этой таблицы: номер текущей частоты 0 означает «создать файл заново».

Запись S-матрицы по частотам

save_S_matrix(sss, id, имя, si, extrapol_flag) записывает матрицу текущей частоты глобальной таблицы:

  1. Open_S_file(имя, S_WR): для точки 0 файл открывается "wb+" (стирается), для остальных — "rb+".
  2. Для точки 0 пишется заголовок: метка и версия, NS, две метки программы, строка сетки, имена файлов, основная таблица на get_frq_nf() записей и пустая таблица интерполяции.
  3. update_offset_table заносит частоту и смещение конца файла.
  4. В конец файла дописывается блок частоты.
  5. Файл закрывается.

Порядок вызовов для файла на nf частот:

set_frq_nf(nf);                      // или set_frequency(...)
for (k = 0; k < nf; ++k) {
    set_current_frq_num(k);
    set_frq_element(f_Гц[k], k);
    save_S_matrix(S[k], &id[k], имя, si, 0);
}

Возврат: 0 — успех, −1 — файл не открылся или ошибка записи.

Чтение S-файла

read_S_matrix(имя, &si, &extrapol_flag, &sss, &frq, &id) читает все частоты:

  1. Read_TITLE — проверка метки SMT и версии (не младше 102), чтение NS, пропуск двух меток программы.
  2. Read_GRID — строка сетки (extrapol_flag должен быть 0..2) и имена файлов.
  3. Число записанных частот из основной таблицы смещений; выделение массивов frq.f, id, sss.
  4. Для каждой частоты: запись таблицы (частота и смещение) → переход к блоку → num (0..MAX_INPUT_NUM), числа мод, dim (1..255) → матрица dim² пар double.

Коды возврата:

Код Причина
0 успех
−1 ошибка чтения или недопустимое значение в файле (длина строки, num, dim, extrapol_flag)
−2 файл не открылся; не S-файл; версия младше 102; нет памяти под индекс сетки
−3 нет памяти под массивы частот

Если памяти не хватило на матрицу частоты с номером k > 0, читаются только первые k частот, frq.max = k, и функция возвращает 0 (сообщение-предупреждение — заглушка, см. подводные камни).

Владение памятью

Всё, что возвращает read_S_matrix, выделено функцией alloc_mem_err (malloc) и освобождается вызывающим:

Что Чем освобождать
frq.f free_mem
id free_mem
sss (массив указателей и матрицы) Free_S_read(&sss, frq.max)
si (массив и имена файлов в нём) Free_GRID_Index(&si, extrapol_flag)

Free_S (sadd.cpp) делает всё это одним вызовом. Функции чтения одного элемента (read_S_matrix_element…) возвращают массивы частот и значений, выделенные new[]; их освобождает вызывающая программа.

alloc_mem_err — это malloc с вызовом put_error_messege(FATAL_MEM_ALLOC_ERROR) при отказе (сообщение — заглушка); free_mem_null освобождает память и обнуляет указатель.

Запись столбца S-матрицы

save_S_matrix_element(in1, имя, столбец, f, nInput) — основной способ, которым программы пакета строят .s. Один расчёт с возбуждением входа in1 даёт столбец S(1..nInput, in1) на частоте f (Гц); вызов кладёт его в файл:

  1. Проверка 1 <= nInput <= MAX_INPUT_NUM, иначе −1.
  2. Файл читается read_S_matrix. * Не прочитался. Если файл существует и не пуст — возврат −2, файл не трогается. Иначе создаётся новый файл на одну частоту: матрица nInput × nInput, по одной моде на входе, все элементы FLT_MAX, кроме столбца in1. * Прочитался, частота f в нём есть (совпадение с относительной точностью 1e−15). Структура должна совпадать: ровно nInput входов, по одной моде на каждом, иначе возврат −1 и файл не меняется. Столбец заменяется, и файл перезаписывается целиком (точки по порядку через save_S_matrix). * Прочитался, частоты f нет. Новая частота пишется во временный файл <имя>$, затем S_add(имя, <имя>$) сливает файлы, временный файл удаляется.

Частота нового файла задаётся вызовом set_frequency(f*1e-9, 0, 1) — то есть в ГГц, в расчёте на то, что текущие единицы глобальной таблицы — ГГц (значение по умолчанию). Ни одна программа пакета единицы не меняет.

Объединение S-файлов

S_add(файл1, файл2) читает оба файла, проверяет совместимость сеток (Compare_S_ind: одинаковый extrapol_flag, при одной сетке — равные шаги), сливает частотные точки (Unite_two_S) и пишет результат в файл1.

Unite_two_S:

  1. Частоты первого набора, точно совпавшие с какой-либо частотой второго, помечаются нулём — остаётся точка второго набора.
  2. Считаются оставшиеся точки; если их FREQ_MAX_NUM (100) или больше — ошибка −1.
  3. Точки обоих наборов копируются в общий массив и сортируются по частоте (qsort, cmpgle).
  4. Возвращаются новые массивы частот, описаний входов и указателей на матрицы; сами матрицы не копируются, а берутся из исходных наборов.

Отсюда предел: в одном .s, собранном через save_S_matrix_element, не больше 99 частот.

Чтение одного элемента из файлов других программ

read_S_matrix_element(&in1, &mod1, &in2, &mod2, имя, &s, &f, &n) возвращает частотную зависимость элемента S(вход in1 мода mod1; вход in2 мода mod2). Форматы пробуются по очереди, пока число точек n не станет больше нуля:

  1. S-файл TMC (read_S_matrix_element_TMC) — через read_S_matrix. Номера входов ограничиваются числом входов первой частоты, моды — не меньше 1; берутся только частоты, где у обоих входов есть нужные моды. Частоты — Гц.
  2. Текст HFSS (read_S_matrix_element_HFSS). Строки вида … -> P<вход> … M<мода> до строки !END EXCITATION_MAPS задают порядок пар «вход, мода»; их число — размерность матрицы N. Далее для каждой частоты: частота в ГГц (переводится в Гц) и N² пар (Re, Im) по строкам. Если пара не найдена, чтение не удаётся.
  3. Текст CST (read_S_matrix_element_CST). Первая строка — заголовок со столбцами WavePort<вход>):Mode(<мода>, их число — размерность N; вторая строка пропускается; далее по строке на частоту: частота (без пересчёта единиц) и N² пар «модуль, фаза в градусах», которые переводятся в (Re, Im). Если пара в заголовке не найдена, берётся первый столбец.

Во всех форматах номера входов и мод исправляются в пределы, имеющиеся в файле, и возвращаются через те же параметры. Признак неудачи — n <= 0.

Подводные камни

  • Сообщения об ошибках не выводятся. put_error_messege(int, ...) в errors.cpp — заглушка, всегда возвращает 0. Об ошибке можно узнать только по коду возврата. Следствие: при нехватке памяти read_S_matrix молча возвращает часть частот.
  • Одно состояние на процесс. Открытый S-файл, число PS заголовка и таблица частот — статические переменные. Функции библиотеки нельзя вызывать из нескольких потоков одновременно, а два процесса не должны писать один .s одновременно (блокировок нет).
  • Не больше 99 частот в файле, собранном по столбцам (см. объединение).
  • Структура файла фиксируется первой записью. Если .s от прошлого расчёта имеет другое число входов, save_S_matrix_element возвращает −1 и файл не меняет; если файл существует, но не читается как S-файл, — −2. Перед расчётом с другой конфигурацией портов старый .s нужно удалить.
  • Частота 0 Гц при слиянии Unite_two_S неотличима от метки «точка заменена» и теряется.
  • Единицы. save_S_matrix_element предполагает, что текущие единицы глобальной таблицы — ГГц; частоты CST читаются без пересчёта, HFSS — переводятся из ГГц.
  • Не более 2 ГБ. Смещение блока в таблице — 4-байтовое целое.
  • put_S_table, make_S_matrix_name, copy_S_matrix входят в библиотеку, но вызывают функции листинга и задания TAMIC (open_listing_file, l_printf, get_tpl_file_name, copy_file …), которых в сборке нет. Программы их не вызывают; вызов привёл бы к ошибке линковки.

Наследие TAMIC

Каталог содержит файлы утилиты TAMIC для работы с S-файлами из командной строки. В сборку Qt6-версии они не входят (как и в Windows-проект) и оставлены для сверки:

Файл Что в нём
main_s.cpp точка входа утилиты
gtargenv.cpp разбор ключей командной строки
sread.cpp главная процедура processor
s_db.cpp имя файла и флаги вывода
stxtable.cpp текстовая таблица S-матриц для других САПР
wrtslst.cpp вывод S-матриц в листинг
listing.cpp листинг <имя>.lst (объявления — listing.h)
outtrace.cpp строка состояния текстового экрана DOS
read_s1.cpp чтение матрицы на текущей частоте с интерполяцией
s_cut.cpp сокращение многомодовой матрицы до одномодовой

Заголовок ys_proc.h объявляет функции утилиты пересчёта S → Y, которых в исходниках пакета нет; _file.h — функции файлового меню DOS, тоже без определений. Объявления сохранены, потому что заголовки подключаются собираемыми файлами.

sfile95 library — scattering-matrix files (.s)

Purpose and place in the package

The sfile95 library (directory src/libs/sfile95) reads and writes S-files — binary .s files containing the scattering matrix of a multiport over a set of frequencies. It is the only code in the package that knows the layout of the .s file: all programs work with it only through the library functions.

Who uses the library in the Qt6 version:

Who What it calls Purpose
PlanarRT_H / PlanarRT_X compute kernels (through the TMCIndan library and the class CTmcTtoS → CTmcSMatrix) save_S_matrix_element after a computation with one port excited, write the S-matrix column at the frequency from the SMATRIX section; for a #STEP computed with an error, write zeros
TMCROS (CTmcSMatrix, CTmcWideband) save_S_matrix_element build a .s from time signals, including a multi-frequency computation in a single pass
TMC_DN (CTmcSMatrix) save_S_matrix_element the same for the radiation-pattern program
TMCGROUT (CTMCGROUTDoc) read_S_matrix_element read the frequency dependence of one S-matrix element for a plot

How the S-matrix is obtained from the signals is described in the theory section: S-matrix from time signals, multi-frequency computation.

The public declarations are in the shared headers src/Include: s_file.h (format and low-level I/O), proc_s.h (external interface for programs), frqdata.h (frequency table), ys_proc.h and listing.h (legacy of the TAMIC utilities). The memory allocation functions alloc_mem_err, free_mem, free_mem_null are declared in tmc_lib.h but defined here (s_memf.cpp); they are also used by the prepr library. Because of this prepr and sfile95 depend on each other, and when programs are linked the libraries are put into a group (--start-group … --end-group).

Contents

The build includes 13 .cpp files — exactly those in the Windows project SFILE95.vcxproj.

File Role
s_file.cpp the single open S-file of the process: Open_S_file, Close_S_file, read_S, write_S, skip_string
write_s.cpp writing the S-matrix of one frequency save_S_matrix; header, grid string, empty offset tables
sofftbl.cpp update_offset_table — entering the frequency and block offset into the table
read_s.cpp reading all frequencies read_S_matrix; freeing with Free_S_read, Free_GRID_Index
s_wemt.cpp save_S_matrix_element — writing one column at one frequency (the main entry point for writing)
sadd.cpp S_add — merging two S-files; Compare_S_ind, Free_S
unite_s.cpp Unite_two_S — merging the frequency points of two sets with sorting
s_remt.cpp read_S_matrix_element and variants for the TMC, HFSS, CST formats
frqdata.cpp the global frequency table FREQUENCY and access functions
s_memf.cpp alloc_mem_err, free_mem, free_mem_null; the stubs stat_messege, get_comp_file_flag
errors.cpp the stub put_error_messege(int, ...) and message texts
s_table.cpp put_S_table — printing the matrix to the listing (legacy, not called by the programs)
wrrd_s.cpp make_S_matrix_name, copy_S_matrix (legacy, not called by the programs)
_file.h, error2.h local headers: DOS file-menu constants, additional error codes

The files of the directory that are not part of the build are listed in the section TAMIC legacy.

S-file format

The S-file is binary, with little-endian byte order. Field types in the build: integer fields of the header and blocks are INT_1 = short, 2 bytes; offsets are int, 4 bytes; frequencies, grid steps and matrix elements are double, 8 bytes (typedef.h always defines _HIGH_ACCURACY, so _real = double). The diagram in the header comment of write_s.cpp is written for the TAMIC types; below is the actual layout that the code writes and reads.

A "Pascal" string (PS) is a length of type INT_1, followed by that many bytes of text (without a terminating zero), followed by a separator. The separator is the INT_1 value 0x0a0d, i.e. the bytes 0D 0A.

Header

Offset, bytes Length Contents
0 4 label SMT and byte 0 (SMT_LABEL)
4 4 version as text: 102 and byte 0 (SMT_VERSION)
8 2 separator
10 2 NS — number of PS in the header: 7 + 2*extrapol_flag
12 2 separator
14 PS MAIN_LABEL — program label (for Rt-H: TAMIC-RTH V 2.00)
… PS TWP_LABEL — second program label
… PS grid string (see below)
… PS × 2(extrapol_flag+1) for each grid: name of the .tpl task file, name of the .s S-file
… PS main offset table
… PS offset table of interpolation coefficients (always empty)

Grid string: length 2 + 24*(extrapol_flag+1), then extrapol_flag (INT_1, 0..2 — number of grids minus one; always 0 in the package), then for each grid three double values delta1, delta2, delta3 — grid steps along X, Y, Z, m; then a separator. The files written by save_S_matrix_element contain one grid with zero steps, the task name Tamic Output Signal Viewer and the name of the S-file itself.

Offset tables

Length Contents
2 (WORD) length of the table string: 2 + 12*NF, where NF is the number of points in the global frequency table when the file is created
2 (WORD) number of written frequencies
12 × NF records: frequency double, Hz, and int offset of the start of the frequency block from the beginning of the file
2 separator

Space for all NF records is reserved when the file is created (write_offset_table writes zeros). When frequency number k is written, the function update_offset_table:

  1. takes the current file length — this is the offset of the future block;
  2. moves to the beginning of the file + 14 bytes and skips PS up to the required table (skip_string: for the main table — NS-2 strings, for the interpolation table — NS-1);
  3. skips the table length and writes the number of written frequencies k+1;
  4. moves to record k (12*k bytes) and writes the frequency and offset;
  5. returns to the end of the file.

The offset is stored as a signed 4-byte integer: an S-file larger than 2 GB cannot be written.

Block of one frequency

Blocks are appended to the end of the file in the order in which the frequencies are written.

Length Contents
8 frequency, Hz (double)
2 num — number of ports, 0..MAX_INPUT_NUM
2 × num number of modes at each port
2 dim — matrix dimension, 1..255 (sum of modes over the ports)
2 separator
16 × dim² matrix: (Re, Im) pairs of double, row by row
2 separator

The rows and columns of the matrix are ordered by port, and within a port by mode. The element S(i, j) (i — receiving port, j — excited port; with one mode per port) is at index (i-1)*dim + (j-1). Elements that have not been written yet are filled by save_S_matrix_element with the value FLT_MAX (both parts).

Frequency table

Writing a multi-frequency file relies on the global frequency table (frqdata.cpp) — a single static FREQUENCY structure per process:

  • f[] — up to FREQ_MAX_NUM = 100 frequencies, always in Hz;
  • max — number of points, num — index of the current point;
  • code — current units (0 — Hz, 1 — kHz, 2 — MHz, 3 — GHz; default 3).

The current units apply only at the input and output of functions that convert: set_frequency(f0, df, nf) and set_frequency_arr take frequencies in the current units and multiply them by unit[code]; get_frq_f0(1) and get_frq_df(1) return values in the current units. All other functions work in Hz.

save_S_matrix takes the frequency and the point index from exactly this table: a current frequency index of 0 means "create the file anew".

Writing the S-matrix frequency by frequency

save_S_matrix(sss, id, name, si, extrapol_flag) writes the matrix of the current frequency of the global table:

  1. Open_S_file(name, S_WR): for point 0 the file is opened with "wb+" (erased), for the others — with "rb+".
  2. For point 0 the header is written: label and version, NS, two program labels, grid string, file names, the main table for get_frq_nf() records and an empty interpolation table.
  3. update_offset_table enters the frequency and the offset of the end of the file.
  4. The frequency block is appended to the end of the file.
  5. The file is closed.

Call sequence for a file with nf frequencies:

set_frq_nf(nf);                      // or set_frequency(...)
for (k = 0; k < nf; ++k) {
    set_current_frq_num(k);
    set_frq_element(f_Hz[k], k);
    save_S_matrix(S[k], &id[k], name, si, 0);
}

Return: 0 — success, −1 — the file failed to open or a write error occurred.

Reading an S-file

read_S_matrix(name, &si, &extrapol_flag, &sss, &frq, &id) reads all frequencies:

  1. Read_TITLE — check of the SMT label and the version (not older than 102), reading NS, skipping the two program labels.
  2. Read_GRID — the grid string (extrapol_flag must be 0..2) and the file names.
  3. The number of written frequencies from the main offset table; allocation of the arrays frq.f, id, sss.
  4. For each frequency: table record (frequency and offset) → jump to the block → num (0..MAX_INPUT_NUM), mode counts, dim (1..255) → matrix of dim² double pairs.

Return codes:

Code Cause
0 success
−1 read error or invalid value in the file (string length, num, dim, extrapol_flag)
−2 the file failed to open; not an S-file; version older than 102; no memory for the grid index
−3 no memory for the frequency arrays

If there is not enough memory for the matrix of frequency number k > 0, only the first k frequencies are read, frq.max = k, and the function returns 0 (the warning message is a stub, see pitfalls).

Memory ownership

Everything returned by read_S_matrix is allocated by the function alloc_mem_err (malloc) and is freed by the caller:

What How to free it
frq.f free_mem
id free_mem
sss (array of pointers and the matrices) Free_S_read(&sss, frq.max)
si (the array and the file names in it) Free_GRID_Index(&si, extrapol_flag)

Free_S (sadd.cpp) does all of this in a single call. The functions that read a single element (read_S_matrix_element…) return arrays of frequencies and values allocated with new[]; the calling program frees them.

alloc_mem_err is malloc with a call to put_error_messege(FATAL_MEM_ALLOC_ERROR) on failure (the message is a stub); free_mem_null frees the memory and zeroes the pointer.

Writing an S-matrix column

save_S_matrix_element(in1, name, column, f, nInput) is the main way in which the package programs build a .s file. One computation with port in1 excited gives the column S(1..nInput, in1) at frequency f (Hz); the call puts it into the file:

  1. Check 1 <= nInput <= MAX_INPUT_NUM, otherwise −1.
  2. The file is read with read_S_matrix. * Not read. If the file exists and is not empty — return −2, the file is not touched. Otherwise a new file for one frequency is created: a matrix nInput × nInput, one mode per port, all elements FLT_MAX except column in1. * Read, and frequency f is present in it (match with a relative tolerance of 1e−15). The structure must match: exactly nInput ports, one mode at each, otherwise return −1 and the file is not changed. The column is replaced, and the file is rewritten completely (points in order via save_S_matrix). * Read, and frequency f is absent. The new frequency is written to a temporary file <name>$, then S_add(name, <name>$) merges the files, and the temporary file is deleted.

The frequency of a new file is set by the call set_frequency(f*1e-9, 0, 1) — that is, in GHz, on the assumption that the current units of the global table are GHz (the default value). No program of the package changes the units.

Merging S-files

S_add(file1, file2) reads both files, checks that the grids are compatible (Compare_S_ind: the same extrapol_flag, and for a single grid — equal steps), merges the frequency points (Unite_two_S) and writes the result to file1.

Unite_two_S:

  1. Frequencies of the first set that exactly match some frequency of the second are marked with zero — the point of the second set remains.
  2. The remaining points are counted; if there are FREQ_MAX_NUM (100) or more — error −1.
  3. The points of both sets are copied into a common array and sorted by frequency (qsort, cmpgle).
  4. New arrays of frequencies, port descriptions and matrix pointers are returned; the matrices themselves are not copied but taken from the source sets.

Hence the limit: a single .s assembled through save_S_matrix_element holds at most 99 frequencies.

Reading a single element from files of other programs

read_S_matrix_element(&in1, &mod1, &in2, &mod2, name, &s, &f, &n) returns the frequency dependence of the element S(port in1 mode mod1; port in2 mode mod2). The formats are tried one after another until the number of points n becomes greater than zero:

  1. TMC S-file (read_S_matrix_element_TMC) — via read_S_matrix. Port numbers are limited to the number of ports of the first frequency, modes are at least 1; only those frequencies are taken where both ports have the required modes. Frequencies are in Hz.
  2. HFSS text (read_S_matrix_element_HFSS). Lines of the form … -> P<port> … M<mode> up to the line !END EXCITATION_MAPS define the order of the "port, mode" pairs; their number is the matrix dimension N. Then, for each frequency: the frequency in GHz (converted to Hz) and N² (Re, Im) pairs row by row. If the pair is not found, reading fails.
  3. CST text (read_S_matrix_element_CST). The first line is a header with columns WavePort<port>):Mode(<mode>, their number is the dimension N; the second line is skipped; then one line per frequency: the frequency (without unit conversion) and N² pairs "magnitude, phase in degrees", which are converted to (Re, Im). If the pair is not found in the header, the first column is taken.

In all formats the port and mode numbers are clamped to the ranges present in the file and returned through the same parameters. The failure indicator is n <= 0.

Pitfalls

  • Error messages are not output. put_error_messege(int, ...) in errors.cpp is a stub that always returns 0. An error can be detected only by the return code. Consequence: when memory runs short, read_S_matrix silently returns only part of the frequencies.
  • One state per process. The open S-file, the number of header PS and the frequency table are static variables. The library functions must not be called from several threads at the same time, and two processes must not write the same .s simultaneously (there is no locking).
  • At most 99 frequencies in a file assembled column by column (see merging).
  • The file structure is fixed by the first write. If a .s from a previous computation has a different number of ports, save_S_matrix_element returns −1 and does not change the file; if the file exists but cannot be read as an S-file — −2. Before a computation with a different port configuration the old .s must be deleted.
  • A frequency of 0 Hz is indistinguishable from the "point replaced" mark when merging with Unite_two_S, and is lost.
  • Units. save_S_matrix_element assumes that the current units of the global table are GHz; CST frequencies are read without conversion, HFSS ones are converted from GHz.
  • At most 2 GB. The block offset in the table is a 4-byte integer.
  • put_S_table, make_S_matrix_name, copy_S_matrix are part of the library, but they call TAMIC listing and task-file functions (open_listing_file, l_printf, get_tpl_file_name, copy_file …) that are not in the build. The programs do not call them; a call would lead to a link error.

TAMIC legacy

The directory contains files of the TAMIC utility for working with S-files from the command line. They are not part of the Qt6 version build (nor of the Windows project) and are kept for comparison:

File What it contains
main_s.cpp entry point of the utility
gtargenv.cpp parsing of command-line switches
sread.cpp the main procedure processor
s_db.cpp file name and output flags
stxtable.cpp text table of S-matrices for other CAD systems
wrtslst.cpp output of S-matrices to the listing
listing.cpp the <name>.lst listing (declarations — listing.h)
outtrace.cpp status bar of the DOS text screen
read_s1.cpp reading the matrix at the current frequency with interpolation
s_cut.cpp reduction of a multimode matrix to a single-mode one

The header ys_proc.h declares functions of the S → Y conversion utility that do not exist in the package sources; _file.h declares DOS file-menu functions, also without definitions. The declarations are kept because the headers are included by files that are built.