aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.dir-locals.el4
-rw-r--r--.envrc18
-rw-r--r--.gitignore5
-rw-r--r--README.org144
-rw-r--r--UNLICENSE24
-rwxr-xr-xbuild.sh8
-rw-r--r--channels-lock.scm21
-rw-r--r--doc/gost/gost-7-32-bibliography.sty57
-rw-r--r--doc/gost/gost-7-32-captions.sty23
-rw-r--r--doc/gost/gost-7-32-counters.sty37
-rw-r--r--doc/gost/gost-7-32-headings.sty98
-rw-r--r--doc/gost/gost-7-32-lists.sty15
-rw-r--r--doc/gost/gost-7-32-tables.sty29
-rw-r--r--doc/gost/gost-7-32-toc.sty34
-rw-r--r--doc/gost/gost-7-32.cls62
-rw-r--r--doc/ox-init.el32
-rw-r--r--doc/report.org585
-rw-r--r--doc/scratch.txt20
-rw-r--r--doc/setup.org42
-rw-r--r--doc/spbstu-report.cls73
-rw-r--r--manifest.scm53
-rw-r--r--src/dynamic-array.h56
-rw-r--r--src/expert-system.c21
-rw-r--r--src/inference-engine.c244
-rw-r--r--src/inference-engine.h10
-rw-r--r--src/knowledge-base.c64
-rw-r--r--src/knowledge-base.h171
-rw-r--r--src/utils.h14
28 files changed, 1964 insertions, 0 deletions
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 @@
1;;; Directory Local Variables -*- no-byte-compile: t -*-
2;;; For more information see (info "(emacs) Directory Variables")
3
4((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 @@
1CHANNELS=./channels-lock.scm
2MANIFEST=./manifest.scm
3LOAD_PATH=./lib
4ROOT=./.guix-shell
5
6TIME_MACHINE_FLAGS+=" --channels=$CHANNELS"
7SHELL_FLAGS+=" --manifest=$MANIFEST"
8SHELL_FLAGS+=" --search-paths"
9SHELL_FLAGS+=" --root=$ROOT"
10SHELL_FLAGS+=" --load-path=$LOAD_PATH"
11
12use_guix_shell() {
13 test -d "$ROOT" && unlink "$ROOT"
14 eval "$(guix time-machine $TIME_MACHINE_FLAGS -- shell $SHELL_FLAGS "$@")"
15}
16
17use guix_shell
18export TEXINPUTS=${TEXINPUTS}:./:./gost/
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..714ed7b
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
1*.pdf
2*.html
3*.png
4*.dot
5/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 @@
1#+title: Implementation of an expert system
2#+subtitle: for GNU/Linux distribution recommendation
3
4* Task[fn:1]
5Independently select a subject area (have it approved by the
6professor), build a production model of an expert system (for example,
7for fault diagnosis) and have it approved by the professor. After
8that, implement the expert system using CLIPS[fn:2]. The minimum number
9of tree depth is 4 (excluding the root), and there must be at least 30
10nodes.
11
12* Documentation
13The exported report can be found at [[https://git.michalec.dev/uni/term-04/graph-theory/coursework/report.pdf][this link]].
14
15* Showcase
16#+caption: Decision tree
17#+attr_html: :width 100%
18[[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]]
19
20*Header of the knowledge base:*
21#+begin_example
22QUESTIONS:
23 1 2 3 4 5 6 7 8 9 A B
241100000000000000000000: Вы опытный пользователь?
250011000000000000000000: Вы нуждаетесь в максимальной конфиденциальности?
260000110000000000000000: Вы хотите установить систему на переносной накопитель?
270000001100000000000000: Вы хотите управлять сборкой пакетов?
280000000011000000000000: Вы собираетесь использовать данную систему для взлома?
290000000000110000000000: Вам нужна поддержка нескольких языков?
300000000000001100000000: Вы хотите настраивать систему декларативно?
310000000000000011000000: Вас интересуют фиксированные или вращающиеся выпуски...?
320000000000000000110000: Вам важно чтобы дистрибутив весил мало?
330000000000000000001100: Вы хотите описывать настройки на схеме GNU Guile?
340000000000000000000011: Вы собираетесь играть в компьютерные игры?
35
36DECISIONS:
37 1 2 3 4 5 6 7 8 9 A B
380101010000010000000000: Tails
390101010000100000000000: Whonix
400101100000000000000000: Qubes OS
410110000100000100000100: GNU Guix
420110000100000100001000: Nix OS
430110000100001000000000: Gentoo
440110001000000001010000: Debian
450110001000000001100000: Rocky Linux
460110001000000010010000: Void Linux
470110001000000010100000: Arch Linux
481000010001000000000000: Kali Linux
491000010010000000000000: Puppy Linux
501000100000000001100001: Pop! OS
511000100000000001100010: Fedora
521000100000000010000000: Majaro
53
54decision-tree.dot:0:0: Decision tree is ready for viewing.
55#+end_example
56
57*Example of a Tails recommendation:*
58#+begin_example
59Вы опытный пользователь?
60 [1] Опытный
61 [2] Неопытный
62>
63> 3
64> 0
65> -1234
66> asdf
67>
68> 1
69Вы нуждаетесь в максимальной конфиденциальности?
70 [1] Нуждаюсь
71 [2] Не нуждаюсь
72> 1
73Вы хотите установить систему на переносной накопитель?
74 [1] Хочу
75 [2] Не хочу
76> 1
77Вам нужна поддержка нескольких языков?
78 [1] Нужна
79 [2] Не нужна
80> 1
81Рекомендация: Tails
82#+end_example
83
84*Example of a GNU Guix recommendation:*
85#+begin_example
86Вы опытный пользователь?
87 [1] Опытный
88 [2] Неопытный
89> 1
90Вы нуждаетесь в максимальной конфиденциальности?
91 [1] Нуждаюсь
92 [2] Не нуждаюсь
93> 2
94Вы хотите управлять сборкой пакетов?
95 [1] Хочу
96 [2] Не хочу
97> 1
98Вы хотите настраивать систему декларативно?
99 [1] Хочу
100 [2] Не хочу
101> 1
102Вы хотите описывать настройки на схеме GNU Guile?
103 [1] Хочу
104 [2] Не хочу
105> 1
106Рекомендация: GNU Guix
107#+end_src
108#+end_example
109
110*Example of a Kali Linux recommendation:*
111#+begin_example
112Вы опытный пользователь?
113 [1] Опытный
114 [2] Неопытный
115> 2
116Вы хотите установить систему на переносной накопитель?
117 [1] Хочу
118 [2] Не хочу
119> 1
120Вы собираетесь использовать данную систему для взлома?
121 [1] Собираюсь
122 [2] Не собираюсь
123> 1
124Рекомендация: Kali Linux
125#+end_src
126#+end_example
127
128* Unlicense
129#+include: UNLICENSE verse
130
131* Footnotes
132[fn:1] Original text:
133#+HTML: <i>
134#+begin_quote
135Самостоятельно выбрать предметную область (согласовать ее с
136преподавателем), построить продукционную модель экспертной системы
137(например, поиска неисправности) и согласовать ее с преподавателем.
138После этого реализовать экспертную систему средствами CLIPS.
139Минимальное количество ярусов дерева - 4 (не считая корня), не менее -
14030 узлов.
141#+end_quote
142#+HTML: </i>
143
144[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 @@
1This is free and unencumbered software released into the public domain.
2
3Anyone is free to copy, modify, publish, use, compile, sell, or
4distribute this software, either in source code form or as a compiled
5binary, for any purpose, commercial or non-commercial, and by any
6means.
7
8In jurisdictions that recognize copyright laws, the author or authors
9of this software dedicate any and all copyright interest in the
10software to the public domain. We make this dedication for the benefit
11of the public at large and to the detriment of our heirs and
12successors. We intend this dedication to be an overt act of
13relinquishment in perpetuity of all present and future rights to this
14software under copyright law.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22OTHER DEALINGS IN THE SOFTWARE.
23
24For more information, please refer to <https://unlicense.org/>
diff --git a/build.sh b/build.sh
new file mode 100755
index 0000000..3d26241
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,8 @@
1#!/bin/sh
2
3set -xe
4
5gcc -std=gnu99 -ggdb3 -o expert-system \
6 src/expert-system.c \
7 src/knowledge-base.c \
8 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 @@
1(use-modules (guix channels))
2
3(list
4 (channel
5 (name 'guix)
6 (branch "master")
7 (url "https://git.savannah.gnu.org/git/guix.git")
8 (commit "b6dec0108f99d75066bad15aaa124b84bb0261f3")
9 (introduction (make-channel-introduction
10 "d264237d55ca5e2c756cc7a44374a7dbca850505"
11 (openpgp-fingerprint
12 "BBB0 2DDF 2CEA F6A8 0D1D E643 A2A0 6DF2 A33A 54FA"))))
13 (channel
14 (name 'nonguix)
15 (url "https://gitlab.com/nonguix/nonguix")
16 (commit "25bcda2b9107b948a1c858e41aba1b7f95b76228")
17 (introduction
18 (make-channel-introduction
19 "897c1a470da759236cc11798f4e0a5f7d4d59fbc"
20 (openpgp-fingerprint
21 "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 @@
1\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017]
2
3\def\UrlBreaks{\do\/\do-}
4\RequirePackage{url}
5
6\newdimen\bibindent
7\renewenvironment{thebibliography}[1]{
8 \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}%
9 \list{\@biblabel{\@arabic\c@enumiv}}%
10 {\settowidth\labelwidth{\@biblabel{#1}}%
11 \leftmargin\labelwidth
12 \advance\leftmargin\labelsep
13 \@openbib@code
14 \usecounter{enumiv}%
15 \let\p@enumiv\@empty
16 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
17 \sloppy\clubpenalty4000\widowpenalty4000%
18 \sfcode`\.\@m
19}{
20 \setcounter{totalbib}{\c@enumiv}%
21 \def\@noitemerr
22 {\@latex@warning{Empty `thebibliography' environment}}%
23 \endlist
24}
25\renewcommand\@biblabel{}%
26\setlength\bibindent{1.5em}
27
28% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И.
29%\makeatletter
30\renewcommand*{\@biblabel}[1]{\hfill#1.}
31
32
33%
34% Remove References header completely
35% Stolen from original article.cls
36%
37\makeatletter
38\renewenvironment{thebibliography}[1]{%
39% \usection{\refname}%
40% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}%
41 \list{\@biblabel{\@arabic\c@enumiv}}%
42 {\settowidth\labelwidth{\@biblabel{#1}}%
43 \leftmargin\labelwidth
44 \advance\leftmargin\labelsep
45 \@openbib@code
46 \usecounter{enumiv}%
47 \let\p@enumiv\@empty
48 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
49 \sloppy
50 \clubpenalty4000
51 \@clubpenalty \clubpenalty
52 \widowpenalty4000%
53 \sfcode`\.\@m}
54 {\def\@noitemerr
55 {\@latex@warning{Empty `thebibliography' environment}}%
56 \endlist}
57\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 @@
1\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{caption}
4\RequirePackage{subcaption}
5
6%
7% Table caption aligned to the left with dash as a separator
8%
9\captionsetup[table]{labelsep=endash, skip=0pt, singlelinecheck=off}
10
11%
12% Dash as separator in figure caption and centering
13%
14\captionsetup[figure]{labelsep=endash, justification=centering}
15
16%
17% Listing caption
18%
19\captionsetup[listing]{labelsep=endash, justification=centering}
20
21\addto\captionsrussian{\renewcommand{\figurename}{Рисунок}}
22\addto\captionsrussian{\renewcommand{\mintedname}{Листинг}}
23\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 @@
1\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017]
2
3%
4% Values for capital russian letters counter
5%
6\makeatletter
7\newcommand\AlphRus[1]{%
8 \expandafter \@AlphRus \csname c@#1\endcsname
9}
10
11\newcommand\@AlphRus[1]{%
12 \ifcase #1%
13 \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or
14 Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or
15 Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я%
16 \else \@ctrerr
17\fi
18}
19\makeatother
20
21%
22% Values for lowercase russian letters counter
23%
24\makeatletter
25\newcommand\alphRus[1]{%
26 \expandafter \@alphRus \csname c@#1\endcsname
27}
28
29\newcommand\@alphRus[1]{%
30 \ifcase #1%
31 \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or
32 л\or м\or н\or п\or р\or с\or т\or у\or ф\or
33 х\or ц\or ш\or щ\or э\or ю\or я%
34 \else \@ctrerr
35\fi
36}
37\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 @@
1\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{titlesec}
4\RequirePackage{titling}
5\RequirePackage{setspace}
6
7\RequirePackage{gost-7-32-counters}
8
9%
10% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection
11%
12\titleformat{\section}[block]{\newpage\cleardoublepage\large\setstretch{1}\bfseries}{\thesection}{0.5em}{}
13\titlespacing{\section}{0cm}{0cm}{0.5cm}
14
15\titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{}
16\titlespacing{\subsection}{0cm}{0.5cm}{0.5cm}
17
18\titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent]
19\titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm}
20
21%
22% Make special headings, that have their own formatting rules:
23% - centered
24% - all-caps
25% - bold
26%
27% Only three of them must appear in TOC: introduction, conclusion and references
28%
29\newcommand{\introduction}{
30 \addcontentsline{toc}{section}{ВВЕДЕНИЕ}
31 \begin{center}
32 \bfseries\large
33 ВВЕДЕНИЕ
34 \end{center}
35}
36
37\newcommand{\conclusion}{
38 \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ}
39 \begin{center}
40 \bfseries\large
41 ЗАКЛЮЧЕНИЕ
42 \end{center}
43}
44
45\newcommand{\references}{
46 \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ}
47 \begin{center}
48 \bfseries\large
49 СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
50 \end{center}
51}
52
53\newcommand{\essay}{
54 \begin{center}
55 \bfseries\large
56 РЕФЕРАТ
57 \end{center}
58}
59
60\newcommand{\definitions}{
61 \begin{center}
62 \bfseries\large
63 ОПРЕДЕЛЕНИЯ
64 \end{center}
65}
66
67\newcommand{\abbreviations}{
68 \begin{center}
69 \bfseries\large
70 ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
71 \end{center}
72}
73
74\newcommand{\defsabbrs}{
75 \begin{center}
76 \bfseries\large
77 ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
78 \end{center}
79}
80
81%
82% Appendices headings. Appendices have autoincrementing number,
83% that is represented with russian letter.
84% This heading must appear in TOC
85%
86\newcounter{appendixcnt}
87\setcounter{appendixcnt}{1}
88
89\renewcommand{\appendix}[1]{
90 \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1}
91 \begin{center}
92 \bfseries\large
93 ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}
94
95 #1
96 \end{center}
97 \stepcounter{appendixcnt}
98}
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 @@
1\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{enumitem}
4\RequirePackage{gost-7-32-counters}
5
6\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1}
7
8\setlist{nosep}
9\setlist[itemize, 1]{label=\textendash}
10\setlist[itemize, 2]{label=\bullet}
11
12\setlist[enumerate, 2]{label=\alphRus*)}
13
14\setlist[1]{wide=\parindent}
15\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 @@
1\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{tabularx}
4
5%
6% Center-aligned column with automatic width
7%
8\newcolumntype{Y}{>{\centering\arraybackslash}X}
9
10%
11% Right-aligned column with automatic width
12%
13\newcolumntype{Z}{>{\raggedleft\arraybackslash}X}
14
15%
16% Table with designations
17%
18\newenvironment{designations}{
19 \noindent
20 \tabularx{\textwidth}{@{}
21 >{\raggedright \arraybackslash \hsize=0.25\hsize}X
22 >{\centering \arraybackslash \hsize=0.05\hsize}X
23 >{\arraybackslash \hsize=0.70\hsize}X
24 }
25}{
26 \endtabularx
27}
28
29\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 @@
1\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017]
2
3%% \RequirePackage{tocloft}
4\RequirePackage[
5 bookmarks=true,
6 colorlinks=true,
7 unicode=true,
8 urlcolor=black,
9 linkcolor=black,
10 anchorcolor=black,
11 citecolor=black,
12 menucolor=black,
13 filecolor=black
14]{hyperref}
15
16%
17% Set custom font styles
18%
19%% \renewcommand{\cftsecfont}{\normalfont}
20%% \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}
21%% \renewcommand{\cftsecpagefont}{\normalsize}
22%% \renewcommand{\cfttoctitlefont}{\hfill\large\bfseries}
23%% \renewcommand{\cftaftertoctitle}{\hfill\hfill}
24%% \renewcommand{\cfttoctitlefont}{\hfill\hfill\normalfont\large\bfseries}
25\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{}
26\titlespacing{\tableofcontents}{0cm}{0cm}{1cm}
27
28%
29% Set indents and line spacing
30%
31%% \setlength{\cftbeforesecskip}{0cm}
32%% \setlength{\cftbeforesubsecskip}{0cm}
33%% \setlength{\cftbeforesubsubsecskip}{0cm}
34%% \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 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017]
3
4%
5% Supported font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12%
13% Set A4 paper format
14%
15\LoadClass[a4paper]{extarticle}
16
17%
18% Use 1.5 line spacing
19%
20\RequirePackage{setspace}
21\spacing{1.5}
22
23%
24% First paragraph indentation
25%
26\RequirePackage{indentfirst}
27\setlength{\parindent}{12.5mm}
28
29%
30% Page margin
31%
32\RequirePackage[
33 left=2.5cm,
34 right=2cm,
35 top=2cm,
36 bottom=2cm,
37 footskip=1cm,
38]{geometry}
39
40%
41% Use TMR-like font
42%
43\RequirePackage{fontspec}
44\RequirePackage{xunicode}
45\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
46\setmainfont{Times New Roman}
47
48%
49% Use russian language
50%
51\RequirePackage[main=russian, english]{babel}
52\babelhyphenation[russian]{}
53
54%
55% gost-7-32 packages
56%
57\RequirePackage{gost-7-32-headings}
58\RequirePackage{gost-7-32-toc}
59\RequirePackage{gost-7-32-lists}
60\RequirePackage{gost-7-32-bibliography}
61\RequirePackage{gost-7-32-captions}
62\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 @@
1;;; ox-init --- Initialization script for async org exprort session
2;;; Commentary:
3;;; Code:
4(org-babel-do-load-languages
5 'org-babel-load-languages
6 '((latex . t)
7 (C . t)))
8
9(require 'ox-extra)
10(ox-extras-activate '(ignore-headlines))
11
12(require 'oc-bibtex)
13
14(setq org-latex-src-block-backend 'minted)
15
16(setq org-latex-bib-compiler "biber")
17
18(setq org-latex-remove-logfiles nil)
19
20(setq org-latex-caption-above '(table src-block special-block))
21
22(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f"
23 "%bib %b"
24 "%latex -shell-escape -interaction nonstopmode -output-directory %o %f"))
25(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}"
26 ("\\section{%s}" . "\\usection{%s}")
27 ("\\subsection{%s}" . "\\subsection*{%s}")
28 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
29 ("\\paragraph{%s}" . "\\paragraph*{%s}")
30 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))))
31
32;;; 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 @@
1#+TITLE: Реализация экспертной системы по рекомендации дистрибутива GNU/Linux
2#+AUTHOR: Михалец Мартин
3#+LATEX_HEADER: \reportof{О ВЫПОЛНЕНИИ КУРСОВОЙ РАБОТЫ}
4#+LATEX_HEADER: \subject{по дисциплине «Теория графов»}
5#+LATEX_HEADER: \reviewertitle{}\reviewer{Востров Алексей Владимирович}
6#+DATE: 2024
7
8#+SETUPFILE: setup.org
9#+LATEX: \sloppy
10#+LATEX: \renewcommand{\arraystretch}{0.65}
11
12* Введение
13:PROPERTIES:
14:UNNUMBERED: t
15:END:
16В данном отчёте представлено описание курсовой работы по дисциплине
17«Теория графов». Работа включает в себя реализацию экспертной системы
18по рекомендации дистрибутива GNU/Linux.
19
20Работа была выполнена в виде консольного приложения разработанного на
21языке программирования Си (=-std=gnu99=) с использованием только
22стандартной библиотеки =libc=.
23
24* Описание предметной области
25В качестве предметной области были выбраны рекомендации дистрибутивов
26GNU/Linux на основе требовании к их характеристикам. Поскольку
27GNU/Linux дистрибутивов относительно много (сотни), была сделана
28субъективная выборка 15 интереснейших из них дистрибутивов с их
29характеристиками приведенными в таблицы [[distributions]].
30
31Рекомендации:
32- Tails
33- Whonix
34- Qubes OS
35- GNU Guix
36- Nix OS
37- Gentoo
38- Debian
39- Rocky Linux
40- Void Linux
41- Arch Linux
42- Kali Linux
43- Puppy Linux
44- Pop! OS
45- Fedora
46- Majaro
47
48Критерии/вопросы:
49- опытный :: Вы опытный пользователь?
50- конфиденциальность :: Вы нуждаетесь в максимальной конфиденциальности?
51- переносной накопитель :: Вы хотите установить систему на переносной накопитель?
52- управление сборкой пакетов :: Вы хотите управлять сборкой пакетов?
53- взлом :: Вы собираетесь использовать данную систему для взлома?
54- несколько языков :: Вам нужна поддержка нескольких языков?
55- декларативная настройка :: Вы хотите настраивать систему декларативно?
56- фиксированные выпуски :: Вас интересуют фиксированные или вращающиеся выпуски изменении пакетов?
57- малый вес :: Вам важно чтобы дистрибутив весил мало?
58- GNU Guile :: Вы хотите описывать настройки на схеме GNU Guile?
59- игры :: Вы собираетесь играть в компьютерные игры?
60
61* Математическое описание
62** Экспертная система
63/Экспертная система/ --- это программное средство, воплощающее в себе
64опыт эксперта, основывавшегося на его знаниях в определённой отрасли.
65Используется для высокоэффективного решения задач в интересующей
66пользователя предметной области.
67
68/Продукционная модель/ --- это модель, основанная на представлении
69знания в виде правил «Если (условие), то (действие)». Под «условием»
70понимается некоторое предложение-образец, по которому осуществляется
71поиск в базе знаний, а под «действием» -- действия, выполняемые при
72успешном исходе поиска.
73
74Режимы экспертной системы:
751. /Режим приобретения знаний/ --- работу с экспертно системой
76 осуществляет эксперт при посредничестве инженера по знаниям. В
77 этом режиме эксперт, используя компонент приобретения знаний,
78 наполняет систему данными, которые, позволяют системе решать задачи
79 из данной предметно области;
802. /Режим решения задачи/ --- общение с экспертными системами
81 осуществляет пользователь, не обязательно эксперт, которого
82 интересует концевой итог работы и иногда способ его получения.
83
84Структуру экспертной системы можно изобразить с помощью схемы,
85представленной на рисунке [[expert-system-structure]].
86
87#+name: expert-system-structure
88#+caption: Структура экспертной системы
89#+attr_latex: :float nil :width .8\linewidth
90[[./expert-system-structure.png]]
91
92** База знаний
93/База знаний/ --- база данных, содержащая правила вывода и информацию о
94человеческом опыте и знаниях в некоторой предметной области.
95
96В таблице [[distributions]] представлена база знаний.
97
98#+name: distributions
99#+caption: База знаний
100#+attr_latex: :float nil :align |l|c|c|c|c|c|
101|----------------------------+------------+-------------+-------------+------------+------------|
102| | Tails | Whonix | Qubes OS | GNU Guix | Nix OS |
103|----------------------------+------------+-------------+-------------+------------+------------|
104| опытный | 1 | 1 | 1 | 1 | 1 |
105| конфиденциальность | 1 | 1 | 1 | 0 | 0 |
106| переносной накопитель | 1 | 1 | 0 | 1 | 1 |
107| управление сборкой пакетов | ? | ? | ? | 1 | 1 |
108| взлом | ? | ? | ? | ? | ? |
109| несколько языков | 1 | 0 | ? | ? | ? |
110| декларативная настройка | ? | ? | ? | 1 | 1 |
111| фиксированные выпуски | ? | ? | ? | ? | ? |
112| малый вес | ? | ? | ? | ? | ? |
113| GNU Guile | ? | ? | ? | 1 | 0 |
114| игры | ? | ? | ? | ? | ? |
115|----------------------------+------------+-------------+-------------+------------+------------|
116|----------------------------+------------+-------------+-------------+------------+------------|
117| | Gentoo | Debian | Rocky Linux | Void Linux | Arch Linux |
118|----------------------------+------------+-------------+-------------+------------+------------|
119| опытный | 1 | 1 | 1 | 1 | 1 |
120| конфиденциальность | 0 | 0 | 0 | 0 | 0 |
121| переносной накопитель | ? | ? | ? | ? | ? |
122| управление сборкой пакетов | 1 | 0 | 0 | 0 | 0 |
123| взлом | ? | ? | ? | ? | ? |
124| несколько языков | ? | ? | ? | ? | ? |
125| декларативная настройка | 0 | ? | ? | ? | ? |
126| фиксированные выпуски | ? | 1 | 1 | 0 | 0 |
127| малый вес | ? | 1 | 0 | 1 | 0 |
128| GNU Guile | ? | ? | ? | ? | ? |
129| игры | ? | ? | ? | ? | ? |
130|----------------------------+------------+-------------+-------------+------------+------------|
131|----------------------------+------------+-------------+-------------+------------+------------|
132| | Kali Linux | Puppy Linux | Pop! OS | Fedora | Majaro |
133|----------------------------+------------+-------------+-------------+------------+------------|
134| опытный | 0 | 0 | 0 | 0 | 0 |
135| конфиденциальность | ? | ? | 0 | 0 | 0 |
136| переносной накопитель | 1 | 1 | ? | ? | ? |
137| управление сборкой пакетов | ? | ? | ? | ? | ? |
138| взлом | 1 | 0 | ? | ? | ? |
139| несколько языков | ? | ? | ? | ? | ? |
140| декларативная настройка | ? | ? | 1 | 1 | 0 |
141| фиксированные выпуски | ? | ? | 0 | 1 | ? |
142| малый вес | ? | ? | ? | ? | ? |
143| GNU Guile | ? | ? | ? | ? | ? |
144| игры | ? | ? | 1 | 0 | ? |
145|----------------------------+------------+-------------+-------------+------------+------------|
146
147** Машина вывода
148/Машина вывода/ --- программа, которая выполняет логический вывод из
149предварительно построенной базы фактов и правил в соответствии с
150законами формальной логики.
151
152** Дерево решений
153Экспертную систему можно представить как дерево решений.
154Алгебраическая структура:
155#+begin_export latex
156\begin{displaymath}
157 G = <V,E,B>,
158\end{displaymath}
159#+end_export
160где $V$ --- множество узлов (вопросы), $E$ --- множество ребер (связь
161вопрос-рекомендация), $B$ --- атрибут ребер (ответ ребра). Каждая
162вершина графа помечена уточняющим вопросом экспертной системы к
163пользователю или ее ответом на задачу. Если вершина помечена вопросом
164ЭС, то из нее выходят две дуги. Дуги помечены ответом пользователя.
165Вершины, соответствующие ответам ЭС --- листья. Работа экспертной
166системы сводится к пути по графу. Такой путь состоит из
167последовательности однотипных шагов, на каждом из которых пользователь
168должен решить, по какой дуге он пойдет из очередной вершины. На
169рисунке [[decision-tree]] представлено бинарное дерево решений.
170
171Характеристика дерева:
172- 15 узлов (вопросов/правил)
173- 16 листьев (рекомендации/фактов)
174- итого 31 вершин
175- 5 ярусов не считая корня
176
177@@latex:\KOMAoptions{paper=A3}@@
178@@latex:\recalctypearea@@
179@@latex:\begin{landscape}@@
180@@latex:\thispagestyle{empty}@@
181#+name: decision-tree
182#+caption: Бинарное дерево решений
183#+attr_latex: :float nil :width \linewidth
184[[./decision-tree.pdf]]
185@@latex:\vfill\raisebox{-10pt}{\makebox[\linewidth]{\thepage}}@@
186@@latex:\end{landscape}@@
187@@latex:\KOMAoptions{paper=A4}@@
188@@latex:\recalctypearea@@
189
190* Реализация
191** База знании
192База знании заполняется редактированием определении макросов ~QUESTIONS~
193и ~DECISIONS~, примеры которых приведены в листингах [[questions]] и
194[[decisions]], соответственно. Использование данных макросов нам
195позволяет структурированный ввод знаний, который бы иначе был
196разброшен по нескольким определениям структур, перечислении и
197массивов. В листинге [[macro-expansions]] приведено использование данных
198макросов, для заполнения 9 символов.
199
200#+name: questions
201#+caption: Пример определения вопросов
202#+begin_src c
203#define QUESTIONS \
204 QUESTION(advanced, "Опытный пользователь?", "Опытный", "Неопытный") \
205 QUESTION(confidentiality, "Конфиденциальность?", "Да", "Нет" ) \
206 QUESTION(usb, "Переносной накопитель?", "Да", "Нет" )
207#+end_src
208
209#+name: decisions
210#+caption: Пример определения решении
211#+begin_src c
212#define DECISIONS \
213 DECISION(WHONIX, "Whonix", \
214 .advanced = ANSWER_YES, \
215 .confidentiality = ANSWER_YES, \
216 .usb = ANSWER_YES, \
217 .multilang = ANSWER_NO, \
218 ) \
219 DECISION(QUBES_OS, "Qubes OS", \
220 .advanced = ANSWER_YES, \
221 .confidentiality = ANSWER_YES, \
222 .usb = ANSWER_NO, \
223 ) \
224 DECISION(GNU_GUIX, "GNU Guix", \
225 .advanced = ANSWER_YES, \
226 .confidentiality = ANSWER_NO, \
227 .control = ANSWER_YES, \
228 .declarative = ANSWER_YES, \
229 .scheme = ANSWER_YES, \
230 )
231#+end_src
232
233#+name: macro-expansions
234#+caption: Некоторые применения макросов
235#+begin_src c
236#define QUESTION(symbol, label, yes, no) QUESTION_##symbol,
237enum question { QUESTIONS QUESTION_COUNT };
238#undef QUESTION
239
240#define QUESTION(symbol, label, yes, no) \
241 PREDICATE_Y_##symbol = 1 << __COUNTER__, \
242 PREDICATE_N_##symbol = 1 << __COUNTER__,
243enum predicate { QUESTIONS };
244#undef QUESTION
245
246#define QUESTION(symbol, label, yes, no) \
247 enum answer symbol : ANSWER_COUNT;
248struct decision_predicates { QUESTIONS; };
249#undef QUESTION
250
251#define QUESTION(symbol, label, yes, no) [QUESTION_##symbol] = label,
252char *question_labels[QUESTION_COUNT] = { QUESTIONS };
253#undef QUESTION
254
255#define QUESTION(symbol, label, yes, no) [QUESTION_##symbol] = { yes, no },
256struct question_branch_labels question_branch_labels[QUESTION_COUNT] = { QUESTIONS };
257#undef QUESTION
258
259#define DECISION(symbol, label, ...) [DECISION_##symbol] = { __VA_ARGS__ },
260struct decision_predicates decision_predicates[DECISION_COUNT] = { DECISIONS };
261#undef DECISION
262
263#define QUESTION(symbol, label, yes, no) \
264 if (QUESTION_##symbol == question) return decision_predicates[decision].symbol;
265enum answer
266get_decision_predicate (enum decision decision, enum question question)
267{ QUESTIONS return ANSWER_MALFORMED; }
268#undef QUESTION
269#+end_src
270
271** Машина вывода
272Машина вывода строит дерево решении. Процедура, отвечающая за
273построение дерева решении (приведена в листинге [[build_decision_tree]]),
274сначала анализируют базу знании, вычисляет порядок, в котором будут
275задаваться вопросы по количеству известных ответов на них, потом
276запускает рекурсивную функцию построения уже самого дерева.
277
278Рекурсивная функция построения дерева решении (приведена в листинге
279[[build_decision_tree_impl]]) сначала находит вопрос, по которому
280достаточно знании, дальше она по нему разделяет оставшиеся
281рекомендации и по обоим группам рекурсивно вызывается до момента,
282когда либо остается одна рекомендация, либо хватает знании, в случае
283чего выдается ошибка.
284
285
286#+name: build_decision_tree
287#+caption: Процедура построения дерева решении
288#+attr_latex: :float nil
289#+begin_src c
290void
291build_decision_tree (void)
292{
293 // compute answers_known[question] and question_order[order]
294 for (int question = 0; question < QUESTION_COUNT; ++question) {
295 for (int decision = 0; decision < DECISION_COUNT; ++decision)
296 answers_known[question] += is_answer_known (decision, question);
297
298 int order = 0;
299 while (order < question &&
300 answers_known[question] <=
301 answers_known[question_queue[order]]) {
302 order += 1;
303 }
304
305 memmove (&question_queue[order + 1],
306 &question_queue[order + 0],
307 (question - order)*sizeof (*question_queue));
308 question_queue[order] = question;
309 }
310
311 // initialize context and run recursive function on it
312 enum decision decisions[DECISION_COUNT];
313 for (int decision = 0; decision < DECISION_COUNT; ++decision)
314 decisions[decision] = DECISION_COUNT - 1 - decision;
315 DYNAMIC_ARRAY_ENSURE_CAPACITY (decision_tree, MAX_DECISION_TREE_NODE_COUNT);
316 DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0});
317 build_decision_tree_impl (decisions, decisions + DECISION_COUNT, 0,
318 &decision_tree.items[0]);
319 DYNAMIC_ARRAY_SHRINK (decision_tree);
320}
321#+end_src
322
323#+name: build_decision_tree_impl
324#+caption: Рекурсивная функция построения дерева решении
325#+attr_latex: :float nil
326#+begin_src c
327static void
328build_decision_tree_impl (enum decision *begin,
329 enum decision *end, int order,
330 DECISION_TREE_NODE node)
331{
332 if (begin + 1 == end) {
333 node->decision = *begin; // INSERT DECISION
334 return;
335 }
336
337 enum question question;
338 for (; order < QUESTION_COUNT; ++order) {
339 question = question_queue[order];
340 enum decision *decision;
341 for (decision = begin; decision < end; ++decision) {
342 if (!is_answer_known (*decision, question)) break;
343 } if (decision == end) break;
344 } ASSERT (order != QUESTION_COUNT && "NOT ENOUGH KNOWLEDGE");
345 node->question = question; // INSERT QUESTION
346
347 enum decision *pivot = begin;
348 for (enum decision *decision = begin; decision < end; ++decision) {
349 if (get_decision_predicate (*decision, question) == ANSWER_NO) {
350 pivot = decision;
351 break;
352 }
353 }
354
355 for (enum decision *head = pivot + 1; head < end; ++head) {
356 if (get_decision_predicate (*head, question) == ANSWER_YES) {
357 enum decision tmp = *pivot;
358 *pivot++ = *head;
359 *head = tmp;
360 }
361 }
362
363 DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0});
364 node->branch_yes = decision_tree.count - 1; // BRANCH YES
365 build_decision_tree_impl (begin, pivot, order + 1,
366 &decision_tree.items[decision_tree.count - 1]);
367 DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0});
368 node->branch_no = decision_tree.count - 1; // BRANCH NO
369 build_decision_tree_impl (pivot, end, order + 1,
370 &decision_tree.items[decision_tree.count - 1]);
371}
372#+end_src
373
374** Текстовый человеко-машинный интерфейс
375Текстовый человеко-машинный интерфейс последовательно запрашивает у
376пользователя ответ на очередной вопрос до нахождения именно единой
377рекомендации, что в данной реализации достигается всегда. Процедура,
378проходящая по дереву в зависимости от ответов пользователя приведена в
379листинге [[question_user]].
380
381#+name: question_user
382#+caption: Функция опроса пользователя
383#+attr_latex: :float nil
384#+begin_src c
385void
386question_user (void)
387{
388 char *line = NULL;
389 size_t line_size = 0;
390 struct decision_tree_node *node = &decision_tree.items[0];
391 while (node->branch_yes && node->branch_no) {
392 enum question question = node->question;
393 printf ("%s\n", question_labels[question]);
394 printf (" [1] %s\n", question_branch_labels[question].answer_yes);
395 printf (" [2] %s\n", question_branch_labels[question].answer_no);
396 for (;;) {
397 printf ("> ");
398 getline (&line, &line_size, stdin);
399 enum answer answer = 0;
400 sscanf (line, "%d", &answer);
401 if (answer < 1 || answer > 2) continue;
402 switch (answer) {
403 case ANSWER_YES: node = &decision_tree.items[node->branch_yes]; break;
404 case ANSWER_NO: node = &decision_tree.items[node->branch_no ]; break;
405 default: break;
406 } break;
407 }
408 } free (line);
409 printf ("Рекомендация: %s\n", decision_labels[node->decision]);
410}
411#+end_src
412
413* Результаты работы
414В качестве результатов работы приведено 3 сеанса представленных в
415листингах [[tails]]-[[kali-linux]], причём каждый из сеансов имеет одинаковый
416заголовок содержащий базу знаний (см. листинг [[header]]).
417
418#+name: header
419#+caption: Загаловка базы знаний экспертной системы
420#+attr_latex: :float nil
421#+begin_src text
422QUESTIONS:
423 1 2 3 4 5 6 7 8 9 A B
4241100000000000000000000: Вы опытный пользователь?
4250011000000000000000000: Вы нуждаетесь в максимальной конфиденциальности?
4260000110000000000000000: Вы хотите установить систему на переносной накопитель?
4270000001100000000000000: Вы хотите управлять сборкой пакетов?
4280000000011000000000000: Вы собираетесь использовать данную систему для взлома?
4290000000000110000000000: Вам нужна поддержка нескольких языков?
4300000000000001100000000: Вы хотите настраивать систему декларативно?
4310000000000000011000000: Вас интересуют фиксированные или вращающиеся выпуски...?
4320000000000000000110000: Вам важно чтобы дистрибутив весил мало?
4330000000000000000001100: Вы хотите описывать настройки на схеме GNU Guile?
4340000000000000000000011: Вы собираетесь играть в компьютерные игры?
435
436DECISIONS:
437 1 2 3 4 5 6 7 8 9 A B
4380101010000010000000000: Tails
4390101010000100000000000: Whonix
4400101100000000000000000: Qubes OS
4410110000100000100000100: GNU Guix
4420110000100000100001000: Nix OS
4430110000100001000000000: Gentoo
4440110001000000001010000: Debian
4450110001000000001100000: Rocky Linux
4460110001000000010010000: Void Linux
4470110001000000010100000: Arch Linux
4481000010001000000000000: Kali Linux
4491000010010000000000000: Puppy Linux
4501000100000000001100001: Pop! OS
4511000100000000001100010: Fedora
4521000100000000010000000: Majaro
453
454decision-tree.dot:0:0: Decision tree is ready for viewing.
455#+end_src
456
457#+name: tails
458#+caption: Пример рекомендации Tails
459#+attr_latex: :float nil
460#+begin_src text
461Вы опытный пользователь?
462 [1] Опытный
463 [2] Неопытный
464>
465> 3
466> 0
467> -1234
468> asdf
469>
470> 1
471Вы нуждаетесь в максимальной конфиденциальности?
472 [1] Нуждаюсь
473 [2] Не нуждаюсь
474> 1
475Вы хотите установить систему на переносной накопитель?
476 [1] Хочу
477 [2] Не хочу
478> 1
479Вам нужна поддержка нескольких языков?
480 [1] Нужна
481 [2] Не нужна
482> 1
483Рекомендация: Tails
484#+end_src
485
486#+name: guix
487#+caption: Пример рекомендации GNU Guix
488#+attr_latex: :float nil
489#+begin_src text
490Вы опытный пользователь?
491 [1] Опытный
492 [2] Неопытный
493> 1
494Вы нуждаетесь в максимальной конфиденциальности?
495 [1] Нуждаюсь
496 [2] Не нуждаюсь
497> 2
498Вы хотите управлять сборкой пакетов?
499 [1] Хочу
500 [2] Не хочу
501> 1
502Вы хотите настраивать систему декларативно?
503 [1] Хочу
504 [2] Не хочу
505> 1
506Вы хотите описывать настройки на схеме GNU Guile?
507 [1] Хочу
508 [2] Не хочу
509> 1
510Рекомендация: GNU Guix
511#+end_src
512
513#+name: kali-linux
514#+caption: Пример рекомендации Kali Linux
515#+attr_latex: :float nil
516#+begin_src text
517Вы опытный пользователь?
518 [1] Опытный
519 [2] Неопытный
520> 2
521Вы хотите установить систему на переносной накопитель?
522 [1] Хочу
523 [2] Не хочу
524> 1
525Вы собираетесь использовать данную систему для взлома?
526 [1] Собираюсь
527 [2] Не собираюсь
528> 1
529Рекомендация: Kali Linux
530#+end_src
531
532* Заключение
533:PROPERTIES:
534:UNNUMBERED: t
535:END:
536В результате работы была реализована экспертная система по
537рекомендации дистрибутива GNU/Linux. Система была представлена в виде
538дерева решений, где узлы --- это вопросы (правила), а листья ---
539рекомендации (факты). Дерево содержит всего 5 ярусов не считая корня,
54015 узлов и 16 листьев.
541
542*Достоинства программы:*
543- Собрать программу тривиально, поскольку она написана на Си с
544 использованием стандартной библиотеки исключительно.
545- Программа умеет работать и с не полным описанием решении, в ситуации
546 где либо нет данных знании, либо они не применяются к данному
547 решению.
548- Программа сама генерирует визуализацию дерева решении в =dot= формате.
549
550*Недостатки программы:*
551- Применение текстового человеко-машинного интерфейса имеет свои
552 недостатки. Для эксплоративного выбора дистрибутива было бы удобнее
553 визуально строить дерево, с возможностью выбрать и другой ответ на
554 вопрос ближе у корня дерева.
555- Нет поддержки промежуточных сообщении к набору ответов на уже
556 заданный вопросы. Такие сообщения бы могли помочь понять
557 пользователю понять на правильном ли он пути, чего удобство бы росло
558 с количеством ярусов дерева решении.
559
560*Масштабирование программы:*
561- При сомнении пользователя в ответе на вопрос можно было бы
562 рассмотреть обе ветки, с помощью их добавления в очередь вопросов.
563- Вместо поддержки строго 2 ответов на вопрос, можно было бы добавить
564 поддержку вариабельного количества, что позволило бы задавать более
565 мощные и интуитивные вопросы.
566
567* Используемая литература
568:PROPERTIES:
569:UNNUMBERED: t
570:END:
5711. Expert system --- Википедия // URL:
572 [[https://en.wikipedia.org/wiki/Expert_system]] (Дата обращения:
573 22.05.2024)
5742. Knowledge base --- Википедия // URL:
575 [[https://en.wikipedia.org/wiki/Knowledge_base]] (Дата обращения:
576 22.05.2024)
5773. Inference engine --- Википедия // URL:
578 [[https://en.wikipedia.org/wiki/Inference_engine]] (Дата обращения:
579 22.05.2024)
580
581# Local Variables:
582# org-confirm-babel-evaluate: nil
583# org-export-async-init-file: "ox-init.el"
584# org-export-in-background: t
585# 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 @@
1SORT - DIVIDE - FIND NEXT DECISION POINT / ABORT NOT ENOUGH KNOWLEDGE
2
31 2 3 4 8 9 7 5 6 A B
4Y Y Y - - - - - Y - - Tails
5Y Y Y - - - - - N - - Whonix
6Y Y N - - - - - - - - Qubes OS
7Y N - Y - - Y - - Y - GNU Guix
8Y N - Y N - Y - - N - Nix OS
9Y N - Y - - N - - - - Gentoo
10Y N - N Y Y - - - - - Debian
11Y N - N Y N - - - - - Rocky Linux
12Y N - N N Y - - - - - Void Linux
13Y N - N N N - - - - - Arch Linux
14
15N - Y - Y - - Y - - - Kali Linux
16N - Y - - N - N - - - Puppy Linux
17
18N - N - Y N - - - - Y Pop! OS
19N - N - Y N - - - - N Fedora
20N - 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 @@
1#+OPTIONS: ':nil *:t -:t ::t <:t H:3 \n:nil ^:{} arch:headline
2#+OPTIONS: author:t broken-links:nil c:nil creator:nil
3#+OPTIONS: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t
4#+OPTIONS: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t
5#+OPTIONS: timestamp:nil title:t toc:t todo:nil |:t
6#+SELECT_TAGS: export
7#+EXCLUDE_TAGS: noexport
8#+CREATOR: Emacs 29.1 (Org mode 9.6.9)
9#+BIBLIOGRAPHY: biblio.bib
10#+CITE_EXPORT: biblatex
11#+LATEX_COMPILER: xelatex
12#+LATEX_CLASS: spbstu-report
13#+LATEX_CLASS_OPTIONS: [12pt]
14#+LATEX_HEADER: \usepackage{enumitem}
15#+LATEX_HEADER: \usepackage{array}
16#+LATEX_HEADER: \newcolumntype{C}{>{$}c<{$}} % math-mode version of "c" column type
17#+LATEX_HEADER: \usepackage{float}
18#+LATEX_HEADER: \usepackage{tikz}
19#+LATEX_HEADER: \usepackage{pgfplots}
20#+LATEX_HEADER: \pgfplotsset{compat=1.18}
21#+LATEX_HEADER: \usepackage[paper=A4,DIV=12]{typearea}
22#+LATEX_HEADER: \usepackage{pdflscape}
23#+LATEX_HEADER: \usepackage{afterpage}
24#+LATEX_HEADER: \usepackage{minted}
25#+LATEX_HEADER: \usemintedstyle{bw}
26#+LATEX_HEADER: \setminted{baselinestretch=1,linenos,breaklines}
27#+LATEX_HEADER: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}}
28#+LATEX_HEADER: \usepackage{algorithm}
29#+LATEX_HEADER: \usepackage{algpseudocode}
30#+LATEX_HEADER: \makeatletter
31#+LATEX_HEADER: \renewcommand{\ALG@name}{Алгоритм}
32#+LATEX_HEADER: \makeatother
33#+LATEX_HEADER: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
34#+LATEX_HEADER: \setmainfont{Times New Roman}
35#+LATEX_HEADER: \setmonofont{Iosevka Term Slab}[Contextuals=AlternateOff]
36#+LATEX_HEADER: \newcommand*{\myref}[2]{\hyperref[{#1}]{{#2}~\ref*{#1}}}
37#+LATEX_HEADER: \newcommand{\hlabel}{\phantomsection\label}
38#+LATEX_HEADER: \newcommand*{\fullref}[1]{\hyperref[{#1}]{\autoref*{#1} \nameref*{#1}}}
39#+LATEX_HEADER: \setlength{\abovecaptionskip}{5pt}
40#+LATEX_HEADER: \setlength{\belowcaptionskip}{0pt}
41#+LATEX_HEADER: \hypersetup{hidelinks}
42#+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 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов]
3
4%
5% Support font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12\LoadClass[a4paper]{gost-7-32}
13
14\RequirePackage{csquotes}
15\RequirePackage{amsmath}
16\RequirePackage{adjustbox}
17\RequirePackage{setspace}
18
19\newcommand{\usection}[1]{\section*{#1}\addcontentsline{toc}{section}{#1}}
20
21\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}}
22\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}}
23\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}}
24\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}}
25\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$}
26\renewcommand{\maketitle}{
27 \begin{titlepage}
28 \begin{center}
29 \vspace{2cm}
30 \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ}
31
32 \normalsize{Федеральное государственное автономное
33 образовательное учреждение высшего образования
34 \enquote{Санкт-Петербургский политехнический университет Петра Великого}}
35
36 \vspace{0.5cm}
37 \normalsize{Институт компьютерных наук и кибербезопасности}
38
39 \normalsize{Высшая школа технологии искусственного интеллекта}
40
41 \normalsize{Направление 02.03.01 Математика и компьютерные науки}
42
43 \vspace{2cm}
44 \LARGE{ОТЧЁТ}
45
46 \normalsize{\@reportof}
47
48 \large{\@subject}
49
50 \large{\textit{\@title}}
51 \end{center}
52
53 \vspace{3cm}
54 \small{
55 \begin{tabular}{lrrl}
56 \!\!\!Студент, & \hspace{2cm} & & \\
57 \!\!\!группы 5130201/20002 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\
58 \!\!\!Преподаватель, & \hspace{2cm} & \\
59 \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\
60 &&\hspace{5cm}
61 \end{tabular}
62 \begin{flushright}
63 \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г.
64 \end{flushright}
65 }
66
67 \vspace*{\fill}
68 \begin{center}
69 \small{Санкт-Петербург, \@date}
70 \end{center}
71 \end{titlepage}
72 \setcounter{page}{2}
73}
diff --git a/manifest.scm b/manifest.scm
new file mode 100644
index 0000000..8943948
--- /dev/null
+++ b/manifest.scm
@@ -0,0 +1,53 @@
1(use-modules (gnu packages base)
2 (gnu packages commencement)
3 (gnu packages tex)
4 (nongnu packages fonts))
5
6(packages->manifest (list
7 gcc-toolchain
8 font-microsoft-times-new-roman
9 texlive-scheme-small
10 texlive-lh
11 texlive-cm
12 texlive-type1cm
13 texlive-ec
14 texlive-wrapfig
15 texlive-adjustbox
16 texlive-graphics
17 texlive-hyperref
18 texlive-latex-fonts
19 texlive-amsfonts
20 texlive-cyrillic
21 texlive-babel-russian
22 texlive-geometry
23 texlive-enumitem
24 texlive-csquotes
25 texlive-float
26 texlive-biblatex
27 texlive-biber
28 texlive-pgfplots
29 texlive-trimspaces
30 texlive-catchfile
31 texlive-hyphen-complete
32 texlive-capt-of
33 texlive-minted
34 texlive-titlesec
35 texlive-titling
36 texlive-scheme-basic
37 texlive-fontspec
38 texlive-beamer
39 texlive-microtype
40 texlive-siunitx
41 texlive-textpos
42 texlive-mathspec
43 texlive-etoolbox
44 texlive-extsizes
45 texlive-cm-super
46 texlive-amsmath
47 texlive-transparent
48 texlive-koma-script
49 texlive-pdflscape
50 texlive-ucs
51 texlive-ulem
52 texlive-algorithms
53 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 @@
1#ifndef INCLUDED_DYNAMIC_ARRAY_H
2#define INCLUDED_DYNAMIC_ARRAY_H
3
4#include "utils.h"
5
6#ifndef DYNAMIC_ARRAY_INIT_CAP
7#define DYNAMIC_ARRAY_INIT_CAP 256
8#endif
9
10#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \
11 ({ \
12 if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \
13 if ((DYNAMIC_ARRAY).capacity == 0) \
14 (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \
15 while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \
16 (DYNAMIC_ARRAY).capacity *= 2; \
17 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
18 (DYNAMIC_ARRAY).capacity * \
19 sizeof (*(DYNAMIC_ARRAY).items)); \
20 ASSERT((DYNAMIC_ARRAY).items); \
21 } \
22 })
23
24#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \
25 ({ \
26 (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \
27 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
28 (DYNAMIC_ARRAY).capacity * \
29 sizeof (*(DYNAMIC_ARRAY).items)); \
30 ASSERT((DYNAMIC_ARRAY).items); \
31 \
32 })
33
34#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \
35 ({ \
36 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \
37 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \
38 })
39
40#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \
41 ({ \
42 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \
43 memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \
44 (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \
45 (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \
46 })
47
48#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; })
49
50#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items)
51
52#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \
53 typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \
54 ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM)
55
56#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 @@
1#include <stdlib.h>
2#include <stdint.h>
3#include <stdio.h>
4#include <stdbool.h>
5
6#include "knowledge-base.h"
7#include "inference-engine.h"
8
9int
10main (void)
11{
12 // TODO(cmmm): auto-rebuild
13 print_knowledge_base ();
14 putchar ('\n');
15 build_decision_tree ();
16 write_decision_tree_in_dot_format ();
17 putchar ('\n');
18 question_user ();
19
20 return EXIT_SUCCESS;
21}
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 @@
1#include "inference-engine.h"
2#include <string.h>
3#include "utils.h"
4#include "dynamic-array.h"
5
6typedef struct decision_tree_node {
7 union {
8 enum question question;
9 enum decision decision;
10 };
11 uint32_t branch_yes;
12 uint32_t branch_no;
13} *DECISION_TREE_NODE;
14
15struct decision_tree {
16 struct decision_tree_node *items;
17 uint32_t count;
18 uint32_t capacity;
19};
20
21#define MAX_DECISION_TREE_NODE_COUNT ((1 << QUESTION_COUNT) - 1)
22
23static struct decision_tree decision_tree = {0};
24
25static int answers_known [QUESTION_COUNT] = {0};
26static int question_queue [QUESTION_COUNT] = {0};
27
28static inline bool
29is_answer_known (enum decision decision, enum question question) {
30 switch (get_decision_predicate (decision, question)) {
31 case ANSWER_YES:
32 case ANSWER_NO:
33 return true;
34 default:
35 return false;
36 }
37}
38
39static void
40build_decision_tree_impl (enum decision *begin,
41 enum decision *end, int order,
42 DECISION_TREE_NODE node)
43{
44 if (begin == end)
45 return;
46
47 if (begin + 1 == end) {
48 // printf ("INSERT DECISION %X\n", *begin);
49 node->decision = *begin;
50 return;
51 }
52
53 enum question question;
54 for (; order < QUESTION_COUNT; ++order) {
55 question = question_queue[order];
56
57 enum decision *decision;
58 for (decision = begin; decision < end; ++decision) {
59 if (!is_answer_known (*decision, question))
60 break;
61 } if (decision == end) break;
62 } ASSERT (order != QUESTION_COUNT && "NOT ENOUGH KNOWLEDGE");
63
64 // printf ("INSERT QUESTION %X\n", question);
65 node->question = question;
66
67 enum decision *pivot = begin;
68 for (enum decision *decision = begin; decision < end; ++decision) {
69 if (get_decision_predicate (*decision, question) == ANSWER_NO) {
70 pivot = decision;
71 break;
72 }
73 }
74
75 for (enum decision *head = pivot + 1; head < end; ++head) {
76 if (get_decision_predicate (*head, question) == ANSWER_YES) {
77 enum decision tmp = *pivot;
78 *pivot++ = *head;
79 *head = tmp;
80 }
81 }
82
83 // for (enum decision *decision = begin; decision < end; ++decision) {
84 // printf ("%s%X\n", decision == pivot ? "->" : " ", *decision + 1);
85 // }
86
87 DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0});
88 // printf ("BRANCH YES TO %X\n", decision_tree.count - 1);
89 node->branch_yes = decision_tree.count - 1;
90 build_decision_tree_impl (begin, pivot, order + 1,
91 &decision_tree.items[decision_tree.count - 1]);
92 DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0});
93 // printf ("BRANCH NO TO %X\n", decision_tree.count - 1);
94 node->branch_no = decision_tree.count - 1;
95 build_decision_tree_impl (pivot, end, order + 1,
96 &decision_tree.items[decision_tree.count - 1]);
97}
98
99void
100build_decision_tree (void)
101{
102 // compute answers_known[question] and question_order[order]
103 for (int question = 0; question < QUESTION_COUNT; ++question) {
104 for (int decision = 0; decision < DECISION_COUNT; ++decision)
105 answers_known[question] += is_answer_known (decision, question);
106
107 int order = 0;
108 while (order < question &&
109 answers_known[question] <=
110 answers_known[question_queue[order]]) {
111 order += 1;
112 }
113
114 memmove (&question_queue[order + 1],
115 &question_queue[order + 0],
116 (question - order)*sizeof (*question_queue));
117 question_queue[order] = question;
118 }
119
120 // initialize context and run recursive function on it
121 enum decision decisions[DECISION_COUNT];
122 for (int decision = 0; decision < DECISION_COUNT; ++decision)
123 decisions[decision] = DECISION_COUNT - 1 - decision;
124 DYNAMIC_ARRAY_ENSURE_CAPACITY (decision_tree, MAX_DECISION_TREE_NODE_COUNT);
125 DYNAMIC_ARRAY_APPEND (decision_tree, (struct decision_tree_node) {0});
126 build_decision_tree_impl (decisions, decisions + DECISION_COUNT, 0,
127 &decision_tree.items[0]);
128 DYNAMIC_ARRAY_SHRINK (decision_tree);
129}
130
131static void
132write_decision_tree_in_dot_format_impl (FILE *file, DECISION_TREE_NODE node)
133{
134 uint32_t node_id = node - decision_tree.items;
135
136 if (node->branch_yes && node->branch_no) {
137 fprintf (file, "\tn%u [label=\"%u: %s\"]\n",
138 node_id, node_id + 1, question_labels[node->question]);
139
140 write_decision_tree_in_dot_format_impl (
141 file, &decision_tree.items[node->branch_yes]);
142 uint32_t branch_yes_id = &decision_tree.items[node->branch_yes] - decision_tree.items;
143 fprintf (file, "\tn%u -> n%u [label=\"%s\"]\n",
144 node_id, branch_yes_id, question_branch_labels[node->question].answer_yes);
145
146 write_decision_tree_in_dot_format_impl (file, &decision_tree.items[node->branch_no]);
147 uint32_t branch_no_id = &decision_tree.items[node->branch_no] - decision_tree.items;
148 fprintf (file, "\tn%u -> n%u [label=\"%s\"]\n", node_id, branch_no_id, question_branch_labels[node->question].answer_no);
149 } else {
150 fprintf (file, "\tn%u [label=\"%u: %s\"]\n", node_id, node_id + 1, decision_labels[node->decision]);
151 }
152}
153
154struct decision_tree_node_stack {
155 struct decision_tree_node **items;
156 uint32_t count;
157 uint32_t capacity;
158};
159
160void
161write_decision_tree_in_dot_format (void)
162{
163 FILE *file = fopen ("decision-tree.dot", "w");
164 if (file == NULL) {
165 fprintf (stderr, "Error opening file!\n");
166 return;
167 }
168
169 fprintf (file, "digraph {\n");
170 fprintf (file, "\trankdir = \"LR\";\n");
171 // write_decision_tree_in_dot_format_impl (file, &decision_tree.items[0]);
172
173 uint32_t node_visual_id = 0;
174 struct decision_tree_node_stack stack1 = {0};
175 struct decision_tree_node_stack stack2 = {0};
176 struct decision_tree_node_stack *front_stack = &stack1;
177 struct decision_tree_node_stack *back_stack = &stack2;
178 DYNAMIC_ARRAY_APPEND (*front_stack, &decision_tree.items[0]);
179 while (front_stack->count) {
180 DYNAMIC_ARRAY_RESET (*back_stack);
181 DYNAMIC_ARRAY_FOREACH (n, *front_stack) {
182 DECISION_TREE_NODE node = *n;
183 uint32_t node_id = node - decision_tree.items;
184
185 if (node->branch_yes && node->branch_no) {
186 fprintf (file, "\tn%u [label=\"%u: %s\"]\n", node_id, ++node_visual_id, question_labels[node->question]);
187
188 DYNAMIC_ARRAY_APPEND (*back_stack, &decision_tree.items[node->branch_yes]);
189 uint32_t branch_yes_id = &decision_tree.items[node->branch_yes] - decision_tree.items;
190 fprintf (file, "\tn%u -> n%u [label=\"%s\"]\n", node_id, branch_yes_id, question_branch_labels[node->question].answer_yes);
191
192 DYNAMIC_ARRAY_APPEND (*back_stack, &decision_tree.items[node->branch_no]);
193 uint32_t branch_no_id = &decision_tree.items[node->branch_no] - decision_tree.items;
194 fprintf (file, "\tn%u -> n%u [label=\"%s\"]\n", node_id, branch_no_id, question_branch_labels[node->question].answer_no);
195 } else {
196 fprintf (file, "\tn%u [label=\"%u: %s\"]\n", node_id, ++node_visual_id, decision_labels[node->decision]);
197 }
198 }
199
200 struct decision_tree_node_stack *tmp = front_stack;
201 front_stack = back_stack;
202 back_stack = tmp;
203 }
204 fprintf (file, "}\n");
205
206 fclose (file);
207
208 puts ("decision-tree.dot:0:0: Decision tree is ready for viewing.");
209}
210
211void
212question_user (void)
213{
214 char *line = NULL;
215 size_t line_size = 0;
216 struct decision_tree_node *node = &decision_tree.items[0];
217 while (node->branch_yes && node->branch_no) {
218 enum question question = node->question;
219 printf ("%s\n", question_labels[question]);
220 printf (" [1] %s\n", question_branch_labels[question].answer_yes);
221 printf (" [2] %s\n", question_branch_labels[question].answer_no);
222
223 enum answer answer = 0;
224 for (;;) {
225 printf ("> ");
226 getline (&line, &line_size, stdin);
227 sscanf (line, "%d", &answer);
228 if (answer < 1 || answer > 2)
229 continue;
230
231 switch (answer) {
232 case ANSWER_YES:
233 node = &decision_tree.items[node->branch_yes];
234 break;
235 case ANSWER_NO:
236 node = &decision_tree.items[node->branch_no];
237 break;
238 default: break;
239 } break;
240 }
241 }
242 free (line);
243 printf ("Рекомендация: %s\n", decision_labels[node->decision]);
244}
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 @@
1#ifndef INCLUDED_INFERENCE_ENGINE_H
2#define INCLUDED_INFERENCE_ENGINE_H
3
4#include "knowledge-base.h"
5
6void build_decision_tree (void);
7void write_decision_tree_in_dot_format (void);
8void question_user (void);
9
10#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 @@
1#include "knowledge-base.h"
2#include <stdio.h>
3
4#define QUESTION(symbol, label, yes, no) \
5[QUESTION_##symbol] = label,
6char *question_labels[QUESTION_COUNT] = {
7 QUESTIONS
8};
9#undef QUESTION
10
11#define QUESTION(symbol, label, yes, no) \
12[QUESTION_##symbol] = { yes, no },
13struct question_branch_labels question_branch_labels[QUESTION_COUNT] = {
14 QUESTIONS
15};
16#undef QUESTION
17
18#define DECISION(symbol, label, ...) [DECISION_##symbol] = label,
19char *decision_labels[DECISION_COUNT] = {
20 DECISIONS
21};
22#undef DECISION
23
24#define DECISION(symbol, label, ...) [DECISION_##symbol] = { __VA_ARGS__ },
25struct decision_predicates decision_predicates[DECISION_COUNT] = {
26 DECISIONS
27};
28#undef DECISION
29
30#define QUESTION(symbol, label, yes, no) \
31 if (QUESTION_##symbol == question) \
32 return decision_predicates[decision].symbol;
33enum answer
34get_decision_predicate (enum decision decision, enum question question)
35{
36 QUESTIONS
37
38 return ANSWER_MALFORMED;
39}
40#undef QUESTION
41
42void
43print_knowledge_base (void)
44{
45 puts ("QUESTIONS:");
46 for (int i = 0; i < QUESTION_COUNT; ++i)
47 printf ("%2X", i + 1);
48 putchar ('\n');
49 for (int i = 0; i < QUESTION_COUNT; ++i) {
50 printf ("%0*b: %s\n", 2*QUESTION_COUNT,
51 (1 << ANSWER_COUNT) - 1 << (QUESTION_COUNT - 1 - i)*ANSWER_COUNT, question_labels[i]);
52 } putchar ('\n');
53
54 puts ("DECISIONS:");
55 for (int i = 0; i < QUESTION_COUNT; ++i)
56 printf ("%2X", i + 1);
57 putchar ('\n');
58 for (int i = 0; i < DECISION_COUNT; ++i) {
59 for (int j = 0; j < QUESTION_COUNT; ++j) {
60 printf ("%0*b", ANSWER_COUNT, get_decision_predicate (i, j));
61 }
62 printf (": %s\n", decision_labels[i]);
63 }
64}
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 @@
1#ifndef INCLUDED_KNOWLEDGE_BASE_H
2#define INCLUDED_KNOWLEDGE_BASE_H
3
4#include <stdlib.h>
5#include <stdio.h>
6#include <stdbool.h>
7#include <stdint.h>
8
9#define QUESTIONS \
10 QUESTION(advanced, "Вы опытный пользователь?", "Опытный", "Неопытный" ) \
11 QUESTION(confidentiality, "Вы нуждаетесь в максимальной конфиденциальности?", "Нуждаюсь", "Не нуждаюсь" ) \
12 QUESTION(usb, "Вы хотите установить систему на переносной накопитель?", "Хочу", "Не хочу" ) \
13 QUESTION(control, "Вы хотите управлять сборкой пакетов?", "Хочу", "Не хочу" ) \
14 QUESTION(hacking, "Вы собираетесь использовать данную систему для взлома?", "Собираюсь", "Не собираюсь") \
15 QUESTION(multilang, "Вам нужна поддержка нескольких языков?", "Нужна", "Не нужна" ) \
16 QUESTION(declarative, "Вы хотите настраивать систему декларативно?", "Хочу", "Не хочу" ) \
17 QUESTION(stability, "Вас интересуют фиксированные или вращающиеся выпуски изменении пакетов?", "Фиксированные", "Вращающиеся" ) \
18 QUESTION(lightweight, "Вам важно чтобы дистрибутив весил мало?", "Важно", "Не важно" ) \
19 QUESTION(scheme, "Вы хотите описывать настройки на схеме GNU Guile?", "Хочу", "Не хочу" ) \
20 QUESTION(games, "Вы собираетесь играть в компьютерные игры?", "Собираюсь", "Не собираюсь")
21
22#define DECISIONS \
23 DECISION(TAILS, "Tails", \
24 .advanced = ANSWER_YES, \
25 .confidentiality = ANSWER_YES, \
26 .usb = ANSWER_YES, \
27 .multilang = ANSWER_YES, \
28 ) \
29 DECISION(WHONIX, "Whonix", \
30 .advanced = ANSWER_YES, \
31 .confidentiality = ANSWER_YES, \
32 .usb = ANSWER_YES, \
33 .multilang = ANSWER_NO, \
34 ) \
35 DECISION(QUBES_OS, "Qubes OS", \
36 .advanced = ANSWER_YES, \
37 .confidentiality = ANSWER_YES, \
38 .usb = ANSWER_NO, \
39 ) \
40 DECISION(GNU_GUIX, "GNU Guix", \
41 .advanced = ANSWER_YES, \
42 .confidentiality = ANSWER_NO, \
43 .control = ANSWER_YES, \
44 .declarative = ANSWER_YES, \
45 .scheme = ANSWER_YES, \
46 ) \
47 DECISION(NIX_OS, "Nix OS", \
48 .advanced = ANSWER_YES, \
49 .confidentiality = ANSWER_NO, \
50 .control = ANSWER_YES, \
51 .declarative = ANSWER_YES, \
52 .scheme = ANSWER_NO, \
53 ) \
54 DECISION(GENTOO, "Gentoo", \
55 .advanced = ANSWER_YES, \
56 .confidentiality = ANSWER_NO, \
57 .control = ANSWER_YES, \
58 .declarative = ANSWER_NO, \
59 ) \
60 DECISION(DEBIAN, "Debian", \
61 .advanced = ANSWER_YES, \
62 .confidentiality = ANSWER_NO, \
63 .control = ANSWER_NO, \
64 .stability = ANSWER_YES, \
65 .lightweight = ANSWER_YES, \
66 ) \
67 DECISION(ROCKY_LINUX, "Rocky Linux", \
68 .advanced = ANSWER_YES, \
69 .confidentiality = ANSWER_NO, \
70 .control = ANSWER_NO, \
71 .stability = ANSWER_YES, \
72 .lightweight = ANSWER_NO, \
73 ) \
74 DECISION(VOID_LINUX, "Void Linux", \
75 .advanced = ANSWER_YES, \
76 .confidentiality = ANSWER_NO, \
77 .control = ANSWER_NO, \
78 .stability = ANSWER_NO, \
79 .lightweight = ANSWER_YES, \
80 ) \
81 DECISION(ARCH_LINUX, "Arch Linux", \
82 .advanced = ANSWER_YES, \
83 .confidentiality = ANSWER_NO, \
84 .control = ANSWER_NO, \
85 .stability = ANSWER_NO, \
86 .lightweight = ANSWER_NO, \
87 ) \
88 DECISION(KALI_LINUX, "Kali Linux", \
89 .advanced = ANSWER_NO, \
90 .usb = ANSWER_YES, \
91 .hacking = ANSWER_YES, \
92 ) \
93 DECISION(PUPPY_LINUX, "Puppy Linux", \
94 .advanced = ANSWER_NO, \
95 .usb = ANSWER_YES, \
96 .hacking = ANSWER_NO, \
97 ) \
98 DECISION(POP_OS, "Pop! OS", \
99 .advanced = ANSWER_NO, \
100 .usb = ANSWER_NO, \
101 .stability = ANSWER_YES, \
102 .lightweight = ANSWER_NO, \
103 .games = ANSWER_YES, \
104 ) \
105 DECISION(FEDORA, "Fedora", \
106 .advanced = ANSWER_NO, \
107 .usb = ANSWER_NO, \
108 .stability = ANSWER_YES, \
109 .lightweight = ANSWER_NO, \
110 .games = ANSWER_NO, \
111 ) \
112 DECISION(MAJARO, "Majaro", \
113 .advanced = ANSWER_NO, \
114 .usb = ANSWER_NO, \
115 .stability = ANSWER_NO, \
116 )
117
118enum answer {
119 ANSWER_UNKNOWN,
120 ANSWER_YES,
121 ANSWER_NO,
122 ANSWER_MALFORMED,
123};
124
125#define ANSWER_COUNT 2
126
127#define QUESTION(symbol, label, yes, no) \
128 QUESTION_##symbol,
129enum question {
130 QUESTIONS
131 QUESTION_COUNT
132};
133#undef QUESTION
134
135#define QUESTION(symbol, label, yes, no) \
136 PREDICATE_Y_##symbol = 1 << __COUNTER__, \
137 PREDICATE_N_##symbol = 1 << __COUNTER__,
138enum predicate {
139 QUESTIONS
140};
141#undef QUESTION
142
143#define DECISION(symbol, label, ...) DECISION_##symbol,
144enum decision {
145 DECISIONS
146 DECISION_COUNT
147};
148#undef DECISION
149
150struct question_branch_labels {
151 char *answer_yes;
152 char *answer_no;
153};
154
155#define QUESTION(symbol, label, yes, no) \
156 enum answer symbol : ANSWER_COUNT;
157struct decision_predicates {
158 QUESTIONS;
159};
160#undef QUESTION
161
162extern char *question_labels[QUESTION_COUNT];
163extern struct question_branch_labels question_branch_labels[QUESTION_COUNT];
164extern char *decision_labels[DECISION_COUNT];
165extern struct decision_predicates decision_predicates[DECISION_COUNT];
166
167extern void print_decision_predicates (struct decision_predicates);
168extern void print_knowledge_base (void);
169extern enum answer get_decision_predicate (enum decision, enum question);
170
171#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 @@
1#ifndef INCLUDED_UTILS_H
2#define INCLUDED_UTILS_H
3
4#include <assert.h>
5#include <stdlib.h>
6
7#define MALLOC malloc
8#define REALLOC realloc
9#define FREE free
10#define ASSERT assert
11
12#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP)
13
14#endif