Работа без окон: консольный и пакетный режим

Обычно расчёт запускают из окна программы. Но часто удобнее иначе: посчитать десяток заданий подряд, запустить длинный счёт на сервере или включить расчёт в свой сценарий обработки. Для этого в пакете есть два способа работы без участия человека.

Способ Что это Где есть
Пакетный режим обычная программа с окном; сама открывает задание, считает и закрывается Windows, Linux, macOS
Счётные ядра отдельные программы без окон вообще, только расчёт Linux

В обоих случаях расчёт один и тот же, и выходные файлы получаются одинаковые.


1. Пакетный режим

Программе передают ключ -Ar и путь к заданию. Она откроет задание, посчитает все шаги и закроется сама.

Windows

"C:\Program Files\TMC Suite\bin\tmc_rth.exe" /Ar "C:\работа\задание.tpl"

Ключ можно писать и через дефис (-Ar), и через косую черту (/Ar) — это равнозначно. Вариант /Arb принимается тоже: исторически он означал «batch», а сейчас действует так же, как /Ar.

Linux

planarrt_h -Arb /home/имя/работа/задание.tpl

macOS

Внутри пакета .app лежит сама программа, к ней и обращаются:

/Applications/PlanarRT_H.app/Contents/MacOS/PlanarRT_H -Arb /Users/имя/работа/задание.tpl

Что программа делает

  1. Открывает файл задания.
  2. Считает шаги с первого по последний (#STEP … #END_STEP).
  3. Пишет выходные файлы рядом с заданием — имена берутся из секции #OUTPUT.
  4. Закрывается.

Путь к заданию указывайте полным. По нему программа определяет каталог, в котором лежат включаемые файлы задания (#include) и файлы распределения (.eps). Если передать только имя файла, она будет искать их не там.

Для X-моды всё то же самое, программа называется tmc_rtx (Windows) или planarrt_x (Linux, macOS).


2. Счётные ядра для Linux

Это отдельные программы — tmc_rth (H-мода) и tmc_rtx (X-мода). Окон у них нет вовсе, графическая оболочка на машине не нужна: их ставят на сервер, где есть только терминал.

tmc_rth /home/имя/работа/задание.tpl
tmc_rtx /home/имя/работа/задание.tpl

Имя выходного файла ядро берёт из самого задания, из секции #OUTPUT, — второй аргумент не нужен.

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

Код Что означает
0 расчёт прошёл
1 ошибка: файл задания не открылся, не прочитался или счёт прервался
2 программа запущена без аргумента

По коду возврата удобно останавливать сценарий, если очередное задание не посчиталось:

tmc_rth /путь/задание.tpl || { echo "не посчиталось"; exit 1; }

Что печатается на экран

Ход разбора задания и счёта идёт в обычный вывод, сообщения об ошибках — в поток ошибок. Полезные строки:

Step:1;Error:no                                 задание прочитано, ошибок нет
Set block 55; points:1057041; eps = {...}       прочитан файл распределения
Step:1;Can't open diel.data file {...}          файл распределения не найден

3. Несколько заданий подряд

Linux и macOS

for f in /home/имя/работа/*.tpl; do
    echo "== $f"
    tmc_rth "$f" || echo "  ошибка, пропускаем"
done

Windows

for %%f in (C:\работа\*.tpl) do (
    echo == %%f
    "C:\Program Files\TMC Suite\bin\tmc_rth.exe" /Ar "%%f"
)

4. Что влияет на скорость

  • Вывод полей и топологии. С выключенными FIELDS и TOPOLOGY в секции #OUTPUT счёт идёт заметно быстрее: на каждом такте не нужно писать на диск всю сетку.
  • Где лежит задание. Держите задание и результаты на локальном диске. Если работать с сетевой папки или с раздела другой системы (например, с раздела Windows, подключённого в Linux), каждая запись идёт длинным путём и счёт замедляется в разы.
  • Синхронизация с FieldView. В меню Config → Synchronization есть режим, в котором ядро после каждого кадра поля ждёт, пока FieldView его прочитает. Для работы без окон он не нужен: ждать некого, и каждый кадр будет стоить лишних секунд. Перед пакетным счётом этот режим выключают.

5. Частые вопросы

Программа закрылась сразу, файлов нет. Скорее всего, не найдено задание или включаемый файл: проверьте, что путь полный и что рядом с заданием лежат файлы, на которые оно ссылается (#include, распределения .eps).

Считает, но выходные файлы не появляются. Посмотрите секцию #OUTPUT: строка FILE <имя>; обязательна и должна идти первой, а имя не должно содержать точку.

Нужно посмотреть результат. Выходные файлы одинаковы во всех трёх системах. Их открывают просмотрщики пакета: .t — TMCROS, .s — TMCGROUT, .DAT — TMC_DN, поля (.ex, .AMP, .FAZ) — FieldView. Файл, посчитанный на Linux, открывается в Windows-версии и наоборот.

Можно ли считать на одной системе, а смотреть на другой. Да, ради этого форматы и сохранены неизменными. Задания и результаты переносятся между Windows, Linux и macOS как есть.

Headless mode: batch runs and console kernels

A calculation is usually started from the program window. Often, though, another way is more convenient: to calculate a dozen tasks one after another, to run a long calculation on a server, or to include the calculation in your own processing script. The package offers two ways of working without a person at the keyboard.

Way What it is Where available
Batch mode the ordinary windowed program: it opens the task, calculates and closes itself Windows, Linux, macOS
Console kernels separate programs with no windows at all, calculation only Linux

The calculation is the same in both cases, and the output files are identical.


1. Batch mode

The program is given the -Ar switch and the path to the task. It opens the task, calculates every step and closes itself.

Windows

"C:\\Program Files\\TMC Suite\\bin\\tmc_rth.exe" /Ar "C:\\work\\task.tpl"

The switch may be written with a hyphen (-Ar) or a slash (/Ar) — both are equivalent. The /Arb form is also accepted: historically it meant “batch”, and today it behaves exactly like /Ar.

Linux

planarrt_h -Arb /home/user/work/task.tpl

macOS

The executable lives inside the .app bundle, and that is what is called:

/Applications/PlanarRT_H.app/Contents/MacOS/PlanarRT_H -Arb /Users/user/work/task.tpl

What the program does

  1. Opens the task file.
  2. Calculates the steps from the first to the last (#STEP … #END_STEP).
  3. Writes the output files next to the task — the names come from the #OUTPUT section.
  4. Closes.

Always give the full path to the task. The program derives from it the directory that holds the included task files (#include) and the .eps distributions. Given a bare file name, it looks for them elsewhere.

For the X-mode everything is the same; the program is called tmc_rtx (Windows) or planarrt_x (Linux, macOS).


2. Console kernels for Linux

These are separate programs — tmc_rth (H-mode) and tmc_rtx (X-mode). They have no windows at all and need no desktop on the machine: they are installed on a server that has only a terminal.

tmc_rth /home/user/work/task.tpl
tmc_rtx /home/user/work/task.tpl

The kernel takes the output file name from the task itself, from the #OUTPUT section — no second argument is needed.

Exit codes

Code Meaning
0 the calculation completed
1 error: the task file could not be opened or read, or the calculation stopped
2 the program was started without an argument

The exit code makes it easy to stop a script when a task fails to calculate:

tmc_rth /path/task.tpl || { echo "calculation failed"; exit 1; }

What is printed

The progress of parsing and calculating goes to the standard output, error messages to the error stream. Useful lines:

Step:1;Error:no                                 the task was read, no errors
Set block 55; points:1057041; eps = {...}       a distribution file was read
Step:1;Can't open diel.data file {...}          the distribution file is missing

3. Several tasks in a row

Linux and macOS

for f in /home/user/work/*.tpl; do
    echo "== $f"
    tmc_rth "$f" || echo "  failed, skipping"
done

Windows

for %%f in (C:\\work\\*.tpl) do (
    echo == %%f
    "C:\\Program Files\\TMC Suite\\bin\\tmc_rth.exe" /Ar "%%f"
)

4. What affects the speed

  • Field and topology output. With FIELDS and TOPOLOGY switched off in the #OUTPUT section the calculation is noticeably faster: the whole grid does not have to be written to disk on every time step.
  • Where the task is stored. Keep the task and its results on a local disk. Working from a network share, or from a partition belonging to another system (a Windows partition mounted under Linux, for example), makes every write take the long way round and slows the calculation down several times over.
  • Synchronisation with FieldView. The menu item Config → Synchronization enables a mode in which the kernel waits after each field frame until FieldView has read it. It is of no use without windows: there is nobody to wait for, and every frame costs extra seconds. Switch this mode off before a batch run.

5. Common questions

The program closed immediately and there are no files. Most likely the task or an included file was not found: check that the path is complete and that the files the task refers to (#include, .eps distributions) are next to it.

It calculates, but no output files appear. Look at the #OUTPUT section: the line FILE <name>; is mandatory, must come first, and the name must not contain a dot.

How to look at the result. The output files are the same on all three systems. The viewers of the package open them: .t — TMCROS, .s — TMCGROUT, .DAT — TMC_DN, fields (.ex, .AMP, .FAZ) — FieldView. A file calculated on Linux opens in the Windows version and the other way round.

Can one system calculate and another display. Yes — that is exactly why the file formats were kept unchanged. Tasks and results move between Windows, Linux and macOS as they are.