aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore6
-rw-r--r--README.org15
-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/optimal-tour.gp115
-rw-r--r--doc/ox-init.el132
-rw-r--r--doc/report.org653
-rw-r--r--doc/setup.org34
-rw-r--r--doc/spbstu-report.cls77
-rw-r--r--src/genetic-algorithm.c870
19 files changed, 2319 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4090660
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
1*.html
2*.pdf
3*.tex
4*.dot
5*.png
6/genetic-algorithm \ No newline at end of file
diff --git a/README.org b/README.org
new file mode 100644
index 0000000..fb0ca36
--- /dev/null
+++ b/README.org
@@ -0,0 +1,15 @@
1#+title: Solving the traveling salesman problem
2#+subtitle: using a genetic algorithm
3#+date: 2025H2
4
5* Documentation
6:PROPERTIES:
7:CUSTOM_ID: documentation
8:END:
9The exported report can be found at [[https://git.michalec.dev/files/uni/term-07/gen-alg/lab-03/report.pdf][this link]].
10
11* Unlicense
12:PROPERTIES:
13:CUSTOM_ID: unlicense
14:END:
15#+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..488a673
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,5 @@
1#!/bin/sh
2
3set -xe
4
5gcc -std=gnu99 -O3 -march=native -lm src/genetic-algorithm.c -o 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/optimal-tour.gp b/doc/optimal-tour.gp
new file mode 100644
index 0000000..ec312d4
--- /dev/null
+++ b/doc/optimal-tour.gp
@@ -0,0 +1,115 @@
1set term cairolatex pdf input blacktext notransparent nocrop size 15cm,10cm noheader
2set output './res/optimal-tour.tex'
3set xlabel '\(x\)'
4set ylabel '\(y\)'
5set xrange [-75:1840]
6set yrange [-95:1275]
7plot '-' with lines lw 9.0 lc 'gray' title '\small{Оптимальный путь}', \
8 '-' with points ps 0.5 pt 2 lc 'blue' title '\small{Координаты}'
9565 575
10605 625
11575 665
12555 815
13510 875
14475 960
15525 1000
16580 1175
17650 1130
18875 920
191150 1160
201340 725
211605 620
221740 245
231530 5
241465 200
251170 65
261215 245
271320 315
281250 400
291220 580
30975 580
31945 685
32880 660
33845 680
34845 655
35835 625
36830 610
37795 645
38770 610
39760 650
40720 635
41685 610
42685 595
43700 580
44700 500
45830 485
46725 370
47660 180
48595 360
49560 365
50480 415
51410 250
5225 185
5325 230
5495 260
55300 465
56145 665
57345 750
58415 635
59420 555
60520 585
61565 575
62e
63565 575
6425 185
65345 750
66945 685
67845 655
68880 660
6925 230
70525 1000
71580 1175
72650 1130
731605 620
741220 580
751465 200
761530 5
77845 680
78725 370
79145 665
80415 635
81510 875
82560 365
83300 465
84520 585
85480 415
86835 625
87975 580
881215 245
891320 315
901250 400
91660 180
92410 250
93420 555
94575 665
951150 1160
96700 580
97685 595
98685 610
99770 610
100795 645
101720 635
102760 650
103475 960
10495 260
105875 920
106700 500
107555 815
108830 485
1091170 65
110830 610
111605 625
112595 360
1131340 725
1141740 245
115e
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.
41CONTENTS is the contents of the row. INFO is a plist used as
42a 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
117ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
118and `:utf-8'. INFO is a plist used as a communication channel.
119
120Translation depends on `:language' property. Return the
121translated string. If no translation is found, try to fall back
122to `: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..c5a5dbb
--- /dev/null
+++ b/doc/report.org
@@ -0,0 +1,653 @@
1#+title: Решение задачи коммивояжера с помощью генетических алгоритмов
2#+subtitle: Вариант 14
3#+author: Михалец М.
4#+date: 2025
5#+latex_header: \reportof{О ВЫПОЛНЕНИИ ПРАКТИЧЕСКОЙ РАБОТЫ №3}
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 зависимости от вероятности различных видов кроссовера, мутации.
27
28#+latex: \bigbreak\noindent
29*Индивидуальное задание вариант 14:*
30
31#+latex: \bigbreak\noindent
32*Дано:* Эвклидовы координаты 52 городов в Берлине (см. [[#A]]). Оптимальный
33тур представлен на Рис. [[optimal-tour]], его длина равна 7498.270020.
34
35#+name: optimal-tour
36#+caption: Оптиматльный тур для заданного набора данных
37#+attr_latex: :options [H]
38#+begin_figure
39\centering
40\input{./res/optimal-tour}
41#+end_figure
42
43#+latex: \bigbreak\noindent
44*Требуется:*
451. Реализовать с использованием генетических алгоритмов решение задачи
46 коммивояжера.
472. Для туров использовать путевое представление.
48
49* Теоретические сведения
50Генетические алгоритмы (ГА) используют принципы и терминологию,
51заимствованные у биологической науки --- генетики. В ГА каждая особь
52представляет потенциальное решение некоторой проблемы. В классическом
53ГА особь кодируется строкой двоичных символов – хромосомой, каждый бит
54которой называется геном. Множество особей – потенциальных решений
55составляет популяцию. Поиск (суб)оптимального решения проблемы
56выполняется в процессе эволюции популяции --- последовательного
57преобразования одного конечного множества решений в другое с помощью
58генетических операторов репродукции, кроссинговера и мутации.
59
60Предварительно простой ГА случайным образом генерирует начальную
61популяцию стрингов (хромосом). Затем алгоритм генерирует следующее
62поколение (популяцию), с помощью трех основных генетических
63операторов:
641. Оператор репродукции (ОР);
652. Оператор скрещивания (кроссинговера, ОК);
663. Оператор мутации (ОМ).
67
68ГА работает до тех пор, пока не будет выполнено заданное количество
69поколений (итераций) процесса эволюции или на некоторой генерации
70будет получено заданное качество или вследствие преждевременной
71сходимости при попадании в некоторый локальный оптимум. На
72Рис. [[simple-genetic-algorithm]] представлен простой генетический алгоритм.
73
74#+name: simple-genetic-algorithm
75#+caption: Простой генетический алгоритм
76#+attr_latex: :options [H] :height .55\textheight
77[[./res/simple-genetic-algorithm.png]]
78
79** Основная терминология в генетических алгоритмах
80/Ген/ --- элементарный код в хромосоме \(s_i\), называемый также знаком
81или детектором (в классическом ГА \(s_i = 0, 1\)).
82
83/Хромосома/ --- упорядоченная последовательность генов в виде
84закодированной структуры данных \(S = (s_1, s_2, \ldots, s_n)\),
85определяющая решение (в простейшем случае двоичная последовательность
86--- строка, где \(s_i = 0, 1\)).
87
88/Локус/ --- местоположение (позиция, номер бита) данного гена в
89хромосоме.
90
91/Аллель/ --- значение, которое принимает данный ген (например, 0 или 1).
92
93/Особь/ --- одно потенциальное решение задачи (представляемое
94хромосомой).
95
96/Популяция/ --- множество особей (хромосом), представляющих
97потенциальные решения.
98
99/Поколение/ --- текущая популяция ГА на данной итерации алгоритма.
100
101/Генотип/ --- набор хромосом данной особи. В популяции могут
102использоваться как отдельные хромосомы, так и целые генотипы.
103
104/Генофонд/ --- множество всех возможных генотипов.
105
106/Фенотип/ --- набор значений, соответствующий данному генотипу. Это
107декодированное множество параметров задачи (например, десятичное
108значение \(x\), соответствующее двоичному коду).
109
110/Размер популяции \(N\)/ --- число особей в популяции.
111
112/Число поколений/ --- количество итераций, в течение которых
113производится поиск.
114
115/Селекция/ --- совокупность правил, определяющих выживание особей на
116основе значений целевой функции.
117
118/Эволюция популяции/ --- чередование поколений, в которых хромосомы
119изменяют свои признаки, чтобы каждая новая популяция лучше
120приспосабливалась к среде.
121
122/Фитнесс-функция/ --- функция полезности, определяющая меру
123приспособленности особи. В задачах оптимизации она совпадает с
124целевой функцией или описывает близость к оптимальному решению.
125
126** Представления хромосом для задачи коммивояжера
127Задача коммивояжера (ЗК) формулируется так: требуется посетить каждый
128из \(N\) городов ровно один раз и вернуться в исходную точку,
129минимизируя суммарную стоимость (или длину) тура. Естественным
130является представление тура как перестановки городов. На практике
131используются три основных представления, каждое со своими операторами
132рекомбинации:
133
134*** Представление соседства
135Тур задаётся списком из \(N\) городов, где в позиции \(i\) указан
136город \(j\), означающий переход из города \(i\) в город \(j\).
137Например, вектор \((2\;4\;8\;3\;9\;7\;1\;5\;6)\) соответствует туру
138\(1\!\to\!2\!\to\!4\!\to\!3\!\to\!8\!\to\!5\!\to\!9\!\to\!6\!\to\!7\).
139У каждого корректного тура есть единственное соседское представление,
140однако не всякая строка в этом представлении корректна (возможны
141преждевременные циклы, например \(1\!\to\!2\!\to\!4\!\to\!1\ldots\)).
142
143*** Порядковое представление
144Тур представляется списком из \(N\) позиций; \(i\)-й элемент равен
145индексу города в текущем упорядоченном списке доступных городов.
146Например, при опорном списке \(C = (1\;2\;3\;4\;5\;6\;7\;8\;9)\) тур
147\(1\!\to\!2\!\to\!4\!\to\!3\!\to\!8\!\to\!5\!\to\!9\!\to\!6\!\to\!7\)
148кодируется как \(l = (1\;1\;2\;1\;4\;1\;3\;1\;1)\), последовательно
149«выбирая» элементы из \(C\).
150
151*** Путевое представление
152Наиболее интуитивное представление: тур записывается как
153последовательность городов, например
154\(5\!\to\!1\!\to\!7\!\to\!8\!\to\!9\!\to\!4\!\to\!6\!\to\!2\!\to\!3\)
155кодируется как \((5\;1\;7\;8\;9\;4\;6\;2\;3)\). Это представление
156сохраняет относительный порядок городов и широко применяется на
157практике.
158
159** Кроссинговеры для представлений ЗК
160Операторы рекомбинации должны сохранять допустимость туров
161(перестановочную природу решения). Для разных представлений
162используются различные кроссинговеры.
163
164*** Кроссинговеры для представления соседства
165*Alternating Edges (обмен рёбрами):* потомок строится, поочерёдно
166выбирая ребра у родителей: одно ребро у первого родителя, следующее
167--- у второго, затем снова у первого и т.д. Если выбранное ребро
168замыкает цикл преждевременно, выбирается другое ещё не использованное
169ребро того же родителя, не образующее цикл.
170
171*Subtour Chunks (обмен подтурами):* потомок формируется конкатенацией
172кусочков (подтуров), поочерёдно взятых у родителей. При образовании
173преждевременного цикла производится «ремонт» аналогично предыдущему
174оператору.
175
176*Heuristic Crossover (эвристический):* стартуя из случайного города, на
177каждом шаге сравниваются два инцидентных ребра, предлагаемых
178родителями, и выбирается более короткое; если возникает цикл или ребро
179уже использовано, выбирается случайный ещё не посещённый город.
180Оператор нацелен на сохранение коротких рёбер, но может иметь
181нестабильную производительность.
182
183*** Кроссинговеры для порядкового представления
184Для порядкового представления корректность потомков обеспечивает классический одноточечный кроссовер: любые два родителя, разрезанные в одной позиции и склеенные, порождают допустимых потомков (поскольку выбор «по индексу» в оставшемся списке городов остаётся корректным).
185
186*** Кроссинговеры для путевого представления
187Для путевого представления широко применяются три оператора,
188гарантирующие корректную перестановку у потомков.
189
190**** PMX (Partially Mapped Crossover)
191*Идея:* обменять подпоследовательности между родителями и построить
192отображение соответствий, которым затем разрешать конфликты
193(дубликаты).
194
195/Пример./ Пусть точки разреза задают сегмент позиций \(4 \dots 7\):
196
197\[p_1 = (1\;2\;3\;|\;4\;5\;6\;7\;|\;8\;9),\quad p_2 =
198(4\;5\;2\;|\;1\;8\;7\;6\;|\;9\;3).\]
199
2001. Копируем сегмент второго родителя в потомка \(o_1\) и формируем
201 отображение \(\{4 \leftrightarrow 1,\; 5 \leftrightarrow 8,\; 6
202 \leftrightarrow 7,\; 7 \leftrightarrow 6\}\): \[o_1 =
203 (\_\;\_\;\_\;|\;1\;8\;7\;6\;|\;\_\;\_).\]
2042. Заполняем прочие позиции по порядку из \(p_1\), применяя
205 отображение при конфликтах: \(1 \mapsto 4\), \(8 \mapsto 5\).
206 \[o_1 = (4\;2\;3\;|\;1\;8\;7\;6\;|\;5\;9).\] Аналогично для \(o_2\)
207 (копируем сегмент из \(p_1\), заполняем остальное из \(p_2\)):
208 \[o_2=(1\;8\;2\;|\;4\;5\;6\;7\;|\;9\;3).\]
209
210PMX сохраняет как позиции части элементов, так и относительный
211порядок/соответствия на остальной части хромосомы.
212
213**** OX (Order Crossover)
214*Идея:* скопировать сегмент одного родителя и дозаполнить оставшиеся
215позиции элементами второго родителя в их порядке появления (пропуская
216уже скопированные).
217
218/Пример./ С теми же родителями и разрезами \(4 \dots 7\):
219
220\[p_1 = (1\;2\;3\;|\;4\;5\;6\;7\;|\;8\;9),\quad
221p_2 = (4\;5\;2\;|\;1\;8\;7\;6\;|\;9\;3).\]
222
2231. Копируем сегмент \(p_1\) в \(o_1\):
224 \[o_1 = (\_\;\_\;\_\;|\;4\;5\;6\;7\;|\;\_\;\_).\]
2252. Обходя \(p_2\) с позиции после правого разреза, дозаполняем:
226 получаем \[o_1 = (2\;1\;8\;|\;4\;5\;6\;7\;|\;9\;3).\] Симметрично
227 для \(o_2\) (копируем сегмент из \(p_2\) и дозаполняем порядком из
228 \(p_1\)): \[o_2 = (3\;4\;5\;|\;1\;8\;7\;6\;|\;9\;2).\] Оператор OX
229 сохраняет относительный порядок городов; циклический сдвиг тура
230 несущественен.
231
232**** CX (Cycle Crossover)
233*Идея:* находить циклы позиций, индуцированные взаимным расположением
234значений у родителей, и наследовать циклы по очереди из разных
235родителей.
236
237/Пример./ Возьмём
238
239\[p_1 = (1\;2\;3\;4\;5\;6\;7\;8\;9),\quad p_2 =
240(4\;5\;2\;1\;8\;7\;6\;9\;3).\]
241
242Построив циклы позиций, получим допустимых потомков, например: \[o_1 =
243(1\;2\;3\;4\;7\;6\;9\;8\;5),\quad o_2 = (4\;1\;2\;8\;5\;6\;7\;3\;9).\]
244
245CX сохраняет абсолютные позиции части элементов и способствует передаче «циклами» взаимных расположений.
246
247Отметим, что путевое представление акцентирует порядок городов (а не
248стартовый город), поэтому туры, отличающиеся циклическим сдвигом,
249эквивалентны.
250
251*** Мутации для путевого представления
252Операторы мутации в ГА для задачи коммивояжёра должны сохранять
253допустимость решения (перестановочную структуру). Для путевого
254представления применяются специализированные операторы, которые
255модифицируют порядок городов, не нарушая корректности тура.
256
257**** Swap (обмен двух элементов)
258*Идея:* выбрать случайным образом две позиции в маршруте и обменять
259находящиеся на них города местами.
260
261/Пример./ Пусть исходный тур:
262
263\[t = (1\;2\;3\;4\;5\;6\;7\;8\;9).\]
264
265Выбираем позиции \(i = 2\) и \(j = 6\) (элементы \(3\) и \(7\)).
266После обмена получаем:
267
268\[t' = (1\;2\;7\;4\;5\;6\;3\;8\;9).\]
269
270Оператор swap обеспечивает локальную модификацию тура, изменяя
271положение только двух городов.
272
273**** Inversion (инверсия сегмента)
274*Идея:* выбрать случайный сегмент маршрута и обратить порядок городов
275внутри него.
276
277/Пример./ Для того же тура выбираем позиции разреза \(i = 3\) и \(j = 7\) (сегмент \(4\;5\;6\;7\)):
278
279\[t = (1\;2\;3\;|\;4\;5\;6\;7\;|\;8\;9).\]
280
281Инвертируем выделенный сегмент:
282
283\[t' = (1\;2\;3\;|\;7\;6\;5\;4\;|\;8\;9).\]
284
285Инверсия сохраняет связность частей маршрута, меняя направление обхода
286в подтуре. Этот оператор особенно эффективен при наличии пересечений
287рёбер, так как инверсия может «распутать» некоторые из них и улучшить
288длину маршрута.
289
290**** Insertion (вырезка и вставка)
291*Идея:* выбрать случайный город, удалить его из текущей позиции и
292вставить в другую случайную позицию маршрута.
293
294/Пример./ Пусть исходный тур:
295
296\[t = (1\;2\;3\;4\;5\;6\;7\;8\;9).\]
297
298Выбираем город на позиции \(i = 3\) (элемент \(4\)) и целевую позицию
299\(j = 7\). Удаляем элемент \(4\):
300
301\[t_{\text{tmp}} = (1\;2\;3\;5\;6\;7\;8\;9).\]
302
303Вставляем \(4\) на позицию \(7\):
304
305\[t' = (1\;2\;3\;5\;6\;7\;4\;8\;9).\]
306
307insertion изменяет расположение одного города относительно других,
308смещая соседей.
309
310Все три оператора гарантируют сохранение корректной перестановки:
311каждый город остаётся в туре ровно один раз.
312
313* Особенности реализации
314В рамках работы была расширена программа =genetic-algorithm.c= для
315экспериментов с генетическим алгоритмом (ГА) для решения задачи
316коммивояжёра. Она позволяет легко управлять параметрами эксперимента,
317брать статистику о времени выполнения, рисовать графики генерации и
318экспортировать таблицы.
319
320- *Кодирование особей (Представление порядка):* каждая хромосома ---
321 массив целочисленных переменных. Декодирование --- линейное в
322 \([-10, 10]\). Для точности \(10^{-3}\) для данного декодирования
323 необходимо использовать хотя бы 15 бит, которые дают шаг
324 дискретизации \approx 0.0006. Длина хромосомы совпадает с
325 количеством пунктов -- 52. За это отвечают:
326 - ~#define CHROMOSOME_SIZE ARRAY_LENGTH (buildings)~
327 - ~int get_index (gene code, uint64_t *mask);~
328 - ~struct point get_point (gene code, uint64_t *mask);~
329 - ~int get_ordinal (gene index, uint64_t *mask);~
330 - ~void create_initial_population (int population_size);~
331
332 Для преобразования представления пути не использует список, а
333 множество представляемое одним целым числом. Это значительно
334 повышает производительность. Данные функции реализованы в виде
335 генераторов, контекст хранится в ~mask~.
336 #+begin_src c
337 gene
338 get_index (gene code, uint64_t *mask)
339 {
340 ASSERT (CHROMOSOME_SIZE < 64);
341
342 const uint64_t end = ((uint64_t) 1 << CHROMOSOME_SIZE);
343 gene idx = 0;
344 uint64_t head = 1;
345 do {
346 bool is_set = !!(*mask & head);
347 if (code == 0 && is_set) break;
348
349 code -= is_set;
350 idx += 1;
351 head <<= 1;
352 } while (head != end);
353 *mask ^= head;
354
355 return idx;
356 }
357
358 gene
359 get_ordinal (gene index, uint64_t *mask)
360 {
361 const uint64_t end = ((uint64_t) 1 << CHROMOSOME_SIZE);
362 gene c = index;
363 uint64_t head = 1;
364 do {
365 if (!index) break;
366
367 c -= !!(*mask & head);
368 index -= 1;
369 head <<= 1;
370 } while (head != end);
371 ASSERT (c < CHROMOSOME_SIZE);
372 *mask ^= head;
373
374 return c;
375 }
376 #+end_src
377- *Фитнесс и минимум/максимум:* Для ускорения вычислений, всё расстояния
378 подсчитаны заранее. За это отвечают:
379 - ~#define MINMAX -1~
380 - ~float distances[CHROMOSOME_SIZE][CHROMOSOME_SIZE];~
381 - ~float fitness_function (chromosome x);~
382 - ~void measure_fitness (int population_size, int generation);~
383 - ~void bake (void);~
384 #+begin_src c
385 float
386 fitness_function (chromosome x)
387 {
388 ASSERT (CHROMOSOME_SIZE < 64);
389
390 float distance = 0;
391 uint64_t mask = ((uint64_t) 1 << CHROMOSOME_SIZE) - 1;
392 int prev = get_index (x[0], &mask);
393 for (int i = 1; i < CHROMOSOME_SIZE; ++i) {
394 int curr = get_index (x[i], &mask);
395 distance += distances[prev][curr];
396 prev = curr;
397 }
398
399 return distance;
400 }
401 #+end_src
402- *Селекция (Турнирная):* вероятности нормируются после сдвига на
403 минимальное значение в поколении (устойчиво к отрицательным
404 фитнессам). Функция: ~void selection__tournament (int
405 population_size, int tournament_size)~.
406- *Кроссинговер (Двухточечный):* попарно по перемешанной популяции. При
407 нечётном размере последняя особь скрещивается со случайной другой
408 особью (возможно повторное участие в кроссинговере одной из особей).
409 Пары скрещиваются с вероятностью \(P_c\), иначе родители добавляются
410 в новую популяцию без изменений. Поддерживаются также одноточечный
411 и равномерный кроссинговеры. Функции:
412 - ~void crossover (int population_size, float probability)~
413 - ~void crossover__two_point (int population_size, float probability)~
414 - ~void crossover__uniform (int population_size, float probability)~
415- *Мутация (SWAP):* с вероятностью \(P_m\) /на хромосому/ заменяются
416 местами 2 города (с переводом представления). Также поддерживается
417 обычная мутация. Функции:
418 - ~void mutation (int population_size, float probability)~
419 - ~void mutation__swap (int population_size, float probability)~
420- *Критерий остановки:* Используются критерий по сохранению лучшего
421 значения 100 поколений и по достижению популяцией максимального
422 возраста в 2000 поколений. За это отвечают:
423 - ~#define GENERATION_MAX 2000~
424 - ~#define FITNESS_TRESHOLD_BEST_REPEAT 100~
425 - ~bool should_stop (int generation)~
426 #+begin_src c
427 bool
428 should_stop (int generation)
429 {
430 static int repeat_count = 0;
431
432 if (generation == GENERATION_MAX)
433 return true;
434
435 if (generation + 1 < FITNESS_TRESHOLD_BEST_REPEAT)
436 return false;
437
438 if (fabs (generation_bests_fitness[generation - 1] -
439 generation_bests_fitness[generation - 0]) < EPSILON) {
440 repeat_count += 1;
441 } else repeat_count = 0;
442
443 return repeat_count >= FITNESS_TRESHOLD_BEST_REPEAT;
444 }
445 #+end_src
446- *Визуализация:* снимок поколения включает оптимальный маршрут
447 (выделенный зелёным цветом), маршрут лучшей особи (выделенный
448 красным цветом), города (синие крестики). Функция: ~void plot (const
449 char *output, int population_size, int generation);~.
450- *Измерение времени:* Выполняются только необходимые операции, пока не
451 достигнут критерии остановки. Функция: ~struct measurement
452 run_experiment__measure (int population_size, float
453 probability_crossover, float probability_mutation)~
454
455* Результаты работы
456На Рис. [[generation-first]]-[[generation-last]] представлены результаты работы генетического алгоритма со следующими параметрами:
457- \(N = 200\) --- размер популяции.
458- \(P_c = 0.2\) --- вероятность кроссинговера.
459- \(P_m = 0.7\) --- вероятность мутации.
460- \(1\) --- количество «элитных» особей, переносимых без изменения в
461 следующее поколение.
462- Критерии остановки --- повтор лучшего значения в последних 100
463 поколениях или достижение возраста в 2000 поколений.
464
465На Рис. [[fitness]] показан график изменения фитнесса по поколениям.
466Видно, что алгоритм постепенно сходится к значению фитнесса
467\(9689.396484\), но оптимального маршрута, со значением фитнесса
468\(7498.270020\), так и не находит.
469
470#+name: fitness
471#+caption: График изменения фитнесса по поколениям
472#+attr_latex: :options [H]
473#+begin_figure
474\centering
475\input{res/fitness}
476#+end_figure
477
478#+name: generation-first
479#+caption: Лучший маршрут поколения №0
480#+attr_latex: :options [H]
481#+begin_figure
482\centering
483\input{res/p200-c0.20-m0.70-g0000}
484#+end_figure
485
486#+caption: Лучший маршрут поколения №20
487#+attr_latex: :options [H]
488#+begin_figure
489\centering
490\input{res/p200-c0.20-m0.70-g0020}
491#+end_figure
492
493#+caption: Лучший маршрут поколения №120
494#+attr_latex: :options [H]
495#+begin_figure
496\centering
497\input{res/p200-c0.20-m0.70-g0120}
498#+end_figure
499
500#+caption: Лучший маршрут поколения №1060
501#+attr_latex: :options [H]
502#+begin_figure
503\centering
504\input{res/p200-c0.20-m0.70-g1060}
505#+end_figure
506
507#+caption: Лучший маршрут поколения №1290
508#+attr_latex: :options [H]
509#+begin_figure
510\centering
511\input{res/p200-c0.20-m0.70-g1290}
512#+end_figure
513
514#+name: generation-last
515#+caption: Лучший маршрут поколения №1390
516#+attr_latex: :options [H]
517#+begin_figure
518\centering
519\input{res/p200-c0.20-m0.70-g1390}
520#+end_figure
521
522* Исследование реализации
523** Проведение измерений
524В рамках лабораторной работы необходимо было исследовать зависимость
525времени выполнения задачи и количества поколений от популяции и
526вероятностей кроссинговера и мутации хромосомы.
527
528Для исследования были выбраны следующие значения параметров:
529- \(N = 10, 25, 50, 100, 500\) --- размер популяции.
530- \(P_c = 0.3, 0.4, 0.5, 0.6, 0.7, 0.8\) --- вероятность
531 кроссинговера.
532- \(P_m = 0.01, 0.1, 0.2, 0.3, 0.4\) --- вероятность мутации.
533
534Результаты измерений представлены в таблицах [[results-10]]-[[results-500]].
535В ячейках указано усредненное время работы ГА в миллисекундах. В
536скобках указано усредненное количество поколений, за которое было
537найдено решение. Каждый эксперимент запускался 100 раз. Лучшее
538значение по времени выполнения для каждого размера популяции выделено
539жирным шрифтом.
540
541#+include: "./res/results-010.org"
542
543#+include: "./res/results-025.org"
544
545#+include: "./res/results-050.org"
546
547#+include: "./res/results-100.org"
548
549#+include: "./res/results-500.org"
550
551** Анализ результатов
5521. Трудность нахождения истинного минимума
553
554 Анализ показывает, что нахождение значения функции меньше ~10000
555 оказалось затруднительным. Даже при оптимальных параметрах
556 алгоритм чаще сходился к локальным минимумам в диапазоне
557 \(10000{-}11000\), что указывает на недостаточную глубину поиска и
558 высокую плотность локальных экстремумов в целевой функции. Для
559 более надёжного приближения к истинному минимуму требуется либо
560 увеличение популяции, либо адаптивное изменение вероятностей
561 мутации и кроссинговера.
5622. Зависимость от размера популяции \(N\)
563
564 Время выполнения растёт почти линейно с увеличением размера
565 популяции \(N\). При переходе от \(N = 10\) к \(N = 500\) среднее
566 время увеличивается примерно на два порядка. Это объясняется
567 ростом количества операций в каждом поколении. При этом
568 стабильность решения возрастает --- практически отсутствуют случаи,
569 когда решение не найдено за 2000 поколений при больших \(N\).
5703. Влияние вероятности кроссинговера \(P_c\)
571
572 Для малых популяций (\(N = 10, 25\)) наименьшее время решения
573 наблюдается при \(P_c = 0.4{-}0.6\). При \(P_c < 0.4\) алгоритм
574 демонстрирует низкую эффективность, а при \(P_c > 0.7\)
575 увеличивается разброс времени и снижается стабильность. Для
576 больших \(N\) эффект сглаживается, но оптимальная зона остаётся в
577 диапазоне \(0.5{-}0.7\).
5784. Влияние вероятности мутации \(P_m\)
579
580 Слишком малые значения (\(P_m < 0.05\)) приводят к стагнации поиска
581 --- алгоритм долго не находит глобальный минимум. Слишком большие
582 (\(P_m > 0.3\)) увеличивают случайность поиска и среднее время
583 выполнения. Оптимальные значения лежат в пределах \(P_m =
584 0.1{-}0.2\).
5855. Количество поколений
586
587 При малых популяциях часто достигался лимит в 2000 поколений, что
588 указывает на низкую вероятность нахождения глобального минимума.
589 При \(N \ge 50\) решение стабильно находилось за 500--1000
590 поколений.
5916. Сводный результат
592 - Минимальное время выполнения при сбалансированных параметрах
593 наблюдается при: \[N = 50{-}100,\quad P_c = 0.5{-}0.6,\quad P_m =
594 0.1{-}0.2.\]
595 - При этих условиях алгоритм демонстрирует оптимальное соотношение
596 скорости и качества поиска.
5977. Интерпретация
598
599 При слишком малой популяции наблюдается недостаточная
600 диверсификация решений, что затрудняет поиск глобального минимума.
601 При чрезмерно большой популяции вычислительные затраты становятся
602 избыточными. Оптимум достигается при умеренном размере популяции и
603 средних значениях вероятностей генетических операторов.
604
605* Ответ на контрольный вопрос
606#+latex: \noindent
607*Вопрос:* В чем основная идея применения ГА для решения задачи
608коммивояжера?
609
610#+latex: \bigbreak\noindent
611*Ответ:* Использовать механизм эволюции для поиска маршрута с
612минимальной длиной среди всех возможных перестановок городов.
613
614* ЗАКЛЮЧЕНИЕ
615:PROPERTIES:
616:UNNUMBERED: t
617:END:
618В ходе третьей лабораторной работы была исследована задача
619коммивояжера с использованием генетических алгоритмов для 52 городов
620Берлина:
621- Изучен теоретический материал о представлениях туров (соседское,
622 порядковое, путевое) и специализированных операторах кроссинговера и
623 мутации для задачи коммивояжера;
624- Создана программа на языке Си с реализацией порядкового
625 представления хромосом, одно-точечного, двух-точечного и
626 равномерного операторов кроссинговера, обычной и SWAP мутации, а
627 также турнирная селекции с поддержкой элитизма;
628- Проведено исследование влияния параметров генетического алгоритма на
629 качество и скорость нахождения решения для популяций размером 10,
630 25, 50, 100 и 500 особей с различными значениями вероятностей
631 кроссинговера и мутации;
632- Получено решение с длиной маршрута 9558.044922, отклоняющееся от
633 оптимального значения 7498.270020 на 27%.
634
635* СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
636:PROPERTIES:
637:UNNUMBERED: t
638:END:
639#+latex: \nocite{METODA}
640#+print_bibliography: :heading none
641
642* ПРИЛОЖЕНИЕ А
643:PROPERTIES:
644:UNNUMBERED: t
645:CUSTOM_ID: A
646:END:
647#+include: "../src/genetic-algorithm.c" src c
648
649# Local Variables:
650# org-confirm-babel-evaluate: nil
651# org-export-async-init-file: "ox-init.el"
652# org-export-in-background: t
653# End:
diff --git a/doc/setup.org b/doc/setup.org
new file mode 100644
index 0000000..07ca141
--- /dev/null
+++ b/doc/setup.org
@@ -0,0 +1,34 @@
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{cellspace}
23# #+latex_header: \setlength\cellspacetoplimit{2ex}
24# #+latex_header: \setlength\cellspacebottomlimit{2ex}
25
26#+latex_header: \usepackage[newfloat]{minted}
27#+latex_header: \usemintedstyle{bw}
28#+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=@@,ignorelexererrors}
29
30#+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}}
31
32#+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
33#+latex_header: \setmainfont{Times New Roman}
34#+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/genetic-algorithm.c b/src/genetic-algorithm.c
new file mode 100644
index 0000000..204c256
--- /dev/null
+++ b/src/genetic-algorithm.c
@@ -0,0 +1,870 @@
1// genetic-algorithm.c --- genetic algorithm
2// Представление порядка
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <stdarg.h>
8#include <math.h>
9#include <time.h>
10#include <float.h>
11#include <string.h>
12#include <assert.h>
13
14#define POPULATION_CAPACITY 500
15#define GENERATION_MAX 2000
16#define FITNESS_TRESHOLD_BEST_REPEAT 500
17#define ELITE_COUNT 1
18#define TOURNAMENT_SIZE 2
19#define PLOT_POPULATION_SIZE 200
20#define PLOT_PROBABILITY_CROSSOVER .2
21#define PLOT_PROBABILITY_MUTATION .7
22#define DIGITS_AFTER_DECIMAL 3
23#define MINMAX -1
24#define X_MIN ( 25 - 100)
25#define X_MAX (1740 + 100)
26#define Y_MIN ( 5 - 100)
27#define Y_MAX (1175 + 100)
28// #define SEED time (NULL)
29#define SEED 1760751688
30#define MEASUREMENT_RUNS 10
31// #define PLOT_PNG
32
33#define ARRAY_LENGTH(T) (sizeof (T)/sizeof (*(T)))
34#define FOR_EACH_ELEMENT(ELEMENT, ARRAY) \
35 for (typeof (*(ARRAY)) *(ELEMENT) = (ARRAY); \
36 (ELEMENT) < (ARRAY) + ARRAY_LENGTH (ARRAY); ++(ELEMENT)) \
37
38int population_sizes [] = { 10, 25, 50, 100, 500 };
39float probabilities_crossover [] = { 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 };
40float probabilities_mutation [] = { 0.01, 0.1, 0.2, 0.3, 0.4 };
41
42struct point { int16_t x, y; };
43struct point buildings[] = {
44 { 565, 575 },
45 { 25, 185 },
46 { 345, 750 },
47 { 945, 685 },
48 { 845, 655 },
49 { 880, 660 },
50 { 25, 230 },
51 { 525, 1000 },
52 { 580, 1175 },
53 { 650, 1130 },
54 { 1605, 620 },
55 { 1220, 580 },
56 { 1465, 200 },
57 { 1530, 5 },
58 { 845, 680 },
59 { 725, 370 },
60 { 145, 665 },
61 { 415, 635 },
62 { 510, 875 },
63 { 560, 365 },
64 { 300, 465 },
65 { 520, 585 },
66 { 480, 415 },
67 { 835, 625 },
68 { 975, 580 },
69 { 1215, 245 },
70 { 1320, 315 },
71 { 1250, 400 },
72 { 660, 180 },
73 { 410, 250 },
74 { 420, 555 },
75 { 575, 665 },
76 { 1150, 1160 },
77 { 700, 580 },
78 { 685, 595 },
79 { 685, 610 },
80 { 770, 610 },
81 { 795, 645 },
82 { 720, 635 },
83 { 760, 650 },
84 { 475, 960 },
85 { 95, 260 },
86 { 875, 920 },
87 { 700, 500 },
88 { 555, 815 },
89 { 830, 485 },
90 { 1170, 65 },
91 { 830, 610 },
92 { 605, 625 },
93 { 595, 360 },
94 { 1340, 725 },
95 { 1740, 245 },
96};
97
98uint8_t best_route__original[] = {
99 1, 49, 32, 45, 19, 41, 8, 9, 10, 43, 33, 51, 11,
100 52, 14, 13, 47, 26, 27, 28, 12, 25, 4, 6, 15, 5,
101 24, 48, 38, 37, 40, 39, 36, 35, 34, 44, 46, 16, 29,
102 50, 20, 23, 30, 2, 7, 42, 21, 17, 3, 18, 31, 22,
103};
104
105uint8_t best_route[] = {
106 0, 47, 30, 42, 17, 37, 6, 6, 6, 35, 26, 39, 6,
107 38, 8, 7, 33, 17, 17, 17, 6, 15, 2, 3, 4, 2,
108 10, 23, 17, 16, 17, 16, 15, 14, 13, 14, 14, 3, 9,
109 12, 5, 7, 7, 0, 1, 6, 3, 1, 0, 0, 1, 0,
110};
111
112#define CHROMOSOME_SIZE ARRAY_LENGTH (buildings)
113
114float distances[CHROMOSOME_SIZE][CHROMOSOME_SIZE] = {
115 { 0, 666.108, 281.114, 395.601, 291.204, 326.267, 640.8, 426.878, 600.188, 561.471, 1040.97, 655.019, 975, 1120.77, 299.04, 260.048, 429.535, 161.555, 305, 210.06, 286.923, 46.0977, 181.177, 274.591, 410.03, 728.972, 798.514, 707.001, 406.263, 360.069, 146.373, 90.5538, 827.315, 135.093, 121.655, 125, 207.966, 240.416, 166.208, 208.926, 395.38, 565.796, 463.816, 154.434, 240.208, 279.866, 791.281, 267.301, 64.0312, 217.083, 789.383, 1220.46, },
116 { 666.108, 0, 649.327, 1047.09, 945.146, 978.085, 45, 956.151, 1134.96, 1132.98, 1638.79, 1258.59, 1440.08, 1515.73, 957.823, 724.034, 494.773, 595.483, 843.401, 564.469, 392.46, 636.416, 509.828, 921.792, 1028.85, 1191.51, 1301.51, 1243.72, 635.02, 390.448, 541.225, 730, 1488.71, 782.081, 776.981, 785, 857.7, 896.939, 827.964, 869.741, 896.172, 102.591, 1123.71, 744.883, 823.286, 859.084, 1151.27, 910.302, 728.011, 596.259, 1421.56, 1716.05, },
117 { 281.114, 649.327, 0, 603.511, 508.945, 542.517, 610.573, 308.058, 485.644, 487.263, 1266.69, 891.361, 1247.76, 1399.73, 504.876, 537.401, 217.313, 134.629, 207.002, 440.965, 288.531, 240.52, 361.179, 505.693, 652.534, 1005.94, 1067.64, 970.322, 651.249, 504.207, 208.926, 245.204, 903.396, 393.605, 373.664, 367.696, 447.465, 462.088, 392.237, 426.878, 246.982, 550.091, 556.597, 434.195, 219.829, 552.675, 1072.31, 504.802, 288.487, 463.249, 995.314, 1483.59, },
118 { 395.601, 1047.09, 603.511, 0, 104.403, 69.6419, 1026.36, 525, 611.003, 533.901, 663.193, 294.364, 711.073, 897.009, 100.125, 384.22, 800.25, 532.353, 474.684, 500.625, 681.487, 436.606, 537.703, 125.3, 109.202, 516.236, 526.806, 417.433, 579.871, 689.529, 540.856, 370.54, 517.349, 266.552, 275.136, 270.601, 190.394, 155.242, 230.489, 188.282, 544.541, 950.329, 245.204, 307.002, 411.096, 230.705, 659.564, 137.295, 345.254, 477.624, 397.02, 908.639, },
119 { 291.204, 945.146, 508.945, 104.403, 0, 35.3553, 923.594, 470.558, 583.631, 513.469, 760.805, 382.426, 769.042, 944.312, 25, 309.233, 700.071, 430.465, 400.78, 406.602, 577.17, 332.453, 436.835, 31.6228, 150.083, 552.268, 584.145, 478.592, 509.755, 594.348, 436.606, 270.185, 589.958, 163.248, 170.88, 166.208, 87.4643, 50.9902, 126.59, 85.1469, 479.505, 847.659, 266.693, 212.25, 331.21, 170.66, 673.591, 47.4342, 241.868, 386.685, 499.925, 984.441, },
120 { 326.267, 978.085, 542.517, 69.6419, 35.3553, 0, 957.04, 491.554, 596.008, 523.259, 726.103, 349.285, 744.194, 922.781, 40.3113, 328.824, 735.017, 465.672, 427.931, 435.23, 611.903, 367.73, 469.068, 57.0088, 124.197, 533.339, 559.129, 452.217, 528.015, 623.699, 471.832, 305.041, 568.243, 196.977, 205.548, 201.308, 120.83, 86.3134, 161.941, 120.416, 504.009, 881.036, 260.048, 240.832, 360.069, 182.003, 661.91, 70.7107, 277.218, 413.793, 464.57, 954.895, },
121 { 640.8, 45, 610.573, 1026.36, 923.594, 957.04, 0, 918.096, 1095.92, 1095.73, 1627.42, 1245.2, 1440.31, 1521.73, 935.361, 713.863, 451.248, 562.25, 807.001, 551.77, 361.732, 609.139, 491.172, 901.18, 1012.42, 1190.09, 1297.79, 1236.74, 636.965, 385.519, 511.517, 701.231, 1459.63, 760.345, 754.205, 761.577, 836.316, 874.714, 804.394, 846.537, 857.555, 76.1577, 1094.81, 726.997, 789.383, 844.423, 1156.83, 890.183, 701.73, 584.637, 1405.08, 1715.07, },
122 { 426.878, 956.151, 308.058, 525, 470.558, 491.554, 918.096, 0, 183.439, 180.347, 1144.9, 812.05, 1234.34, 1414.23, 452.548, 660.984, 506.582, 381.215, 125.897, 635.964, 580.388, 415.03, 586.728, 486.544, 615.549, 1022.8, 1049.4, 941.077, 831.039, 758.765, 457.22, 338.711, 645.155, 455, 435.46, 421.545, 460.57, 446.01, 413.824, 421.574, 64.0312, 855.862, 359.026, 529.74, 187.417, 598.54, 1135.89, 495.101, 383.438, 643.817, 860.145, 1430.47, },
123 { 600.188, 1134.96, 485.644, 611.003, 583.631, 596.008, 1095.92, 183.439, 0, 83.2166, 1165.61, 873.856, 1316.76, 1507.12, 561.471, 817.955, 670.317, 564.646, 308.058, 810.247, 763.217, 593.043, 766.551, 606.238, 714.178, 1126.11, 1134.55, 1024.46, 998.211, 940.492, 640.312, 510.025, 570.197, 606.98, 589.428, 574.674, 596.091, 571.948, 557.853, 555, 239.27, 1035.59, 389.936, 685.584, 360.867, 733.894, 1257.06, 617.839, 550.568, 815.138, 883.233, 1486.78, },
124 { 561.471, 1132.98, 487.263, 533.901, 513.469, 523.259, 1095.73, 180.347, 83.2166, 0, 1082.65, 792.086, 1236.58, 1428.29, 490.433, 763.692, 686.477, 547.951, 290.904, 770.276, 751.482, 560.29, 734.932, 537.82, 638.847, 1049.98, 1055.05, 944.934, 950.053, 912.14, 619.294, 471.01, 500.899, 552.268, 536.144, 521.177, 533.667, 506.211, 499.925, 492.443, 243.977, 1031.95, 307.774, 631.981, 329.014, 669.645, 1185.17, 550.273, 507.001, 771.962, 800.078, 1404.04, },
125 { 1040.97, 1638.79, 1266.69, 663.193, 760.805, 726.103, 1627.42, 1144.9, 1165.61, 1082.65, 0, 387.072, 442.719, 619.556, 762.365, 914.822, 1460.69, 1190.09, 1124.3, 1075.66, 1314.17, 1085.56, 1143.53, 770.016, 631.269, 541.041, 417.433, 417.642, 1042.41, 1250.97, 1186.78, 1030.98, 706.134, 905.884, 920.34, 920.054, 835.06, 810.386, 885.127, 845.532, 1180.04, 1552.32, 789.24, 912.921, 1067.95, 786.67, 705.16, 775.065, 1000.01, 1042.93, 285.044, 398.56, },
126 { 655.019, 1258.59, 891.361, 294.364, 382.426, 349.285, 1245.2, 812.05, 873.856, 792.086, 387.072, 0, 452.134, 653.242, 388.104, 537.703, 1078.36, 806.877, 768.847, 694.136, 927.16, 700.018, 758.172, 387.621, 245, 335.037, 283.24, 182.483, 688.186, 874.643, 800.391, 650.577, 584.209, 520, 535.21, 535.84, 450.999, 429.942, 503.016, 465.296, 836.316, 1169.63, 484.381, 526.118, 705.301, 401.404, 517.422, 391.152, 616.644, 662.59, 188.215, 618.567, },
127 { 975, 1440.08, 1247.76, 711.073, 769.042, 744.194, 1440.31, 1234.34, 1316.76, 1236.58, 442.719, 452.134, 0, 205.548, 784.092, 759.276, 1399.51, 1136.54, 1169.47, 919.918, 1194.76, 1020.42, 1008.19, 759.951, 620.081, 254.018, 185.068, 293.641, 805.248, 1056.18, 1103.65, 1004.15, 1010.36, 854.181, 874.314, 881.192, 806.923, 804.316, 862.699, 836.376, 1248.08, 1371.31, 930.86, 821.721, 1098.33, 696.024, 324.423, 755.86, 959.284, 884.59, 539.676, 278.658, },
128 { 1120.77, 1515.73, 1399.73, 897.009, 944.312, 922.781, 1521.73, 1414.23, 1507.12, 1428.29, 619.556, 653.242, 205.548, 0, 961.691, 883.883, 1534.22, 1280.67, 1340.63, 1034.65, 1313.2, 1164.69, 1127.21, 931.357, 799.156, 396.011, 374.433, 484.175, 887.426, 1146.48, 1238.79, 1160.87, 1215.91, 1009.72, 1030.59, 1039.25, 971.404, 974.59, 1026.16, 1004.45, 1423.04, 1457.48, 1125.28, 966.398, 1267.57, 848.764, 364.966, 925.216, 1113.56, 1000.12, 744.648, 318.904, },
129 { 299.04, 957.823, 504.876, 100.125, 25, 40.3113, 935.361, 452.548, 561.471, 490.433, 762.365, 388.104, 784.092, 961.691, 0, 332.415, 700.161, 432.348, 387.621, 424.794, 585.875, 338.6, 451.054, 55.9017, 164.012, 571.074, 599.041, 492.367, 533.128, 611.658, 443.001, 270.416, 568.705, 176.139, 181.177, 174.642, 102.591, 61.0328, 132.853, 90.1388, 464.004, 859.593, 241.868, 231.138, 319.883, 195.576, 695.593, 71.5891, 246.221, 406.079, 497.041, 995.113, },
130 { 260.048, 724.034, 537.401, 384.22, 309.233, 328.824, 713.863, 660.984, 817.955, 763.692, 914.822, 537.703, 759.276, 883.883, 332.415, 0, 650.711, 407.83, 548.862, 165.076, 435.488, 297.069, 249.098, 277.714, 326.497, 505.693, 597.537, 525.856, 200.811, 337.083, 356.721, 330.946, 897.065, 211.483, 228.528, 243.311, 244.182, 283.769, 265.047, 282.179, 640.781, 639.531, 570.088, 132.382, 476.366, 155.724, 539.49, 261.964, 281.824, 130.384, 710.106, 1022.67, },
131 { 429.535, 494.773, 217.313, 800.25, 700.071, 735.017, 451.248, 506.582, 670.317, 686.477, 1460.69, 1078.36, 1399.51, 1534.22, 700.161, 650.711, 0, 271.662, 421.1, 512.079, 253.032, 383.438, 418.001, 691.158, 834.341, 1149.48, 1226.02, 1136.33, 707.425, 492.392, 296.184, 430, 1120.29, 561.471, 544.518, 542.794, 627.415, 650.308, 575.782, 615.183, 442.634, 408.075, 773.256, 579.008, 436.578, 708.255, 1187.7, 687.204, 461.736, 543.622, 1196.51, 1649.37, },
132 { 161.555, 595.483, 134.629, 532.353, 430.465, 465.672, 562.25, 381.215, 564.646, 547.951, 1190.09, 806.877, 1136.54, 1280.67, 432.348, 407.83, 271.662, 0, 258.118, 306.472, 205.244, 116.297, 229.401, 420.119, 562.694, 890, 959.909, 867.439, 516.769, 385.032, 80.1561, 162.788, 903.244, 290.259, 272.947, 271.155, 355.879, 380.132, 305, 345.326, 330.492, 492.976, 541.133, 315.357, 228.035, 441.277, 946.005, 415.752, 190.263, 328.672, 929.368, 1381.2, },
133 { 305, 843.401, 207.002, 474.684, 400.78, 427.931, 807.001, 125.897, 308.058, 290.904, 1124.3, 768.847, 1169.47, 1340.63, 387.621, 548.862, 421.1, 258.118, 0, 512.445, 460.652, 290.172, 460.977, 410.03, 550.681, 945.476, 984.733, 879.332, 711.003, 632.949, 332.415, 219.829, 700.589, 350.892, 330.189, 317.569, 371.248, 366.231, 318.904, 336.341, 91.9239, 741.923, 367.764, 420.387, 75, 504.48, 1044.84, 415.482, 267.442, 521.967, 843.445, 1381.96, },
134 { 210.06, 564.469, 440.965, 500.625, 406.602, 435.23, 551.77, 635.964, 810.247, 770.276, 1075.66, 694.136, 919.918, 1034.65, 424.794, 165.076, 512.079, 306.472, 512.445, 0, 278.568, 223.607, 94.3398, 378.451, 467.386, 665.902, 761.643, 690.887, 210.297, 189.011, 236.008, 300.375, 990.013, 256.564, 261.773, 275.045, 322.684, 365.548, 313.847, 348.174, 601.041, 476.707, 638.161, 194.486, 450.028, 295.466, 679.779, 364.589, 263.866, 35.3553, 859.069, 1186.09, },
135 { 286.923, 392.46, 288.531, 681.487, 577.17, 611.903, 361.732, 580.388, 763.217, 751.482, 1314.17, 927.16, 1194.76, 1313.2, 585.875, 435.488, 253.032, 205.244, 460.652, 278.568, 0, 250.599, 186.815, 558.413, 684.726, 941.077, 1030.97, 952.221, 459.157, 241.506, 150, 340.037, 1097.96, 416.203, 406.356, 411.4, 491.859, 526.711, 453.1, 495.807, 525.024, 289.914, 733.246, 401.528, 433.042, 530.377, 957.549, 549.477, 344.42, 313.129, 1072.01, 1456.71, },
136 { 46.0977, 636.416, 240.52, 436.606, 332.453, 367.73, 609.139, 415.03, 593.043, 560.29, 1085.56, 700.018, 1020.42, 1164.69, 338.6, 297.069, 383.438, 116.297, 290.172, 223.607, 250.599, 0, 174.642, 317.53, 455.027, 773.709, 844.334, 753.077, 428.515, 352.598, 104.403, 97.0824, 852.951, 180.069, 165.303, 166.883, 251.247, 281.469, 206.155, 248.646, 377.69, 535.023, 488.109, 199.06, 232.648, 325.73, 832.406, 311.006, 93.9415, 237.171, 831.865, 1266.49, },
137 { 181.177, 509.828, 361.179, 537.703, 436.835, 469.068, 491.172, 586.728, 766.551, 734.932, 1143.53, 758.172, 1008.19, 1127.21, 451.054, 249.098, 418.001, 229.401, 460.977, 94.3398, 186.815, 174.642, 0, 412.462, 521.776, 754.404, 845.931, 770.146, 296.015, 179.234, 152.315, 267.442, 1001.96, 275, 272.809, 282.931, 349.464, 390.032, 325.576, 365.548, 545.023, 415.03, 641.132, 235.85, 406.971, 356.931, 773.692, 400.656, 244.387, 127.475, 914.166, 1271.42, },
138 { 274.591, 921.792, 505.693, 125.3, 31.6228, 57.0088, 901.18, 486.544, 606.238, 537.82, 770.016, 387.621, 759.951, 931.357, 55.9017, 277.714, 691.158, 420.119, 410.03, 378.451, 558.413, 317.53, 412.462, 0, 147.054, 537.401, 575.608, 472.07, 478.174, 566.789, 420.862, 263.059, 620.846, 142.302, 152.971, 150.748, 66.7083, 44.7214, 115.434, 79.0569, 491.757, 825.121, 297.7, 183.984, 338.378, 140.089, 652.553, 15.8114, 230, 357.526, 514.806, 981.542, },
139 { 410.03, 1028.85, 652.534, 109.202, 150.083, 124.197, 1012.42, 615.549, 714.178, 638.847, 631.269, 245, 620.081, 799.156, 164.012, 326.497, 834.341, 562.694, 550.681, 467.386, 684.726, 455.027, 521.776, 147.054, 0, 412.098, 435.029, 328.672, 509.141, 654.313, 555.563, 408.932, 605.826, 275, 290.388, 291.548, 207.183, 191.377, 260.864, 226.108, 628.013, 936.376, 354.401, 286.4, 481.274, 173.349, 550.681, 148.071, 372.726, 439.09, 392.747, 835.135, },
140 { 728.972, 1191.51, 1005.94, 516.236, 552.268, 533.339, 1190.09, 1022.8, 1126.11, 1049.98, 541.041, 335.037, 254.018, 396.011, 571.074, 505.693, 1149.48, 890, 945.476, 665.902, 941.077, 773.709, 754.404, 537.401, 412.098, 0, 126.194, 158.902, 558.793, 805.016, 853.302, 765.506, 917.306, 614.37, 635.138, 643.525, 575.543, 580, 630.179, 609.139, 1028.99, 1120.1, 755.794, 574.674, 872.067, 453.679, 185.54, 530.519, 718.679, 630.575, 496.009, 525, },
141 { 798.514, 1301.51, 1067.64, 526.806, 584.145, 559.129, 1297.79, 1049.4, 1134.55, 1055.05, 417.433, 283.24, 185.068, 374.433, 599.041, 597.537, 1226.02, 959.909, 984.733, 761.643, 1030.97, 844.334, 845.931, 575.608, 435.029, 126.194, 0, 110.114, 673.665, 912.318, 931.451, 823.119, 861.931, 674.259, 693.992, 700.179, 624.119, 620.101, 680, 652.553, 1063.04, 1226.23, 751.033, 647.012, 913.906, 518.652, 291.548, 571.948, 779.311, 726.395, 410.488, 425.793, },
142 { 707.001, 1243.72, 970.322, 417.433, 478.592, 452.217, 1236.74, 941.077, 1024.46, 944.934, 417.642, 182.483, 293.641, 484.175, 492.367, 525.856, 1136.33, 867.439, 879.332, 690.887, 952.221, 753.077, 770.146, 472.07, 328.672, 158.902, 110.114, 0, 629.682, 853.288, 844.349, 725.155, 766.551, 578.705, 597.704, 602.764, 523.927, 516.769, 579.763, 550.091, 956.151, 1163.45, 641.112, 559.017, 809.475, 428.515, 344.42, 469.574, 683.118, 656.22, 337.231, 513.931, },
143 { 406.263, 635.02, 651.249, 579.871, 509.755, 528.015, 636.965, 831.039, 998.211, 950.053, 1042.41, 688.186, 805.248, 887.426, 533.128, 200.811, 707.425, 516.769, 711.003, 210.297, 459.157, 428.515, 296.015, 478.174, 509.141, 558.793, 673.665, 629.682, 0, 259.615, 445.225, 492.392, 1095.67, 401.995, 415.752, 430.726, 443.847, 484.2, 458.939, 480.521, 801.639, 570.636, 770.6, 322.49, 643.623, 349.178, 522.805, 462.385, 448.386, 191.377, 871.45, 1081.95, },
144 { 360.069, 390.448, 504.207, 689.529, 594.348, 623.699, 385.519, 758.765, 940.492, 912.14, 1250.97, 874.643, 1056.18, 1146.48, 611.658, 337.083, 492.392, 385.032, 632.949, 189.011, 241.506, 352.598, 179.234, 566.789, 654.313, 805.016, 912.318, 853.288, 259.615, 0, 305.164, 446.598, 1172.9, 439.318, 441.192, 453.018, 509.117, 551.589, 494.292, 531.507, 712.969, 315.159, 815.552, 382.884, 583.31, 481.274, 782.192, 553.173, 422.67, 215.232, 1044.28, 1330.01, },
145 { 146.373, 541.225, 208.926, 540.856, 436.606, 471.832, 511.517, 457.22, 640.312, 619.294, 1186.78, 800.391, 1103.65, 1238.79, 443.001, 356.721, 296.184, 80.1561, 332.415, 236.008, 150, 104.403, 152.315, 420.862, 555.563, 853.302, 931.451, 844.349, 445.225, 305.164, 0, 190.066, 948.117, 281.114, 268.002, 270.647, 354.295, 385.649, 310.483, 353.023, 408.717, 438.919, 583.31, 285.351, 292.959, 415.933, 895.879, 413.673, 197.8, 262.011, 935.575, 1355.91, },
146 { 90.5538, 730, 245.204, 370.54, 270.185, 305.041, 701.231, 338.711, 510.025, 471.01, 1030.98, 650.577, 1004.15, 1160.87, 270.416, 330.946, 430, 162.788, 219.829, 300.375, 340.037, 97.0824, 267.442, 263.059, 408.932, 765.506, 823.119, 725.155, 492.392, 446.598, 190.066, 0, 758.716, 151.162, 130.384, 122.984, 202.608, 220.907, 148.071, 185.607, 311.488, 628.033, 393.732, 207.002, 151.327, 312.13, 845, 260.864, 50, 305.655, 767.349, 1238.4, },
147 { 827.315, 1488.71, 903.396, 517.349, 589.958, 568.243, 1459.63, 645.155, 570.197, 500.899, 706.134, 584.209, 1010.36, 1215.91, 568.705, 897.065, 1120.29, 903.244, 700.589, 990.013, 1097.96, 852.951, 1001.96, 620.846, 605.826, 917.306, 861.931, 766.551, 1095.67, 1172.9, 948.117, 758.716, 0, 734.098, 731.745, 720.226, 668.506, 625.5, 678.62, 642.028, 704.006, 1386.73, 365, 798.812, 687.786, 747.011, 1095.18, 636.318, 763.708, 973.666, 474.684, 1088.73, },
148 { 135.093, 782.081, 393.605, 266.552, 163.248, 196.977, 760.345, 455, 606.98, 552.268, 905.884, 520, 854.181, 1009.72, 176.139, 211.483, 561.471, 290.259, 350.892, 256.564, 416.203, 180.069, 275, 142.302, 275, 614.37, 674.259, 578.705, 401.995, 439.318, 281.114, 151.162, 734.098, 0, 21.2132, 33.541, 76.1577, 115.109, 58.5235, 92.1954, 441.616, 684.416, 382.394, 80, 276.134, 161.012, 697.227, 133.417, 105.119, 243.772, 656.22, 1092.62, },
149 { 121.655, 776.981, 373.664, 275.136, 170.88, 205.548, 754.205, 435.46, 589.428, 536.144, 920.34, 535.21, 874.314, 1030.59, 181.177, 228.528, 544.518, 272.947, 330.189, 261.773, 406.356, 165.303, 272.809, 152.971, 290.388, 635.138, 693.992, 597.704, 415.752, 441.192, 268.002, 130.384, 731.745, 21.2132, 0, 15, 86.3134, 120.83, 53.1507, 93.0054, 421.1, 678.473, 376.464, 96.1769, 255.539, 182.003, 718.418, 145.774, 85.44, 251.645, 667.776, 1111.54, },
150 { 125, 785, 367.696, 270.601, 166.208, 201.308, 761.577, 421.545, 574.674, 521.177, 920.054, 535.84, 881.192, 1039.25, 174.642, 243.311, 542.794, 271.155, 317.569, 275.045, 411.4, 166.883, 282.931, 150.748, 291.548, 643.525, 700.179, 602.764, 430.726, 453.018, 270.647, 122.984, 720.226, 33.541, 15, 0, 85, 115.434, 43.0116, 85, 408.167, 686.003, 363.593, 111.018, 242.745, 191.442, 729.555, 145, 81.3941, 265.707, 665.019, 1116.36, },
151 { 207.966, 857.7, 447.465, 190.394, 87.4643, 120.83, 836.316, 460.57, 596.091, 533.667, 835.06, 450.999, 806.923, 971.404, 102.591, 244.182, 627.415, 355.879, 371.248, 322.684, 491.859, 251.247, 349.464, 66.7083, 207.183, 575.543, 624.119, 523.927, 443.847, 509.117, 354.295, 202.608, 668.506, 76.1577, 86.3134, 85, 0, 43.0116, 55.9017, 41.2311, 457.739, 760.345, 327.3, 130.384, 297.069, 138.654, 676.036, 60, 165.68, 305.164, 581.485, 1036.4, },
152 { 240.416, 896.939, 462.088, 155.242, 50.9902, 86.3134, 874.714, 446.01, 571.948, 506.211, 810.386, 429.942, 804.316, 974.59, 61.0328, 283.769, 650.308, 380.132, 366.231, 365.548, 526.711, 281.469, 390.032, 44.7214, 191.377, 580, 620.101, 516.769, 484.2, 551.589, 385.649, 220.907, 625.5, 115.109, 120.83, 115.434, 43.0116, 0, 75.6637, 35.3553, 449.027, 798.89, 286.4, 173.349, 294.109, 163.783, 690.67, 49.4975, 191.05, 348.174, 550.84, 1026.17, },
153 { 166.208, 827.964, 392.237, 230.489, 126.59, 161.941, 804.394, 413.824, 557.853, 499.925, 885.127, 503.016, 862.699, 1026.16, 132.853, 265.047, 575.782, 305, 318.904, 313.847, 453.1, 206.155, 325.576, 115.434, 260.864, 630.179, 680, 579.763, 458.939, 494.292, 310.483, 148.071, 678.62, 58.5235, 53.1507, 43.0116, 55.9017, 75.6637, 0, 42.72, 407.001, 728.869, 324.423, 136.473, 244.182, 186.011, 726.223, 112.805, 115.434, 302.076, 626.498, 1092.02, },
154 { 208.926, 869.741, 426.878, 188.282, 85.1469, 120.416, 846.537, 421.574, 555, 492.443, 845.532, 465.296, 836.376, 1004.45, 90.1388, 282.179, 615.183, 345.326, 336.341, 348.174, 495.807, 248.646, 365.548, 79.0569, 226.108, 609.139, 652.553, 550.091, 480.521, 531.507, 353.023, 185.607, 642.028, 92.1954, 93.0054, 85, 41.2311, 35.3553, 42.72, 0, 421.1, 770.925, 293.471, 161.555, 263.154, 179.234, 714.37, 80.6226, 157.003, 333.654, 584.829, 1060.39, },
155 { 395.38, 896.172, 246.982, 544.541, 479.505, 504.009, 857.555, 64.0312, 239.27, 243.977, 1180.04, 836.316, 1248.08, 1423.04, 464.004, 640.781, 442.634, 330.492, 91.9239, 601.041, 525.024, 377.69, 545.023, 491.757, 628.013, 1028.99, 1063.04, 956.151, 801.639, 712.969, 408.717, 311.488, 704.006, 441.616, 421.1, 408.167, 457.739, 449.027, 407.001, 421.1, 0, 796.492, 401.995, 512.079, 165.605, 593.001, 1133.16, 498.523, 359.34, 611.882, 896.354, 1453.08, },
156 { 565.796, 102.591, 550.091, 950.329, 847.659, 881.036, 76.1577, 855.862, 1035.59, 1031.95, 1552.32, 1169.63, 1371.31, 1457.48, 859.593, 639.531, 408.075, 492.976, 741.923, 476.707, 289.914, 535.023, 415.03, 825.121, 936.376, 1120.1, 1226.23, 1163.45, 570.636, 315.159, 438.919, 628.033, 1386.73, 684.416, 678.473, 686.003, 760.345, 798.89, 728.869, 770.925, 796.492, 0, 1021.76, 650.865, 720.85, 768.668, 1092.54, 814.079, 627.156, 509.902, 1329, 1645.07, },
157 { 463.816, 1123.71, 556.597, 245.204, 266.693, 260.048, 1094.81, 359.026, 389.936, 307.774, 789.24, 484.381, 930.86, 1125.28, 241.868, 570.088, 773.256, 541.133, 367.764, 638.161, 733.246, 488.109, 641.132, 297.7, 354.401, 755.794, 751.033, 641.112, 770.6, 815.552, 583.31, 393.732, 365, 382.394, 376.464, 363.593, 327.3, 286.4, 324.423, 293.471, 401.995, 1021.76, 0, 455, 336.786, 437.321, 904.461, 313.249, 399.906, 626.099, 504.232, 1097.2, },
158 { 154.434, 744.883, 434.195, 307.002, 212.25, 240.832, 726.997, 529.74, 685.584, 631.981, 912.921, 526.118, 821.721, 966.398, 231.138, 132.382, 579.008, 315.357, 420.387, 194.486, 401.528, 199.06, 235.85, 183.984, 286.4, 574.674, 647.012, 559.017, 322.49, 382.884, 285.351, 207.002, 798.812, 80, 96.1769, 111.018, 130.384, 173.349, 136.473, 161.555, 512.079, 650.865, 455, 0, 346.771, 130.863, 640.41, 170.294, 157.003, 175, 678.399, 1070.81, },
159 { 240.208, 823.286, 219.829, 411.096, 331.21, 360.069, 789.383, 187.417, 360.867, 329.014, 1067.95, 705.301, 1098.33, 1267.57, 319.883, 476.366, 436.578, 228.035, 75, 450.028, 433.042, 232.648, 406.971, 338.378, 481.274, 872.067, 913.906, 809.475, 643.623, 583.31, 292.959, 151.327, 687.786, 276.134, 255.539, 242.745, 297.069, 294.109, 244.182, 263.154, 165.605, 720.85, 336.786, 346.771, 0, 429.564, 969.91, 343.001, 196.469, 456.755, 790.142, 1314.96, },
160 { 279.866, 859.084, 552.675, 230.705, 170.66, 182.003, 844.423, 598.54, 733.894, 669.645, 786.67, 401.404, 696.024, 848.764, 195.576, 155.724, 708.255, 441.277, 504.48, 295.466, 530.377, 325.73, 356.931, 140.089, 173.349, 453.679, 518.652, 428.515, 349.178, 481.274, 415.933, 312.13, 747.011, 161.012, 182.003, 191.442, 138.654, 163.783, 186.011, 179.234, 593.001, 768.668, 437.321, 130.863, 429.564, 0, 540.37, 125, 265, 266.177, 563.649, 941.116, },
161 { 791.281, 1151.27, 1072.31, 659.564, 673.591, 661.91, 1156.83, 1135.89, 1257.06, 1185.17, 705.16, 517.422, 324.423, 364.966, 695.593, 539.49, 1187.7, 946.005, 1044.84, 679.779, 957.549, 832.406, 773.692, 652.553, 550.681, 185.54, 291.548, 344.42, 522.805, 782.192, 895.879, 845, 1095.18, 697.227, 718.418, 729.555, 676.036, 690.67, 726.223, 714.37, 1133.16, 1092.54, 904.461, 640.41, 969.91, 540.37, 0, 642.359, 795.503, 646.258, 681.542, 597.746, },
162 { 267.301, 910.302, 504.802, 137.295, 47.4342, 70.7107, 890.183, 495.101, 617.839, 550.273, 775.065, 391.152, 755.86, 925.216, 71.5891, 261.964, 687.204, 415.752, 415.482, 364.589, 549.477, 311.006, 400.656, 15.8114, 148.071, 530.519, 571.948, 469.574, 462.385, 553.173, 413.673, 260.864, 636.318, 133.417, 145.774, 145, 60, 49.4975, 112.805, 80.6226, 498.523, 814.079, 313.249, 170.294, 343.001, 125, 642.359, 0, 225.499, 343.111, 522.805, 980.472, },
163 { 64.0312, 728.011, 288.487, 345.254, 241.868, 277.218, 701.73, 383.438, 550.568, 507.001, 1000.01, 616.644, 959.284, 1113.56, 246.221, 281.824, 461.736, 190.263, 267.442, 263.866, 344.42, 93.9415, 244.387, 230, 372.726, 718.679, 779.311, 683.118, 448.386, 422.67, 197.8, 50, 763.708, 105.119, 85.44, 81.3941, 165.68, 191.05, 115.434, 157.003, 359.34, 627.156, 399.906, 157.003, 196.469, 265, 795.503, 225.499, 0, 265.189, 741.772, 1196.92, },
164 { 217.083, 596.259, 463.249, 477.624, 386.685, 413.793, 584.637, 643.817, 815.138, 771.962, 1042.93, 662.59, 884.59, 1000.12, 406.079, 130.384, 543.622, 328.672, 521.967, 35.3553, 313.129, 237.171, 127.475, 357.526, 439.09, 630.575, 726.395, 656.22, 191.377, 215.232, 262.011, 305.655, 973.666, 243.772, 251.645, 265.707, 305.164, 348.174, 302.076, 333.654, 611.882, 509.902, 626.099, 175, 456.755, 266.177, 646.258, 343.111, 265.189, 0, 829.608, 1150.76, },
165 { 789.383, 1421.56, 995.314, 397.02, 499.925, 464.57, 1405.08, 860.145, 883.233, 800.078, 285.044, 188.215, 539.676, 744.648, 497.041, 710.106, 1196.51, 929.368, 843.445, 859.069, 1072.01, 831.865, 914.166, 514.806, 392.747, 496.009, 410.488, 337.231, 871.45, 1044.28, 935.575, 767.349, 474.684, 656.22, 667.776, 665.019, 581.485, 550.84, 626.498, 584.829, 896.354, 1329, 504.232, 678.399, 790.142, 563.649, 681.542, 522.805, 741.772, 829.608, 0, 624.82, },
166 { 1220.46, 1716.05, 1483.59, 908.639, 984.441, 954.895, 1715.07, 1430.47, 1486.78, 1404.04, 398.56, 618.567, 278.658, 318.904, 995.113, 1022.67, 1649.37, 1381.2, 1381.96, 1186.09, 1456.71, 1266.49, 1271.42, 981.542, 835.135, 525, 425.793, 513.931, 1081.95, 1330.01, 1355.91, 1238.4, 1088.73, 1092.62, 1111.54, 1116.36, 1036.4, 1026.17, 1092.02, 1060.39, 1453.08, 1645.07, 1097.2, 1070.81, 1314.96, 941.116, 597.746, 980.472, 1196.92, 1150.76, 624.82, 0, },
167};
168
169// #define ASSERT assert
170#define ASSERT
171#define CTZL __builtin_ctzl
172#define EPSILON 1e-12
173
174typedef uint8_t gene;
175typedef gene chromosome[CHROMOSOME_SIZE];
176
177struct measurement {
178 float fitness;
179 float time;
180 int generations;
181};
182
183chromosome population [POPULATION_CAPACITY];
184chromosome population_breeding_pool [POPULATION_CAPACITY];
185float population_fitness [POPULATION_CAPACITY];
186float population_fitness_normalized [POPULATION_CAPACITY];
187float population_fitness_normalized_min;
188float population_cdf [POPULATION_CAPACITY];
189int population_elites [ELITE_COUNT];
190float population_elites_fitness [ELITE_COUNT];
191chromosome generation_bests [GENERATION_MAX + 1];
192float generation_bests_fitness [GENERATION_MAX + 1];
193float generation_average_fitness [GENERATION_MAX + 1];
194struct measurement measurements [ARRAY_LENGTH (probabilities_crossover)]
195 [ARRAY_LENGTH (probabilities_mutation )];
196
197int
198get_index (gene code, uint64_t *mask)
199{
200 ASSERT (CHROMOSOME_SIZE < 64);
201
202 int idx = 0;
203 const uint64_t end = ((uint64_t) 1 << CHROMOSOME_SIZE);
204 uint64_t head = 1;
205 // printf ("%2hhu ", code);
206 do {
207 bool is_set = !!(*mask & head);
208 // printf ("%0*lb %0*lb %d %d %d\n",
209 // CHROMOSOME_SIZE, *mask,
210 // CHROMOSOME_SIZE, head,
211 // code, idx, is_set);
212 if (code == 0 && is_set) break;
213
214 code -= is_set;
215 idx += 1;
216 head <<= 1;
217 } while (head != end);
218 *mask ^= head;
219 // printf ("%2d\n", idx);
220 return idx;
221}
222
223struct point
224get_point (gene code, uint64_t *mask)
225{
226 return buildings[get_index (code, mask)];
227}
228
229gene
230get_ordinal (gene index, uint64_t *mask)
231{
232 const uint64_t end = ((uint64_t) 1 << CHROMOSOME_SIZE);
233 int c = index;
234 uint64_t head = 1;
235 do {
236 if (!index) break;
237
238 c -= !!(*mask & head);
239 index -= 1;
240 head <<= 1;
241 } while (head != end);
242 ASSERT (c < CHROMOSOME_SIZE);
243 *mask ^= head;
244 // printf ("%052lb\n", *mask);
245
246 return c;
247}
248
249float
250fitness_function (chromosome x)
251{
252 ASSERT (CHROMOSOME_SIZE < 64);
253
254 float distance = 0;
255 uint64_t mask = ((uint64_t) 1 << CHROMOSOME_SIZE) - 1;
256 // struct point prev = get_point (x[0], &mask);
257 int prev = get_index (x[0], &mask);
258 for (int i = 1; i < CHROMOSOME_SIZE; ++i) {
259 // struct point p = get_point (x[i], &mask);
260 // float dx = p.x - prev.x;
261 // float dy = p.y - prev.y;
262 // prev = p;
263 // distance += sqrtf (dx*dx + dy*dy);
264 int curr = get_index (x[i], &mask);
265 distance += distances[prev][curr];
266 prev = curr;
267 }
268
269 return distance;
270}
271
272void
273create_initial_population (int population_size)
274{
275 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
276
277 for (int i = 0; i < population_size; ++i) {
278 for (int j = 0; j < CHROMOSOME_SIZE; ++j) {
279 population[i][j] = rand () % (CHROMOSOME_SIZE - j);
280 }
281 }
282}
283
284void
285measure_fitness (int population_size, int generation)
286{
287 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
288
289 population_fitness_normalized_min = FLT_MAX;
290 int population_best_i = 0;
291 float population_best_fitness = -MINMAX*FLT_MAX;
292 float fitness_sum = 0;
293 for (int i = 0; i < ELITE_COUNT; ++i) {
294 population_elites[i] = i;
295 population_elites_fitness[i] = -MINMAX*FLT_MAX;
296 }
297 for (int i = 0; i < population_size; ++i) {
298 float fitness = fitness_function (population[i]);
299 float fitness_normalized = MINMAX*fitness;
300 fitness_sum += fitness;
301 population_fitness [i] = fitness;
302 population_fitness_normalized [i] = fitness_normalized;
303
304 if (fitness_normalized < population_fitness_normalized_min)
305 population_fitness_normalized_min = fitness_normalized;
306
307 if (MINMAX*(fitness - population_best_fitness) > 0) {
308 population_best_i = i;
309 population_best_fitness = fitness;
310 }
311
312 int worst_elite = 0;
313 for (int j = 1; j < ELITE_COUNT; ++j) {
314 if (MINMAX*(population_elites_fitness[ j] -
315 population_elites_fitness[worst_elite]) < 0)
316 worst_elite = j;
317 }
318 if (MINMAX*(fitness - population_elites_fitness[worst_elite]) > 0) {
319 population_elites [worst_elite] = i;
320 population_elites_fitness[worst_elite] = fitness;
321 }
322 }
323 population_fitness_normalized_min -= 1e-12;
324
325 memcpy (generation_bests[generation], population[population_best_i], sizeof (chromosome));
326 generation_bests_fitness[generation] = population_best_fitness;
327 generation_average_fitness[generation] = fitness_sum/population_size;
328}
329
330bool
331should_stop (int generation)
332{
333 static int repeat_count = 0;
334 static float running_average = 0;
335
336 if (generation == GENERATION_MAX)
337 return true;
338
339 if (generation + 1 < FITNESS_TRESHOLD_BEST_REPEAT)
340 return false;
341
342 if (fabs (generation_bests_fitness[generation - 1] -
343 generation_bests_fitness[generation - 0]) < EPSILON) {
344 repeat_count += 1;
345 } else repeat_count = 0;
346
347 return repeat_count >= FITNESS_TRESHOLD_BEST_REPEAT;
348}
349
350void
351selection__fitness_proportionate (int population_size)
352{
353 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
354
355 float population_fitness_sum = 0;
356 for (int i = 0; i < population_size; ++i) {
357 population_fitness_sum +=
358 population_fitness_normalized[i] -= population_fitness_normalized_min;
359 }
360
361 float last = 0;
362 for (int i = 0; i < population_size; ++i) {
363 last = population_cdf[i] =
364 last + population_fitness_normalized[i]/population_fitness_sum;
365 }
366
367 for (int i = 0; i < population_size; ++i) {
368 float a = rand () /(float) RAND_MAX;
369 int j = 0;
370 // TODO(cmmm): use binary search
371 while (j < population_size) {
372 if (population_cdf[j] > a) break;
373 j += 1;
374 }
375
376 memcpy (population_breeding_pool[i], population[j],
377 sizeof (population_breeding_pool[i]));
378 }
379}
380
381void
382selection__tournament (int population_size, int tournament_size)
383{
384 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
385
386 for (int i = 0; i < population_size; ++i) {
387 int group = rand () % (population_size/tournament_size);
388 int j = group*tournament_size;
389 for (int k = group*tournament_size; k < (group + 1)*tournament_size; ++k) {
390 if (MINMAX*(population_fitness[k] - population_fitness[j]) > 0)
391 j = k;
392 }
393
394 memcpy (population_breeding_pool[i], population[j], sizeof (chromosome));
395 }
396}
397
398void
399crossover (int population_size, float probability)
400{
401 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
402
403 for (int i = 0; i < population_size; i += 2) {
404 int i_a = i;
405 int i_b = (i + 1) % population_size;
406
407 if (rand () /(float) RAND_MAX > probability) {
408 memcpy (&population[i_a], &population_breeding_pool[i_a], sizeof (chromosome));
409 memcpy (&population[i_b], &population_breeding_pool[i_b], sizeof (chromosome));
410 } else {
411 int k = 1 + rand () % (CHROMOSOME_SIZE - 1);
412 memcpy (&population[i_a][0], &population_breeding_pool[i_a][0], ( k)*sizeof (gene));
413 memcpy (&population[i_a][k], &population_breeding_pool[i_b][k], (CHROMOSOME_SIZE - k)*sizeof (gene));
414 memcpy (&population[i_b][0], &population_breeding_pool[i_b][0], ( k)*sizeof (gene));
415 memcpy (&population[i_b][k], &population_breeding_pool[i_a][k], (CHROMOSOME_SIZE - k)*sizeof (gene));
416 }
417 }
418}
419
420void
421crossover__two_point (int population_size, float probability)
422{
423 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
424
425 for (int i = 0; i < population_size; i += 2) {
426 int i_a = i;
427 int i_b = (i + 1) % population_size;
428
429 if (rand () /(float) RAND_MAX > probability) {
430 memcpy (&population[i_a], &population_breeding_pool[i_a], sizeof (chromosome));
431 memcpy (&population[i_b], &population_breeding_pool[i_b], sizeof (chromosome));
432 } else {
433 int l = 1 + rand () % (CHROMOSOME_SIZE - 1);
434 int r = 1 + rand () % (CHROMOSOME_SIZE - 1);
435 if (l > r) {
436 l ^= r;
437 r ^= l;
438 l ^= r;
439 }
440 memcpy (&population[i_a][0], &population_breeding_pool[i_a][0], ( l)*sizeof (gene));
441 memcpy (&population[i_a][l], &population_breeding_pool[i_b][l], (r - l)*sizeof (gene));
442 memcpy (&population[i_a][r], &population_breeding_pool[i_a][r], (CHROMOSOME_SIZE - r)*sizeof (gene));
443 memcpy (&population[i_b][0], &population_breeding_pool[i_b][0], ( l)*sizeof (gene));
444 memcpy (&population[i_b][l], &population_breeding_pool[i_a][l], (r - l)*sizeof (gene));
445 memcpy (&population[i_b][r], &population_breeding_pool[i_b][r], (CHROMOSOME_SIZE - r)*sizeof (gene));
446 }
447 }
448}
449
450void
451crossover__uniform (int population_size, float probability)
452{
453 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
454
455 for (int i = 0; i < population_size; i += 2) {
456 int i_a = i;
457 int i_b = (i + 1) % population_size;
458
459 if (rand () /(float) RAND_MAX > probability) {
460 memcpy (&population[i_a], &population_breeding_pool[i_a], sizeof (chromosome));
461 memcpy (&population[i_b], &population_breeding_pool[i_b], sizeof (chromosome));
462 } else {
463 for (int j = 0; j < CHROMOSOME_SIZE; ++j) {
464 if (rand () % 2) {
465 population[i_a][j] = population_breeding_pool[i_a][j];
466 population[i_b][j] = population_breeding_pool[i_b][j];
467 } else {
468 population[i_a][j] = population_breeding_pool[i_b][j];
469 population[i_b][j] = population_breeding_pool[i_a][j];
470 }
471 }
472 }
473 }
474}
475
476void
477mutation (int population_size, float probability)
478{
479 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
480
481 for (int i = 0; i < population_size; ++i) {
482 if (rand () /(float) RAND_MAX > probability)
483 continue;
484
485 int k = rand () % CHROMOSOME_SIZE;
486 population[i][k] = rand () % (CHROMOSOME_SIZE - k);
487 }
488}
489
490void
491mutation__swap (int population_size, float probability)
492{
493 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
494 static chromosome tmp;
495
496 for (int i = 0; i < population_size; ++i) {
497 if (rand () /(float) RAND_MAX > probability)
498 continue;
499
500 int a = rand () % (CHROMOSOME_SIZE);
501 int b = rand () % (CHROMOSOME_SIZE);
502 if (a == b) {
503 if (a == 0) b += 1;
504 else a -= 1;
505 }
506
507 uint64_t mask = ((uint64_t) 1 << CHROMOSOME_SIZE) - 1;
508 for (int j = 0; j < CHROMOSOME_SIZE; ++j)
509 tmp[j] = get_index (population[i][j], &mask);
510 for (int j = 0; j < CHROMOSOME_SIZE; ++j)
511 population[i][j] = get_ordinal (tmp[j == a ? b : j == b ? a : j], &mask);
512 }
513}
514
515void
516plot (const char *output, int population_size, int generation)
517{
518 FILE *gp = popen ("gnuplot", "w");
519 // FILE *gp = fopen ("test.gp", "w");
520#ifdef PLOT_PNG
521 fprintf (gp, "set term pngcairo\n");
522 fprintf (gp, "set output '%s.png'\n", output);
523#else
524 fprintf (gp, "set term cairolatex pdf input blacktext notransparent"
525 " nocrop size 15cm,10cm noheader\n");
526 fprintf (gp, "set output '%s.tex'\n", output);
527#endif
528
529 fprintf (gp, "set title 'Поколение №%lu, \\quad Лучшая особь: %f'\n",
530 generation, generation_bests_fitness[generation]);
531 fprintf (gp, "set xlabel '\\(x\\)'\n");
532 fprintf (gp, "set ylabel '\\(y\\)'\n");
533 fprintf (gp, "set xrange [%hd:%hd]\n", X_MIN, X_MAX);
534 fprintf (gp, "set yrange [%hd:%hd]\n", Y_MIN, Y_MAX);
535
536 fprintf (gp, "plot ");
537 fprintf (gp, "'-' with lines lw 9.0 lc 'gray' title '\\small{Оптимальный путь}',");
538 fprintf (gp, "'-' with lines lw 3.0 lc 'red' title '\\small{Лучшая особь}',");
539 fprintf (gp, "'-' with points ps 0.5 pt 2 lc 'blue' title '\\small{Координаты}'\n");
540
541 uint64_t mask;
542 struct point end;
543
544 mask = ((uint64_t) 1 << CHROMOSOME_SIZE) - 1;
545 end = get_point (best_route[0], &mask);
546 fprintf (gp, "%hd %hd\n", end.x, end.y);
547 for (int i = 1; i < CHROMOSOME_SIZE; ++i) {
548 struct point p = get_point (best_route[i], &mask);
549 fprintf (gp, "%hd %hd\n", p.x, p.y);
550 } fprintf (gp, "%hd %hd\ne\n", end.x, end.y);
551
552 mask = ((uint64_t) 1 << CHROMOSOME_SIZE) - 1;
553 end = get_point (generation_bests[generation][0], &mask);
554 fprintf (gp, "%hd %hd\n", end.x, end.y);
555 for (int i = 1; i < CHROMOSOME_SIZE; ++i) {
556 struct point p = get_point (generation_bests[generation][i], &mask);
557 fprintf (gp, "%hd %hd\n", p.x, p.y);
558 } fprintf (gp, "%hd %hd\ne\n", end.x, end.y);
559
560 for (int i = 0; i < CHROMOSOME_SIZE; ++i) {
561 fprintf (gp, "%hd %hd\n", buildings[i].x, buildings[i].y);
562 } fprintf (gp, "e\n");
563
564 fclose (gp);
565}
566
567void
568plot__fitness_over_generations (const char *output, int generations)
569{
570 FILE *gp = popen ("gnuplot", "w");
571 // FILE *gp = fopen ("test.gp", "w");
572#ifdef PLOT_PNG
573 fprintf (gp, "set term pngcairo\n");
574 fprintf (gp, "set output '%s.png'\n", output);
575#else
576 fprintf (gp, "set term cairolatex pdf input blacktext notransparent"
577 " nocrop size 15cm,10cm noheader\n");
578 fprintf (gp, "set output '%s.tex'\n", output);
579#endif
580
581 fprintf (gp, "set xrange [0:%d]\n", GENERATION_MAX);
582 fprintf (gp, "set yrange [0:30000]\n");
583 fprintf (gp, "set xlabel '№ поколения'\n");
584 fprintf (gp, "set ylabel 'Значение фитнесс-функции' offset graph -0.02,0\n");
585 fprintf (gp, "set y2range [0:30000]\n");
586 fprintf (gp, "set y2tics ('7498.270020' 7498.270020, '9689.396484' 9689.396484)\n");
587 fprintf (gp, "set xtics (1390)\n");
588 fprintf (gp, "set x2tics\n");
589 fprintf (gp, "set arrow from 1390, 0.000000 to 1390,9689.396484 nohead lc 1 dt 2\n");
590 fprintf (gp, "set arrow from 1390,9689.396484 to 2000,9689.396484 nohead lc 1 dt 2\n");
591
592 fprintf (gp, "plot ");
593 fprintf (gp, "'-' with lines title 'Лучшее значение',");
594 fprintf (gp, "'-' with lines title 'Среднее значение',");
595 fprintf (gp, "7498.270020 title 'Оптимальное значение'\n");
596
597 for (int i = 0; i < generations; ++i) {
598 fprintf (gp, "%d %f\n", i, generation_bests_fitness[i]);
599 } fprintf (gp, "e\n");
600
601 for (int i = 0; i < generations; ++i) {
602 fprintf (gp, "%d %f\n", i, generation_average_fitness[i]);
603 } fprintf (gp, "e\n");
604
605 fclose (gp);
606}
607
608void
609run_experiment__plot (int population_size,
610 float probability_crossover,
611 float probability_mutation)
612{
613 void
614 plot_generation (int generation)
615 {
616 static char plot_output[256];
617
618 snprintf (plot_output, sizeof (plot_output), "res/p%llu-c%4.2lf-m%4.2lf-g%04u",
619 population_size, probability_crossover,
620 probability_mutation, generation);
621
622 plot (plot_output, population_size, generation);
623 }
624
625 create_initial_population (population_size);
626 int generation = 0;
627 for (;;) {
628 measure_fitness (population_size, generation);
629
630 if (generation % 10 == 0) {
631 printf ("generation: %4lu, fitness: %lf, ",
632 generation, generation_bests_fitness[generation]);
633 printf ("chromosome:");
634 for (int i = 0; i < CHROMOSOME_SIZE; ++i) {
635 printf (" %2hhu", generation_bests[generation][i]);
636 } printf ("\n");
637 // printf("elites:");
638 // for (int i = 0; i < ELITE_COUNT; ++i) {
639 // printf (" (%lu @ %f)", population_elites[i], population_elites_fitness[i]);
640 // } printf ("\n");
641 }
642 if (generation % 10 == 0)
643 plot_generation (generation);
644
645 if (should_stop (generation))
646 break;
647
648 selection__tournament (population_size, TOURNAMENT_SIZE);
649 for (int i = 0; i < ELITE_COUNT; ++i) {
650 memcpy (&population[population_size - ELITE_COUNT + i],
651 &population[population_elites[i]], sizeof (chromosome));
652 }
653 crossover__two_point (population_size - ELITE_COUNT, probability_crossover);
654 mutation__swap (population_size - ELITE_COUNT, probability_mutation );
655
656 generation += 1;
657 }
658
659 plot__fitness_over_generations ("./res/fitness", generation);
660}
661
662struct measurement
663run_experiment__measure (int population_size,
664 float probability_crossover,
665 float probability_mutation)
666{
667 float total_fitness = 0;
668 float total_time = 0;
669 int total_generations = 0;
670 for (int run = 0; run < MEASUREMENT_RUNS; ++run) {
671 clock_t begin = clock ();
672 create_initial_population (population_size);
673 int generation;
674 for (generation = 0; generation < GENERATION_MAX; ++generation) {
675 measure_fitness (population_size, generation);
676 if (should_stop (generation)) break;
677 selection__tournament (population_size, TOURNAMENT_SIZE);
678 for (int i = 0; i < ELITE_COUNT; ++i) {
679 memcpy (&population[population_size - ELITE_COUNT + i],
680 &population[population_elites[i]], sizeof (chromosome));
681 }
682 crossover__two_point (population_size - ELITE_COUNT, probability_crossover);
683 mutation__swap (population_size - ELITE_COUNT, probability_mutation );
684 }
685 float time = (clock () - begin) /(float) CLOCKS_PER_SEC;
686 total_time += time;
687 total_generations += generation;
688 total_fitness += generation_bests_fitness[generation - (generation == GENERATION_MAX)];
689 }
690
691 return (struct measurement) {
692 .fitness = total_fitness/MEASUREMENT_RUNS,
693 .time = total_time/MEASUREMENT_RUNS,
694 .generations = (total_generations + MEASUREMENT_RUNS/2)/MEASUREMENT_RUNS,
695 };
696}
697
698typedef int (*print_function)(void *user, const char *template, ...);
699typedef int (*cell_function)(int x, int y, print_function, void *);
700
701int
702print__measure (void *user, const char *template, ...)
703{
704 va_list ap;
705 va_start (ap, template);
706 int len = vsnprintf (NULL, 0, template, ap);
707 va_end (ap);
708 return len;
709}
710
711int
712print__stream (void *stream, const char *template, ...)
713{
714 va_list ap;
715 va_start (ap, template);
716 int len = vfprintf (stream, template, ap);
717 va_end (ap);
718 return len;
719}
720
721void
722print_org_table (const char *filename, const char *name, const char *caption,
723 const char *align, int rows, int cols, cell_function cell)
724{
725 int cell_widths[rows][cols];
726 int column_widths[cols];
727 memset (column_widths, 0, sizeof (column_widths));
728 for (int y = 0; y < rows; ++y) {
729 for (int x = 0; x < cols; ++x) {
730 cell_widths[y][x] = cell (x, y, print__measure, NULL);
731 if (cell_widths[y][x] > column_widths[x])
732 column_widths[x] = cell_widths[y][x];;
733 }
734 }
735
736 FILE *stream = fopen (filename, "w");
737 if (name ) fprintf (stream, "#+name: %s\n", name);
738 if (caption) fprintf (stream, "#+caption: %s\n", caption);
739 if (align ) fprintf (stream, "#+attr_latex: :align %s\n", align);
740 for (int y = 0; y < rows; ++y) {
741 fprintf (stream, "|");
742 for (int x = 0; x < cols; ++x) {
743 fprintf (stream, " ");
744 if (x == 0) {
745 for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i)
746 fprintf (stream, " ");
747 }
748 cell (x, y, print__stream, stream);
749 if (x > 0) {
750 for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i)
751 fprintf (stream, " ");
752 }
753 fprintf (stream, " |");
754 } fprintf (stream, "\n");
755 if (y == 0) {
756 fprintf (stream, "|");
757 for (int x = 0; x < cols; ++x) {
758 for (int i = 0; i < column_widths[x] + 2; ++i)
759 fprintf (stream, "-");
760 fprintf (stream, "|");
761 } fprintf (stream, "\n");
762 }
763 }
764
765 fclose (stream);
766}
767
768void
769bake (void)
770{
771 ASSERT (CHROMOSOME_SIZE < 64);
772
773 printf ("best route fitness: %f\n", fitness_function (best_route));
774
775 struct point min = buildings[0];
776 struct point max = buildings[0];
777 for (int i = 1; i < CHROMOSOME_SIZE; ++i) {
778 struct point p = buildings[i];
779 if (p.x < min.x) min.x = p.x;
780 if (p.x > max.x) max.x = p.x;
781 if (p.y < min.y) min.y = p.y;
782 if (p.y > max.y) max.y = p.y;
783 }
784 printf ("min: %hd %hd\n", min.x, min.y);
785 printf ("max: %hd %hd\n", max.x, max.y);
786
787 printf ("{\n");
788 for (int i = 0; i < CHROMOSOME_SIZE; ++i) {
789 struct point a = buildings[i];
790 printf (" { ");
791 for (int j = 0; j < CHROMOSOME_SIZE; ++j) {
792 struct point b = buildings[j];
793 float dx = a.x - b.x;
794 float dy = a.y - b.y;
795 printf ("%g, ", sqrtf (dx*dx + dy*dy));
796 } printf ("},\n");
797 } printf ("};\n");
798
799 uint64_t mask = 0;
800 for (int i = 0; i < CHROMOSOME_SIZE; ++i)
801 printf ("%2hhu, ", get_ordinal (best_route__original[i] - 1, &mask));
802}
803
804int
805main (int argc, char *argv[])
806{
807 // bake (); return 0;
808 printf ("SEED: %u\n", SEED);
809 srand (SEED);
810
811 // memcpy (population, best_route, sizeof (best_route));
812 // plot ("fitness", 1, 0);
813 // return 0;
814
815 // run_experiment__plot (PLOT_POPULATION_SIZE,
816 // PLOT_PROBABILITY_CROSSOVER,
817 // PLOT_PROBABILITY_MUTATION);
818 // return 0;
819
820 struct measurement *best_measurement = &measurements[0][0];
821 FOR_EACH_ELEMENT (population_size, population_sizes) {
822 struct measurement *measurement = &measurements[0][0];
823 FOR_EACH_ELEMENT (probability_crossover, probabilities_crossover) {
824 FOR_EACH_ELEMENT (probability_mutation, probabilities_mutation) {
825 printf ("experiment: %3d %f %f", *population_size,
826 *probability_crossover, *probability_mutation);
827 fflush (stdout);
828 *measurement = run_experiment__measure (*population_size,
829 *probability_crossover,
830 *probability_mutation);
831 printf (" took %f ms\n", measurement->time*1e+3);
832 if (measurement->fitness < best_measurement->fitness)
833 best_measurement = measurement;
834 measurement += 1;
835 }
836 }
837
838 char *table_filename, *table_name, *table_caption;
839 asprintf (&table_filename, "res/results-%03d.org", *population_size);
840 asprintf (&table_name, "results-%d", *population_size);
841 asprintf (&table_caption, "Результаты для \\(N = %d\\)",
842 *population_size);
843 int table_cell (int x, int y, print_function print, void *user)
844 {
845 int m = x - 1;
846 int c = y - 1;
847 if (x == 0 && y == 0) return print (user, "\\(P_c \\;\\backslash\\; P_m\\)");
848 if ( y == 0) return print (user, "%.3g", probabilities_mutation [m]);
849 if (x == 0 ) return print (user, "%.1g", probabilities_crossover[c]);
850
851 int len = 0;
852 bool is_best = &measurements[c][m] == best_measurement;
853 if (is_best) print (user, "*");
854 len += print (user, "\\makecell{%.2f (%d) \\\\ %f}",
855 measurements[c][m].time*1e+3,
856 measurements[c][m].generations,
857 measurements[c][m].fitness);
858 if (is_best) print (user, "*");
859
860 return len;
861 }
862 print_org_table (table_filename, table_name, table_caption, "cccccc",
863 1 + ARRAY_LENGTH (probabilities_crossover),
864 1 + ARRAY_LENGTH (probabilities_mutation), table_cell);
865 }
866
867 return EXIT_SUCCESS;
868}
869
870// genetic-algorithm.c ends here