aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-10 06:15:19 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-10 06:15:19 +0000
commite575815702e42efe5ba9d2732a1c6ae5dc752585 (patch)
treefa91e01ec90f7cd298c190c7fb38fe1bbec5903a
downloadlab-05-e575815702e42efe5ba9d2732a1c6ae5dc752585.tar.gz
publishHEADmaster
-rw-r--r--.gitignore6
-rw-r--r--README.org14
-rw-r--r--UNLICENSE24
-rwxr-xr-xbuild.sh5
-rw-r--r--doc/biblio.bib7
-rw-r--r--doc/gost/gost-7-32-bibliography.sty57
-rw-r--r--doc/gost/gost-7-32-captions.sty30
-rw-r--r--doc/gost/gost-7-32-counters.sty44
-rw-r--r--doc/gost/gost-7-32-headings.sty106
-rw-r--r--doc/gost/gost-7-32-lists.sty17
-rw-r--r--doc/gost/gost-7-32-tables.sty31
-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.el133
-rw-r--r--doc/report.org560
-rw-r--r--doc/setup.org32
-rw-r--r--doc/spbstu-report.cls77
-rw-r--r--src/evolution-strategy.c638
18 files changed, 1877 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..23e2ba1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
1*.html
2*.pdf
3*.tex
4*.dot
5*.png
6/evolution-strategy
diff --git a/README.org b/README.org
new file mode 100644
index 0000000..fdfa4cd
--- /dev/null
+++ b/README.org
@@ -0,0 +1,14 @@
1#+title: Optimization of multidimensional functions using an evolutionary strategy
2#+date: 2025H2
3
4* Documentation
5:PROPERTIES:
6:CUSTOM_ID: documentation
7:END:
8The exported report can be found at [[https://git.michalec.dev/files/uni/term-07/gen-alg/lab-05/report.pdf][this link]].
9
10* Unlicense
11:PROPERTIES:
12:CUSTOM_ID: unlicense
13:END:
14#+include: UNLICENSE verse
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..337f974
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,5 @@
1#!/bin/sh
2
3set -xe
4
5gcc -ggdb3 -std=gnu99 -O3 -march=native -lm src/evolution-strategy.c -o evolution-strategy
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..9ffc4eb
--- /dev/null
+++ b/doc/ox-init.el
@@ -0,0 +1,133 @@
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 ))
30(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}"
31 ("\\section{%s}" . "\\section*{%s}")
32 ("\\subsection{%s}" . "\\subsection*{%s}")
33 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
34 ("\\paragraph{%s}" . "\\paragraph*{%s}")
35 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))))
36
37;; TODO(cmmm): add \addlinespace between rows which don't have 'rule
38;; TODO(cmmm): wrap head columns in something like:
39;; \multicolumn{1}{c}{\bold head1}
40(defun cmmm-org-latex-table-row (table-row contents info)
41 "Transcode a TABLE-ROW element from Org to LaTeX.
42CONTENTS is the contents of the row. INFO is a plist used as
43a communication channel."
44 (let* ((attr (org-export-read-attribute :attr_latex
45 (org-element-parent table-row)))
46 (booktabsp (if (plist-member attr :booktabs) (plist-get attr :booktabs)
47 (plist-get info :latex-tables-booktabs)))
48 (longtablep
49 (member (or (plist-get attr :environment)
50 (plist-get info :latex-default-table-environment))
51 ;; adding xltabular is the only change
52 '("longtable" "longtabu" "xltabular"))))
53 (if (eq (org-element-property :type table-row) 'rule)
54 (cond
55 ((not booktabsp) "\\hline")
56 ((not (org-export-get-previous-element table-row info)) "\\toprule")
57 ((not (org-export-get-next-element table-row info)) "\\bottomrule")
58 ((and longtablep
59 (org-export-table-row-ends-header-p
60 (org-export-get-previous-element table-row info) info))
61 "")
62 (t "\\midrule"))
63 ;; Memorize table header in case it is multiline. We need this
64 ;; information to define contents before "\\endhead" in longtable environments.
65 (when (org-export-table-row-in-header-p table-row info)
66 (let ((table-head-cache (plist-get info :org-latex-table-head-cache)))
67 (unless (hash-table-p table-head-cache)
68 (setq table-head-cache (make-hash-table :test #'eq))
69 (plist-put info :org-latex-table-head-cache table-head-cache))
70 (if-let* ((head-contents (gethash (org-element-parent table-row) table-head-cache)))
71 (puthash (org-element-parent table-row) (concat head-contents "\\\\\n" contents)
72 table-head-cache)
73 (puthash (org-element-parent table-row) contents table-head-cache))))
74 ;; Return LaTeX string as the transcoder.
75 (concat
76 (when (and longtablep (org-export-table-row-ends-header-p table-row info))
77 (let ((columns (cdr (org-export-table-dimensions
78 (org-element-lineage table-row 'table) info))))
79 (format "%s
80\\endfirsthead
81\\multicolumn{%d}{l}{%s} \\\\
82%s
83%s \\\\\n
84%s
85\\endhead
86%s\\multicolumn{%d}{r}{%s} \\\\
87\\endfoot
88\\endlastfoot"
89 (if booktabsp "\\midrule" "\\hline")
90 columns
91 (org-latex--translate "Continued from previous page" info)
92 (cond
93 ((not (org-export-table-row-starts-header-p table-row info))
94 "")
95 (booktabsp "\\toprule\n")
96 (t "\\hline\n"))
97 (gethash (org-element-parent table-row) (plist-get info :org-latex-table-head-cache))
98 (if booktabsp "\\midrule" "\\hline")
99 (if booktabsp "\\midrule" "\\hline")
100 columns
101 (org-latex--translate "Continued on next page" info))))
102
103 (when (not (org-export-get-previous-element table-row info)) "\\toprule\n")
104 contents "\\\\"
105 ;; When BOOKTABS are activated enforce top-rule even when no
106 ;; hline was specifically marked.
107 (when booktabsp
108 (cond
109 ((not (org-export-get-previous-element table-row info)) nil)
110 ((not (org-export-get-next-element table-row info)) "\\bottomrule")
111 (t "\\addlinespace")))
112 "\n"))))
113(advice-add 'org-latex-table-row :override 'cmmm-org-latex-table-row)
114
115(defun cmmm-org-export-translate (s encoding info)
116 "Translate string S according to language specification.
117
118ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
119and `:utf-8'. INFO is a plist used as a communication channel.
120
121Translation depends on `:language' property. Return the
122translated string. If no translation is found, try to fall back
123to `:default' encoding. If it fails, return S."
124 (let* ((lang (plist-get info :language))
125 (translations (cdr (assoc lang
126 (cdr (assoc s org-export-dictionary))))))
127 (or (plist-get translations encoding)
128 (plist-get translations :default)
129 (plist-get translations :utf-8)
130 s)))
131(advice-add 'org-export-translate :override 'cmmm-org-export-translate)
132
133;;; ox-init.el ends here
diff --git a/doc/report.org b/doc/report.org
new file mode 100644
index 0000000..4d933e6
--- /dev/null
+++ b/doc/report.org
@@ -0,0 +1,560 @@
1#+title: Оптимизация многомерных функций с помощью эволюционной стратегии
2#+subtitle: Вариант 14
3#+author: Михалец М.
4#+date: 2025
5#+latex_header: \reportof{О ВЫПОЛНЕНИИ ПРАКТИЧЕСКОЙ РАБОТЫ №5}
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#+latex: \noindent
19В данной работе были поставлены следующие задачи:
20- Изучить теоретический материал;
21- Ознакомиться с вариантами эволюционных стратегии;
22- Рассмотреть способы выполнения оператора мутации;
23- Выполнить индивидуальное задание на любом языке высокого уровня с
24 необходимыми комментариями и выводами
25
26#+latex: \bigbreak\noindent
27*Индивидуальное задание вариант 14:*
28
29#+latex: \bigbreak
30*Дано:* Функция Изома.
31
32\[f(x_1, x_2) = -\cos(x_1)\cos(x_2)\exp(-((x_1 - \pi)^2 + (x_2 - \pi)^2))\]
33
34Область нахождения решения: \(x_1, x_2 \in [-100, 100]\)
35
36Глобальный минимум: \(\min f(x_1, x_2) = f(\pi, \pi) = -1\)
37
38#+latex: \bigbreak
39*Требуется:*
401. Создать программу, использующую генетический алгоритм для
41 нахождения минимума данной функции;
422. Для \(n = 2\) вывести на экран график функции с указанием
43 найденного экстремума и точек популяции. Предусмотреть возможность
44 пошагового просмотра процесса поиска решения;
453. Исследовать зависимость времени поиска, числа поколений
46 (генераций), точности нахождения решения от основных параметров
47 генетического алгоритма: числа особей в популяции, вероятности
48 кроссинговера и мутации;
494. Повторить процесс поиска решения для \(n = 3\), сравнить результаты
50 и скорость работы программы.
51
52* Теоретические сведения
53** Эволюционная стратегия
54Эволюционные стратегии (ЭС) основаны на эволюции популяции
55потенциальных решений. В отличие от классических генетических
56алгоритмов, ЭС используют генетические операторы на уровне фенотипа
57(вещественных чисел), а не генотипа (двоичного кода).
58
59В ЭС целью является движение особей популяции по направлению к лучшей
60области ландшафта фитнес-функции. Особь представляется парой
61действительных векторов: \[v = (x, \sigma),\] где \(x\) --- точка в
62пространстве решений (вектор переменных), а \(\sigma\) --- вектор
63стандартных отклонений (стратегических параметров), который определяет
64силу мутации для каждой переменной.
65
66Основным генетическим оператором в классической ЭС является оператор
67мутации, который выполняется путем сложения координат вектора-родителя
68со случайными числами, подчиняющимися закону нормального
69распределения: \[x^{(t + 1)} = x^{(t)} + \mathcal{N}(0, \sigma)\]
70
71** Многократная эволюционная стратегия
72Многократная эволюционная стратегия отличается от простых версий
73размером популяции (N > 2) и использованием оператора рекомбинации. В
74современных ЭС используются две основные схемы отбора:
75- (µ + λ)-ЭС: µ лучших особей отбираются из объединенной популяции, состоящей из
76µ родителей и λ потомков. Эта стратегия сохраняет лучшие решения
77(элитарная).
78- (µ, λ)-ЭС: µ лучших особей отбираются только из λ потомков.
79 Родители не участвуют в отборе. Эта стратегия позволяет алгоритму
80 выходить из локальных оптимумов.
81
82В данной работе используется стратегия (µ, λ)-ЭС с самоадаптацией
83стратегических параметров σ.
84
85* Особенности реализации
86В рамках работы создана программа =real-genetic-algorithm.c= для
87экспериментов с real-coded генетическим алгоритмом для многомерных
88функций. Она позволяет легко управлять параметрами эксперимента,
89брать статистику о времени выполнения, рисовать графики генерации и
90экспортировать таблицы.
91
92- *Кодирование особей:* Координаты и стратегические параметры хранятся
93 попарно. За это отвечают:
94 - ~#define CHROMOSOME_SIZE 2~
95 - ~struct gene { float value, sigma; }~
96 - ~struct chromosome { float fitness; struct gene genes[CHROMOSOME_SIZE]; }~
97- *Инициализация популяции:*
98 - Координаты (x): генерируются из \(\mathcal{U}(-100, 100)\).
99 - Стратегические параметры (σ): инициализируются небольшими
100 случайными положительными значениями. Эти параметры определяют
101 начальную «силу» мутации.
102 #+begin_src c
103chromosome->genes[j].value = rand_from_range (variable_limits[j].min,
104 variable_limits[j].max);
105chromosome->genes[j].sigma = sigma_initial;
106 #+end_src
107- *Фитнесс и минимум/максимум:* целевая функция передаётся параметром.
108 Для режима /минимизации/ используется внутреннее преобразование при
109 селекции (инвертирование знака/сдвиг), что позволяет единообразно
110 применять рулетку при отрицательных значениях. За это отвечают:
111 - ~#define MINMAX -1~
112 - ~float fitness_function (float *values, size_t stride)~
113 - ~bool measure_fitness (size_t population_size, size_t generation)~
114- *Эволюционная стратегия (μ + λ):* Отбор μ лучших особей производится
115 сортировкой: ~qsort (population, mu + lambda, sizeof (struct
116 chromosome), chromosome__compare_fitness)~.
117- *Мутация (самоадаптивная):* Стратегические параметры σ потомка
118 мутируют первыми. Они умножаются на экспоненту от нормально
119 распределенной случайной величины. Это позволяет шагу мутации
120 адаптироваться:
121 #+begin_src c
122#define TAU (1/sqrtf (2*sqrtf (CHROMOSOME_SIZE)))
123gene->sigma *= exp (TAU*rand_normal (0, 1));
124gene->value = clamp (gene->value + rand_normal (0, gene->sigma),
125 variable_limits[k].min, variable_limits[k].max);
126 #+end_src
127- *Критерий остановки:* используются критерий по достижению ошибки
128 меньше чем 0.00001 и по достижению популяцией максимального возраста
129 в 2000 поколений. За это отвечает: ~bool should_stop (int
130 generation)~.
131- *Визуализация:* снимок поколения включает график целевой функции,
132 точки всей текущей популяции, лучшую особь (выделена зелёным
133 цветом), а также историю лучших по предыдущим поколениям (выделены
134 жёлтым цветом). Функции:
135 - ~void plot (const char *output, size_t population_size, size_t
136 generation);~
137 - ~void run_experiment__plot (int mu, int lambda, float
138 initial_sigma)~
139- *Измерение времени:* Выполняются только необходимые операции, пока не
140 достигнут критерии остановки. Функция: ~struct measurement
141 run_experiment__measure (int mu, int lambda, float initial_sigma)~
142
143* Результаты работы
144На рис. [[convergence]] и [[generation-first]]-[[generation-last]] представлены
145результаты работы генетического алгоритма со следующими параметрами:
146- \(\mu = 40\) --- число родителей.
147- \(\lambda = 240\) --- число потомков.
148- \(\sigma^0 = 2.0\) --- начальные дисперсии.
149- Критерии остановки --- ошибка целевой функции меньше 0.00001 или
150 достигнуто поколение 2000.
151
152#+name: convergence
153#+caption: График изменения фитнесса по поколениям
154#+attr_latex: :options [H]
155#+begin_figure
156\centering
157\input{res/convergence}
158#+end_figure
159
160На поколений №4 находится критичная особь, фитнесс которой отличается
161от 0. На поколений №9 уже все особи находятся на градиенте и
162постепенно спускаются вниз. На поколении №25 достигается заданная
163точность нахождения минимума функции.
164
165#+name: generation-first
166#+caption: График целевой функции и популяции поколения №0, Лучшая особь: 0
167#+attr_latex: :options [H]
168#+begin_figure
169\centering
170#+caption: ​
171#+attr_latex: :options [b]{.55\textwidth}
172#+begin_subfigure
173 \centering
174 \input{res/mu40-lambda240-mp1.00-g0000}
175#+end_subfigure
176\hfill
177#+caption: ​
178#+attr_latex: :options [b]{.44\textwidth}
179#+begin_subfigure
180 \centering
181 \input{res/mu40-lambda240-mp1.00-g0000-map}
182#+end_subfigure
183#+caption: ​
184#+attr_latex: :options [b]{.55\textwidth}
185#+begin_subfigure
186 \centering
187 \input{res/mu40-lambda240-mp1.00-g0000-zoom}
188#+end_subfigure
189\hfill
190#+caption: ​
191#+attr_latex: :options [b]{.44\textwidth}
192#+begin_subfigure
193 \centering
194 \input{res/mu40-lambda240-mp1.00-g0000-zoom-map}
195#+end_subfigure
196#+end_figure
197
198#+caption: График целевой функции и популяции поколения №4, Лучшая особь: \num{-9.2035e-25}
199#+attr_latex: :options [H]
200#+begin_figure
201\centering
202#+caption: ​
203#+attr_latex: :options [b]{.55\textwidth}
204#+begin_subfigure
205 \centering
206 \input{res/mu40-lambda240-mp1.00-g0004}
207#+end_subfigure
208\hfill
209#+caption: ​
210#+attr_latex: :options [b]{.44\textwidth}
211#+begin_subfigure
212 \centering
213 \input{res/mu40-lambda240-mp1.00-g0004-map}
214#+end_subfigure
215#+caption: ​
216#+attr_latex: :options [b]{.55\textwidth}
217#+begin_subfigure
218 \centering
219 \input{res/mu40-lambda240-mp1.00-g0004-zoom}
220#+end_subfigure
221\hfill
222#+caption: ​
223#+attr_latex: :options [b]{.44\textwidth}
224#+begin_subfigure
225 \centering
226 \input{res/mu40-lambda240-mp1.00-g0004-zoom-map}
227#+end_subfigure
228#+end_figure
229
230#+caption: График целевой функции и популяции поколения №9, Лучшая особь: \num{-0.454163}
231#+attr_latex: :options [H]
232#+begin_figure
233\centering
234#+caption: ​
235#+attr_latex: :options [b]{.55\textwidth}
236#+begin_subfigure
237 \centering
238 \input{res/mu40-lambda240-mp1.00-g0009}
239#+end_subfigure
240\hfill
241#+caption: ​
242#+attr_latex: :options [b]{.44\textwidth}
243#+begin_subfigure
244 \centering
245 \input{res/mu40-lambda240-mp1.00-g0009-map}
246#+end_subfigure
247#+caption: ​
248#+attr_latex: :options [b]{.55\textwidth}
249#+begin_subfigure
250 \centering
251 \input{res/mu40-lambda240-mp1.00-g0009-zoom}
252#+end_subfigure
253\hfill
254#+caption: ​
255#+attr_latex: :options [b]{.44\textwidth}
256#+begin_subfigure
257 \centering
258 \input{res/mu40-lambda240-mp1.00-g0009-zoom-map}
259#+end_subfigure
260#+end_figure
261
262#+caption: График целевой функции и популяции поколения №10, Лучшая особь: \num{-0.896702}
263#+attr_latex: :options [H]
264#+begin_figure
265\centering
266#+caption: ​
267#+attr_latex: :options [b]{.55\textwidth}
268#+begin_subfigure
269 \centering
270 \input{res/mu40-lambda240-mp1.00-g0010}
271#+end_subfigure
272\hfill
273#+caption: ​
274#+attr_latex: :options [b]{.44\textwidth}
275#+begin_subfigure
276 \centering
277 \input{res/mu40-lambda240-mp1.00-g0010-map}
278#+end_subfigure
279#+caption: ​
280#+attr_latex: :options [b]{.55\textwidth}
281#+begin_subfigure
282 \centering
283 \input{res/mu40-lambda240-mp1.00-g0010-zoom}
284#+end_subfigure
285\hfill
286#+caption: ​
287#+attr_latex: :options [b]{.44\textwidth}
288#+begin_subfigure
289 \centering
290 \input{res/mu40-lambda240-mp1.00-g0010-zoom-map}
291#+end_subfigure
292#+end_figure
293
294#+caption: График целевой функции и популяции поколения №11, Лучшая особь: \num{-0.927069}
295#+attr_latex: :options [H]
296#+begin_figure
297\centering
298#+caption: ​
299#+attr_latex: :options [b]{.55\textwidth}
300#+begin_subfigure
301 \centering
302 \input{res/mu40-lambda240-mp1.00-g0011}
303#+end_subfigure
304\hfill
305#+caption: ​
306#+attr_latex: :options [b]{.44\textwidth}
307#+begin_subfigure
308 \centering
309 \input{res/mu40-lambda240-mp1.00-g0011-map}
310#+end_subfigure
311#+caption: ​
312#+attr_latex: :options [b]{.55\textwidth}
313#+begin_subfigure
314 \centering
315 \input{res/mu40-lambda240-mp1.00-g0011-zoom}
316#+end_subfigure
317\hfill
318#+caption: ​
319#+attr_latex: :options [b]{.44\textwidth}
320#+begin_subfigure
321 \centering
322 \input{res/mu40-lambda240-mp1.00-g0011-zoom-map}
323#+end_subfigure
324#+end_figure
325
326#+caption: График целевой функции и популяции поколения №13, Лучшая особь: \num{-0.994118}
327#+attr_latex: :options [H]
328#+begin_figure
329\centering
330#+caption: ​
331#+attr_latex: :options [b]{.55\textwidth}
332#+begin_subfigure
333 \centering
334 \input{res/mu40-lambda240-mp1.00-g0013}
335#+end_subfigure
336\hfill
337#+caption: ​
338#+attr_latex: :options [b]{.44\textwidth}
339#+begin_subfigure
340 \centering
341 \input{res/mu40-lambda240-mp1.00-g0013-map}
342#+end_subfigure
343#+caption: ​
344#+attr_latex: :options [b]{.55\textwidth}
345#+begin_subfigure
346 \centering
347 \input{res/mu40-lambda240-mp1.00-g0013-zoom}
348#+end_subfigure
349\hfill
350#+caption: ​
351#+attr_latex: :options [b]{.44\textwidth}
352#+begin_subfigure
353 \centering
354 \input{res/mu40-lambda240-mp1.00-g0013-zoom-map}
355#+end_subfigure
356#+end_figure
357
358#+caption: График целевой функции и популяции поколения №15, Лучшая особь: \num{-0.999128}
359#+attr_latex: :options [H]
360#+begin_figure
361\centering
362#+caption: ​
363#+attr_latex: :options [b]{.55\textwidth}
364#+begin_subfigure
365 \centering
366 \input{res/mu40-lambda240-mp1.00-g0015}
367#+end_subfigure
368\hfill
369#+caption: ​
370#+attr_latex: :options [b]{.44\textwidth}
371#+begin_subfigure
372 \centering
373 \input{res/mu40-lambda240-mp1.00-g0015-map}
374#+end_subfigure
375#+caption: ​
376#+attr_latex: :options [b]{.55\textwidth}
377#+begin_subfigure
378 \centering
379 \input{res/mu40-lambda240-mp1.00-g0015-zoom}
380#+end_subfigure
381\hfill
382#+caption: ​
383#+attr_latex: :options [b]{.44\textwidth}
384#+begin_subfigure
385 \centering
386 \input{res/mu40-lambda240-mp1.00-g0015-zoom-map}
387#+end_subfigure
388#+end_figure
389
390#+name: generation-last
391#+caption: График целевой функции и популяции поколения №25, Лучшая особь: \num{-1}
392#+attr_latex: :options [H]
393#+begin_figure
394\centering
395#+caption: ​
396#+attr_latex: :options [b]{.55\textwidth}
397#+begin_subfigure
398 \centering
399 \input{res/mu40-lambda240-mp1.00-g0025}
400#+end_subfigure
401\hfill
402#+caption: ​
403#+attr_latex: :options [b]{.44\textwidth}
404#+begin_subfigure
405 \centering
406 \input{res/mu40-lambda240-mp1.00-g0025-map}
407#+end_subfigure
408#+caption: ​
409#+attr_latex: :options [b]{.55\textwidth}
410#+begin_subfigure
411 \centering
412 \input{res/mu40-lambda240-mp1.00-g0025-zoom}
413#+end_subfigure
414\hfill
415#+caption: ​
416#+attr_latex: :options [b]{.44\textwidth}
417#+begin_subfigure
418 \centering
419 \input{res/mu40-lambda240-mp1.00-g0025-zoom-map}
420#+end_subfigure
421#+end_figure
422
423* Исследование реализации
424** Проведение измерений
425В рамках лабораторной работы необходимо было исследовать зависимость
426времени выполнения задачи и количества поколений от популяции и
427начальных стратегических параметров.
428
429Для исследования были выбраны следующие значения параметров:
430- \(\mu/\lambda = 10/70, 20/70, 20/140, 40/140, 40/280, 80/280\) ---
431 количество родителей / количество потомков.
432- \(\sigma^0 = 0.1, 0.2, 0.4, 0.8, 1, 2, 4, 8, 15, 30, 50, 100\) ---
433 начальная дисперсия.
434
435Результаты измерений представлены в таблице [[results]]. В ячейках
436указано усредненное время работы ЭС в миллисекундах. В скобках
437указано усредненное количество поколений, за которое было найдено
438решение, а на второй строке указанное среднее значение целевой
439функции. Каждый эксперимент запускался 100 раз. Лучшее значение по
440времени выполнения для каждого размера популяции выделено жирным
441шрифтом.
442
443#+include: "./res/results.org"
444
445** Анализ результатов
446#+latex: \noindent
447*Общие тенденции*
448
449Из таблицы видно, что производительность ЭС сильно зависит как от
450размера популяции (\(\mu/\lambda\)), так и от начального значения
451дисперсии \(\sigma^0\).
452
453При слишком малых \(\sigma^0 \le 0.1\) стратегия деградирует: время
454велико (до 35 мс) и поколений требуется > 1000. Это указывает на
455слабое разнообразие мутаций.
456
457При слишком больших \(\sigma^0 \ge 50\) время снова растёт, хотя
458качество решения (целевой минимум близок к −1) сохраняется. Это
459эффект *переизбыточного шага мутации*, при котором поиск теряет
460точность.
461
462Оптимальный диапазон \(\sigma^0\) ≈ 0.2–8 — в этой зоне время
463минимально, а значения функции близки к глобальному минимуму.
464
465#+latex: \bigbreak\noindent
466*Влияние размера популяции*
467
468Рост \(\lambda\) снижает число поколений, но повышает вычислительные
469затраты на одно поколение.
470
471Минимальное общее время почти всегда достигается при *крупной популяции
472(80/280)*, особенно при \(\sigma^0 = 0.2 - 4.0\). Например, для
473\(\sigma^0 = 0.2\) и \(\mu/\lambda = 20/140\) время = *1.11 мс*, что
474лучше, чем для малых популяций.
475
476Это указывает, что *параллелизм отбора и высокая вариативность потомков
477ускоряют сходимость*, несмотря на большее число вычислений в каждом
478поколении.
479
480#+latex: \bigbreak\noindent
481*Влияние \(\sigma^0\)*
482
483Поведение типично для адаптивных стратегий:
484- Слишком малое σ → поиск медленный (эксплуатация без исследования).
485- Слишком большое σ → долгая стабилизация и скачки вокруг оптимума.
486- *Средние значения (σ ≈ 0.8 – 2.0)* дают наилучший баланс скорости и
487 точности (время ≤ 2 мс, (f(x) ≈ −0.9)).
488
489#+latex: \bigbreak\noindent
490*Рекомендации:*
491- Для подобных функций (гладкие, но с узким минимумом) использовать
492 *умеренные σ ≈ 0.5–2.0*.
493- Поддерживать *относительно большую популяцию* (λ ≥ 7 μ).
494- Применять *самоадаптацию σ* с ограничениями, чтобы избежать вырождения шага.
495- Если цель — минимальное время при сохранении качества, выбрать
496 параметры близкие к \[\mu/\lambda = 20/140,\quad \sigma^0 \in [0.2,
497 2.0].\]
498
499
500* Ответ на контрольный вопрос
501#+latex: \noindent
502*Вопрос:* Что такое локальный и глобальный оператор кроссинговера?
503
504#+latex: \bigbreak\noindent
505*Ответ:*
506
507- *Локальный оператор кроссинговера:*
508
509 Комбинирует близкие (по признакам или по приспособленности) особи.
510 Цель --- тонкая настройка решения в окрестности уже хороших точек.
511 Результат — небольшие изменения, плавная эволюция, высокая
512 вероятность улучшить локальный экстремум. Пример: кроссинговер
513 между двумя похожими векторами параметров.
514- *Глобальный оператор кроссинговера:*
515
516 Комбинирует произвольные особи из популяции (без учёта расстояния
517 или близости). Цель --- широкое исследование пространства решений,
518 увеличение разнообразия. Результат — сильная вариация, шанс выйти
519 из локальных минимумов, но и риск деградации качества.
520
521*Итог:*
522- Локальный кроссинговер = эксплуатация (exploitation).
523- Глобальный кроссинговер = исследование (exploration).
524
525Эффективные эволюционные стратегии чередуют оба типа для баланса
526поиска.
527
528* ЗАКЛЮЧЕНИЕ
529:PROPERTIES:
530:UNNUMBERED: t
531:END:
532В ходе лабораторной работы была реализована программа для поиска
533минимума функции с использованием эволюционной стратегии. Было
534проведено исследование зависимости точности и скорости сходимости от
535размера популяции и начальных стратегических параметров.
536
537В результате исследования было установлено, что увеличение популяции и
538выбор оптимальных начальных параметров повышают точность и надежность
539алгоритма. Алгоритм показал свою эффективность при решении задачи
540оптимизации многомерной функции Изома, успешно находя глобальный
541минимум.
542
543* СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
544:PROPERTIES:
545:UNNUMBERED: t
546:END:
547#+latex: \nocite{METODA}
548#+print_bibliography: :heading none
549
550* ПРИЛОЖЕНИЕ А
551:PROPERTIES:
552:UNNUMBERED: t
553:END:
554#+include: "../src/evolution-strategy.c" src c
555
556# Local Variables:
557# org-confirm-babel-evaluate: nil
558# org-export-async-init-file: "ox-init.el"
559# org-export-in-background: t
560# End:
diff --git a/doc/setup.org b/doc/setup.org
new file mode 100644
index 0000000..175d50f
--- /dev/null
+++ b/doc/setup.org
@@ -0,0 +1,32 @@
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#+latex_header: \usepackage{makecell}
22#+latex_header: \usepackage{siunitx}
23
24#+latex_header: \usepackage[newfloat]{minted}
25#+latex_header: \usemintedstyle{bw}
26#+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=@@,ignorelexererrors}
27
28#+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}}
29
30#+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
31#+latex_header: \setmainfont{Times New Roman}
32#+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..60c44ad
--- /dev/null
+++ b/doc/spbstu-report.cls
@@ -0,0 +1,77 @@
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 \end{center}
56
57 \vspace{3cm}
58 \small{
59 \begin{tabular}{lrrl}
60 \!\!\!Студент, & \hspace{2cm} & & \\
61 \!\!\!группы 5130201/20101 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\
62 \!\!\!Преподаватель, & \hspace{2cm} & \\
63 \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\
64 &&\hspace{5cm}
65 \end{tabular}
66 \begin{flushright}
67 \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г.
68 \end{flushright}
69 }
70
71 \vspace*{\fill}
72 \begin{center}
73 \small{\@city, \@date}
74 \end{center}
75 \end{titlepage}
76 \setcounter{page}{2}
77}
diff --git a/src/evolution-strategy.c b/src/evolution-strategy.c
new file mode 100644
index 0000000..8a5042a
--- /dev/null
+++ b/src/evolution-strategy.c
@@ -0,0 +1,638 @@
1// evolution-strategy.c --- evolution strategy
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 360
14#define CHROMOSOME_SIZE 2
15#define GENERATION_MAX 2000
16#define FITNESS_OPTIMAL -1
17#define FITNESS_TRESHOLD_EPSILON 1e-6
18#define MINMAX -1
19#define X_MIN ((float) -100)
20#define X_MAX ((float) +100)
21#define Y_MIN X_MIN
22#define Y_MAX X_MAX
23#define SIGMA_INITIAL 2.0
24#define TAU (1/sqrtf (2*sqrtf (CHROMOSOME_SIZE)))
25
26#define Z_MIN ((float) -1.0)
27#define Z_MAX ((float) +0.5)
28#define X_MIN_ZOOM ((float) M_PI - 2)
29#define X_MAX_ZOOM ((float) M_PI + 2)
30#define Y_MIN_ZOOM X_MIN_ZOOM
31#define Y_MAX_ZOOM X_MAX_ZOOM
32#define PLOT_SAMPLE_COUNT 100
33
34// #define SEED time (NULL)
35#define SEED 1762730873
36
37#define MEASUREMENT_RUNS 100
38
39struct population_size { int mu, lambda; } population_sizes [] = {
40 { 10, 70 },
41 { 20, 70 },
42 { 20, 140 },
43 { 40, 140 },
44 { 40, 280 },
45 { 80, 280 },
46};
47
48float initial_sigmas [] = {
49 0.1,
50 0.2,
51 0.4,
52 0.8,
53 1.0,
54 2.0,
55 4.0,
56 8.0,
57 15.0,
58 30.0,
59 50.0,
60 100.0,
61};
62
63struct {
64 float min;
65 float max;
66} variable_limits[CHROMOSOME_SIZE] = {
67 { X_MIN, X_MAX },
68 { Y_MIN, Y_MAX },
69};
70
71#define ASSERT assert
72#define CTZL __builtin_ctzl
73#define EPSILON 1e-12
74
75#define PRINT_EXP(FMT, ...) printf (#__VA_ARGS__" = "FMT"\n", __VA_ARGS__)
76
77#define ARRAY_LENGTH(T) (sizeof (T)/sizeof (*(T)))
78#define FOR_EACH_ELEMENT(ELEMENT, ARRAY) \
79 for (typeof (*(ARRAY)) *(ELEMENT) = (ARRAY); \
80 (ELEMENT) < (ARRAY) + ARRAY_LENGTH (ARRAY); ++(ELEMENT)) \
81
82struct gene {
83 float value;
84 float sigma;
85};
86
87struct chromosome {
88 float fitness;
89 struct gene genes[CHROMOSOME_SIZE];
90};
91
92struct measurement {
93 float fitness;
94 float time;
95 int generations;
96};
97
98struct chromosome population [POPULATION_CAPACITY];
99struct chromosome generation_bests[GENERATION_MAX + 1];
100float generation_average_fitness[GENERATION_MAX + 1];
101
102float plot_samples [PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3];
103float plot_samples_zoom[PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3];
104struct measurement measurements[ARRAY_LENGTH (initial_sigmas )]
105 [ARRAY_LENGTH (population_sizes)];
106
107float
108easom (float x1, float x2)
109{
110 return -(cosf (x1)*cosf (x2)*expf (-((x1 - M_PI)*(x1 - M_PI) +
111 (x2 - M_PI)*(x2 - M_PI))));
112}
113
114float
115fitness_function (float *values, size_t stride)
116{
117 float x1 = *values; values += stride / sizeof(*values);
118 float x2 = *values;
119 return easom (x1, x2);
120}
121
122float
123rand_normal (float mean, float stddev) {
124 float u1 = ((float) rand () + 1)/((float) RAND_MAX + 1);
125 float u2 = ((float) rand () + 1)/((float) RAND_MAX + 1);
126 float z0 = sqrtf (-2.0*logf (u1))*cosf (2*M_PI*u2);
127 return mean + z0*stddev;
128}
129
130float
131rand_from_range (float min, float max)
132{
133 return min + (max - min)*(rand () /(float) RAND_MAX);
134}
135
136void
137create_initial_population (int population_size, float sigma_initial)
138{
139 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
140
141 for (int i = 0; i < population_size; ++i) {
142 for (int j = 0; j < CHROMOSOME_SIZE; ++j) {
143 population[i].genes[j].value = rand_from_range (variable_limits[j].min,
144 variable_limits[j].max);
145 population[i].genes[j].sigma = sigma_initial;
146 }
147 }
148}
149
150void
151measure_fitness (int from, int to)
152{
153 ASSERT (0 <= from && from <= POPULATION_CAPACITY);
154 ASSERT (0 <= to && to <= POPULATION_CAPACITY);
155 ASSERT (from <= to);
156
157 for (int i = from; i < to; ++i) {
158 population[i].fitness = fitness_function (&population[i].genes[0].value,
159 sizeof (*population[i].genes));
160 }
161}
162
163bool
164should_stop (int generation)
165{
166 if (generation >= GENERATION_MAX)
167 return true;
168
169 if (fabs (generation_bests[generation].fitness - FITNESS_OPTIMAL) < FITNESS_TRESHOLD_EPSILON)
170 return true;
171
172 return false;
173}
174
175void
176crossover_oprator ( struct chromosome *to,
177 const struct chromosome *from_a,
178 const struct chromosome *from_b)
179{
180 for (int k = 0; k < CHROMOSOME_SIZE; ++k) {
181 const struct chromosome *from = rand () % 2 ? from_a : from_b;
182 to->genes[k].value = from->genes[k].value;
183 to->genes[k].sigma = from->genes[k].sigma;
184 }
185}
186
187void
188crossover (int mu, int lambda)
189{
190 ASSERT (mu > 0);
191 ASSERT (lambda > 0);
192 ASSERT (mu + lambda <= POPULATION_CAPACITY);
193
194 for (int i = 0; i < lambda; ++i) {
195 crossover_oprator (&population[mu + i],
196 &population[rand () % mu],
197 &population[rand () % mu]);
198 }
199}
200
201float
202clamp (float value, float min, float max)
203{
204 if (value < min) return min;
205 if (value > max) return max;
206 return value;
207}
208
209void
210mutation_operator (struct chromosome *chromosome)
211{
212 for (int k = 0; k < CHROMOSOME_SIZE; ++k) {
213 struct gene *gene = &chromosome->genes[k];
214 gene->sigma *= exp (TAU*rand_normal (0, 1));
215 gene->value = clamp (gene->value + rand_normal (0, gene->sigma),
216 variable_limits[k].min, variable_limits[k].max);
217 }
218}
219
220void
221mutation (int mu, int lambda, float probability)
222{
223 for (int i = 0; i < lambda; ++i) {
224 if (rand () /(float) RAND_MAX > probability) continue;
225 mutation_operator (&population[mu + i]);
226 }
227}
228
229void
230plot (const char *output, int population_size, int generation,
231 float x_min, float x_max, float y_min, float y_max,
232 float samples[PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3])
233{
234 const char *ext = "tex";
235 FILE *gp = popen ("gnuplot", "w");
236 // FILE *gp = fopen ("test.gp", "w");
237 // fprintf (gp, "set term pngcairo\n");
238 fprintf (gp, "set term cairolatex png input blacktext notransparent"
239 " nocrop size 9cm,9cm noheader\n");
240 fprintf (gp, "set output '%s.%s'\n", output, ext);
241
242 fprintf (gp, "set lmargin at screen 0.30\n");
243 fprintf (gp, "set rmargin at screen 0.83\n");
244 fprintf (gp, "set bmargin at screen 0.05\n");
245 fprintf (gp, "set tmargin at screen 1.00\n");
246
247 fprintf (gp, "set xlabel '\\(x_1\\)'\n");
248 fprintf (gp, "set ylabel '\\(x_2\\)'\n");
249 fprintf (gp, "set zlabel '\\(f(x_1, x_2)\\)' offset graph -0.1, 0 rotate by 90\n");
250 fprintf (gp, "set xrange [%f:%f]\n", x_min, x_max);
251 fprintf (gp, "set yrange [%f:%f]\n", y_min, y_max);
252 fprintf (gp, "set zrange [%f:%f]\n", Z_MIN, Z_MAX);
253 fprintf (gp, "set xtics offset graph -0.05, graph -0.10\n");
254 fprintf (gp, "set ytics offset graph +0.05, graph +0.05\n");
255 fprintf (gp, "set ztics offset graph +0.02, graph +0.05\n");
256 fprintf (gp, "unset key\n");
257
258 fprintf (gp, "set pm3d at bs interpolate 0,0 explicit\n");
259 fprintf (gp, "set ticslevel 0\n");
260
261 fprintf (gp, "set view equal xy\n");
262 fprintf (gp, "unset colorbox\n");
263 fprintf (gp, "splot ");
264 fprintf (gp, "'-' smooth acsplines with pm3d title '%s', ", "\\small{Целевая функция}");
265 if (generation > 0)
266 fprintf (gp, "'-' with points pt 3 ps 1 lc 'yellow' title '\\small{Лучшие особи}',");
267 fprintf (gp, "'-' with points pt 3 ps 1.2 lc 'magenta' title '\\small{Минимум}',");
268 fprintf (gp, "'-' with points pt 7 ps 1 lc 'green' title '\\small{Лучшая особь поколения}',");
269 fprintf (gp, "'-' with points pt 7 ps 0.5 lc 'red' title '\\small{Популяция}'\n");
270
271 for (int x = 0; x < PLOT_SAMPLE_COUNT; ++x) {
272 for (int y = 0; y < PLOT_SAMPLE_COUNT; ++y) {
273 fprintf (gp, "%f %f %f\n",
274 samples[x][y][0],
275 samples[x][y][1],
276 samples[x][y][2]);
277 } fprintf (gp, "\n");
278 } fprintf (gp, "e\n");
279
280 if (generation > 0) {
281 for (int i = 0; i < generation; ++i) {
282 for (int j = 0; j < CHROMOSOME_SIZE; ++j)
283 fprintf (gp, "%f ", generation_bests[i].genes[j].value);
284 fprintf (gp, "%f\n", generation_bests[i].fitness);
285 } fprintf (gp, "e\n");
286 }
287
288 fprintf (gp, "%f %f %f\ne\n", M_PI, M_PI, -1.);
289
290 for (int j = 0; j < CHROMOSOME_SIZE; ++j)
291 fprintf (gp, "%f ", generation_bests[generation].genes[j].value);
292 fprintf (gp, "%f\ne\n", generation_bests[generation].fitness);
293
294 for (int i = 0; i < population_size; ++i) {
295 for (int j = 0; j < CHROMOSOME_SIZE; ++j)
296 fprintf (gp, "%f ", population[i].genes[j].value);
297 fprintf (gp, "%f\n", population[i].fitness);
298 } fprintf (gp, "e\n");
299
300 fprintf (gp, "set term cairolatex png input blacktext notransparent"
301 " nocrop size 7cm,7cm noheader\n");
302 fprintf (gp, "set output '%s-map.%s'\n", output, ext);
303 fprintf (gp, "set lmargin at screen 0.15\n");
304 fprintf (gp, "set rmargin at screen 0.85\n");
305 fprintf (gp, "set bmargin at screen 0.15\n");
306 fprintf (gp, "set tmargin at screen 0.90\n");
307 fprintf (gp, "set xtics offset graph 0, graph +0.02\n");
308 fprintf (gp, "set ytics nooffset\n");
309 fprintf (gp, "set xlabel offset graph 0, graph +0.05\n");
310 // fprintf (gp, "set title offset 0,-1\n");
311 fprintf (gp, "set view map\n");
312 fprintf (gp, "unset key\n");
313 fprintf (gp, "set colorbox\n");
314 fprintf (gp, "refresh\n");
315
316 fclose (gp);
317}
318
319int
320chromosome__compare_fitness (const void *lhs, const void *rhs)
321{
322 const struct chromosome *lhs_chromosome = lhs;
323 const struct chromosome *rhs_chromosome = rhs;
324
325 float diff = MINMAX*(rhs_chromosome->fitness - lhs_chromosome->fitness);
326 if (diff < 0) return -1;
327 if (diff > 0) return 1;
328 return 0;
329}
330
331void
332plot__fitness_over_generations (const char *output, int generations)
333{
334 FILE *gp = popen ("gnuplot", "w");
335 // FILE *gp = fopen ("test.gp", "w");
336
337 // fprintf (gp, "set term pngcairo\n");
338 // fprintf (gp, "set output '%s.png'\n", output);
339
340 fprintf (gp, "set term cairolatex pdf input blacktext notransparent"
341 " nocrop size 15cm,10cm noheader\n");
342 fprintf (gp, "set output '%s.tex'\n", output);
343
344 fprintf (gp, "set xrange [0:%d]\n", generations);
345 fprintf (gp, "set yrange [-1.1:0.1]\n");
346 fprintf (gp, "set xlabel '№ поколения'\n");
347 fprintf (gp, "set ylabel 'Значение фитнесс-функции' offset graph -0.02,0\n");
348
349 fprintf (gp, "plot ");
350 fprintf (gp, "'-' with lines title 'Лучшее значение',");
351 fprintf (gp, "'-' with lines title 'Среднее значение',");
352 fprintf (gp, "-1 dt 2 title 'Оптимальное значение'\n");
353
354 for (int i = 0; i <= generations; ++i) {
355 fprintf (gp, "%d %f\n", i, generation_bests[i].fitness);
356 } fprintf (gp, "e\n");
357
358 for (int i = 0; i <= generations; ++i) {
359 fprintf (gp, "%d %f\n", i, generation_average_fitness[i]);
360 } fprintf (gp, "e\n");
361
362 fclose (gp);
363}
364
365void
366run_experiment__plot (int mu, int lambda, float probability_mutation)
367{
368 void
369 plot_generation (int generation)
370 {
371 static char plot_output[256];
372
373 snprintf (plot_output, sizeof (plot_output), "res/mu%d-lambda%d-mp%4.2f-g%04d",
374 mu, lambda, probability_mutation, generation);
375 plot (plot_output, mu, generation,
376 X_MIN, X_MAX, Y_MIN, Y_MAX, plot_samples);
377
378 snprintf (plot_output, sizeof (plot_output), "res/mu%d-lambda%d-mp%4.2f-g%04d-zoom",
379 mu, lambda, probability_mutation, generation);
380 plot (plot_output, mu, generation,
381 X_MIN_ZOOM, X_MAX_ZOOM, Y_MIN_ZOOM, Y_MAX_ZOOM, plot_samples_zoom);
382 }
383
384 create_initial_population (mu, SIGMA_INITIAL);
385 measure_fitness (0, mu);
386 int min = 0;
387 for (int i = 1; i < mu; ++i) {
388 if (population[i].fitness < population[min].fitness)
389 min = i;
390 } memcpy (&generation_bests[0], &population[min], sizeof (struct chromosome));
391 int generation;
392 for (generation = 0; generation < GENERATION_MAX; ++generation) {
393 bool stop = should_stop (generation);
394
395 float sum = 0;
396 for (int i = 1; i < mu; ++i) {
397 sum += population[i].fitness;
398 } generation_average_fitness[generation] = sum/mu;
399
400 printf ("generation: %4d, fitness: %g, ",
401 generation, generation_bests[generation].fitness);
402 printf ("chromosome:");
403 for (int i = 0; i < CHROMOSOME_SIZE; ++i) {
404 printf (" %g/%g",
405 generation_bests[generation].genes[i].value,
406 generation_bests[generation].genes[i].sigma);
407 } printf ("\n");
408 // plot_generation (generation);
409
410 if (stop) break;
411 crossover (mu, lambda);
412 mutation (mu, lambda, probability_mutation);
413 measure_fitness (mu, mu + lambda);
414 qsort (population, mu + lambda, sizeof (struct chromosome),
415 chromosome__compare_fitness);
416
417 memcpy (&generation_bests[generation + 1], &population[0],
418 sizeof (struct chromosome));
419 }
420
421 plot__fitness_over_generations ("res/convergence", generation);
422}
423
424struct measurement
425run_experiment__measure (int mu, int lambda, float initial_sigma)
426{
427 float total_fitness = 0;
428 float total_time = 0;
429 int total_generations = 0;
430 for (int run = 0; run < MEASUREMENT_RUNS; ++run) {
431 clock_t begin = clock ();
432 create_initial_population (mu, initial_sigma);
433 int generation = 0;
434 measure_fitness (0, mu);
435 int min = 0;
436 for (int i = 1; i < mu; ++i) {
437 if (population[i].fitness < population[min].fitness)
438 min = i;
439 } memcpy (&generation_bests[generation], &population[min],
440 sizeof (struct chromosome));
441 while (!should_stop (generation++)) {
442 crossover (mu, lambda);
443 mutation (mu, lambda, 1);
444 measure_fitness (mu, mu + lambda);
445 qsort (population, mu + lambda, sizeof (struct chromosome),
446 chromosome__compare_fitness);
447 memcpy (&generation_bests[generation], &population[0],
448 sizeof (struct chromosome));
449 }
450
451 float time = (clock () - begin) /(float) CLOCKS_PER_SEC;
452 total_time += time;
453 total_generations += generation;
454 total_fitness += generation_bests[generation - (generation == GENERATION_MAX)].fitness;
455 }
456
457 return (struct measurement) {
458 .fitness = total_fitness/MEASUREMENT_RUNS,
459 .time = total_time/MEASUREMENT_RUNS,
460 .generations = (total_generations + MEASUREMENT_RUNS/2)/MEASUREMENT_RUNS,
461 };
462}
463
464void
465sample_fitness_function (float x_min, float x_max,
466 float y_min, float y_max,
467 float samples[PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3])
468{
469 float x = x_min;
470 float dx = (x_max - x_min)/(PLOT_SAMPLE_COUNT - 1);
471 for (int i = 0; i < PLOT_SAMPLE_COUNT; ++i) {
472 float y = y_min;
473 float dy = (y_max - y_min)/(PLOT_SAMPLE_COUNT - 1);
474 for (int j = 0; j < PLOT_SAMPLE_COUNT; ++j) {
475 samples[i][j][0] = x;
476 samples[i][j][1] = y;
477 samples[i][j][2] = fitness_function ((float *) samples[i][j], sizeof (float));
478 y += dy;
479 } x += dx;
480 }
481}
482
483typedef int (*print_function)(void *user, const char *template, ...);
484typedef int (*cell_function)(int x, int y, print_function, void *);
485
486int
487print__measure (void *user, const char *template, ...)
488{
489 va_list ap;
490 va_start (ap, template);
491 int len = vsnprintf (NULL, 0, template, ap);
492 va_end (ap);
493 return len;
494}
495
496int
497print__stream (void *stream, const char *template, ...)
498{
499 va_list ap;
500 va_start (ap, template);
501 int len = vfprintf (stream, template, ap);
502 va_end (ap);
503 return len;
504}
505
506void
507print_org_table (const char *filename, const char *name, const char *caption,
508 const char *align, int rows, int cols, cell_function cell)
509{
510 int cell_widths[rows][cols];
511 int column_widths[cols];
512 memset (column_widths, 0, sizeof (column_widths));
513 for (int y = 0; y < rows; ++y) {
514 for (int x = 0; x < cols; ++x) {
515 cell_widths[y][x] = cell (x, y, print__measure, NULL);
516 if (cell_widths[y][x] > column_widths[x])
517 column_widths[x] = cell_widths[y][x];;
518 }
519 }
520
521 FILE *stream = fopen (filename, "w");
522 if (name ) fprintf (stream, "#+name: %s\n", name);
523 if (caption) fprintf (stream, "#+caption: %s\n", caption);
524 if (align ) fprintf (stream, "#+attr_latex: :align %s\n", align);
525 for (int y = 0; y < rows; ++y) {
526 fprintf (stream, "|");
527 for (int x = 0; x < cols; ++x) {
528 fprintf (stream, " ");
529 if (x == 0) {
530 for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i)
531 fprintf (stream, " ");
532 }
533 cell (x, y, print__stream, stream);
534 if (x > 0) {
535 for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i)
536 fprintf (stream, " ");
537 }
538 fprintf (stream, " |");
539 } fprintf (stream, "\n");
540 if (y == 0) {
541 fprintf (stream, "|");
542 for (int x = 0; x < cols; ++x) {
543 for (int i = 0; i < column_widths[x] + 2; ++i)
544 fprintf (stream, "-");
545 fprintf (stream, "|");
546 } fprintf (stream, "\n");
547 }
548 }
549
550 fclose (stream);
551}
552
553struct measurement *best_measurement;
554int
555table_cell (int x, int y, print_function print, void *user)
556{
557 int p = x - 1;
558 int s = y - 1;
559 if (x == 0 && y == 0) return print (user, "\\(\\sigma^0 \\;\\backslash\\; \\mu/\\lambda\\)");
560 if ( y == 0) return print (user, "%d/%d", population_sizes[p].mu, population_sizes[p].lambda);
561 if (x == 0 ) return print (user, "%.2g", initial_sigmas[s]);
562
563 int len = 0;
564 bool is_best = &measurements[s][p] == best_measurement;
565 if (is_best) print (user, "*");
566 len += print (user, "\\makecell{%.2f (%lu) \\\\ %f}",
567 measurements[s][p].time*1e+3,
568 measurements[s][p].generations,
569 measurements[s][p].fitness);
570 if (is_best) print (user, "*");
571
572 return len;
573}
574
575int
576main (int argc, char *argv[])
577{
578 PRINT_EXP ("%d", POPULATION_CAPACITY);
579 PRINT_EXP ("%d", CHROMOSOME_SIZE);
580 PRINT_EXP ("%d", GENERATION_MAX);
581 PRINT_EXP ("%f", FITNESS_TRESHOLD_EPSILON);
582 PRINT_EXP ("%+f", MINMAX);
583 PRINT_EXP ("%+g", X_MIN);
584 PRINT_EXP ("%+g", X_MAX);
585 PRINT_EXP ("%+g", Y_MIN);
586 PRINT_EXP ("%+g", Y_MAX);
587 PRINT_EXP ("%d", SIGMA_INITIAL);
588 PRINT_EXP ("%+f", Z_MIN);
589 PRINT_EXP ("%+f", Z_MAX);
590 PRINT_EXP ("%+f", X_MIN_ZOOM);
591 PRINT_EXP ("%+f", X_MAX_ZOOM);
592 PRINT_EXP ("%+f", Y_MIN_ZOOM);
593 PRINT_EXP ("%+f", Y_MAX_ZOOM);
594 PRINT_EXP ("%d", PLOT_SAMPLE_COUNT);
595 PRINT_EXP ("%lu", SEED);
596 PRINT_EXP ("%d", MEASUREMENT_RUNS);
597
598 srand (SEED);
599
600 sample_fitness_function (X_MIN, X_MAX,
601 Y_MIN, Y_MAX, plot_samples);
602 sample_fitness_function (X_MIN_ZOOM, X_MAX_ZOOM,
603 Y_MIN_ZOOM, Y_MAX_ZOOM, plot_samples_zoom);
604 run_experiment__plot (40, 240, 1);
605 return 0;
606
607 best_measurement = &measurements[0][0];
608 struct measurement *measurement = &measurements[0][0];
609 FOR_EACH_ELEMENT (population_size, population_sizes) {
610 FOR_EACH_ELEMENT (initial_sigma, initial_sigmas) {
611 printf ("experiment: [%3d/%3d] %7.3f",
612 population_size->mu,
613 population_size->lambda, *initial_sigma);
614 fflush (stdout);
615 *measurement = run_experiment__measure (population_size->mu,
616 population_size->lambda,
617 *initial_sigma);
618 printf (" @ %+8.6f/%4d (%6.2f ms)\n", measurement->fitness, measurement->generations, measurement->time*1e+3);
619 if (measurement->time < best_measurement->time)
620 best_measurement = measurement;
621 measurement += 1;
622 }
623 }
624
625 char *table_filename = NULL;
626 char *table_name = NULL;
627 char *table_caption = NULL;
628 asprintf (&table_filename, "res/results.org");
629 asprintf (&table_name, "results");
630 asprintf (&table_caption, "Результаты");
631 print_org_table (table_filename, table_name, table_caption, "ccc",
632 1 + ARRAY_LENGTH (initial_sigmas),
633 1 + ARRAY_LENGTH (population_sizes), table_cell);
634
635 return EXIT_SUCCESS;
636}
637
638// evolution-strategy.c ends here