diff options
| author | 2026-11-09 21:45:29 +0000 | |
|---|---|---|
| committer | 2026-11-10 04:53:46 +0000 | |
| commit | e932f4212d50dfbbf7e7601f1b217793f2a31a87 (patch) | |
| tree | 5ea72f1a5c5a02e6d2cdaf55084b599086fef1ec | |
| download | lab-01-e932f4212d50dfbbf7e7601f1b217793f2a31a87.tar.gz | |
| -rw-r--r-- | .gitignore | 5 | ||||
| -rw-r--r-- | README.org | 31 | ||||
| -rw-r--r-- | UNLICENSE | 24 | ||||
| -rwxr-xr-x | build.sh | 5 | ||||
| -rw-r--r-- | doc/biblio.bib | 7 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-bibliography.sty | 57 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-captions.sty | 30 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-counters.sty | 44 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-headings.sty | 106 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-lists.sty | 17 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-tables.sty | 31 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-toc.sty | 34 | ||||
| -rw-r--r-- | doc/gost/gost-7-32.cls | 62 | ||||
| -rw-r--r-- | doc/ox-init.el | 132 | ||||
| -rw-r--r-- | doc/report.org | 418 | ||||
| -rw-r--r-- | doc/setup.org | 30 | ||||
| -rw-r--r-- | doc/spbstu-report.cls | 79 | ||||
| -rw-r--r-- | src/simple-genetic-algorithm.c | 480 |
18 files changed, 1592 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..49ee6be --- /dev/null +++ b/.gitignore | |||
| @@ -0,0 +1,5 @@ | |||
| 1 | *.html | ||
| 2 | |||
| 3 | *.tex | ||
| 4 | *.dot | ||
| 5 | *.png | ||
diff --git a/README.org b/README.org new file mode 100644 index 0000000..8447fdd --- /dev/null +++ b/README.org | |||
| @@ -0,0 +1,31 @@ | |||
| 1 | #+title: Simple genetic algorithm | ||
| 2 | #+date: 2025H2 | ||
| 3 | |||
| 4 | * Introduction | ||
| 5 | :PROPERTIES: | ||
| 6 | :CUSTOM_ID: introduction | ||
| 7 | :UNNUMBERED: toc | ||
| 8 | :END: | ||
| 9 | The purpose of this work is to study the basic principles of the | ||
| 10 | functioning of genetic algorithms and to acquire practical skills in | ||
| 11 | their implementation. Genetic algorithms are one of the most | ||
| 12 | effective methods for solving optimization problems based on the | ||
| 13 | mechanisms of natural selection and evolution. | ||
| 14 | |||
| 15 | In the course of the work, it was necessary to familiarize oneself | ||
| 16 | with the theoretical foundations of the method, study various ways of | ||
| 17 | encoding chromosomes, and also consider the implementation of the main | ||
| 18 | operators of the genetic algorithm - reproduction, cross-over, and | ||
| 19 | mutation. | ||
| 20 | |||
| 21 | * Documentation | ||
| 22 | :PROPERTIES: | ||
| 23 | :CUSTOM_ID: documentation | ||
| 24 | :END: | ||
| 25 | The exported report can be found at [[https://git.michalec.dev/files/uni/term-07/gen-alg/lab-01/report.pdf][this link]]. | ||
| 26 | |||
| 27 | * Unlicense | ||
| 28 | :PROPERTIES: | ||
| 29 | :CUSTOM_ID: unlicense | ||
| 30 | :END: | ||
| 31 | #+include: UNLICENSE verse | ||
diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE | |||
| @@ -0,0 +1,24 @@ | |||
| 1 | This is free and unencumbered software released into the public domain. | ||
| 2 | |||
| 3 | Anyone is free to copy, modify, publish, use, compile, sell, or | ||
| 4 | distribute this software, either in source code form or as a compiled | ||
| 5 | binary, for any purpose, commercial or non-commercial, and by any | ||
| 6 | means. | ||
| 7 | |||
| 8 | In jurisdictions that recognize copyright laws, the author or authors | ||
| 9 | of this software dedicate any and all copyright interest in the | ||
| 10 | software to the public domain. We make this dedication for the benefit | ||
| 11 | of the public at large and to the detriment of our heirs and | ||
| 12 | successors. We intend this dedication to be an overt act of | ||
| 13 | relinquishment in perpetuity of all present and future rights to this | ||
| 14 | software under copyright law. | ||
| 15 | |||
| 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
| 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ||
| 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | ||
| 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | ||
| 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | ||
| 22 | OTHER DEALINGS IN THE SOFTWARE. | ||
| 23 | |||
| 24 | For more information, please refer to <https://unlicense.org/> | ||
diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..fd8ab1b --- /dev/null +++ b/build.sh | |||
| @@ -0,0 +1,5 @@ | |||
| 1 | #!/bin/sh | ||
| 2 | |||
| 3 | set -xe | ||
| 4 | |||
| 5 | gcc -std=gnu99 -O3 -march=native -lm src/simple-genetic-algorithm.c -o simple-genetic-algorithm | ||
diff --git a/doc/biblio.bib b/doc/biblio.bib new file mode 100644 index 0000000..51443f5 --- /dev/null +++ b/doc/biblio.bib | |||
| @@ -0,0 +1,7 @@ | |||
| 1 | @book{METODA, | ||
| 2 | title = {Методические указания по выполнению лабораторных работ к курсу «Генетические алгоритмы»}, | ||
| 3 | address = {Санкт-Петербург}, | ||
| 4 | publisher = {СПБПУ}, | ||
| 5 | pages = {119}, | ||
| 6 | language = {russian} | ||
| 7 | } | ||
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..79a4620 --- /dev/null +++ b/doc/gost/gost-7-32-captions.sty | |||
| @@ -0,0 +1,30 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{caption} | ||
| 4 | \RequirePackage{subcaption} | ||
| 5 | \RequirePackage{capt-of} | ||
| 6 | |||
| 7 | % | ||
| 8 | % Table caption aligned to the left with dash as a separator | ||
| 9 | % | ||
| 10 | \captionsetup[table]{labelsep=endash, skip=0.5em, justification=centering, singlelinecheck=off} | ||
| 11 | |||
| 12 | % | ||
| 13 | % Dash as separator in figure caption and centering | ||
| 14 | % | ||
| 15 | \captionsetup[figure]{labelsep=endash, justification=centering} | ||
| 16 | |||
| 17 | % | ||
| 18 | % Listing caption | ||
| 19 | % | ||
| 20 | \captionsetup[listing]{labelsep=endash, skip=0.5em, singlelinecheck=off, position=above} | ||
| 21 | |||
| 22 | \addto\captionsrussian{\renewcommand{\figurename}{Рис.}} | ||
| 23 | \addto\captionsrussian{\captionsetup[listing]{name=Рис.}} | ||
| 24 | \makeatletter | ||
| 25 | \AtBeginDocument{% | ||
| 26 | \let\c@figure\c@listing | ||
| 27 | \let\thefigure\thelisting | ||
| 28 | \let\ftype@listing\ftype@figure | ||
| 29 | } | ||
| 30 | \makeatother | ||
diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty new file mode 100644 index 0000000..ee95480 --- /dev/null +++ b/doc/gost/gost-7-32-counters.sty | |||
| @@ -0,0 +1,44 @@ | |||
| 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 | ||
| 38 | |||
| 39 | % Increment figure counter when using lstlisting | ||
| 40 | % \let\oldlstlisting\lstlisting | ||
| 41 | % \renewcommand{\lstlisting}[1][]{% | ||
| 42 | % \refstepcounter{figure} | ||
| 43 | % \oldlstlisting[#1] | ||
| 44 | % } | ||
diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty new file mode 100644 index 0000000..033f4a8 --- /dev/null +++ b/doc/gost/gost-7-32-headings.sty | |||
| @@ -0,0 +1,106 @@ | |||
| 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]{\centering\large\setstretch{1}\bfseries}{\thesection}{0.5em}{} | ||
| 13 | \titlespacing*{\section}{0cm}{0cm}{0.5cm} | ||
| 14 | \newcommand{\sectionbreak}{\clearpage} | ||
| 15 | |||
| 16 | \titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{} | ||
| 17 | \titlespacing{\subsection}{0cm}{0.5cm}{0.5cm} | ||
| 18 | |||
| 19 | \titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent] | ||
| 20 | \titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm} | ||
| 21 | |||
| 22 | \makeatletter | ||
| 23 | \let\oldsection\section | ||
| 24 | \newcommand{\@sectionnostar}[1]{\phantomsection\oldsection*{#1}\addcontentsline{toc}{section}{#1}} | ||
| 25 | \newcommand{\@sectionstar}[1]{\oldsection{#1}} | ||
| 26 | \renewcommand{\section}{\sectionbreak\@ifstar{\@sectionnostar}{\@sectionstar}} | ||
| 27 | \makeatother | ||
| 28 | |||
| 29 | % | ||
| 30 | % Make special headings, that have their own formatting rules: | ||
| 31 | % - centered | ||
| 32 | % - all-caps | ||
| 33 | % - bold | ||
| 34 | % | ||
| 35 | % Only three of them must appear in TOC: introduction, conclusion and references | ||
| 36 | % | ||
| 37 | \newcommand{\introduction}{ | ||
| 38 | \addcontentsline{toc}{section}{ВВЕДЕНИЕ} | ||
| 39 | \begin{center} | ||
| 40 | \bfseries\large | ||
| 41 | ВВЕДЕНИЕ | ||
| 42 | \end{center} | ||
| 43 | } | ||
| 44 | |||
| 45 | \newcommand{\conclusion}{ | ||
| 46 | \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ} | ||
| 47 | \begin{center} | ||
| 48 | \bfseries\large | ||
| 49 | ЗАКЛЮЧЕНИЕ | ||
| 50 | \end{center} | ||
| 51 | } | ||
| 52 | |||
| 53 | \newcommand{\references}{ | ||
| 54 | \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ} | ||
| 55 | \begin{center} | ||
| 56 | \bfseries\large | ||
| 57 | СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ | ||
| 58 | \end{center} | ||
| 59 | } | ||
| 60 | |||
| 61 | \newcommand{\essay}{ | ||
| 62 | \begin{center} | ||
| 63 | \bfseries\large | ||
| 64 | РЕФЕРАТ | ||
| 65 | \end{center} | ||
| 66 | } | ||
| 67 | |||
| 68 | \newcommand{\definitions}{ | ||
| 69 | \begin{center} | ||
| 70 | \bfseries\large | ||
| 71 | ОПРЕДЕЛЕНИЯ | ||
| 72 | \end{center} | ||
| 73 | } | ||
| 74 | |||
| 75 | \newcommand{\abbreviations}{ | ||
| 76 | \begin{center} | ||
| 77 | \bfseries\large | ||
| 78 | ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ | ||
| 79 | \end{center} | ||
| 80 | } | ||
| 81 | |||
| 82 | \newcommand{\defsabbrs}{ | ||
| 83 | \begin{center} | ||
| 84 | \bfseries\large | ||
| 85 | ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ | ||
| 86 | \end{center} | ||
| 87 | } | ||
| 88 | |||
| 89 | % | ||
| 90 | % Appendices headings. Appendices have autoincrementing number, | ||
| 91 | % that is represented with russian letter. | ||
| 92 | % This heading must appear in TOC | ||
| 93 | % | ||
| 94 | \newcounter{appendixcnt} | ||
| 95 | \setcounter{appendixcnt}{1} | ||
| 96 | |||
| 97 | \renewcommand{\appendix}[1]{ | ||
| 98 | \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1} | ||
| 99 | \begin{center} | ||
| 100 | \bfseries\large | ||
| 101 | ПРИЛОЖЕНИЕ \AlphRus{appendixcnt} | ||
| 102 | |||
| 103 | #1 | ||
| 104 | \end{center} | ||
| 105 | \stepcounter{appendixcnt} | ||
| 106 | } | ||
diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty new file mode 100644 index 0000000..6f41980 --- /dev/null +++ b/doc/gost/gost-7-32-lists.sty | |||
| @@ -0,0 +1,17 @@ | |||
| 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 | \setlist[itemize, 3]{label=\bullet} | ||
| 12 | |||
| 13 | \setlist[enumerate, 2]{label=\alphRus*)} | ||
| 14 | |||
| 15 | \setlist[1]{wide=\parindent} | ||
| 16 | \setlist[2]{wide=2\parindent, leftmargin=\parindent} | ||
| 17 | \setlist[3]{wide=2\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..c3954c3 --- /dev/null +++ b/doc/gost/gost-7-32-tables.sty | |||
| @@ -0,0 +1,31 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{booktabs} | ||
| 4 | \RequirePackage{xltabular} | ||
| 5 | \renewcommand\tabularxcolumn[1]{m{#1}} % for vertical centering text | ||
| 6 | |||
| 7 | % | ||
| 8 | % Center-aligned column with automatic width | ||
| 9 | % | ||
| 10 | \newcolumntype{C}{>{\centering\arraybackslash}X} | ||
| 11 | |||
| 12 | % | ||
| 13 | % Right-aligned column with automatic width | ||
| 14 | % | ||
| 15 | \newcolumntype{R}{>{\raggedleft\arraybackslash}X} | ||
| 16 | |||
| 17 | % | ||
| 18 | % Table with designations | ||
| 19 | % | ||
| 20 | \newenvironment{designations}{ | ||
| 21 | \noindent | ||
| 22 | \tabularx{\textwidth}{@{} | ||
| 23 | >{\raggedright \arraybackslash \hsize=0.25\hsize}X | ||
| 24 | >{\centering \arraybackslash \hsize=0.05\hsize}X | ||
| 25 | >{\arraybackslash \hsize=0.70\hsize}X | ||
| 26 | } | ||
| 27 | }{ | ||
| 28 | \endtabularx | ||
| 29 | } | ||
| 30 | |||
| 31 | \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..328079d --- /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 | hidelinks | ||
| 15 | ]{hyperref} | ||
| 16 | |||
| 17 | % | ||
| 18 | % Set custom font styles | ||
| 19 | % | ||
| 20 | \renewcommand{\cftsecfont}{\normalfont} | ||
| 21 | \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} | ||
| 22 | \renewcommand{\cftsecpagefont}{\normalsize} | ||
| 23 | \renewcommand{\cftaftertoctitle}{\hfill\hfill} | ||
| 24 | \renewcommand{\cfttoctitlefont}{\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..efbe9d8 --- /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 | \singlespacing % or \setstretch{1} | ||
| 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..47ef892 --- /dev/null +++ b/doc/ox-init.el | |||
| @@ -0,0 +1,132 @@ | |||
| 1 | ;;; ox-init.el --- 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 | |||
| 8 | (require 'ox-extra) | ||
| 9 | (ox-extras-activate '(ignore-headlines)) | ||
| 10 | |||
| 11 | (setq org-latex-src-block-backend 'minted) | ||
| 12 | |||
| 13 | (require 'oc-bibtex) | ||
| 14 | (setq org-latex-bib-compiler "biber") | ||
| 15 | |||
| 16 | (setq org-latex-remove-logfiles nil) | ||
| 17 | |||
| 18 | (setq org-export-default-language "ru") | ||
| 19 | |||
| 20 | (setq org-latex-default-packages-alist nil) | ||
| 21 | |||
| 22 | (setq org-latex-tables-booktabs t) | ||
| 23 | |||
| 24 | (setq org-latex-caption-above '(table)) | ||
| 25 | |||
| 26 | (setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f" | ||
| 27 | "%bib %b" | ||
| 28 | "%latex -shell-escape -interaction nonstopmode -output-directory %o %f")) | ||
| 29 | (setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}" | ||
| 30 | ("\\section{%s}" . "\\section*{%s}") | ||
| 31 | ("\\subsection{%s}" . "\\subsection*{%s}") | ||
| 32 | ("\\subsubsection{%s}" . "\\subsubsection*{%s}") | ||
| 33 | ("\\paragraph{%s}" . "\\paragraph*{%s}") | ||
| 34 | ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) | ||
| 35 | |||
| 36 | ;; TODO(cmmm): add \addlinespace between rows which don't have 'rule | ||
| 37 | ;; TODO(cmmm): wrap head columns in something like: | ||
| 38 | ;; \multicolumn{1}{c}{\bold head1} | ||
| 39 | (defun cmmm-org-latex-table-row (table-row contents info) | ||
| 40 | "Transcode a TABLE-ROW element from Org to LaTeX. | ||
| 41 | CONTENTS is the contents of the row. INFO is a plist used as | ||
| 42 | a communication channel." | ||
| 43 | (let* ((attr (org-export-read-attribute :attr_latex | ||
| 44 | (org-element-parent table-row))) | ||
| 45 | (booktabsp (if (plist-member attr :booktabs) (plist-get attr :booktabs) | ||
| 46 | (plist-get info :latex-tables-booktabs))) | ||
| 47 | (longtablep | ||
| 48 | (member (or (plist-get attr :environment) | ||
| 49 | (plist-get info :latex-default-table-environment)) | ||
| 50 | ;; adding xltabular is the only change | ||
| 51 | '("longtable" "longtabu" "xltabular")))) | ||
| 52 | (if (eq (org-element-property :type table-row) 'rule) | ||
| 53 | (cond | ||
| 54 | ((not booktabsp) "\\hline") | ||
| 55 | ((not (org-export-get-previous-element table-row info)) "\\toprule") | ||
| 56 | ((not (org-export-get-next-element table-row info)) "\\bottomrule") | ||
| 57 | ((and longtablep | ||
| 58 | (org-export-table-row-ends-header-p | ||
| 59 | (org-export-get-previous-element table-row info) info)) | ||
| 60 | "") | ||
| 61 | (t "\\midrule")) | ||
| 62 | ;; Memorize table header in case it is multiline. We need this | ||
| 63 | ;; information to define contents before "\\endhead" in longtable environments. | ||
| 64 | (when (org-export-table-row-in-header-p table-row info) | ||
| 65 | (let ((table-head-cache (plist-get info :org-latex-table-head-cache))) | ||
| 66 | (unless (hash-table-p table-head-cache) | ||
| 67 | (setq table-head-cache (make-hash-table :test #'eq)) | ||
| 68 | (plist-put info :org-latex-table-head-cache table-head-cache)) | ||
| 69 | (if-let* ((head-contents (gethash (org-element-parent table-row) table-head-cache))) | ||
| 70 | (puthash (org-element-parent table-row) (concat head-contents "\\\\\n" contents) | ||
| 71 | table-head-cache) | ||
| 72 | (puthash (org-element-parent table-row) contents table-head-cache)))) | ||
| 73 | ;; Return LaTeX string as the transcoder. | ||
| 74 | (concat | ||
| 75 | ;; When BOOKTABS are activated enforce top-rule even when no | ||
| 76 | ;; hline was specifically marked. | ||
| 77 | (and booktabsp (not (org-export-get-previous-element table-row info)) | ||
| 78 | "\\toprule\n") | ||
| 79 | contents "\\\\\n" | ||
| 80 | (cond | ||
| 81 | ;; Special case for long tables. Define header and footers. | ||
| 82 | ((and longtablep (org-export-table-row-ends-header-p table-row info)) | ||
| 83 | (let ((columns (cdr (org-export-table-dimensions | ||
| 84 | (org-element-lineage table-row 'table) info)))) | ||
| 85 | (format "%s | ||
| 86 | \\endfirsthead | ||
| 87 | \\multicolumn{%d}{l}{%s} \\\\ | ||
| 88 | %s | ||
| 89 | %s \\\\\n | ||
| 90 | %s | ||
| 91 | \\endhead | ||
| 92 | %s\\multicolumn{%d}{r}{%s} \\\\ | ||
| 93 | \\endfoot | ||
| 94 | \\endlastfoot" | ||
| 95 | (if booktabsp "\\midrule" "\\hline") | ||
| 96 | columns | ||
| 97 | (org-latex--translate "Continued from previous page" info) | ||
| 98 | (cond | ||
| 99 | ((not (org-export-table-row-starts-header-p table-row info)) | ||
| 100 | "") | ||
| 101 | (booktabsp "\\toprule\n") | ||
| 102 | (t "\\hline\n")) | ||
| 103 | (gethash (org-element-parent table-row) (plist-get info :org-latex-table-head-cache)) | ||
| 104 | (if booktabsp "\\midrule" "\\hline") | ||
| 105 | (if booktabsp "\\midrule" "\\hline") | ||
| 106 | columns | ||
| 107 | (org-latex--translate "Continued on next page" info)))) | ||
| 108 | ;; When BOOKTABS are activated enforce bottom rule even when | ||
| 109 | ;; no hline was specifically marked. | ||
| 110 | ((and booktabsp (not (org-export-get-next-element table-row info))) | ||
| 111 | "\\bottomrule")))))) | ||
| 112 | (advice-add 'org-latex-table-row :override 'cmmm-org-latex-table-row) | ||
| 113 | |||
| 114 | (defun cmmm-org-export-translate (s encoding info) | ||
| 115 | "Translate string S according to language specification. | ||
| 116 | |||
| 117 | ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1' | ||
| 118 | and `:utf-8'. INFO is a plist used as a communication channel. | ||
| 119 | |||
| 120 | Translation depends on `:language' property. Return the | ||
| 121 | translated string. If no translation is found, try to fall back | ||
| 122 | to `:default' encoding. If it fails, return S." | ||
| 123 | (let* ((lang (plist-get info :language)) | ||
| 124 | (translations (cdr (assoc lang | ||
| 125 | (cdr (assoc s org-export-dictionary)))))) | ||
| 126 | (or (plist-get translations encoding) | ||
| 127 | (plist-get translations :default) | ||
| 128 | (plist-get translations :utf-8) | ||
| 129 | s))) | ||
| 130 | (advice-add 'org-export-translate :override 'cmmm-org-export-translate) | ||
| 131 | |||
| 132 | ;;; ox-init.el ends here | ||
diff --git a/doc/report.org b/doc/report.org new file mode 100644 index 0000000..6788e20 --- /dev/null +++ b/doc/report.org | |||
| @@ -0,0 +1,418 @@ | |||
| 1 | #+title: Простой генетический алгоритм | ||
| 2 | #+subtitle: Вариант 14 | ||
| 3 | #+author: Михалец М. | ||
| 4 | #+date: 2025 | ||
| 5 | #+latex_header: \reportof{О ВЫПОЛНЕНИИ ПРАКТИЧЕСКОЙ РАБОТЫ №1} | ||
| 6 | #+latex_header: \subject{по дисциплине «Генетические алгоритмы»} | ||
| 7 | #+latex_header: \university{Федеральное государственное автономное образовательное учреждение высшего образования \enquote{Санкт-Петербургский политехнический университет Петра Великого}} | ||
| 8 | #+latex_header: \institute{Институт компьютерных наук и кибербезопасности} | ||
| 9 | #+latex_header: \school{Высшая школа технологии искусственного интеллекта} | ||
| 10 | #+latex_header: \direction{02.03.01 Математика и компьютерные науки} | ||
| 11 | #+latex_header: \reviewertitle{}\reviewer{Большаков А.А.} | ||
| 12 | #+latex_header: \city{Санкт-Петербург} | ||
| 13 | |||
| 14 | #+setupfile: setup.org | ||
| 15 | #+latex: \sloppy | ||
| 16 | |||
| 17 | * ВВЕДЕНИЕ | ||
| 18 | :PROPERTIES: | ||
| 19 | :UNNUMBERED: t | ||
| 20 | :END: | ||
| 21 | Цель данной работы --- изучение основных принципов функционирования | ||
| 22 | генетических алгоритмов и приобретение практических навыков их | ||
| 23 | реализации. Генетические алгоритмы представляют собой один из | ||
| 24 | эффективных методов решения задач оптимизации, основанный на | ||
| 25 | механизмах естественного отбора и эволюции. | ||
| 26 | |||
| 27 | В процессе выполнения работы необходимо было ознакомиться с | ||
| 28 | теоретическими основами метода, изучить различные способы кодирования | ||
| 29 | хромосом, а также рассмотреть реализацию основных операторов | ||
| 30 | генетического алгоритма --- репродукции, кроссинговера и мутации. | ||
| 31 | Итогом работы является выполнение индивидуального задания на языке | ||
| 32 | высокого уровня Си с детальными комментариями и анализом полученных | ||
| 33 | результатов. | ||
| 34 | |||
| 35 | * Постановка задачи | ||
| 36 | #+latex: \noindent | ||
| 37 | В данной работе были поставлены следующие задачи: | ||
| 38 | - Изучить теоретический материал; | ||
| 39 | - Ознакомиться с вариантами кодирования хромосомы; | ||
| 40 | - Рассмотреть способы выполнения операторов репродукции, кроссинговера | ||
| 41 | и мутации; | ||
| 42 | - Выполнить индивидуальное задание на любом языке высокого уровня с | ||
| 43 | необходимыми комментариями и выводами | ||
| 44 | |||
| 45 | #+latex: \bigbreak\noindent | ||
| 46 | *Индивидуальное задание вариант 14:* | ||
| 47 | |||
| 48 | #+latex: \bigbreak | ||
| 49 | *Дано:* Функция одной переменной \(f(x) = \frac{\cos(x - 0.5)}{|x|}\); | ||
| 50 | промежуток нахождения решения \(x \in [-10, 10]\) | ||
| 51 | (см. Рис. [[fitness-function]]). | ||
| 52 | |||
| 53 | #+latex: \bigbreak | ||
| 54 | *Требуется:* | ||
| 55 | 1. Разработать простой генетический алгоритм для нахождения минимума | ||
| 56 | данной функции в заданном промежутке; | ||
| 57 | 2. Исследовать зависимость времени поиска, числа поколений (генераций) | ||
| 58 | и точности нахождения решения от числа особей в популяции и | ||
| 59 | вероятности кроссинговера и мутации; | ||
| 60 | 3. Вывести на экран график функции с указанием найденного экстремума | ||
| 61 | для каждого поколения; | ||
| 62 | 4. Сравнить найденное решение с действительным. | ||
| 63 | |||
| 64 | #+latex: \bigbreak | ||
| 65 | *Ограничения:* | ||
| 66 | 1. \(\min f(x) = \frac{\cos(x - 0.5)}{|x|} \approx -0.41101\) | ||
| 67 | 2. Точность решения составляет 3 знака после запятой. | ||
| 68 | |||
| 69 | #+name: fitness-function | ||
| 70 | #+caption: График целевой функции | ||
| 71 | #+attr_latex: :options [H] | ||
| 72 | #+begin_figure | ||
| 73 | \centering | ||
| 74 | \input{res/fitness-function} | ||
| 75 | #+end_figure | ||
| 76 | |||
| 77 | * Теоретические сведения | ||
| 78 | Генетические алгоритмы (ГА) используют принципы и терминологию, | ||
| 79 | заимствованные у биологической науки --- генетики. В ГА каждая особь | ||
| 80 | представляет потенциальное решение некоторой проблемы. В классическом | ||
| 81 | ГА особь кодируется строкой двоичных символов – хромосомой, каждый бит | ||
| 82 | которой называется геном. Множество особей – потенциальных решений | ||
| 83 | составляет популяцию. Поиск (суб)оптимального решения проблемы | ||
| 84 | выполняется в процессе эволюции популяции --- последовательного | ||
| 85 | преобразования одного конечного множества решений в другое с помощью | ||
| 86 | генетических операторов репродукции, кроссинговера и мутации. | ||
| 87 | |||
| 88 | Предварительно простой ГА случайным образом генерирует начальную | ||
| 89 | популяцию стрингов (хромосом). Затем алгоритм генерирует следующее | ||
| 90 | поколение (популяцию), с помощью трех основных генетических | ||
| 91 | операторов: | ||
| 92 | 1. Оператор репродукции (ОР); | ||
| 93 | 2. Оператор скрещивания (кроссинговера, ОК); | ||
| 94 | 3. Оператор мутации (ОМ). | ||
| 95 | |||
| 96 | ГА работает до тех пор, пока не будет выполнено заданное количество | ||
| 97 | поколений (итераций) процесса эволюции или на некоторой генерации | ||
| 98 | будет получено заданное качество или вследствие преждевременной | ||
| 99 | сходимости при попадании в некоторый локальный оптимум. На | ||
| 100 | Рис. [[simple-genetic-algorithm]] представлен простой генетический алгоритм. | ||
| 101 | |||
| 102 | #+name: simple-genetic-algorithm | ||
| 103 | #+caption: Простой генетический алгоритм | ||
| 104 | #+attr_latex: :options [H] :height .55\textheight | ||
| 105 | [[./res/simple-genetic-algorithm.png]] | ||
| 106 | |||
| 107 | ** Основная терминология в генетических алгоритмах | ||
| 108 | /Ген/ --- элементарный код в хромосоме \(s_i\), называемый также знаком | ||
| 109 | или детектором (в классическом ГА \(s_i = 0, 1\)). | ||
| 110 | |||
| 111 | /Хромосома/ --- упорядоченная последовательность генов в виде | ||
| 112 | закодированной структуры данных \(S = (s_1, s_2, \ldots, s_n)\), | ||
| 113 | определяющая решение (в простейшем случае двоичная последовательность | ||
| 114 | --- строка, где \(s_i = 0, 1\)). | ||
| 115 | |||
| 116 | /Локус/ --- местоположение (позиция, номер бита) данного гена в | ||
| 117 | хромосоме. | ||
| 118 | |||
| 119 | /Аллель/ --- значение, которое принимает данный ген (например, 0 или 1). | ||
| 120 | |||
| 121 | /Особь/ --- одно потенциальное решение задачи (представляемое | ||
| 122 | хромосомой). | ||
| 123 | |||
| 124 | /Популяция/ --- множество особей (хромосом), представляющих | ||
| 125 | потенциальные решения. | ||
| 126 | |||
| 127 | /Поколение/ --- текущая популяция ГА на данной итерации алгоритма. | ||
| 128 | |||
| 129 | /Генотип/ --- набор хромосом данной особи. В популяции могут | ||
| 130 | использоваться как отдельные хромосомы, так и целые генотипы. | ||
| 131 | |||
| 132 | /Генофонд/ --- множество всех возможных генотипов. | ||
| 133 | |||
| 134 | /Фенотип/ --- набор значений, соответствующий данному генотипу. Это | ||
| 135 | декодированное множество параметров задачи (например, десятичное | ||
| 136 | значение \(x\), соответствующее двоичному коду). | ||
| 137 | |||
| 138 | /Размер популяции \(N\)/ --- число особей в популяции. | ||
| 139 | |||
| 140 | /Число поколений/ --- количество итераций, в течение которых | ||
| 141 | производится поиск. | ||
| 142 | |||
| 143 | /Селекция/ --- совокупность правил, определяющих выживание особей на | ||
| 144 | основе значений целевой функции. | ||
| 145 | |||
| 146 | /Эволюция популяции/ --- чередование поколений, в которых хромосомы | ||
| 147 | изменяют свои признаки, чтобы каждая новая популяция лучше | ||
| 148 | приспосабливалась к среде. | ||
| 149 | |||
| 150 | /Фитнесс-функция/ --- функция полезности, определяющая меру | ||
| 151 | приспособленности особи. В задачах оптимизации она совпадает с | ||
| 152 | целевой функцией или описывает близость к оптимальному решению. | ||
| 153 | |||
| 154 | ** Генетические операторы | ||
| 155 | *** Оператор репродукции | ||
| 156 | /Репродукция/ --- процесс копирования хромосом в промежуточную популяцию | ||
| 157 | для дальнейшего «размножения» в соответствии со значениями | ||
| 158 | фитнесс-функции. В данной работе рассматривается метод колеса | ||
| 159 | рулетки. Каждой хромосоме соответствует сектор, пропорциональный | ||
| 160 | значению фитнесс-функции. Хромосомы с большим значением имеют больше | ||
| 161 | шансов попасть в следующее поколение. | ||
| 162 | |||
| 163 | #+caption: Колесо рулетки | ||
| 164 | #+attr_latex: :width .35\textwidth | ||
| 165 | [[./res/pie.png]] | ||
| 166 | |||
| 167 | *** Оператор скрещивания (кроссинговера) | ||
| 168 | Одноточечный кроссинговер выполняется следующим образом: | ||
| 169 | 1. Из промежуточной популяции выбираются две хромосомы (родители). | ||
| 170 | 2. Определяется случайная точка скрещивания \(k \in [1, n - 1]\), где | ||
| 171 | \(n\) -- длина хромосомы. | ||
| 172 | #+attr_latex: :width .35\textwidth | ||
| 173 | [[./res/crossover-1.png]] | ||
| 174 | 3. Две новые хромосомы (потомки) формируются путём обмена подстрок | ||
| 175 | после точки \(k\). | ||
| 176 | #+attr_latex: :width .2\textwidth | ||
| 177 | [[./res/crossover-2.png]] | ||
| 178 | |||
| 179 | *** Оператор мутации | ||
| 180 | Мутация применяется с малой вероятностью $P_m \approx 0.001$: | ||
| 181 | 1. В хромосоме \(A = a_1a_2 \ldots a_n\) выбирается случайная позиция \(k\). | ||
| 182 | 2. Ген \(a_k\) инвертируется: \(a_k' = \lnot a_k\). | ||
| 183 | |||
| 184 | * Особенности реализации | ||
| 185 | В рамках работы создана программа =simple-genetic-algorithm.c= для | ||
| 186 | экспериментов с простым генетическим алгоритмом (ГА) на одной | ||
| 187 | переменной. Она позволяет легко управлять параметрами эксперимента, | ||
| 188 | брать статистику о времени выполнения, рисовать графики генерации и | ||
| 189 | экспортировать таблицы. | ||
| 190 | |||
| 191 | - *Кодирование особей:* каждая хромосома --- целочисленная беззнаковая | ||
| 192 | переменная с ограничением на количество используемых битов. | ||
| 193 | Декодирование --- линейное в \([-10, 10]\). Для точности | ||
| 194 | \(10^{-3}\) для данного декодирования необходимо использовать хотя | ||
| 195 | бы 15 бит, которые дают шаг дискретизации \approx 0.0006. Длина | ||
| 196 | хромосомы была округлена до 16. За это отвечают: | ||
| 197 | - ~#define CHROMOSOME_SIZE 16~ | ||
| 198 | - ~uint8_t bits_for_precision (int digits_after_decimal);~ | ||
| 199 | - ~double decode (chromosome gene);~ | ||
| 200 | - *Фитнесс и минимум/максимум:* целевая функция передаётся параметром. | ||
| 201 | Для режима /минимизации/ используется внутреннее преобразование при | ||
| 202 | селекции (инвертирование знака/сдвиг), что позволяет единообразно | ||
| 203 | применять рулетку при отрицательных значениях. За это отвечают: | ||
| 204 | - ~#define MINMAX -1~ | ||
| 205 | - ~bool measure_fitness (size_t population_size);~ | ||
| 206 | - *Селекция (рулетка):* вероятности нормируются после сдвига на | ||
| 207 | минимальное значение в поколении (устойчиво к отрицательным | ||
| 208 | фитнессам). Функция: ~void fitness_proportionate_selection (size_t | ||
| 209 | population_size)~. | ||
| 210 | - *Кроссинговер:* одноточечный, попарно по перемешанной популяции. При | ||
| 211 | нечётном размере последняя особь скрещивается со случайной другой | ||
| 212 | особью (возможно повторное участие в кроссинговере одной из особей). | ||
| 213 | Пары скрещиваются с вероятностью \(P_c\), иначе родители добавляются | ||
| 214 | в новую популяцию без изменений. Функция: ~void crossover (size_t | ||
| 215 | population_size, double probability)~ | ||
| 216 | - *Мутация:* с вероятностью \(P_m\) /на хромосому/ инвертируется ровно | ||
| 217 | один случайный бит. Функция: ~void mutation (size_t population_size, | ||
| 218 | double probability)~. | ||
| 219 | - *Критерий остановки:* поддержаны критерии по дисперсии значений | ||
| 220 | фитнесс функции в популяции и по среднему значению (настраиваемые | ||
| 221 | пороги), но для экспериментов в данной лабораторной работе | ||
| 222 | используются критерий по лучшему значению и по достижению популяцией | ||
| 223 | максимального возраста в 200 поколений. Проверка выполняется внутри | ||
| 224 | функции: ~measure_fitness~. | ||
| 225 | - *Визуализация:* снимок поколения включает график целевой функции, | ||
| 226 | точки всей текущей популяции, лучшую особь (выделена зелёным | ||
| 227 | цветом), а также историю лучших по предыдущим поколениям (выделены | ||
| 228 | жёлтым цветом). Функция: ~void plot (const char *output, size_t | ||
| 229 | population_size, size_t generation);~. | ||
| 230 | - *Измерение времени:* Выполняются только необходимые операции, пока не | ||
| 231 | достигнут критерии остановки. Функция: ~struct measurement | ||
| 232 | run_experiment__measure (size_t population_size, double | ||
| 233 | probability_crossover, double probability_mutation)~ | ||
| 234 | |||
| 235 | * Результаты работы | ||
| 236 | На Рис. [[generation-first]]-[[generation-last]] представлены результаты работы генетического алгоритма со следующими параметрами: | ||
| 237 | - \(N = 25\) --- размер популяции. | ||
| 238 | - \(P_c = 0.5\) --- вероятность кроссинговера. | ||
| 239 | - \(P_m = 0.1\) --- вероятность мутации. | ||
| 240 | - \(-0.411\) --- минимальное значение фитнесс функции по популяции для | ||
| 241 | остановки алгоритма. Настоящий минимум функции равен примерно | ||
| 242 | \(-0.41101\). | ||
| 243 | |||
| 244 | С каждым поколением точность найденного минимума становится выше. На | ||
| 245 | втором поколении популяция еще распределена по всей области поиска | ||
| 246 | решения. На поколении 8 особи «конденсируются» вблизи двух лучших | ||
| 247 | минимумов, а с поколения 11 вблизи глобального минимума. На поколении | ||
| 248 | 13 достигается заданная точность нахождения минимума функции. | ||
| 249 | |||
| 250 | #+name: generation-first | ||
| 251 | #+caption: График целевой функции и популяции поколения №0 | ||
| 252 | #+attr_latex: :options [H] | ||
| 253 | #+begin_figure | ||
| 254 | \centering | ||
| 255 | \input{res/p25-c0.50-m0.10-g000} | ||
| 256 | #+end_figure | ||
| 257 | |||
| 258 | #+caption: График целевой функции и популяции поколения №1 | ||
| 259 | #+attr_latex: :options [H] | ||
| 260 | #+begin_figure | ||
| 261 | \centering | ||
| 262 | \input{res/p25-c0.50-m0.10-g001} | ||
| 263 | #+end_figure | ||
| 264 | |||
| 265 | #+caption: График целевой функции и популяции поколения №2 | ||
| 266 | #+attr_latex: :options [H] | ||
| 267 | #+begin_figure | ||
| 268 | \centering | ||
| 269 | \input{res/p25-c0.50-m0.10-g002} | ||
| 270 | #+end_figure | ||
| 271 | |||
| 272 | #+caption: График целевой функции и популяции поколения №3 | ||
| 273 | #+attr_latex: :options [H] | ||
| 274 | #+begin_figure | ||
| 275 | \centering | ||
| 276 | \input{res/p25-c0.50-m0.10-g003} | ||
| 277 | #+end_figure | ||
| 278 | |||
| 279 | #+caption: График целевой функции и популяции поколения №5 | ||
| 280 | #+attr_latex: :options [H] | ||
| 281 | #+begin_figure | ||
| 282 | \centering | ||
| 283 | \input{res/p25-c0.50-m0.10-g005} | ||
| 284 | #+end_figure | ||
| 285 | |||
| 286 | #+caption: График целевой функции и популяции поколения №8 | ||
| 287 | #+attr_latex: :options [H] | ||
| 288 | #+begin_figure | ||
| 289 | \centering | ||
| 290 | \input{res/p25-c0.50-m0.10-g008} | ||
| 291 | #+end_figure | ||
| 292 | |||
| 293 | #+caption: График целевой функции и популяции поколения №11 | ||
| 294 | #+attr_latex: :options [H] | ||
| 295 | #+begin_figure | ||
| 296 | \centering | ||
| 297 | \input{res/p25-c0.50-m0.10-g011} | ||
| 298 | #+end_figure | ||
| 299 | |||
| 300 | #+caption: График целевой функции и популяции поколения №12 | ||
| 301 | #+attr_latex: :options [H] | ||
| 302 | #+begin_figure | ||
| 303 | \centering | ||
| 304 | \input{res/p25-c0.50-m0.10-g012} | ||
| 305 | #+end_figure | ||
| 306 | |||
| 307 | #+name: generation-last | ||
| 308 | #+caption: График целевой функции и популяции поколения №13 | ||
| 309 | #+attr_latex: :options [H] | ||
| 310 | #+begin_figure | ||
| 311 | \centering | ||
| 312 | \input{res/p25-c0.50-m0.10-g013} | ||
| 313 | #+end_figure | ||
| 314 | |||
| 315 | * Исследование реализации | ||
| 316 | ** Проведение измерений | ||
| 317 | В рамках лабораторной работы необходимо было исследовать зависимость | ||
| 318 | времени выполнения задачи и количества поколений от популяции и | ||
| 319 | вероятностей кроссинговера и мутации хромосомы. | ||
| 320 | |||
| 321 | Для исследования были выбраны следующие значения параметров: | ||
| 322 | - \(N = 10, 25, 50, 100\) --- размер популяции. | ||
| 323 | - \(P_c = 0.3, 0.4, 0.5, 0.6, 0.7, 0.8\) --- вероятность | ||
| 324 | кроссинговера. | ||
| 325 | - \(P_m = 0.001, 0.01, 0.05, 0.1, 0.2\) --- вероятность мутации. | ||
| 326 | |||
| 327 | Результаты измерений представлены в таблицах [[results-10]]-[[results-100]]. | ||
| 328 | В ячейках указано усредненное время в микросекундах нахождения | ||
| 329 | минимума функции. В скобках указано усредненное количество поколений, | ||
| 330 | за которое было найдено решение. Каждый эксперимент запускался 100 | ||
| 331 | раз. Если ячейка перечеркнута, то это означает, что решение ни разу | ||
| 332 | не было найдено за 200 поколений. Лучшее значение по времени | ||
| 333 | выполнения для каждого размера популяции выделено жирным шрифтом. | ||
| 334 | |||
| 335 | #+include: "./res/results-010.org" | ||
| 336 | |||
| 337 | #+include: "./res/results-025.org" | ||
| 338 | |||
| 339 | #+include: "./res/results-050.org" | ||
| 340 | |||
| 341 | #+include: "./res/results-100.org" | ||
| 342 | |||
| 343 | ** Анализ результатов | ||
| 344 | #+latex: \noindent | ||
| 345 | *Ключевые наблюдения:* | ||
| 346 | 1. Из \(P_m\) себя лучше показало наибольшее значение \(0.2\) при всех | ||
| 347 | размерах популяции \(N\). | ||
| 348 | 2. Эффект \(P_c\) положительно растёт с размером популяции \(N\). | ||
| 349 | 3. При небольших популяциях (\(N = 10\)) вероятность ОК \(P_c\) не | ||
| 350 | влияла на скорость схождения; наилучшее время при \(P_c = 0.3\) | ||
| 351 | (175 μс, 162 пок.) --- лучшее среди всех экспериментов. При \(P_c | ||
| 352 | \in (0.4, 0.8)\) и \(P_m = 0.001\) решение не находилось за 200 | ||
| 353 | поколений. | ||
| 354 | 4. Для \(N = 25\) значительный минимум времени при \(P_c = 0.7\), (310 | ||
| 355 | μс, 107 пок.). | ||
| 356 | 5. Для \(N=50\) лучшее время при \(P_c = 0.5\) (302 μс, 50 пок.). | ||
| 357 | 6. Для \(N=100\) оптимальны высокие \(P_c\); лучший результат при | ||
| 358 | \(P_c = 0.8\), (368 μс, 27 пок.). | ||
| 359 | 7. Увеличение \(P_c\) и \(P_m\) ускоряет достижение решения и снижает | ||
| 360 | число поколений. | ||
| 361 | 8. С ростом размерности популяции \(N\) вероятность нахождения | ||
| 362 | оптимального решения так же растёт. | ||
| 363 | 9. Для больших \(N\) эффект высоких значений \(P_c\) и \(P_m\) | ||
| 364 | становился более выраженным --- снижение времени было значительным. | ||
| 365 | 10. Рост \(N\) не гарантирует ускорения: число поколений может | ||
| 366 | уменьшаться, но суммарное время часто растёт из-за большей | ||
| 367 | стоимости одной итерации. | ||
| 368 | |||
| 369 | #+latex: \bigbreak\noindent | ||
| 370 | *Практические выводы:* | ||
| 371 | 1. Поскольку затраты времени низкие, для стоит выбирать большие | ||
| 372 | размеры популяции \(N\), в которых показывают себя лучше большие | ||
| 373 | \(P_c\) и \(P_m\). | ||
| 374 | 2. С ростом \(N\) скорее всего оптимальные \(P_c\) и \(P_m\) | ||
| 375 | снижаются, не стоит считать, что их большие значения себя всегда | ||
| 376 | показывают лучше. | ||
| 377 | |||
| 378 | * Ответ на контрольный вопрос | ||
| 379 | #+latex: \noindent | ||
| 380 | *Вопрос:* Исследуйте зависимость работы ПГА от значения вероятности ОК | ||
| 381 | (\(P_c\)). | ||
| 382 | |||
| 383 | #+latex: \bigbreak\noindent | ||
| 384 | *Ответ:* Для популяции крайне малых размеров (\(N = 10\)) значение | ||
| 385 | вероятности ОК (\(P_c\)) имеет минимальный эффект, но с ростом размера | ||
| 386 | популяции большие значения \(P_c\) себя показывают лучше. | ||
| 387 | |||
| 388 | * ЗАКЛЮЧЕНИЕ | ||
| 389 | :PROPERTIES: | ||
| 390 | :UNNUMBERED: t | ||
| 391 | :END: | ||
| 392 | В ходе первой лабораторной работы: | ||
| 393 | 1. Был изучен теоретический материал, основная терминология ГА, | ||
| 394 | генетические операторы, использующиеся в простых ГА; | ||
| 395 | 2. Реализована программа на языке Си для нахождения минимума заданной | ||
| 396 | функции; | ||
| 397 | 3. Проведено исследование зависимости времени выполнения программы и | ||
| 398 | количества поколений от мощности популяции и вероятностей | ||
| 399 | кроссинговера и мутации. | ||
| 400 | |||
| 401 | * СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ | ||
| 402 | :PROPERTIES: | ||
| 403 | :UNNUMBERED: t | ||
| 404 | :END: | ||
| 405 | #+latex: \nocite{METODA} | ||
| 406 | #+print_bibliography: :heading none | ||
| 407 | |||
| 408 | * ПРИЛОЖЕНИЕ А | ||
| 409 | :PROPERTIES: | ||
| 410 | :UNNUMBERED: t | ||
| 411 | :END: | ||
| 412 | #+include: "../src/simple-genetic-algorithm.c" src c | ||
| 413 | |||
| 414 | # Local Variables: | ||
| 415 | # org-confirm-babel-evaluate: nil | ||
| 416 | # org-export-async-init-file: "ox-init.el" | ||
| 417 | # org-export-in-background: t | ||
| 418 | # End: | ||
diff --git a/doc/setup.org b/doc/setup.org new file mode 100644 index 0000000..4bd1382 --- /dev/null +++ b/doc/setup.org | |||
| @@ -0,0 +1,30 @@ | |||
| 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:t |:t | ||
| 6 | # #+creator: Emacs 29.1 (Org mode 9.6.9) | ||
| 7 | |||
| 8 | #+select_tags: export | ||
| 9 | #+exclude_tags: noexport | ||
| 10 | |||
| 11 | #+bibliography: biblio.bib | ||
| 12 | #+cite_export: biblatex | ||
| 13 | |||
| 14 | #+latex_compiler: xelatex | ||
| 15 | #+latex_class: spbstu-report | ||
| 16 | # #+latex_class_options: [draft] | ||
| 17 | |||
| 18 | #+latex_header: \usepackage{enumitem} | ||
| 19 | #+latex_header: \usepackage{float} | ||
| 20 | #+latex_header: \usepackage{soul} | ||
| 21 | |||
| 22 | #+latex_header: \usepackage[newfloat]{minted} | ||
| 23 | #+latex_header: \usemintedstyle{bw} | ||
| 24 | #+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=@@,ignorelexererrors} | ||
| 25 | |||
| 26 | #+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}} | ||
| 27 | |||
| 28 | #+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} | ||
| 29 | #+latex_header: \setmainfont{Times New Roman} | ||
| 30 | #+latex_header: \setmonofont{Aporetic Serif Mono}[Contextuals=AlternateOff] | ||
diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls new file mode 100644 index 0000000..3937b79 --- /dev/null +++ b/doc/spbstu-report.cls | |||
| @@ -0,0 +1,79 @@ | |||
| 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{amssymb} | ||
| 17 | \RequirePackage{adjustbox} | ||
| 18 | \RequirePackage{graphicx} | ||
| 19 | \RequirePackage{wrapfig} | ||
| 20 | \RequirePackage{rotating} | ||
| 21 | |||
| 22 | \newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}} | ||
| 23 | \newcommand{\@university}{}\newcommand{\university}[1]{\renewcommand{\@university}{#1}} | ||
| 24 | \newcommand{\@institute}{}\newcommand{\institute}[1]{\renewcommand{\@institute}{#1}} | ||
| 25 | \newcommand{\@school}{}\newcommand{\school}[1]{\renewcommand{\@school}{#1}} | ||
| 26 | \newcommand{\@direction}{}\newcommand{\direction}[1]{\renewcommand{\@direction}{#1}} | ||
| 27 | \newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}} | ||
| 28 | \newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}} | ||
| 29 | \newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}} | ||
| 30 | \newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$} | ||
| 31 | \newcommand{\@city}{}\newcommand{\city}[1]{\renewcommand{\@city}{#1}} | ||
| 32 | \renewcommand{\maketitle}{ | ||
| 33 | \begin{titlepage} | ||
| 34 | \begin{center} | ||
| 35 | \vspace{2cm} | ||
| 36 | \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ} | ||
| 37 | |||
| 38 | \normalsize{\@university} | ||
| 39 | |||
| 40 | \vspace{0.5cm} | ||
| 41 | \normalsize{\@institute} | ||
| 42 | |||
| 43 | \normalsize{\@school} | ||
| 44 | |||
| 45 | \normalsize{Направление \@direction} | ||
| 46 | |||
| 47 | \vspace{2cm} | ||
| 48 | \LARGE{ОТЧЁТ} | ||
| 49 | |||
| 50 | \normalsize{\@reportof} | ||
| 51 | |||
| 52 | \large{\@subject} | ||
| 53 | |||
| 54 | \large{\textit{\@title}} | ||
| 55 | |||
| 56 | \normalsize{\textit{\@subtitle}} | ||
| 57 | \end{center} | ||
| 58 | |||
| 59 | \vspace{3cm} | ||
| 60 | \small{ | ||
| 61 | \begin{tabular}{lrrl} | ||
| 62 | \!\!\!Студент, & \hspace{2cm} & & \\ | ||
| 63 | \!\!\!группы 5130201/20101 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\ | ||
| 64 | \!\!\!Преподаватель, & \hspace{2cm} & \\ | ||
| 65 | \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\ | ||
| 66 | &&\hspace{5cm} | ||
| 67 | \end{tabular} | ||
| 68 | \begin{flushright} | ||
| 69 | \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г. | ||
| 70 | \end{flushright} | ||
| 71 | } | ||
| 72 | |||
| 73 | \vspace*{\fill} | ||
| 74 | \begin{center} | ||
| 75 | \small{\@city, \@date} | ||
| 76 | \end{center} | ||
| 77 | \end{titlepage} | ||
| 78 | \setcounter{page}{2} | ||
| 79 | } | ||
diff --git a/src/simple-genetic-algorithm.c b/src/simple-genetic-algorithm.c new file mode 100644 index 0000000..728fc78 --- /dev/null +++ b/src/simple-genetic-algorithm.c | |||
| @@ -0,0 +1,480 @@ | |||
| 1 | // simple-genetic-algorithm.c --- simple genetic algorithm | ||
| 2 | #include <stdlib.h> | ||
| 3 | #include <stdio.h> | ||
| 4 | #include <stdint.h> | ||
| 5 | #include <stdbool.h> | ||
| 6 | #include <stdarg.h> | ||
| 7 | #include <math.h> | ||
| 8 | #include <time.h> | ||
| 9 | #include <float.h> | ||
| 10 | #include <string.h> | ||
| 11 | #include <assert.h> | ||
| 12 | |||
| 13 | #define POPULATION_CAPACITY 100 | ||
| 14 | #define CHROMOSOME_SIZE 16 | ||
| 15 | #define GENERATION_MAX 200 | ||
| 16 | #define FITNESS_TRESHOLD_AVERAGE -0.411 | ||
| 17 | #define FITNESS_TRESHOLD_VARIANCE -1 | ||
| 18 | #define FITNESS_TRESHOLD_BEST FITNESS_TRESHOLD_AVERAGE | ||
| 19 | #define DIGITS_AFTER_DECIMAL 3 | ||
| 20 | #define MINMAX -1 | ||
| 21 | #define X_MIN ((double) -10) | ||
| 22 | #define X_MAX ((double) +10) | ||
| 23 | #define Y_MIN ((double) -0.5) | ||
| 24 | #define Y_MAX ((double) +2.0) | ||
| 25 | #define PLOT_SAMPLE_COUNT 400 | ||
| 26 | // #define SEED time (NULL) | ||
| 27 | #define SEED 1760052039 | ||
| 28 | #define MEASUREMENT_RUNS 100 | ||
| 29 | |||
| 30 | size_t population_sizes [] = { 10, 25, 50, 100 }; | ||
| 31 | double probabilities_crossover [] = { 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 }; | ||
| 32 | double probabilities_mutation [] = { 0.001, 0.01, 0.05, 0.1, 0.2 }; | ||
| 33 | |||
| 34 | #define ASSERT assert | ||
| 35 | #define CTZL __builtin_ctzl | ||
| 36 | #define EPSILON 1e-12 | ||
| 37 | |||
| 38 | #define ARRAY_LENGTH(T) (sizeof (T)/sizeof (*(T))) | ||
| 39 | #define FOR_EACH_ELEMENT(ELEMENT, ARRAY) \ | ||
| 40 | for (typeof (*(ARRAY)) *(ELEMENT) = (ARRAY); \ | ||
| 41 | (ELEMENT) < (ARRAY) + ARRAY_LENGTH (ARRAY); ++(ELEMENT)) \ | ||
| 42 | |||
| 43 | #if CHROMOSOME_SIZE < 2 | ||
| 44 | #error "CHROMOSOME_SIZE smaller than 2" | ||
| 45 | #elif CHROMOSOME_SIZE <= 8 | ||
| 46 | typedef uint8_t chromosome; | ||
| 47 | #elif CHROMOSOME_SIZE <= 16 | ||
| 48 | typedef uint16_t chromosome; | ||
| 49 | #elif CHROMOSOME_SIZE <= 32 | ||
| 50 | typedef uint32_t chromosome; | ||
| 51 | #else | ||
| 52 | #error "CHROMOSOME_SIZE larger than 32" | ||
| 53 | #endif | ||
| 54 | |||
| 55 | #define CHROMOSOME_MAX ((chromosome) -1 >> (8*sizeof (chromosome) - CHROMOSOME_SIZE)) | ||
| 56 | |||
| 57 | struct sample { | ||
| 58 | double x, y; | ||
| 59 | }; | ||
| 60 | struct measurement { | ||
| 61 | double time; | ||
| 62 | size_t generations; | ||
| 63 | }; | ||
| 64 | |||
| 65 | chromosome population [POPULATION_CAPACITY]; | ||
| 66 | chromosome population_breeding_pool [POPULATION_CAPACITY]; | ||
| 67 | double population_fitness [POPULATION_CAPACITY]; | ||
| 68 | double population_fitness_normalized [POPULATION_CAPACITY]; | ||
| 69 | double population_fitness_normalized_min; | ||
| 70 | double population_cdf [POPULATION_CAPACITY]; | ||
| 71 | size_t population_best_i; | ||
| 72 | double population_best_fitness; | ||
| 73 | chromosome generation_bests [GENERATION_MAX]; | ||
| 74 | double generation_bests_fitness [GENERATION_MAX]; | ||
| 75 | struct sample plot_samples [PLOT_SAMPLE_COUNT]; | ||
| 76 | struct measurement measurements [ARRAY_LENGTH (probabilities_crossover)] | ||
| 77 | [ARRAY_LENGTH (probabilities_mutation )]; | ||
| 78 | |||
| 79 | double | ||
| 80 | decode (chromosome chromosome) | ||
| 81 | { | ||
| 82 | return X_MIN + chromosome*(X_MAX - X_MIN)/CHROMOSOME_MAX; | ||
| 83 | } | ||
| 84 | |||
| 85 | double | ||
| 86 | fitness_function (double x) | ||
| 87 | { | ||
| 88 | return cos (x - 0.5)/fabs (x); | ||
| 89 | } | ||
| 90 | |||
| 91 | uint8_t | ||
| 92 | bits_for_precision (int digits_after_decimal) | ||
| 93 | { | ||
| 94 | ASSERT (digits_after_decimal < 18); | ||
| 95 | |||
| 96 | uint64_t interval_count_min = ceil ((X_MAX - X_MIN)*pow (10, digits_after_decimal)); | ||
| 97 | uint64_t interval_count = 1; | ||
| 98 | while (interval_count < interval_count_min) | ||
| 99 | interval_count <<= 1; | ||
| 100 | return CTZL (interval_count); | ||
| 101 | } | ||
| 102 | |||
| 103 | void | ||
| 104 | create_initial_population (size_t population_size) | ||
| 105 | { | ||
| 106 | ASSERT (population_size > 0); | ||
| 107 | ASSERT (population_size <= POPULATION_CAPACITY); | ||
| 108 | |||
| 109 | for (size_t i = 0; i < population_size; ++i) { | ||
| 110 | population[i] = rand () % (1 << CHROMOSOME_SIZE); | ||
| 111 | } | ||
| 112 | } | ||
| 113 | |||
| 114 | bool | ||
| 115 | measure_fitness (size_t population_size) | ||
| 116 | { | ||
| 117 | ASSERT (population_size > 0); | ||
| 118 | ASSERT (population_size <= POPULATION_CAPACITY); | ||
| 119 | |||
| 120 | population_fitness_normalized_min = DBL_MAX; | ||
| 121 | // double fitness_average = 0; | ||
| 122 | // double fitness_variance = 0; | ||
| 123 | population_best_i = 0; | ||
| 124 | population_best_fitness = DBL_MAX; | ||
| 125 | for (size_t i = 0; i < population_size; ++i) { | ||
| 126 | double fitness = fitness_function (decode (population[i])); | ||
| 127 | double fitness_normalized = MINMAX*fitness; | ||
| 128 | population_fitness [i] = fitness; | ||
| 129 | population_fitness_normalized [i] = fitness_normalized; | ||
| 130 | if (fitness_normalized < population_fitness_normalized_min) | ||
| 131 | population_fitness_normalized_min = fitness_normalized; | ||
| 132 | // fitness_average += fitness; | ||
| 133 | // fitness_variance += fitness*fitness; | ||
| 134 | if (MINMAX*(fitness - population_best_fitness) > 0) { | ||
| 135 | population_best_i = i; | ||
| 136 | population_best_fitness = fitness; | ||
| 137 | } | ||
| 138 | } | ||
| 139 | population_fitness_normalized_min -= 1e-12; | ||
| 140 | // fitness_average /= population_size; | ||
| 141 | // fitness_variance = fitness_variance/population_size - | ||
| 142 | // fitness_average*fitness_average; | ||
| 143 | // printf ("%lg\n", fitness_average); | ||
| 144 | // if (fitness_average - FITNESS_TRESHOLD_AVERAGE < EPSILON) return true; | ||
| 145 | // if (fitness_variance - FITNESS_TRESHOLD_VARIANCE < EPSILON) return true; | ||
| 146 | // printf ("%lg\n", population_best_fitness); | ||
| 147 | if (MINMAX*(population_best_fitness - FITNESS_TRESHOLD_BEST) > 0) return true; | ||
| 148 | return false; | ||
| 149 | } | ||
| 150 | |||
| 151 | void | ||
| 152 | fitness_proportionate_selection (size_t population_size) | ||
| 153 | { | ||
| 154 | ASSERT (population_size > 0); | ||
| 155 | ASSERT (population_size <= POPULATION_CAPACITY); | ||
| 156 | |||
| 157 | double population_fitness_sum = 0; | ||
| 158 | for (size_t i = 0; i < population_size; ++i) { | ||
| 159 | population_fitness_sum += | ||
| 160 | population_fitness_normalized[i] -= population_fitness_normalized_min; | ||
| 161 | } | ||
| 162 | |||
| 163 | double last = 0; | ||
| 164 | for (size_t i = 0; i < population_size; ++i) { | ||
| 165 | last = population_cdf[i] = | ||
| 166 | last + population_fitness_normalized[i]/population_fitness_sum; | ||
| 167 | } | ||
| 168 | |||
| 169 | for (size_t i = 0; i < population_size; ++i) { | ||
| 170 | double a = rand () /(double) RAND_MAX; | ||
| 171 | size_t j = 0; | ||
| 172 | // TODO(cmmm): use binary search | ||
| 173 | while (j < population_size) { | ||
| 174 | if (population_cdf[j] > a) break; | ||
| 175 | j += 1; | ||
| 176 | } | ||
| 177 | |||
| 178 | population_breeding_pool[i] = population[j]; | ||
| 179 | } | ||
| 180 | } | ||
| 181 | |||
| 182 | void | ||
| 183 | crossover (size_t population_size, double probability) | ||
| 184 | { | ||
| 185 | ASSERT (population_size > 0); | ||
| 186 | ASSERT (population_size <= POPULATION_CAPACITY); | ||
| 187 | |||
| 188 | for (size_t i = 0; i < population_size; i += 2) { | ||
| 189 | size_t i_a = i; | ||
| 190 | size_t i_b = (i + 1) % population_size; | ||
| 191 | |||
| 192 | chromosome a = population_breeding_pool[i_a]; | ||
| 193 | chromosome b = population_breeding_pool[i_b]; | ||
| 194 | |||
| 195 | if (rand () /(double) RAND_MAX > probability) { | ||
| 196 | population[i_a] = a; | ||
| 197 | population[i_b] = b; | ||
| 198 | } else { | ||
| 199 | size_t k = rand () % (CHROMOSOME_SIZE - 1) + 1; | ||
| 200 | chromosome mask_left = (1 << k) - 1; | ||
| 201 | chromosome mask_right = -1 << k; | ||
| 202 | population[i_a] = a & mask_left | b & mask_right; | ||
| 203 | population[i_b] = b & mask_left | a & mask_right; | ||
| 204 | } | ||
| 205 | } | ||
| 206 | } | ||
| 207 | |||
| 208 | void | ||
| 209 | mutation (size_t population_size, double probability) | ||
| 210 | { | ||
| 211 | ASSERT (population_size > 0); | ||
| 212 | ASSERT (population_size <= POPULATION_CAPACITY); | ||
| 213 | |||
| 214 | for (size_t i = 0; i < population_size; ++i) { | ||
| 215 | if (rand () /(double) RAND_MAX > probability) | ||
| 216 | continue; | ||
| 217 | |||
| 218 | size_t k = rand () % CHROMOSOME_SIZE; | ||
| 219 | population[i] ^= 1 << k; | ||
| 220 | } | ||
| 221 | } | ||
| 222 | |||
| 223 | void | ||
| 224 | plot (const char *output, size_t population_size, size_t generation) | ||
| 225 | { | ||
| 226 | // FILE *gp = popen ("gnuplot", "w"); | ||
| 227 | FILE *gp = fopen ("test.gp", "w"); | ||
| 228 | // fprintf (gp, "set term png\n"); | ||
| 229 | fprintf (gp, "set term cairolatex pdf input blacktext notransparent" | ||
| 230 | " nocrop size 15cm,10cm noheader\n"); | ||
| 231 | fprintf (gp, "set output '%s'\n", output); | ||
| 232 | |||
| 233 | fprintf (gp, "set size ratio 0.66\n"); | ||
| 234 | fprintf (gp, "set lmargin at screen 0.1\n"); | ||
| 235 | fprintf (gp, "set rmargin at screen 0.9\n"); | ||
| 236 | fprintf (gp, "set bmargin at screen 0.1\n"); | ||
| 237 | fprintf (gp, "set tmargin at screen 0.9\n"); | ||
| 238 | |||
| 239 | fprintf (gp, "set title 'Поколение №%lu, \\quad Лучшая особь: %lf'\n", | ||
| 240 | generation, population_best_fitness); | ||
| 241 | fprintf (gp, "set xlabel '\\(x\\)'\n"); | ||
| 242 | fprintf (gp, "set ylabel '\\(f(x)\\)'\n"); | ||
| 243 | fprintf (gp, "set xrange [%lf:%lf]\n", X_MIN, X_MAX); | ||
| 244 | fprintf (gp, "set yrange [%lf:%lf]\n", Y_MIN, Y_MAX); | ||
| 245 | |||
| 246 | fprintf (gp, "plot "); | ||
| 247 | fprintf (gp, "'-' with lines title '%s',", "\\small{Целевая функция}"); | ||
| 248 | if (generation > 0) | ||
| 249 | fprintf (gp, "'-' with points pt 7 ps 1 lc 'yellow' title '\\small{Лучшие особи}',"); | ||
| 250 | fprintf (gp, "'-' with points pt 7 ps 1 lc 'green' title '\\small{Лучшая особь поколения}',"); | ||
| 251 | fprintf (gp, "'-' with points pt 7 ps 0.5 lc 'red' title '\\small{Популяция}'\n"); | ||
| 252 | for (size_t i = 0; i < PLOT_SAMPLE_COUNT; ++i) { | ||
| 253 | fprintf (gp, "%lf %lf\n", plot_samples[i].x, plot_samples[i].y); | ||
| 254 | } fprintf (gp, "e\n"); | ||
| 255 | if (generation > 0) { | ||
| 256 | for (size_t i = 0; i < generation; ++i) { | ||
| 257 | double x = decode (generation_bests[i]); | ||
| 258 | fprintf (gp, "%lf %lf\n", x, generation_bests_fitness[i]); | ||
| 259 | } fprintf (gp, "e\n"); | ||
| 260 | } | ||
| 261 | fprintf (gp, "%lf %lf\ne\n", | ||
| 262 | decode (population[population_best_i]), | ||
| 263 | population_best_fitness); | ||
| 264 | for (size_t i = 0; i < population_size; ++i) { | ||
| 265 | double x = decode (population[i]); | ||
| 266 | fprintf (gp, "%lf %lf\n", x, population_fitness[i]); | ||
| 267 | } fprintf (gp, "e\n"); | ||
| 268 | fclose (gp); | ||
| 269 | } | ||
| 270 | |||
| 271 | void | ||
| 272 | run_experiment__plot (size_t population_size, | ||
| 273 | double probability_crossover, | ||
| 274 | double probability_mutation) | ||
| 275 | { | ||
| 276 | void | ||
| 277 | plot_generation (size_t generation) | ||
| 278 | { | ||
| 279 | static char plot_output[256]; | ||
| 280 | |||
| 281 | snprintf (plot_output, sizeof (plot_output), "res/p%llu-c%4.2lf-m%4.2lf-g%03u.tex", | ||
| 282 | population_size, probability_crossover, | ||
| 283 | probability_mutation, generation); | ||
| 284 | |||
| 285 | plot (plot_output, population_size, generation); | ||
| 286 | } | ||
| 287 | |||
| 288 | create_initial_population (population_size); | ||
| 289 | measure_fitness (population_size); | ||
| 290 | size_t generation; | ||
| 291 | for (generation = 0; generation < GENERATION_MAX; ++generation) { | ||
| 292 | if (measure_fitness (population_size)) break; | ||
| 293 | |||
| 294 | generation_bests [generation] = population[population_best_i]; | ||
| 295 | generation_bests_fitness [generation] = population_best_fitness; | ||
| 296 | printf ("fitness: %lf\n", population_best_fitness); | ||
| 297 | plot_generation (generation); | ||
| 298 | |||
| 299 | fitness_proportionate_selection (population_size); | ||
| 300 | crossover (population_size, probability_crossover); | ||
| 301 | mutation (population_size, probability_mutation); | ||
| 302 | } | ||
| 303 | if (generation == GENERATION_MAX) | ||
| 304 | measure_fitness (population_size); | ||
| 305 | printf ("fitness: %lf\n", population_best_fitness); | ||
| 306 | printf ("chromosome: %0*b\n", CHROMOSOME_SIZE, population[population_best_i]); | ||
| 307 | plot_generation (generation); | ||
| 308 | } | ||
| 309 | |||
| 310 | struct measurement | ||
| 311 | run_experiment__measure (size_t population_size, | ||
| 312 | double probability_crossover, | ||
| 313 | double probability_mutation) | ||
| 314 | { | ||
| 315 | double total_time = 0; | ||
| 316 | size_t total_generations = 0; | ||
| 317 | for (int run = 0; run < MEASUREMENT_RUNS; ++run) { | ||
| 318 | clock_t begin = clock (); | ||
| 319 | create_initial_population (population_size); | ||
| 320 | size_t generation; | ||
| 321 | for (generation = 0; generation < GENERATION_MAX; ++generation) { | ||
| 322 | if (measure_fitness (population_size)) break; | ||
| 323 | fitness_proportionate_selection (population_size); | ||
| 324 | crossover (population_size, probability_crossover); | ||
| 325 | mutation (population_size, probability_mutation); | ||
| 326 | } | ||
| 327 | double time = (clock () - begin) /(double) CLOCKS_PER_SEC; | ||
| 328 | total_time += time; | ||
| 329 | total_generations += generation; | ||
| 330 | } | ||
| 331 | |||
| 332 | return (struct measurement) { | ||
| 333 | .time = total_time/MEASUREMENT_RUNS, | ||
| 334 | .generations = (total_generations + MEASUREMENT_RUNS/2)/MEASUREMENT_RUNS, | ||
| 335 | }; | ||
| 336 | } | ||
| 337 | |||
| 338 | void | ||
| 339 | sample_fitness_function () | ||
| 340 | { | ||
| 341 | double x = X_MIN; | ||
| 342 | double dx = (X_MAX - X_MIN)/PLOT_SAMPLE_COUNT; | ||
| 343 | for (size_t i = 0; i < PLOT_SAMPLE_COUNT; ++i) { | ||
| 344 | plot_samples[i].x = x; | ||
| 345 | plot_samples[i].y = fitness_function (x); | ||
| 346 | x += dx; | ||
| 347 | } | ||
| 348 | } | ||
| 349 | |||
| 350 | typedef int (*print_function)(void *user, const char *template, ...); | ||
| 351 | typedef int (*cell_function)(int x, int y, print_function, void *); | ||
| 352 | |||
| 353 | int | ||
| 354 | print__measure (void *user, const char *template, ...) | ||
| 355 | { | ||
| 356 | va_list ap; | ||
| 357 | va_start (ap, template); | ||
| 358 | int len = vsnprintf (NULL, 0, template, ap); | ||
| 359 | va_end (ap); | ||
| 360 | return len; | ||
| 361 | } | ||
| 362 | |||
| 363 | int | ||
| 364 | print__stream (void *stream, const char *template, ...) | ||
| 365 | { | ||
| 366 | va_list ap; | ||
| 367 | va_start (ap, template); | ||
| 368 | int len = vfprintf (stream, template, ap); | ||
| 369 | va_end (ap); | ||
| 370 | return len; | ||
| 371 | } | ||
| 372 | |||
| 373 | void | ||
| 374 | print_org_table (const char *filename, const char *name, const char *caption, | ||
| 375 | int rows, int cols, cell_function cell) | ||
| 376 | { | ||
| 377 | int cell_widths[rows][cols]; | ||
| 378 | int column_widths[cols]; | ||
| 379 | memset (column_widths, 0, sizeof (column_widths)); | ||
| 380 | for (int y = 0; y < rows; ++y) { | ||
| 381 | for (int x = 0; x < cols; ++x) { | ||
| 382 | cell_widths[y][x] = cell (x, y, print__measure, NULL); | ||
| 383 | if (cell_widths[y][x] > column_widths[x]) | ||
| 384 | column_widths[x] = cell_widths[y][x];; | ||
| 385 | } | ||
| 386 | } | ||
| 387 | |||
| 388 | FILE *stream = fopen (filename, "w"); | ||
| 389 | fprintf (stream, "#+name: %s\n", name); | ||
| 390 | fprintf (stream, "#+caption: %s\n", caption); | ||
| 391 | for (int y = 0; y < rows; ++y) { | ||
| 392 | fprintf (stream, "|"); | ||
| 393 | for (int x = 0; x < cols; ++x) { | ||
| 394 | fprintf (stream, " "); | ||
| 395 | if (x == 0) { | ||
| 396 | for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i) | ||
| 397 | fprintf (stream, " "); | ||
| 398 | } | ||
| 399 | cell (x, y, print__stream, stream); | ||
| 400 | if (x > 0) { | ||
| 401 | for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i) | ||
| 402 | fprintf (stream, " "); | ||
| 403 | } | ||
| 404 | fprintf (stream, " |"); | ||
| 405 | } fprintf (stream, "\n"); | ||
| 406 | if (y == 0) { | ||
| 407 | fprintf (stream, "|"); | ||
| 408 | for (int x = 0; x < cols; ++x) { | ||
| 409 | for (int i = 0; i < column_widths[x] + 2; ++i) | ||
| 410 | fprintf (stream, "-"); | ||
| 411 | fprintf (stream, "|"); | ||
| 412 | } fprintf (stream, "\n"); | ||
| 413 | } | ||
| 414 | } | ||
| 415 | |||
| 416 | fclose (stream); | ||
| 417 | } | ||
| 418 | |||
| 419 | int | ||
| 420 | main (int argc, char *argv[]) | ||
| 421 | { | ||
| 422 | ASSERT (CHROMOSOME_SIZE >= bits_for_precision (DIGITS_AFTER_DECIMAL)); | ||
| 423 | |||
| 424 | printf ("SEED: %u\n", SEED); | ||
| 425 | srand (SEED); | ||
| 426 | sample_fitness_function (); | ||
| 427 | |||
| 428 | run_experiment__plot (25, .5, .1); | ||
| 429 | return 0; | ||
| 430 | |||
| 431 | struct measurement *best_measurement = &measurements[0][0]; | ||
| 432 | FOR_EACH_ELEMENT (population_size, population_sizes) { | ||
| 433 | struct measurement *measurement = &measurements[0][0]; | ||
| 434 | FOR_EACH_ELEMENT (probability_crossover, probabilities_crossover) { | ||
| 435 | FOR_EACH_ELEMENT (probability_mutation, probabilities_mutation) { | ||
| 436 | *measurement = run_experiment__measure (*population_size, | ||
| 437 | *probability_crossover, | ||
| 438 | *probability_mutation); | ||
| 439 | if (measurement->time < best_measurement->time) | ||
| 440 | best_measurement = measurement; | ||
| 441 | measurement += 1; | ||
| 442 | } | ||
| 443 | } | ||
| 444 | |||
| 445 | char *table_filename, *table_name, *table_caption; | ||
| 446 | asprintf (&table_filename, "res/results-%03lu.org", *population_size); | ||
| 447 | asprintf (&table_name, "results-%lu", *population_size); | ||
| 448 | asprintf (&table_caption, "Результаты для \\(N = %lu\\)", | ||
| 449 | *population_size); | ||
| 450 | int table_cell (int x, int y, print_function print, void *user) | ||
| 451 | { | ||
| 452 | int m = x - 1; | ||
| 453 | int c = y - 1; | ||
| 454 | if (x == 0 && y == 0) return print (user, "\\(P_c \\;\\backslash\\; P_m\\)"); | ||
| 455 | if ( y == 0) return print (user, "%.3lg", probabilities_mutation [m]); | ||
| 456 | if (x == 0 ) return print (user, "%.1lg", probabilities_crossover[c]); | ||
| 457 | |||
| 458 | int len = 0; | ||
| 459 | bool max_generation_reached = | ||
| 460 | measurements[c][m].generations == GENERATION_MAX; | ||
| 461 | bool is_best = &measurements[c][m] == best_measurement; | ||
| 462 | if (max_generation_reached) len += print (user, "\\st{"); | ||
| 463 | if (is_best) print (user, "*"); | ||
| 464 | len += print (user, "%.2lf (%lu)", | ||
| 465 | measurements[c][m].time*1000000, | ||
| 466 | measurements[c][m].generations); | ||
| 467 | if (is_best) print (user, "*"); | ||
| 468 | if (max_generation_reached) len += print (user, "}"); | ||
| 469 | |||
| 470 | return len; | ||
| 471 | } | ||
| 472 | print_org_table (table_filename, table_name, table_caption, | ||
| 473 | 1 + ARRAY_LENGTH (probabilities_crossover), | ||
| 474 | 1 + ARRAY_LENGTH (probabilities_mutation), table_cell); | ||
| 475 | } | ||
| 476 | |||
| 477 | return EXIT_SUCCESS; | ||
| 478 | } | ||
| 479 | |||
| 480 | // simple-genetic-algorithm.c ends here | ||
