From 04f8b646c1c8a2435931bea9d1acffdde138f81e Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sat, 7 Nov 2026 08:06:01 +0300 Subject: publish --- .dir-locals.el | 4 + .envrc | 18 ++ .gitignore | 5 + README.org | 144 +++++++++ UNLICENSE | 24 ++ build.sh | 8 + channels-lock.scm | 21 ++ doc/gost/gost-7-32-bibliography.sty | 57 ++++ doc/gost/gost-7-32-captions.sty | 23 ++ doc/gost/gost-7-32-counters.sty | 37 +++ doc/gost/gost-7-32-headings.sty | 98 ++++++ doc/gost/gost-7-32-lists.sty | 15 + doc/gost/gost-7-32-tables.sty | 29 ++ doc/gost/gost-7-32-toc.sty | 34 +++ doc/gost/gost-7-32.cls | 62 ++++ doc/ox-init.el | 32 ++ doc/report.org | 585 ++++++++++++++++++++++++++++++++++++ doc/scratch.txt | 20 ++ doc/setup.org | 42 +++ doc/spbstu-report.cls | 73 +++++ manifest.scm | 53 ++++ src/dynamic-array.h | 56 ++++ src/expert-system.c | 21 ++ src/inference-engine.c | 244 +++++++++++++++ src/inference-engine.h | 10 + src/knowledge-base.c | 64 ++++ src/knowledge-base.h | 171 +++++++++++ src/utils.h | 14 + 28 files changed, 1964 insertions(+) create mode 100644 .dir-locals.el create mode 100644 .envrc create mode 100644 .gitignore create mode 100644 README.org create mode 100644 UNLICENSE create mode 100755 build.sh create mode 100644 channels-lock.scm create mode 100644 doc/gost/gost-7-32-bibliography.sty create mode 100644 doc/gost/gost-7-32-captions.sty create mode 100644 doc/gost/gost-7-32-counters.sty create mode 100644 doc/gost/gost-7-32-headings.sty create mode 100644 doc/gost/gost-7-32-lists.sty create mode 100644 doc/gost/gost-7-32-tables.sty create mode 100644 doc/gost/gost-7-32-toc.sty create mode 100644 doc/gost/gost-7-32.cls create mode 100644 doc/ox-init.el create mode 100644 doc/report.org create mode 100644 doc/scratch.txt create mode 100644 doc/setup.org create mode 100644 doc/spbstu-report.cls create mode 100644 manifest.scm create mode 100644 src/dynamic-array.h create mode 100644 src/expert-system.c create mode 100644 src/inference-engine.c create mode 100644 src/inference-engine.h create mode 100644 src/knowledge-base.c create mode 100644 src/knowledge-base.h create mode 100644 src/utils.h diff --git a/.dir-locals.el b/.dir-locals.el new file mode 100644 index 0000000..986612d --- /dev/null +++ b/.dir-locals.el @@ -0,0 +1,4 @@ +;;; Directory Local Variables -*- no-byte-compile: t -*- +;;; For more information see (info "(emacs) Directory Variables") + +((t . ((compile-command . "bear -- ./build.sh")))) diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..5e9e6bf --- /dev/null +++ b/.envrc @@ -0,0 +1,18 @@ +CHANNELS=./channels-lock.scm +MANIFEST=./manifest.scm +LOAD_PATH=./lib +ROOT=./.guix-shell + +TIME_MACHINE_FLAGS+=" --channels=$CHANNELS" +SHELL_FLAGS+=" --manifest=$MANIFEST" +SHELL_FLAGS+=" --search-paths" +SHELL_FLAGS+=" --root=$ROOT" +SHELL_FLAGS+=" --load-path=$LOAD_PATH" + +use_guix_shell() { + test -d "$ROOT" && unlink "$ROOT" + eval "$(guix time-machine $TIME_MACHINE_FLAGS -- shell $SHELL_FLAGS "$@")" +} + +use guix_shell +export TEXINPUTS=${TEXINPUTS}:./:./gost/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..714ed7b --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.pdf +*.html +*.png +*.dot +/expert-system diff --git a/README.org b/README.org new file mode 100644 index 0000000..bc98270 --- /dev/null +++ b/README.org @@ -0,0 +1,144 @@ +#+title: Implementation of an expert system +#+subtitle: for GNU/Linux distribution recommendation + +* Task[fn:1] +Independently select a subject area (have it approved by the +professor), build a production model of an expert system (for example, +for fault diagnosis) and have it approved by the professor. After +that, implement the expert system using CLIPS[fn:2]. The minimum number +of tree depth is 4 (excluding the root), and there must be at least 30 +nodes. + +* Documentation +The exported report can be found at [[https://git.michalec.dev/uni/term-04/graph-theory/coursework/report.pdf][this link]]. + +* Showcase +#+caption: Decision tree +#+attr_html: :width 100% +[[https://git.michalec.dev/uni/term-04/graph-theory/coursework/decision-tree.png][https://git.michalec.dev/uni/term-04/graph-theory/coursework/decision-tree.png]] + +*Header of the knowledge base:* +#+begin_example +QUESTIONS: + 1 2 3 4 5 6 7 8 9 A B +1100000000000000000000: Вы опытный пользователь? +0011000000000000000000: Вы нуждаетесь в максимальной конфиденциальности? +0000110000000000000000: Вы хотите установить систему на переносной накопитель? +0000001100000000000000: Вы хотите управлять сборкой пакетов? +0000000011000000000000: Вы собираетесь использовать данную систему для взлома? +0000000000110000000000: Вам нужна поддержка нескольких языков? +0000000000001100000000: Вы хотите настраивать систему декларативно? +0000000000000011000000: Вас интересуют фиксированные или вращающиеся выпуски...? +0000000000000000110000: Вам важно чтобы дистрибутив весил мало? +0000000000000000001100: Вы хотите описывать настройки на схеме GNU Guile? +0000000000000000000011: Вы собираетесь играть в компьютерные игры? + +DECISIONS: + 1 2 3 4 5 6 7 8 9 A B +0101010000010000000000: Tails +0101010000100000000000: Whonix +0101100000000000000000: Qubes OS +0110000100000100000100: GNU Guix +0110000100000100001000: Nix OS +0110000100001000000000: Gentoo +0110001000000001010000: Debian +0110001000000001100000: Rocky Linux +0110001000000010010000: Void Linux +0110001000000010100000: Arch Linux +1000010001000000000000: Kali Linux +1000010010000000000000: Puppy Linux +1000100000000001100001: Pop! OS +1000100000000001100010: Fedora +1000100000000010000000: Majaro + +decision-tree.dot:0:0: Decision tree is ready for viewing. +#+end_example + +*Example of a Tails recommendation:* +#+begin_example +Вы опытный пользователь? + [1] Опытный + [2] Неопытный +> +> 3 +> 0 +> -1234 +> asdf +> +> 1 +Вы нуждаетесь в максимальной конфиденциальности? + [1] Нуждаюсь + [2] Не нуждаюсь +> 1 +Вы хотите установить систему на переносной накопитель? + [1] Хочу + [2] Не хочу +> 1 +Вам нужна поддержка нескольких языков? + [1] Нужна + [2] Не нужна +> 1 +Рекомендация: Tails +#+end_example + +*Example of a GNU Guix recommendation:* +#+begin_example +Вы опытный пользователь? + [1] Опытный + [2] Неопытный +> 1 +Вы нуждаетесь в максимальной конфиденциальности? + [1] Нуждаюсь + [2] Не нуждаюсь +> 2 +Вы хотите управлять сборкой пакетов? + [1] Хочу + [2] Не хочу +> 1 +Вы хотите настраивать систему декларативно? + [1] Хочу + [2] Не хочу +> 1 +Вы хотите описывать настройки на схеме GNU Guile? + [1] Хочу + [2] Не хочу +> 1 +Рекомендация: GNU Guix +#+end_src +#+end_example + +*Example of a Kali Linux recommendation:* +#+begin_example +Вы опытный пользователь? + [1] Опытный + [2] Неопытный +> 2 +Вы хотите установить систему на переносной накопитель? + [1] Хочу + [2] Не хочу +> 1 +Вы собираетесь использовать данную систему для взлома? + [1] Собираюсь + [2] Не собираюсь +> 1 +Рекомендация: Kali Linux +#+end_src +#+end_example + +* Unlicense +#+include: UNLICENSE verse + +* Footnotes +[fn:1] Original text: +#+HTML: +#+begin_quote +Самостоятельно выбрать предметную область (согласовать ее с +преподавателем), построить продукционную модель экспертной системы +(например, поиска неисправности) и согласовать ее с преподавателем. +После этого реализовать экспертную систему средствами CLIPS. +Минимальное количество ярусов дерева - 4 (не считая корня), не менее - +30 узлов. +#+end_quote +#+HTML: + +[fn:2] Hell no, I'm doing it in C. diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..3d26241 --- /dev/null +++ b/build.sh @@ -0,0 +1,8 @@ +#!/bin/sh + +set -xe + +gcc -std=gnu99 -ggdb3 -o expert-system \ + src/expert-system.c \ + src/knowledge-base.c \ + src/inference-engine.c diff --git a/channels-lock.scm b/channels-lock.scm new file mode 100644 index 0000000..1da4533 --- /dev/null +++ b/channels-lock.scm @@ -0,0 +1,21 @@ +(use-modules (guix channels)) + +(list + (channel + (name 'guix) + (branch "master") + (url "https://git.savannah.gnu.org/git/guix.git") + (commit "b6dec0108f99d75066bad15aaa124b84bb0261f3") + (introduction (make-channel-introduction + "d264237d55ca5e2c756cc7a44374a7dbca850505" + (openpgp-fingerprint + "BBB0 2DDF 2CEA F6A8 0D1D E643 A2A0 6DF2 A33A 54FA")))) + (channel + (name 'nonguix) + (url "https://gitlab.com/nonguix/nonguix") + (commit "25bcda2b9107b948a1c858e41aba1b7f95b76228") + (introduction + (make-channel-introduction + "897c1a470da759236cc11798f4e0a5f7d4d59fbc" + (openpgp-fingerprint + "2A39 3FFF 68F4 EF7A 3D29 12AF 6F51 20A0 22FB B2D5"))))) diff --git a/doc/gost/gost-7-32-bibliography.sty b/doc/gost/gost-7-32-bibliography.sty new file mode 100644 index 0000000..dca60fa --- /dev/null +++ b/doc/gost/gost-7-32-bibliography.sty @@ -0,0 +1,57 @@ +\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017] + +\def\UrlBreaks{\do\/\do-} +\RequirePackage{url} + +\newdimen\bibindent +\renewenvironment{thebibliography}[1]{ + \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy\clubpenalty4000\widowpenalty4000% + \sfcode`\.\@m +}{ + \setcounter{totalbib}{\c@enumiv}% + \def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist +} +\renewcommand\@biblabel{}% +\setlength\bibindent{1.5em} + +% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И. +%\makeatletter +\renewcommand*{\@biblabel}[1]{\hfill#1.} + + +% +% Remove References header completely +% Stolen from original article.cls +% +\makeatletter +\renewenvironment{thebibliography}[1]{% +% \usection{\refname}% +% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy + \clubpenalty4000 + \@clubpenalty \clubpenalty + \widowpenalty4000% + \sfcode`\.\@m} + {\def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist} +\makeatother diff --git a/doc/gost/gost-7-32-captions.sty b/doc/gost/gost-7-32-captions.sty new file mode 100644 index 0000000..1dff33f --- /dev/null +++ b/doc/gost/gost-7-32-captions.sty @@ -0,0 +1,23 @@ +\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{caption} +\RequirePackage{subcaption} + +% +% Table caption aligned to the left with dash as a separator +% +\captionsetup[table]{labelsep=endash, skip=0pt, singlelinecheck=off} + +% +% Dash as separator in figure caption and centering +% +\captionsetup[figure]{labelsep=endash, justification=centering} + +% +% Listing caption +% +\captionsetup[listing]{labelsep=endash, justification=centering} + +\addto\captionsrussian{\renewcommand{\figurename}{Рисунок}} +\addto\captionsrussian{\renewcommand{\mintedname}{Листинг}} +\addto\captionsrussian{\captionsetup[listing]{name=Листинг}} diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty new file mode 100644 index 0000000..d694c93 --- /dev/null +++ b/doc/gost/gost-7-32-counters.sty @@ -0,0 +1,37 @@ +\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017] + +% +% Values for capital russian letters counter +% +\makeatletter +\newcommand\AlphRus[1]{% + \expandafter \@AlphRus \csname c@#1\endcsname +} + +\newcommand\@AlphRus[1]{% + \ifcase #1% + \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or + Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or + Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я% + \else \@ctrerr +\fi +} +\makeatother + +% +% Values for lowercase russian letters counter +% +\makeatletter +\newcommand\alphRus[1]{% + \expandafter \@alphRus \csname c@#1\endcsname +} + +\newcommand\@alphRus[1]{% + \ifcase #1% + \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or + л\or м\or н\or п\or р\or с\or т\or у\or ф\or + х\or ц\or ш\or щ\or э\or ю\or я% + \else \@ctrerr +\fi +} +\makeatother diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty new file mode 100644 index 0000000..d0bb40e --- /dev/null +++ b/doc/gost/gost-7-32-headings.sty @@ -0,0 +1,98 @@ +\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{titlesec} +\RequirePackage{titling} +\RequirePackage{setspace} + +\RequirePackage{gost-7-32-counters} + +% +% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection +% +\titleformat{\section}[block]{\newpage\cleardoublepage\large\setstretch{1}\bfseries}{\thesection}{0.5em}{} +\titlespacing{\section}{0cm}{0cm}{0.5cm} + +\titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{} +\titlespacing{\subsection}{0cm}{0.5cm}{0.5cm} + +\titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent] +\titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm} + +% +% Make special headings, that have their own formatting rules: +% - centered +% - all-caps +% - bold +% +% Only three of them must appear in TOC: introduction, conclusion and references +% +\newcommand{\introduction}{ + \addcontentsline{toc}{section}{ВВЕДЕНИЕ} + \begin{center} + \bfseries\large + ВВЕДЕНИЕ + \end{center} +} + +\newcommand{\conclusion}{ + \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ} + \begin{center} + \bfseries\large + ЗАКЛЮЧЕНИЕ + \end{center} +} + +\newcommand{\references}{ + \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ} + \begin{center} + \bfseries\large + СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ + \end{center} +} + +\newcommand{\essay}{ + \begin{center} + \bfseries\large + РЕФЕРАТ + \end{center} +} + +\newcommand{\definitions}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ + \end{center} +} + +\newcommand{\abbreviations}{ + \begin{center} + \bfseries\large + ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +\newcommand{\defsabbrs}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +% +% Appendices headings. Appendices have autoincrementing number, +% that is represented with russian letter. +% This heading must appear in TOC +% +\newcounter{appendixcnt} +\setcounter{appendixcnt}{1} + +\renewcommand{\appendix}[1]{ + \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1} + \begin{center} + \bfseries\large + ПРИЛОЖЕНИЕ \AlphRus{appendixcnt} + + #1 + \end{center} + \stepcounter{appendixcnt} +} diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty new file mode 100644 index 0000000..b68d55f --- /dev/null +++ b/doc/gost/gost-7-32-lists.sty @@ -0,0 +1,15 @@ +\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{enumitem} +\RequirePackage{gost-7-32-counters} + +\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1} + +\setlist{nosep} +\setlist[itemize, 1]{label=\textendash} +\setlist[itemize, 2]{label=\bullet} + +\setlist[enumerate, 2]{label=\alphRus*)} + +\setlist[1]{wide=\parindent} +\setlist[2]{wide=2\parindent, leftmargin=\parindent} diff --git a/doc/gost/gost-7-32-tables.sty b/doc/gost/gost-7-32-tables.sty new file mode 100644 index 0000000..750ab75 --- /dev/null +++ b/doc/gost/gost-7-32-tables.sty @@ -0,0 +1,29 @@ +\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{tabularx} + +% +% Center-aligned column with automatic width +% +\newcolumntype{Y}{>{\centering\arraybackslash}X} + +% +% Right-aligned column with automatic width +% +\newcolumntype{Z}{>{\raggedleft\arraybackslash}X} + +% +% Table with designations +% +\newenvironment{designations}{ + \noindent + \tabularx{\textwidth}{@{} + >{\raggedright \arraybackslash \hsize=0.25\hsize}X + >{\centering \arraybackslash \hsize=0.05\hsize}X + >{\arraybackslash \hsize=0.70\hsize}X + } +}{ + \endtabularx +} + +\newcommand{\designation}[2]{#1 &---& #2. \\} diff --git a/doc/gost/gost-7-32-toc.sty b/doc/gost/gost-7-32-toc.sty new file mode 100644 index 0000000..c3b835a --- /dev/null +++ b/doc/gost/gost-7-32-toc.sty @@ -0,0 +1,34 @@ +\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017] + +%% \RequirePackage{tocloft} +\RequirePackage[ + bookmarks=true, + colorlinks=true, + unicode=true, + urlcolor=black, + linkcolor=black, + anchorcolor=black, + citecolor=black, + menucolor=black, + filecolor=black +]{hyperref} + +% +% Set custom font styles +% +%% \renewcommand{\cftsecfont}{\normalfont} +%% \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} +%% \renewcommand{\cftsecpagefont}{\normalsize} +%% \renewcommand{\cfttoctitlefont}{\hfill\large\bfseries} +%% \renewcommand{\cftaftertoctitle}{\hfill\hfill} +%% \renewcommand{\cfttoctitlefont}{\hfill\hfill\normalfont\large\bfseries} +\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{} +\titlespacing{\tableofcontents}{0cm}{0cm}{1cm} + +% +% Set indents and line spacing +% +%% \setlength{\cftbeforesecskip}{0cm} +%% \setlength{\cftbeforesubsecskip}{0cm} +%% \setlength{\cftbeforesubsubsecskip}{0cm} +%% \setlength{\cftbeforeparaskip}{0cm} diff --git a/doc/gost/gost-7-32.cls b/doc/gost/gost-7-32.cls new file mode 100644 index 0000000..c13b00e --- /dev/null +++ b/doc/gost/gost-7-32.cls @@ -0,0 +1,62 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017] + +% +% Supported font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +% +% Set A4 paper format +% +\LoadClass[a4paper]{extarticle} + +% +% Use 1.5 line spacing +% +\RequirePackage{setspace} +\spacing{1.5} + +% +% First paragraph indentation +% +\RequirePackage{indentfirst} +\setlength{\parindent}{12.5mm} + +% +% Page margin +% +\RequirePackage[ + left=2.5cm, + right=2cm, + top=2cm, + bottom=2cm, + footskip=1cm, +]{geometry} + +% +% Use TMR-like font +% +\RequirePackage{fontspec} +\RequirePackage{xunicode} +\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +\setmainfont{Times New Roman} + +% +% Use russian language +% +\RequirePackage[main=russian, english]{babel} +\babelhyphenation[russian]{} + +% +% gost-7-32 packages +% +\RequirePackage{gost-7-32-headings} +\RequirePackage{gost-7-32-toc} +\RequirePackage{gost-7-32-lists} +\RequirePackage{gost-7-32-bibliography} +\RequirePackage{gost-7-32-captions} +\RequirePackage{gost-7-32-tables} diff --git a/doc/ox-init.el b/doc/ox-init.el new file mode 100644 index 0000000..913d021 --- /dev/null +++ b/doc/ox-init.el @@ -0,0 +1,32 @@ +;;; ox-init --- Initialization script for async org exprort session +;;; Commentary: +;;; Code: +(org-babel-do-load-languages + 'org-babel-load-languages + '((latex . t) + (C . t))) + +(require 'ox-extra) +(ox-extras-activate '(ignore-headlines)) + +(require 'oc-bibtex) + +(setq org-latex-src-block-backend 'minted) + +(setq org-latex-bib-compiler "biber") + +(setq org-latex-remove-logfiles nil) + +(setq org-latex-caption-above '(table src-block special-block)) + +(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f" + "%bib %b" + "%latex -shell-escape -interaction nonstopmode -output-directory %o %f")) +(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}" + ("\\section{%s}" . "\\usection{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}") + ("\\paragraph{%s}" . "\\paragraph*{%s}") + ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) + +;;; ox-init.el ends here diff --git a/doc/report.org b/doc/report.org new file mode 100644 index 0000000..ba38fe2 --- /dev/null +++ b/doc/report.org @@ -0,0 +1,585 @@ +#+TITLE: Реализация экспертной системы по рекомендации дистрибутива GNU/Linux +#+AUTHOR: Михалец Мартин +#+LATEX_HEADER: \reportof{О ВЫПОЛНЕНИИ КУРСОВОЙ РАБОТЫ} +#+LATEX_HEADER: \subject{по дисциплине «Теория графов»} +#+LATEX_HEADER: \reviewertitle{}\reviewer{Востров Алексей Владимирович} +#+DATE: 2024 + +#+SETUPFILE: setup.org +#+LATEX: \sloppy +#+LATEX: \renewcommand{\arraystretch}{0.65} + +* Введение +:PROPERTIES: +:UNNUMBERED: t +:END: +В данном отчёте представлено описание курсовой работы по дисциплине +«Теория графов». Работа включает в себя реализацию экспертной системы +по рекомендации дистрибутива GNU/Linux. + +Работа была выполнена в виде консольного приложения разработанного на +языке программирования Си (=-std=gnu99=) с использованием только +стандартной библиотеки =libc=. + +* Описание предметной области +В качестве предметной области были выбраны рекомендации дистрибутивов +GNU/Linux на основе требовании к их характеристикам. Поскольку +GNU/Linux дистрибутивов относительно много (сотни), была сделана +субъективная выборка 15 интереснейших из них дистрибутивов с их +характеристиками приведенными в таблицы [[distributions]]. + +Рекомендации: +- Tails +- Whonix +- Qubes OS +- GNU Guix +- Nix OS +- Gentoo +- Debian +- Rocky Linux +- Void Linux +- Arch Linux +- Kali Linux +- Puppy Linux +- Pop! OS +- Fedora +- Majaro + +Критерии/вопросы: +- опытный :: Вы опытный пользователь? +- конфиденциальность :: Вы нуждаетесь в максимальной конфиденциальности? +- переносной накопитель :: Вы хотите установить систему на переносной накопитель? +- управление сборкой пакетов :: Вы хотите управлять сборкой пакетов? +- взлом :: Вы собираетесь использовать данную систему для взлома? +- несколько языков :: Вам нужна поддержка нескольких языков? +- декларативная настройка :: Вы хотите настраивать систему декларативно? +- фиксированные выпуски :: Вас интересуют фиксированные или вращающиеся выпуски изменении пакетов? +- малый вес :: Вам важно чтобы дистрибутив весил мало? +- GNU Guile :: Вы хотите описывать настройки на схеме GNU Guile? +- игры :: Вы собираетесь играть в компьютерные игры? + +* Математическое описание +** Экспертная система +/Экспертная система/ --- это программное средство, воплощающее в себе +опыт эксперта, основывавшегося на его знаниях в определённой отрасли. +Используется для высокоэффективного решения задач в интересующей +пользователя предметной области. + +/Продукционная модель/ --- это модель, основанная на представлении +знания в виде правил «Если (условие), то (действие)». Под «условием» +понимается некоторое предложение-образец, по которому осуществляется +поиск в базе знаний, а под «действием» -- действия, выполняемые при +успешном исходе поиска. + +Режимы экспертной системы: +1. /Режим приобретения знаний/ --- работу с экспертно системой + осуществляет эксперт при посредничестве инженера по знаниям. В + этом режиме эксперт, используя компонент приобретения знаний, + наполняет систему данными, которые, позволяют системе решать задачи + из данной предметно области; +2. /Режим решения задачи/ --- общение с экспертными системами + осуществляет пользователь, не обязательно эксперт, которого + интересует концевой итог работы и иногда способ его получения. + +Структуру экспертной системы можно изобразить с помощью схемы, +представленной на рисунке [[expert-system-structure]]. + +#+name: expert-system-structure +#+caption: Структура экспертной системы +#+attr_latex: :float nil :width .8\linewidth +[[./expert-system-structure.png]] + +** База знаний +/База знаний/ --- база данных, содержащая правила вывода и информацию о +человеческом опыте и знаниях в некоторой предметной области. + +В таблице [[distributions]] представлена база знаний. + +#+name: distributions +#+caption: База знаний +#+attr_latex: :float nil :align |l|c|c|c|c|c| +|----------------------------+------------+-------------+-------------+------------+------------| +| | Tails | Whonix | Qubes OS | GNU Guix | Nix OS | +|----------------------------+------------+-------------+-------------+------------+------------| +| опытный | 1 | 1 | 1 | 1 | 1 | +| конфиденциальность | 1 | 1 | 1 | 0 | 0 | +| переносной накопитель | 1 | 1 | 0 | 1 | 1 | +| управление сборкой пакетов | ? | ? | ? | 1 | 1 | +| взлом | ? | ? | ? | ? | ? | +| несколько языков | 1 | 0 | ? | ? | ? | +| декларативная настройка | ? | ? | ? | 1 | 1 | +| фиксированные выпуски | ? | ? | ? | ? | ? | +| малый вес | ? | ? | ? | ? | ? | +| GNU Guile | ? | ? | ? | 1 | 0 | +| игры | ? | ? | ? | ? | ? | +|----------------------------+------------+-------------+-------------+------------+------------| +|----------------------------+------------+-------------+-------------+------------+------------| +| | Gentoo | Debian | Rocky Linux | Void Linux | Arch Linux | +|----------------------------+------------+-------------+-------------+------------+------------| +| опытный | 1 | 1 | 1 | 1 | 1 | +| конфиденциальность | 0 | 0 | 0 | 0 | 0 | +| переносной накопитель | ? | ? | ? | ? | ? | +| управление сборкой пакетов | 1 | 0 | 0 | 0 | 0 | +| взлом | ? | ? | ? | ? | ? | +| несколько языков | ? | ? | ? | ? | ? | +| декларативная настройка | 0 | ? | ? | ? | ? | +| фиксированные выпуски | ? | 1 | 1 | 0 | 0 | +| малый вес | ? | 1 | 0 | 1 | 0 | +| GNU Guile | ? | ? | ? | ? | ? | +| игры | ? | ? | ? | ? | ? | +|----------------------------+------------+-------------+-------------+------------+------------| +|----------------------------+------------+-------------+-------------+------------+------------| +| | Kali Linux | Puppy Linux | Pop! OS | Fedora | Majaro | +|----------------------------+------------+-------------+-------------+------------+------------| +| опытный | 0 | 0 | 0 | 0 | 0 | +| конфиденциальность | ? | ? | 0 | 0 | 0 | +| переносной накопитель | 1 | 1 | ? | ? | ? | +| управление сборкой пакетов | ? | ? | ? | ? | ? | +| взлом | 1 | 0 | ? | ? | ? | +| несколько языков | ? | ? | ? | ? | ? | +| декларативная настройка | ? | ? | 1 | 1 | 0 | +| фиксированные выпуски | ? | ? | 0 | 1 | ? | +| малый вес | ? | ? | ? | ? | ? | +| GNU Guile | ? | ? | ? | ? | ? | +| игры | ? | ? | 1 | 0 | ? | +|----------------------------+------------+-------------+-------------+------------+------------| + +** Машина вывода +/Машина вывода/ --- программа, которая выполняет логический вывод из +предварительно построенной базы фактов и правил в соответствии с +законами формальной логики. + +** Дерево решений +Экспертную систему можно представить как дерево решений. +Алгебраическая структура: +#+begin_export latex +\begin{displaymath} + G = , +\end{displaymath} +#+end_export +где $V$ --- множество узлов (вопросы), $E$ --- множество ребер (связь +вопрос-рекомендация), $B$ --- атрибут ребер (ответ ребра). Каждая +вершина графа помечена уточняющим вопросом экспертной системы к +пользователю или ее ответом на задачу. Если вершина помечена вопросом +ЭС, то из нее выходят две дуги. Дуги помечены ответом пользователя. +Вершины, соответствующие ответам ЭС --- листья. Работа экспертной +системы сводится к пути по графу. Такой путь состоит из +последовательности однотипных шагов, на каждом из которых пользователь +должен решить, по какой дуге он пойдет из очередной вершины. На +рисунке [[decision-tree]] представлено бинарное дерево решений. + +Характеристика дерева: +- 15 узлов (вопросов/правил) +- 16 листьев (рекомендации/фактов) +- итого 31 вершин +- 5 ярусов не считая корня + +@@latex:\KOMAoptions{paper=A3}@@ +@@latex:\recalctypearea@@ +@@latex:\begin{landscape}@@ +@@latex:\thispagestyle{empty}@@ +#+name: decision-tree +#+caption: Бинарное дерево решений +#+attr_latex: :float nil :width \linewidth +[[./decision-tree.pdf]] +@@latex:\vfill\raisebox{-10pt}{\makebox[\linewidth]{\thepage}}@@ +@@latex:\end{landscape}@@ +@@latex:\KOMAoptions{paper=A4}@@ +@@latex:\recalctypearea@@ + +* Реализация +** База знании +База знании заполняется редактированием определении макросов ~QUESTIONS~ +и ~DECISIONS~, примеры которых приведены в листингах [[questions]] и +[[decisions]], соответственно. Использование данных макросов нам +позволяет структурированный ввод знаний, который бы иначе был +разброшен по нескольким определениям структур, перечислении и +массивов. В листинге [[macro-expansions]] приведено использование данных +макросов, для заполнения 9 символов. + +#+name: questions +#+caption: Пример определения вопросов +#+begin_src c +#define QUESTIONS \ + QUESTION(advanced, "Опытный пользователь?", "Опытный", "Неопытный") \ + QUESTION(confidentiality, "Конфиденциальность?", "Да", "Нет" ) \ + QUESTION(usb, "Переносной накопитель?", "Да", "Нет" ) +#+end_src + +#+name: decisions +#+caption: Пример определения решении +#+begin_src c +#define DECISIONS \ + DECISION(WHONIX, "Whonix", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_YES, \ + .usb = ANSWER_YES, \ + .multilang = ANSWER_NO, \ + ) \ + DECISION(QUBES_OS, "Qubes OS", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_YES, \ + .usb = ANSWER_NO, \ + ) \ + DECISION(GNU_GUIX, "GNU Guix", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_NO, \ + .control = ANSWER_YES, \ + .declarative = ANSWER_YES, \ + .scheme = ANSWER_YES, \ + ) +#+end_src + +#+name: macro-expansions +#+caption: Некоторые применения макросов +#+begin_src c +#define QUESTION(symbol, label, yes, no) QUESTION_##symbol, +enum question { QUESTIONS QUESTION_COUNT }; +#undef QUESTION + +#define QUESTION(symbol, label, yes, no) \ + PREDICATE_Y_##symbol = 1 << __COUNTER__, \ + PREDICATE_N_##symbol = 1 << __COUNTER__, +enum predicate { QUESTIONS }; +#undef QUESTION + +#define QUESTION(symbol, label, yes, no) \ + enum answer symbol : ANSWER_COUNT; +struct decision_predicates { QUESTIONS; }; +#undef QUESTION + +#define QUESTION(symbol, label, yes, no) [QUESTION_##symbol] = label, +char *question_labels[QUESTION_COUNT] = { QUESTIONS }; +#undef QUESTION + +#define QUESTION(symbol, label, yes, no) [QUESTION_##symbol] = { yes, no }, +struct question_branch_labels question_branch_labels[QUESTION_COUNT] = { QUESTIONS }; +#undef QUESTION + +#define DECISION(symbol, label, ...) [DECISION_##symbol] = { __VA_ARGS__ }, +struct decision_predicates decision_predicates[DECISION_COUNT] = { DECISIONS }; +#undef DECISION + +#define QUESTION(symbol, label, yes, no) \ + if (QUESTION_##symbol == question) return decision_predicates[decision].symbol; +enum answer +get_decision_predicate (enum decision decision, enum question question) +{ QUESTIONS return ANSWER_MALFORMED; } +#undef QUESTION +#+end_src + +** Машина вывода +Машина вывода строит дерево решении. Процедура, отвечающая за +построение дерева решении (приведена в листинге [[build_decision_tree]]), +сначала анализируют базу знании, вычисляет порядок, в котором будут +задаваться вопросы по количеству известных ответов на них, потом +запускает рекурсивную функцию построения уже самого дерева. + +Рекурсивная функция построения дерева решении (приведена в листинге +[[build_decision_tree_impl]]) сначала находит вопрос, по которому +достаточно знании, дальше она по нему разделяет оставшиеся +рекомендации и по обоим группам рекурсивно вызывается до момента, +когда либо остается одна рекомендация, либо хватает знании, в случае +чего выдается ошибка. + + +#+name: build_decision_tree +#+caption: Процедура построения дерева решении +#+attr_latex: :float nil +#+begin_src c +void +build_decision_tree (void) +{ + // compute answers_known[question] and question_order[order] + for (int question = 0; question < QUESTION_COUNT; ++question) { + for (int decision = 0; decision < DECISION_COUNT; ++decision) + answers_known[question] += is_answer_known (decision, question); + + int order = 0; + while (order < question && + answers_known[question] <= + answers_known[question_queue[order]]) { + order += 1; + } + + memmove (&question_queue[order + 1], + &question_queue[order + 0], + (question - order)*sizeof (*question_queue)); + question_queue[order] = question; + } + + // initialize context and run recursive function on it + enum decision decisions[DECISION_COUNT]; + for (int decision = 0; decision < DECISION_COUNT; ++decision) + decisions[decision] = DECISION_COUNT - 1 - decision; + DYNAMIC_ARRAY_ENSURE_CAPACITY (decision_tree, MAX_DECISION_TREE_NODE_COUNT); + DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0}); + build_decision_tree_impl (decisions, decisions + DECISION_COUNT, 0, + &decision_tree.items[0]); + DYNAMIC_ARRAY_SHRINK (decision_tree); +} +#+end_src + +#+name: build_decision_tree_impl +#+caption: Рекурсивная функция построения дерева решении +#+attr_latex: :float nil +#+begin_src c +static void +build_decision_tree_impl (enum decision *begin, + enum decision *end, int order, + DECISION_TREE_NODE node) +{ + if (begin + 1 == end) { + node->decision = *begin; // INSERT DECISION + return; + } + + enum question question; + for (; order < QUESTION_COUNT; ++order) { + question = question_queue[order]; + enum decision *decision; + for (decision = begin; decision < end; ++decision) { + if (!is_answer_known (*decision, question)) break; + } if (decision == end) break; + } ASSERT (order != QUESTION_COUNT && "NOT ENOUGH KNOWLEDGE"); + node->question = question; // INSERT QUESTION + + enum decision *pivot = begin; + for (enum decision *decision = begin; decision < end; ++decision) { + if (get_decision_predicate (*decision, question) == ANSWER_NO) { + pivot = decision; + break; + } + } + + for (enum decision *head = pivot + 1; head < end; ++head) { + if (get_decision_predicate (*head, question) == ANSWER_YES) { + enum decision tmp = *pivot; + *pivot++ = *head; + *head = tmp; + } + } + + DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0}); + node->branch_yes = decision_tree.count - 1; // BRANCH YES + build_decision_tree_impl (begin, pivot, order + 1, + &decision_tree.items[decision_tree.count - 1]); + DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0}); + node->branch_no = decision_tree.count - 1; // BRANCH NO + build_decision_tree_impl (pivot, end, order + 1, + &decision_tree.items[decision_tree.count - 1]); +} +#+end_src + +** Текстовый человеко-машинный интерфейс +Текстовый человеко-машинный интерфейс последовательно запрашивает у +пользователя ответ на очередной вопрос до нахождения именно единой +рекомендации, что в данной реализации достигается всегда. Процедура, +проходящая по дереву в зависимости от ответов пользователя приведена в +листинге [[question_user]]. + +#+name: question_user +#+caption: Функция опроса пользователя +#+attr_latex: :float nil +#+begin_src c +void +question_user (void) +{ + char *line = NULL; + size_t line_size = 0; + struct decision_tree_node *node = &decision_tree.items[0]; + while (node->branch_yes && node->branch_no) { + enum question question = node->question; + printf ("%s\n", question_labels[question]); + printf (" [1] %s\n", question_branch_labels[question].answer_yes); + printf (" [2] %s\n", question_branch_labels[question].answer_no); + for (;;) { + printf ("> "); + getline (&line, &line_size, stdin); + enum answer answer = 0; + sscanf (line, "%d", &answer); + if (answer < 1 || answer > 2) continue; + switch (answer) { + case ANSWER_YES: node = &decision_tree.items[node->branch_yes]; break; + case ANSWER_NO: node = &decision_tree.items[node->branch_no ]; break; + default: break; + } break; + } + } free (line); + printf ("Рекомендация: %s\n", decision_labels[node->decision]); +} +#+end_src + +* Результаты работы +В качестве результатов работы приведено 3 сеанса представленных в +листингах [[tails]]-[[kali-linux]], причём каждый из сеансов имеет одинаковый +заголовок содержащий базу знаний (см. листинг [[header]]). + +#+name: header +#+caption: Загаловка базы знаний экспертной системы +#+attr_latex: :float nil +#+begin_src text +QUESTIONS: + 1 2 3 4 5 6 7 8 9 A B +1100000000000000000000: Вы опытный пользователь? +0011000000000000000000: Вы нуждаетесь в максимальной конфиденциальности? +0000110000000000000000: Вы хотите установить систему на переносной накопитель? +0000001100000000000000: Вы хотите управлять сборкой пакетов? +0000000011000000000000: Вы собираетесь использовать данную систему для взлома? +0000000000110000000000: Вам нужна поддержка нескольких языков? +0000000000001100000000: Вы хотите настраивать систему декларативно? +0000000000000011000000: Вас интересуют фиксированные или вращающиеся выпуски...? +0000000000000000110000: Вам важно чтобы дистрибутив весил мало? +0000000000000000001100: Вы хотите описывать настройки на схеме GNU Guile? +0000000000000000000011: Вы собираетесь играть в компьютерные игры? + +DECISIONS: + 1 2 3 4 5 6 7 8 9 A B +0101010000010000000000: Tails +0101010000100000000000: Whonix +0101100000000000000000: Qubes OS +0110000100000100000100: GNU Guix +0110000100000100001000: Nix OS +0110000100001000000000: Gentoo +0110001000000001010000: Debian +0110001000000001100000: Rocky Linux +0110001000000010010000: Void Linux +0110001000000010100000: Arch Linux +1000010001000000000000: Kali Linux +1000010010000000000000: Puppy Linux +1000100000000001100001: Pop! OS +1000100000000001100010: Fedora +1000100000000010000000: Majaro + +decision-tree.dot:0:0: Decision tree is ready for viewing. +#+end_src + +#+name: tails +#+caption: Пример рекомендации Tails +#+attr_latex: :float nil +#+begin_src text +Вы опытный пользователь? + [1] Опытный + [2] Неопытный +> +> 3 +> 0 +> -1234 +> asdf +> +> 1 +Вы нуждаетесь в максимальной конфиденциальности? + [1] Нуждаюсь + [2] Не нуждаюсь +> 1 +Вы хотите установить систему на переносной накопитель? + [1] Хочу + [2] Не хочу +> 1 +Вам нужна поддержка нескольких языков? + [1] Нужна + [2] Не нужна +> 1 +Рекомендация: Tails +#+end_src + +#+name: guix +#+caption: Пример рекомендации GNU Guix +#+attr_latex: :float nil +#+begin_src text +Вы опытный пользователь? + [1] Опытный + [2] Неопытный +> 1 +Вы нуждаетесь в максимальной конфиденциальности? + [1] Нуждаюсь + [2] Не нуждаюсь +> 2 +Вы хотите управлять сборкой пакетов? + [1] Хочу + [2] Не хочу +> 1 +Вы хотите настраивать систему декларативно? + [1] Хочу + [2] Не хочу +> 1 +Вы хотите описывать настройки на схеме GNU Guile? + [1] Хочу + [2] Не хочу +> 1 +Рекомендация: GNU Guix +#+end_src + +#+name: kali-linux +#+caption: Пример рекомендации Kali Linux +#+attr_latex: :float nil +#+begin_src text +Вы опытный пользователь? + [1] Опытный + [2] Неопытный +> 2 +Вы хотите установить систему на переносной накопитель? + [1] Хочу + [2] Не хочу +> 1 +Вы собираетесь использовать данную систему для взлома? + [1] Собираюсь + [2] Не собираюсь +> 1 +Рекомендация: Kali Linux +#+end_src + +* Заключение +:PROPERTIES: +:UNNUMBERED: t +:END: +В результате работы была реализована экспертная система по +рекомендации дистрибутива GNU/Linux. Система была представлена в виде +дерева решений, где узлы --- это вопросы (правила), а листья --- +рекомендации (факты). Дерево содержит всего 5 ярусов не считая корня, +15 узлов и 16 листьев. + +*Достоинства программы:* +- Собрать программу тривиально, поскольку она написана на Си с + использованием стандартной библиотеки исключительно. +- Программа умеет работать и с не полным описанием решении, в ситуации + где либо нет данных знании, либо они не применяются к данному + решению. +- Программа сама генерирует визуализацию дерева решении в =dot= формате. + +*Недостатки программы:* +- Применение текстового человеко-машинного интерфейса имеет свои + недостатки. Для эксплоративного выбора дистрибутива было бы удобнее + визуально строить дерево, с возможностью выбрать и другой ответ на + вопрос ближе у корня дерева. +- Нет поддержки промежуточных сообщении к набору ответов на уже + заданный вопросы. Такие сообщения бы могли помочь понять + пользователю понять на правильном ли он пути, чего удобство бы росло + с количеством ярусов дерева решении. + +*Масштабирование программы:* +- При сомнении пользователя в ответе на вопрос можно было бы + рассмотреть обе ветки, с помощью их добавления в очередь вопросов. +- Вместо поддержки строго 2 ответов на вопрос, можно было бы добавить + поддержку вариабельного количества, что позволило бы задавать более + мощные и интуитивные вопросы. + +* Используемая литература +:PROPERTIES: +:UNNUMBERED: t +:END: +1. Expert system --- Википедия // URL: + [[https://en.wikipedia.org/wiki/Expert_system]] (Дата обращения: + 22.05.2024) +2. Knowledge base --- Википедия // URL: + [[https://en.wikipedia.org/wiki/Knowledge_base]] (Дата обращения: + 22.05.2024) +3. Inference engine --- Википедия // URL: + [[https://en.wikipedia.org/wiki/Inference_engine]] (Дата обращения: + 22.05.2024) + +# Local Variables: +# org-confirm-babel-evaluate: nil +# org-export-async-init-file: "ox-init.el" +# org-export-in-background: t +# End: diff --git a/doc/scratch.txt b/doc/scratch.txt new file mode 100644 index 0000000..98a6c1c --- /dev/null +++ b/doc/scratch.txt @@ -0,0 +1,20 @@ +SORT - DIVIDE - FIND NEXT DECISION POINT / ABORT NOT ENOUGH KNOWLEDGE + +1 2 3 4 8 9 7 5 6 A B +Y Y Y - - - - - Y - - Tails +Y Y Y - - - - - N - - Whonix +Y Y N - - - - - - - - Qubes OS +Y N - Y - - Y - - Y - GNU Guix +Y N - Y N - Y - - N - Nix OS +Y N - Y - - N - - - - Gentoo +Y N - N Y Y - - - - - Debian +Y N - N Y N - - - - - Rocky Linux +Y N - N N Y - - - - - Void Linux +Y N - N N N - - - - - Arch Linux + +N - Y - Y - - Y - - - Kali Linux +N - Y - - N - N - - - Puppy Linux + +N - N - Y N - - - - Y Pop! OS +N - N - Y N - - - - N Fedora +N - N - N - - - - - - Majaro diff --git a/doc/setup.org b/doc/setup.org new file mode 100644 index 0000000..f4b5ab7 --- /dev/null +++ b/doc/setup.org @@ -0,0 +1,42 @@ +#+OPTIONS: ':nil *:t -:t ::t <:t H:3 \n:nil ^:{} arch:headline +#+OPTIONS: author:t broken-links:nil c:nil creator:nil +#+OPTIONS: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t +#+OPTIONS: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t +#+OPTIONS: timestamp:nil title:t toc:t todo:nil |:t +#+SELECT_TAGS: export +#+EXCLUDE_TAGS: noexport +#+CREATOR: Emacs 29.1 (Org mode 9.6.9) +#+BIBLIOGRAPHY: biblio.bib +#+CITE_EXPORT: biblatex +#+LATEX_COMPILER: xelatex +#+LATEX_CLASS: spbstu-report +#+LATEX_CLASS_OPTIONS: [12pt] +#+LATEX_HEADER: \usepackage{enumitem} +#+LATEX_HEADER: \usepackage{array} +#+LATEX_HEADER: \newcolumntype{C}{>{$}c<{$}} % math-mode version of "c" column type +#+LATEX_HEADER: \usepackage{float} +#+LATEX_HEADER: \usepackage{tikz} +#+LATEX_HEADER: \usepackage{pgfplots} +#+LATEX_HEADER: \pgfplotsset{compat=1.18} +#+LATEX_HEADER: \usepackage[paper=A4,DIV=12]{typearea} +#+LATEX_HEADER: \usepackage{pdflscape} +#+LATEX_HEADER: \usepackage{afterpage} +#+LATEX_HEADER: \usepackage{minted} +#+LATEX_HEADER: \usemintedstyle{bw} +#+LATEX_HEADER: \setminted{baselinestretch=1,linenos,breaklines} +#+LATEX_HEADER: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}} +#+LATEX_HEADER: \usepackage{algorithm} +#+LATEX_HEADER: \usepackage{algpseudocode} +#+LATEX_HEADER: \makeatletter +#+LATEX_HEADER: \renewcommand{\ALG@name}{Алгоритм} +#+LATEX_HEADER: \makeatother +#+LATEX_HEADER: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +#+LATEX_HEADER: \setmainfont{Times New Roman} +#+LATEX_HEADER: \setmonofont{Iosevka Term Slab}[Contextuals=AlternateOff] +#+LATEX_HEADER: \newcommand*{\myref}[2]{\hyperref[{#1}]{{#2}~\ref*{#1}}} +#+LATEX_HEADER: \newcommand{\hlabel}{\phantomsection\label} +#+LATEX_HEADER: \newcommand*{\fullref}[1]{\hyperref[{#1}]{\autoref*{#1} \nameref*{#1}}} +#+LATEX_HEADER: \setlength{\abovecaptionskip}{5pt} +#+LATEX_HEADER: \setlength{\belowcaptionskip}{0pt} +#+LATEX_HEADER: \hypersetup{hidelinks} +#+LATEX_HEADER: \newcommand{\overbar}[1]{\mkern 1.5mu\overline{\mkern-1.5mu#1\mkern-1.5mu}\mkern 1.5mu} diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls new file mode 100644 index 0000000..422edf2 --- /dev/null +++ b/doc/spbstu-report.cls @@ -0,0 +1,73 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов] + +% +% Support font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +\LoadClass[a4paper]{gost-7-32} + +\RequirePackage{csquotes} +\RequirePackage{amsmath} +\RequirePackage{adjustbox} +\RequirePackage{setspace} + +\newcommand{\usection}[1]{\section*{#1}\addcontentsline{toc}{section}{#1}} + +\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}} +\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}} +\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}} +\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}} +\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$} +\renewcommand{\maketitle}{ + \begin{titlepage} + \begin{center} + \vspace{2cm} + \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ} + + \normalsize{Федеральное государственное автономное + образовательное учреждение высшего образования + \enquote{Санкт-Петербургский политехнический университет Петра Великого}} + + \vspace{0.5cm} + \normalsize{Институт компьютерных наук и кибербезопасности} + + \normalsize{Высшая школа технологии искусственного интеллекта} + + \normalsize{Направление 02.03.01 Математика и компьютерные науки} + + \vspace{2cm} + \LARGE{ОТЧЁТ} + + \normalsize{\@reportof} + + \large{\@subject} + + \large{\textit{\@title}} + \end{center} + + \vspace{3cm} + \small{ + \begin{tabular}{lrrl} + \!\!\!Студент, & \hspace{2cm} & & \\ + \!\!\!группы 5130201/20002 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\ + \!\!\!Преподаватель, & \hspace{2cm} & \\ + \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\ + &&\hspace{5cm} + \end{tabular} + \begin{flushright} + \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г. + \end{flushright} + } + + \vspace*{\fill} + \begin{center} + \small{Санкт-Петербург, \@date} + \end{center} + \end{titlepage} + \setcounter{page}{2} +} diff --git a/manifest.scm b/manifest.scm new file mode 100644 index 0000000..8943948 --- /dev/null +++ b/manifest.scm @@ -0,0 +1,53 @@ +(use-modules (gnu packages base) + (gnu packages commencement) + (gnu packages tex) + (nongnu packages fonts)) + +(packages->manifest (list + gcc-toolchain + font-microsoft-times-new-roman + texlive-scheme-small + texlive-lh + texlive-cm + texlive-type1cm + texlive-ec + texlive-wrapfig + texlive-adjustbox + texlive-graphics + texlive-hyperref + texlive-latex-fonts + texlive-amsfonts + texlive-cyrillic + texlive-babel-russian + texlive-geometry + texlive-enumitem + texlive-csquotes + texlive-float + texlive-biblatex + texlive-biber + texlive-pgfplots + texlive-trimspaces + texlive-catchfile + texlive-hyphen-complete + texlive-capt-of + texlive-minted + texlive-titlesec + texlive-titling + texlive-scheme-basic + texlive-fontspec + texlive-beamer + texlive-microtype + texlive-siunitx + texlive-textpos + texlive-mathspec + texlive-etoolbox + texlive-extsizes + texlive-cm-super + texlive-amsmath + texlive-transparent + texlive-koma-script + texlive-pdflscape + texlive-ucs + texlive-ulem + texlive-algorithms + texlive-algorithmicx)) diff --git a/src/dynamic-array.h b/src/dynamic-array.h new file mode 100644 index 0000000..212e9f4 --- /dev/null +++ b/src/dynamic-array.h @@ -0,0 +1,56 @@ +#ifndef INCLUDED_DYNAMIC_ARRAY_H +#define INCLUDED_DYNAMIC_ARRAY_H + +#include "utils.h" + +#ifndef DYNAMIC_ARRAY_INIT_CAP +#define DYNAMIC_ARRAY_INIT_CAP 256 +#endif + +#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ + ({ \ + if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ + if ((DYNAMIC_ARRAY).capacity == 0) \ + (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ + while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ + (DYNAMIC_ARRAY).capacity *= 2; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + } \ + }) + +#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ + ({ \ + (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + \ + }) + +#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ + }) + +#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ + memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ + (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ + }) + +#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) + +#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ + typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ + ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) + +#endif diff --git a/src/expert-system.c b/src/expert-system.c new file mode 100644 index 0000000..3462c44 --- /dev/null +++ b/src/expert-system.c @@ -0,0 +1,21 @@ +#include +#include +#include +#include + +#include "knowledge-base.h" +#include "inference-engine.h" + +int +main (void) +{ + // TODO(cmmm): auto-rebuild + print_knowledge_base (); + putchar ('\n'); + build_decision_tree (); + write_decision_tree_in_dot_format (); + putchar ('\n'); + question_user (); + + return EXIT_SUCCESS; +} diff --git a/src/inference-engine.c b/src/inference-engine.c new file mode 100644 index 0000000..db4f33a --- /dev/null +++ b/src/inference-engine.c @@ -0,0 +1,244 @@ +#include "inference-engine.h" +#include +#include "utils.h" +#include "dynamic-array.h" + +typedef struct decision_tree_node { + union { + enum question question; + enum decision decision; + }; + uint32_t branch_yes; + uint32_t branch_no; +} *DECISION_TREE_NODE; + +struct decision_tree { + struct decision_tree_node *items; + uint32_t count; + uint32_t capacity; +}; + +#define MAX_DECISION_TREE_NODE_COUNT ((1 << QUESTION_COUNT) - 1) + +static struct decision_tree decision_tree = {0}; + +static int answers_known [QUESTION_COUNT] = {0}; +static int question_queue [QUESTION_COUNT] = {0}; + +static inline bool +is_answer_known (enum decision decision, enum question question) { + switch (get_decision_predicate (decision, question)) { + case ANSWER_YES: + case ANSWER_NO: + return true; + default: + return false; + } +} + +static void +build_decision_tree_impl (enum decision *begin, + enum decision *end, int order, + DECISION_TREE_NODE node) +{ + if (begin == end) + return; + + if (begin + 1 == end) { + // printf ("INSERT DECISION %X\n", *begin); + node->decision = *begin; + return; + } + + enum question question; + for (; order < QUESTION_COUNT; ++order) { + question = question_queue[order]; + + enum decision *decision; + for (decision = begin; decision < end; ++decision) { + if (!is_answer_known (*decision, question)) + break; + } if (decision == end) break; + } ASSERT (order != QUESTION_COUNT && "NOT ENOUGH KNOWLEDGE"); + + // printf ("INSERT QUESTION %X\n", question); + node->question = question; + + enum decision *pivot = begin; + for (enum decision *decision = begin; decision < end; ++decision) { + if (get_decision_predicate (*decision, question) == ANSWER_NO) { + pivot = decision; + break; + } + } + + for (enum decision *head = pivot + 1; head < end; ++head) { + if (get_decision_predicate (*head, question) == ANSWER_YES) { + enum decision tmp = *pivot; + *pivot++ = *head; + *head = tmp; + } + } + + // for (enum decision *decision = begin; decision < end; ++decision) { + // printf ("%s%X\n", decision == pivot ? "->" : " ", *decision + 1); + // } + + DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0}); + // printf ("BRANCH YES TO %X\n", decision_tree.count - 1); + node->branch_yes = decision_tree.count - 1; + build_decision_tree_impl (begin, pivot, order + 1, + &decision_tree.items[decision_tree.count - 1]); + DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0}); + // printf ("BRANCH NO TO %X\n", decision_tree.count - 1); + node->branch_no = decision_tree.count - 1; + build_decision_tree_impl (pivot, end, order + 1, + &decision_tree.items[decision_tree.count - 1]); +} + +void +build_decision_tree (void) +{ + // compute answers_known[question] and question_order[order] + for (int question = 0; question < QUESTION_COUNT; ++question) { + for (int decision = 0; decision < DECISION_COUNT; ++decision) + answers_known[question] += is_answer_known (decision, question); + + int order = 0; + while (order < question && + answers_known[question] <= + answers_known[question_queue[order]]) { + order += 1; + } + + memmove (&question_queue[order + 1], + &question_queue[order + 0], + (question - order)*sizeof (*question_queue)); + question_queue[order] = question; + } + + // initialize context and run recursive function on it + enum decision decisions[DECISION_COUNT]; + for (int decision = 0; decision < DECISION_COUNT; ++decision) + decisions[decision] = DECISION_COUNT - 1 - decision; + DYNAMIC_ARRAY_ENSURE_CAPACITY (decision_tree, MAX_DECISION_TREE_NODE_COUNT); + DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0}); + build_decision_tree_impl (decisions, decisions + DECISION_COUNT, 0, + &decision_tree.items[0]); + DYNAMIC_ARRAY_SHRINK (decision_tree); +} + +static void +write_decision_tree_in_dot_format_impl (FILE *file, DECISION_TREE_NODE node) +{ + uint32_t node_id = node - decision_tree.items; + + if (node->branch_yes && node->branch_no) { + fprintf (file, "\tn%u [label=\"%u: %s\"]\n", + node_id, node_id + 1, question_labels[node->question]); + + write_decision_tree_in_dot_format_impl ( + file, &decision_tree.items[node->branch_yes]); + uint32_t branch_yes_id = &decision_tree.items[node->branch_yes] - decision_tree.items; + fprintf (file, "\tn%u -> n%u [label=\"%s\"]\n", + node_id, branch_yes_id, question_branch_labels[node->question].answer_yes); + + write_decision_tree_in_dot_format_impl (file, &decision_tree.items[node->branch_no]); + uint32_t branch_no_id = &decision_tree.items[node->branch_no] - decision_tree.items; + fprintf (file, "\tn%u -> n%u [label=\"%s\"]\n", node_id, branch_no_id, question_branch_labels[node->question].answer_no); + } else { + fprintf (file, "\tn%u [label=\"%u: %s\"]\n", node_id, node_id + 1, decision_labels[node->decision]); + } +} + +struct decision_tree_node_stack { + struct decision_tree_node **items; + uint32_t count; + uint32_t capacity; +}; + +void +write_decision_tree_in_dot_format (void) +{ + FILE *file = fopen ("decision-tree.dot", "w"); + if (file == NULL) { + fprintf (stderr, "Error opening file!\n"); + return; + } + + fprintf (file, "digraph {\n"); + fprintf (file, "\trankdir = \"LR\";\n"); + // write_decision_tree_in_dot_format_impl (file, &decision_tree.items[0]); + + uint32_t node_visual_id = 0; + struct decision_tree_node_stack stack1 = {0}; + struct decision_tree_node_stack stack2 = {0}; + struct decision_tree_node_stack *front_stack = &stack1; + struct decision_tree_node_stack *back_stack = &stack2; + DYNAMIC_ARRAY_APPEND (*front_stack, &decision_tree.items[0]); + while (front_stack->count) { + DYNAMIC_ARRAY_RESET (*back_stack); + DYNAMIC_ARRAY_FOREACH (n, *front_stack) { + DECISION_TREE_NODE node = *n; + uint32_t node_id = node - decision_tree.items; + + if (node->branch_yes && node->branch_no) { + fprintf (file, "\tn%u [label=\"%u: %s\"]\n", node_id, ++node_visual_id, question_labels[node->question]); + + DYNAMIC_ARRAY_APPEND (*back_stack, &decision_tree.items[node->branch_yes]); + uint32_t branch_yes_id = &decision_tree.items[node->branch_yes] - decision_tree.items; + fprintf (file, "\tn%u -> n%u [label=\"%s\"]\n", node_id, branch_yes_id, question_branch_labels[node->question].answer_yes); + + DYNAMIC_ARRAY_APPEND (*back_stack, &decision_tree.items[node->branch_no]); + uint32_t branch_no_id = &decision_tree.items[node->branch_no] - decision_tree.items; + fprintf (file, "\tn%u -> n%u [label=\"%s\"]\n", node_id, branch_no_id, question_branch_labels[node->question].answer_no); + } else { + fprintf (file, "\tn%u [label=\"%u: %s\"]\n", node_id, ++node_visual_id, decision_labels[node->decision]); + } + } + + struct decision_tree_node_stack *tmp = front_stack; + front_stack = back_stack; + back_stack = tmp; + } + fprintf (file, "}\n"); + + fclose (file); + + puts ("decision-tree.dot:0:0: Decision tree is ready for viewing."); +} + +void +question_user (void) +{ + char *line = NULL; + size_t line_size = 0; + struct decision_tree_node *node = &decision_tree.items[0]; + while (node->branch_yes && node->branch_no) { + enum question question = node->question; + printf ("%s\n", question_labels[question]); + printf (" [1] %s\n", question_branch_labels[question].answer_yes); + printf (" [2] %s\n", question_branch_labels[question].answer_no); + + enum answer answer = 0; + for (;;) { + printf ("> "); + getline (&line, &line_size, stdin); + sscanf (line, "%d", &answer); + if (answer < 1 || answer > 2) + continue; + + switch (answer) { + case ANSWER_YES: + node = &decision_tree.items[node->branch_yes]; + break; + case ANSWER_NO: + node = &decision_tree.items[node->branch_no]; + break; + default: break; + } break; + } + } + free (line); + printf ("Рекомендация: %s\n", decision_labels[node->decision]); +} diff --git a/src/inference-engine.h b/src/inference-engine.h new file mode 100644 index 0000000..13344f7 --- /dev/null +++ b/src/inference-engine.h @@ -0,0 +1,10 @@ +#ifndef INCLUDED_INFERENCE_ENGINE_H +#define INCLUDED_INFERENCE_ENGINE_H + +#include "knowledge-base.h" + +void build_decision_tree (void); +void write_decision_tree_in_dot_format (void); +void question_user (void); + +#endif diff --git a/src/knowledge-base.c b/src/knowledge-base.c new file mode 100644 index 0000000..58a9d07 --- /dev/null +++ b/src/knowledge-base.c @@ -0,0 +1,64 @@ +#include "knowledge-base.h" +#include + +#define QUESTION(symbol, label, yes, no) \ +[QUESTION_##symbol] = label, +char *question_labels[QUESTION_COUNT] = { + QUESTIONS +}; +#undef QUESTION + +#define QUESTION(symbol, label, yes, no) \ +[QUESTION_##symbol] = { yes, no }, +struct question_branch_labels question_branch_labels[QUESTION_COUNT] = { + QUESTIONS +}; +#undef QUESTION + +#define DECISION(symbol, label, ...) [DECISION_##symbol] = label, +char *decision_labels[DECISION_COUNT] = { + DECISIONS +}; +#undef DECISION + +#define DECISION(symbol, label, ...) [DECISION_##symbol] = { __VA_ARGS__ }, +struct decision_predicates decision_predicates[DECISION_COUNT] = { + DECISIONS +}; +#undef DECISION + +#define QUESTION(symbol, label, yes, no) \ + if (QUESTION_##symbol == question) \ + return decision_predicates[decision].symbol; +enum answer +get_decision_predicate (enum decision decision, enum question question) +{ + QUESTIONS + + return ANSWER_MALFORMED; +} +#undef QUESTION + +void +print_knowledge_base (void) +{ + puts ("QUESTIONS:"); + for (int i = 0; i < QUESTION_COUNT; ++i) + printf ("%2X", i + 1); + putchar ('\n'); + for (int i = 0; i < QUESTION_COUNT; ++i) { + printf ("%0*b: %s\n", 2*QUESTION_COUNT, + (1 << ANSWER_COUNT) - 1 << (QUESTION_COUNT - 1 - i)*ANSWER_COUNT, question_labels[i]); + } putchar ('\n'); + + puts ("DECISIONS:"); + for (int i = 0; i < QUESTION_COUNT; ++i) + printf ("%2X", i + 1); + putchar ('\n'); + for (int i = 0; i < DECISION_COUNT; ++i) { + for (int j = 0; j < QUESTION_COUNT; ++j) { + printf ("%0*b", ANSWER_COUNT, get_decision_predicate (i, j)); + } + printf (": %s\n", decision_labels[i]); + } +} diff --git a/src/knowledge-base.h b/src/knowledge-base.h new file mode 100644 index 0000000..1d31a9a --- /dev/null +++ b/src/knowledge-base.h @@ -0,0 +1,171 @@ +#ifndef INCLUDED_KNOWLEDGE_BASE_H +#define INCLUDED_KNOWLEDGE_BASE_H + +#include +#include +#include +#include + +#define QUESTIONS \ + QUESTION(advanced, "Вы опытный пользователь?", "Опытный", "Неопытный" ) \ + QUESTION(confidentiality, "Вы нуждаетесь в максимальной конфиденциальности?", "Нуждаюсь", "Не нуждаюсь" ) \ + QUESTION(usb, "Вы хотите установить систему на переносной накопитель?", "Хочу", "Не хочу" ) \ + QUESTION(control, "Вы хотите управлять сборкой пакетов?", "Хочу", "Не хочу" ) \ + QUESTION(hacking, "Вы собираетесь использовать данную систему для взлома?", "Собираюсь", "Не собираюсь") \ + QUESTION(multilang, "Вам нужна поддержка нескольких языков?", "Нужна", "Не нужна" ) \ + QUESTION(declarative, "Вы хотите настраивать систему декларативно?", "Хочу", "Не хочу" ) \ + QUESTION(stability, "Вас интересуют фиксированные или вращающиеся выпуски изменении пакетов?", "Фиксированные", "Вращающиеся" ) \ + QUESTION(lightweight, "Вам важно чтобы дистрибутив весил мало?", "Важно", "Не важно" ) \ + QUESTION(scheme, "Вы хотите описывать настройки на схеме GNU Guile?", "Хочу", "Не хочу" ) \ + QUESTION(games, "Вы собираетесь играть в компьютерные игры?", "Собираюсь", "Не собираюсь") + +#define DECISIONS \ + DECISION(TAILS, "Tails", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_YES, \ + .usb = ANSWER_YES, \ + .multilang = ANSWER_YES, \ + ) \ + DECISION(WHONIX, "Whonix", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_YES, \ + .usb = ANSWER_YES, \ + .multilang = ANSWER_NO, \ + ) \ + DECISION(QUBES_OS, "Qubes OS", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_YES, \ + .usb = ANSWER_NO, \ + ) \ + DECISION(GNU_GUIX, "GNU Guix", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_NO, \ + .control = ANSWER_YES, \ + .declarative = ANSWER_YES, \ + .scheme = ANSWER_YES, \ + ) \ + DECISION(NIX_OS, "Nix OS", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_NO, \ + .control = ANSWER_YES, \ + .declarative = ANSWER_YES, \ + .scheme = ANSWER_NO, \ + ) \ + DECISION(GENTOO, "Gentoo", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_NO, \ + .control = ANSWER_YES, \ + .declarative = ANSWER_NO, \ + ) \ + DECISION(DEBIAN, "Debian", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_NO, \ + .control = ANSWER_NO, \ + .stability = ANSWER_YES, \ + .lightweight = ANSWER_YES, \ + ) \ + DECISION(ROCKY_LINUX, "Rocky Linux", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_NO, \ + .control = ANSWER_NO, \ + .stability = ANSWER_YES, \ + .lightweight = ANSWER_NO, \ + ) \ + DECISION(VOID_LINUX, "Void Linux", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_NO, \ + .control = ANSWER_NO, \ + .stability = ANSWER_NO, \ + .lightweight = ANSWER_YES, \ + ) \ + DECISION(ARCH_LINUX, "Arch Linux", \ + .advanced = ANSWER_YES, \ + .confidentiality = ANSWER_NO, \ + .control = ANSWER_NO, \ + .stability = ANSWER_NO, \ + .lightweight = ANSWER_NO, \ + ) \ + DECISION(KALI_LINUX, "Kali Linux", \ + .advanced = ANSWER_NO, \ + .usb = ANSWER_YES, \ + .hacking = ANSWER_YES, \ + ) \ + DECISION(PUPPY_LINUX, "Puppy Linux", \ + .advanced = ANSWER_NO, \ + .usb = ANSWER_YES, \ + .hacking = ANSWER_NO, \ + ) \ + DECISION(POP_OS, "Pop! OS", \ + .advanced = ANSWER_NO, \ + .usb = ANSWER_NO, \ + .stability = ANSWER_YES, \ + .lightweight = ANSWER_NO, \ + .games = ANSWER_YES, \ + ) \ + DECISION(FEDORA, "Fedora", \ + .advanced = ANSWER_NO, \ + .usb = ANSWER_NO, \ + .stability = ANSWER_YES, \ + .lightweight = ANSWER_NO, \ + .games = ANSWER_NO, \ + ) \ + DECISION(MAJARO, "Majaro", \ + .advanced = ANSWER_NO, \ + .usb = ANSWER_NO, \ + .stability = ANSWER_NO, \ + ) + +enum answer { + ANSWER_UNKNOWN, + ANSWER_YES, + ANSWER_NO, + ANSWER_MALFORMED, +}; + +#define ANSWER_COUNT 2 + +#define QUESTION(symbol, label, yes, no) \ + QUESTION_##symbol, +enum question { + QUESTIONS + QUESTION_COUNT +}; +#undef QUESTION + +#define QUESTION(symbol, label, yes, no) \ + PREDICATE_Y_##symbol = 1 << __COUNTER__, \ + PREDICATE_N_##symbol = 1 << __COUNTER__, +enum predicate { + QUESTIONS +}; +#undef QUESTION + +#define DECISION(symbol, label, ...) DECISION_##symbol, +enum decision { + DECISIONS + DECISION_COUNT +}; +#undef DECISION + +struct question_branch_labels { + char *answer_yes; + char *answer_no; +}; + +#define QUESTION(symbol, label, yes, no) \ + enum answer symbol : ANSWER_COUNT; +struct decision_predicates { + QUESTIONS; +}; +#undef QUESTION + +extern char *question_labels[QUESTION_COUNT]; +extern struct question_branch_labels question_branch_labels[QUESTION_COUNT]; +extern char *decision_labels[DECISION_COUNT]; +extern struct decision_predicates decision_predicates[DECISION_COUNT]; + +extern void print_decision_predicates (struct decision_predicates); +extern void print_knowledge_base (void); +extern enum answer get_decision_predicate (enum decision, enum question); + +#endif diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..d9ae7dc --- /dev/null +++ b/src/utils.h @@ -0,0 +1,14 @@ +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include + +#define MALLOC malloc +#define REALLOC realloc +#define FREE free +#define ASSERT assert + +#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP) + +#endif -- cgit v1.3.1