Граф знаний (graphify)

Этот раздел описывает семантический граф знаний пакета TMC Suite, построенный инструментом graphify. Граф — это машинно- и человекочитаемая карта связей между файлами, классами, функциями и понятиями проекта. Он предназначен для публикации в интернете: посетитель сможет визуально увидеть семантические связи внутри Tamic, искать по ним и переиспользовать эту семантику в собственном проекте.

Интерактивный граф: открыть graph.html (самодостаточная страница — узлы кликабельны, есть поиск). Данные графа: graph.json. В собранном Sphinx-сайте граф встроен прямо в эту страницу (см. RST-версию).


1. Зачем это в архитектуре

Обычная документация (API, сборка, руководство пользователя) описывает компоненты по отдельности. Граф знаний показывает пакет как единую сеть связей: какие модули ссылаются друг на друга, какие функции вызываются вместе, какие понятия принадлежат одной смысловой группе. Это даёт три практических эффекта:

  • Навигация по смыслу. Можно начать с любого узла (например, «Чтение S-матриц») и пройти по связям к смежным частям, не зная заранее имён файлов.
  • Поиск внутри. Граф включает поисковый индекс — по слову находятся все связанные узлы и сообщества.
  • Переиспользование. Данные графа выгружены в открытом формате (graph.json), пригодном для GraphRAG-конвейеров и сторонних инструментов. Любой, кто строит свой проект вокруг Tamic, может опереться на готовую семантику, а не разбирать исходники с нуля.

2. Что входит в граф

Граф строится по всему репозиторию (исходники C++/MFC/OpenGL, заголовки, документация). Текущие показатели сборки:

Показатель Значение
Узлы (файлы, классы, функции, понятия) 4728
Связи (ссылки, вызовы, смысловое родство) 9402
Сообщества (смысловые группы) 346
Источник 1233 файла · ~1,24 млн слов
Достоверность связей 98 % извлечено напрямую (EXTRACTED), 2 % выведено (INFERRED)

Узлы группируются в сообщества — автоматически выделенные смысловые кластеры (например: «TMCGROUT: координаты графика», «Чтение S-матриц (SFILE95)», «TMCIndan: вывод (IndanOutput)», «FieldView: повороты/сдвиги», «Расчёт диаграмм направленности (DiaNapGr)»). Внутри сообществ выделяются узлы-концентраторы (god nodes) — точки, через которые проходит больше всего связей; они служат «входами» при навигации.


3. Артефакты (что публикуется)

Все файлы графа лежат в каталоге graphify-out/ в корне проекта:

Файл Назначение Для публикации
graph.html Интерактивный граф — открывается в браузере, узлы кликабельны, есть поиск Да — это основная страница для сайта
graph.json Сырые данные графа в открытом формате (GraphRAG-ready) Да — для переиспользования и поиска сторонними инструментами
GRAPH_REPORT.md Аудит-отчёт: сводка, концентраторы, неожиданные связи, стоимость построения По желанию
manifest.json, cost.json, cache/ Служебные (инкрементальная пересборка, учёт) Нет — внутренние

Для размещения онлайн достаточно выложить graph.html (самодостаточная страница) и, при желании, graph.json рядом — чтобы желающие могли скачать данные графа.


4. Как граф поддерживается в актуальном состоянии

Граф строится из кода без обращения к платным сервисам на этапе обновления — обновление идёт по синтаксическому разбору (AST). После правок в коде граф пересобирается командой:

graphify update .

Полная пересборка (с переразбором всех файлов) и экспорт интерактивного HTML:

graphify .            # построить/обновить граф
graphify export html  # пересобрать graph.html

Запросы к уже построенному графу (без пересборки) — для поиска и трассировки связей:

graphify query "Как данные ядра попадают во вьювер?"   # обзорный ответ по графу
graphify path "PlanarRT_H" "FieldView"                 # кратчайший путь между узлами
graphify explain "Чтение S-матриц"                      # пояснение одного узла/понятия

5. Статус и назначение

Граф знаний — дополнительный, справочный слой документации. Он не входит в собранные программы и не влияет на расчёты; это инструмент навигации и переиспользования. Предназначен для открытой публикации вместе с остальной архитектурной документацией, чтобы внешние разработчики и исследователи могли изучать семантику Tamic и опираться на неё в своих проектах.

Knowledge graph (graphify)

This section describes the semantic knowledge graph of the TMC Suite package, built with the graphify tool. The graph is a machine- and human-readable map of the relationships between the files, classes, functions and concepts of the project. It is intended for online publication: a visitor can visually see the semantic relationships inside Tamic, search through them, and reuse that semantics in their own project.

Interactive graph: open graph.html (a self-contained page — the nodes are clickable and there is a search). Graph data: graph.json. In the compiled Sphinx site the graph is embedded directly into this page (see the RST version).


1. Why this belongs in the architecture

Ordinary documentation (API, build, user manual) describes the components individually. The knowledge graph shows the package as a single network of relationships: which modules reference each other, which functions are called together, which concepts belong to a single semantic group. This gives three practical benefits:

  • Navigation by meaning. You can start from any node (for example, "Reading S-matrices") and walk the relationships to adjacent parts without knowing the file names in advance.
  • Internal search. The graph includes a search index — a word finds all related nodes and communities.
  • Reuse. The graph data is exported in an open format (graph.json), suitable for GraphRAG pipelines and third-party tools. Anyone building their own project around Tamic can rely on ready-made semantics instead of studying the sources from scratch.

2. What the graph contains

The graph is built over the entire repository (C++/MFC/OpenGL sources, headers, documentation). Current build figures:

Metric Value
Nodes (files, classes, functions, concepts) 4728
Relationships (references, calls, semantic kinship) 9402
Communities (semantic groups) 346
Source 1233 files · ~1.24 million words
Relationship confidence 98% extracted directly (EXTRACTED), 2% inferred (INFERRED)

The nodes are grouped into communities — automatically identified semantic clusters (for example: "TMCGROUT: graph coordinates", "Reading S-matrices (SFILE95)", "TMCIndan: output (IndanOutput)", "FieldView: rotations/shifts", "Radiation-pattern computation (DiaNapGr)"). Within the communities there are hub nodes (god nodes) — points through which the most relationships pass; they serve as "entry points" during navigation.


3. Artifacts (what is published)

All graph files live in the graphify-out/ directory at the project root:

File Purpose For publication
graph.html Interactive graph — opens in a browser, nodes are clickable, has search Yes — this is the main page for the site
graph.json Raw graph data in an open format (GraphRAG-ready) Yes — for reuse and search by third-party tools
GRAPH_REPORT.md Audit report: summary, hubs, unexpected relationships, build cost Optional
manifest.json, cost.json, cache/ Service files (incremental rebuild, accounting) No — internal

To host it online it is enough to publish graph.html (a self-contained page) and, optionally, graph.json next to it — so that those interested can download the graph data.


4. How the graph is kept up to date

The graph is built from the code without calling paid services during updates — an update runs over the syntactic parse (AST). After changes to the code, the graph is rebuilt with the command:

graphify update .

A full rebuild (re-parsing all files) and export of the interactive HTML:

graphify .            # build/update the graph
graphify export html  # rebuild graph.html

Queries against an already-built graph (without a rebuild) — for search and tracing relationships:

graphify query "How does kernel data reach the viewer?"   # overview answer over the graph
graphify path "PlanarRT_H" "FieldView"                    # shortest path between nodes
graphify explain "Reading S-matrices"                      # explanation of a single node/concept

5. Status and purpose

The knowledge graph is an additional, reference documentation layer. It is not part of the compiled programs and does not affect the computations; it is a tool for navigation and reuse. It is intended for open publication together with the rest of the architecture documentation, so that external developers and researchers can study the semantics of Tamic and build on it in their own projects.