From e932f4212d50dfbbf7e7601f1b217793f2a31a87 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 00:45:29 +0300 Subject: publish --- .gitignore | 5 + README.org | 31 +++ UNLICENSE | 24 ++ build.sh | 5 + doc/biblio.bib | 7 + doc/gost/gost-7-32-bibliography.sty | 57 +++++ doc/gost/gost-7-32-captions.sty | 30 +++ doc/gost/gost-7-32-counters.sty | 44 ++++ doc/gost/gost-7-32-headings.sty | 106 ++++++++ doc/gost/gost-7-32-lists.sty | 17 ++ doc/gost/gost-7-32-tables.sty | 31 +++ doc/gost/gost-7-32-toc.sty | 34 +++ doc/gost/gost-7-32.cls | 62 +++++ doc/ox-init.el | 132 ++++++++++ doc/report.org | 418 +++++++++++++++++++++++++++++++ doc/setup.org | 30 +++ doc/spbstu-report.cls | 79 ++++++ src/simple-genetic-algorithm.c | 480 ++++++++++++++++++++++++++++++++++++ 18 files changed, 1592 insertions(+) create mode 100644 .gitignore create mode 100644 README.org create mode 100644 UNLICENSE create mode 100755 build.sh create mode 100644 doc/biblio.bib create mode 100644 doc/gost/gost-7-32-bibliography.sty create mode 100644 doc/gost/gost-7-32-captions.sty create mode 100644 doc/gost/gost-7-32-counters.sty create mode 100644 doc/gost/gost-7-32-headings.sty create mode 100644 doc/gost/gost-7-32-lists.sty create mode 100644 doc/gost/gost-7-32-tables.sty create mode 100644 doc/gost/gost-7-32-toc.sty create mode 100644 doc/gost/gost-7-32.cls create mode 100644 doc/ox-init.el create mode 100644 doc/report.org create mode 100644 doc/setup.org create mode 100644 doc/spbstu-report.cls create mode 100644 src/simple-genetic-algorithm.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..49ee6be --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.html +*.pdf +*.tex +*.dot +*.png diff --git a/README.org b/README.org new file mode 100644 index 0000000..8447fdd --- /dev/null +++ b/README.org @@ -0,0 +1,31 @@ +#+title: Simple genetic algorithm +#+date: 2025H2 + +* Introduction +:PROPERTIES: +:CUSTOM_ID: introduction +:UNNUMBERED: toc +:END: +The purpose of this work is to study the basic principles of the +functioning of genetic algorithms and to acquire practical skills in +their implementation. Genetic algorithms are one of the most +effective methods for solving optimization problems based on the +mechanisms of natural selection and evolution. + +In the course of the work, it was necessary to familiarize oneself +with the theoretical foundations of the method, study various ways of +encoding chromosomes, and also consider the implementation of the main +operators of the genetic algorithm - reproduction, cross-over, and +mutation. + +* Documentation +:PROPERTIES: +:CUSTOM_ID: documentation +:END: +The exported report can be found at [[https://git.michalec.dev/files/uni/term-07/gen-alg/lab-01/report.pdf][this link]]. + +* Unlicense +:PROPERTIES: +:CUSTOM_ID: unlicense +:END: +#+include: UNLICENSE verse diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..fd8ab1b --- /dev/null +++ b/build.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +set -xe + +gcc -std=gnu99 -O3 -march=native -lm src/simple-genetic-algorithm.c -o simple-genetic-algorithm diff --git a/doc/biblio.bib b/doc/biblio.bib new file mode 100644 index 0000000..51443f5 --- /dev/null +++ b/doc/biblio.bib @@ -0,0 +1,7 @@ +@book{METODA, + title = {Методические указания по выполнению лабораторных работ к курсу «Генетические алгоритмы»}, + address = {Санкт-Петербург}, + publisher = {СПБПУ}, + pages = {119}, + language = {russian} +} diff --git a/doc/gost/gost-7-32-bibliography.sty b/doc/gost/gost-7-32-bibliography.sty new file mode 100644 index 0000000..dca60fa --- /dev/null +++ b/doc/gost/gost-7-32-bibliography.sty @@ -0,0 +1,57 @@ +\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017] + +\def\UrlBreaks{\do\/\do-} +\RequirePackage{url} + +\newdimen\bibindent +\renewenvironment{thebibliography}[1]{ + \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy\clubpenalty4000\widowpenalty4000% + \sfcode`\.\@m +}{ + \setcounter{totalbib}{\c@enumiv}% + \def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist +} +\renewcommand\@biblabel{}% +\setlength\bibindent{1.5em} + +% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И. +%\makeatletter +\renewcommand*{\@biblabel}[1]{\hfill#1.} + + +% +% Remove References header completely +% Stolen from original article.cls +% +\makeatletter +\renewenvironment{thebibliography}[1]{% +% \usection{\refname}% +% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy + \clubpenalty4000 + \@clubpenalty \clubpenalty + \widowpenalty4000% + \sfcode`\.\@m} + {\def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist} +\makeatother diff --git a/doc/gost/gost-7-32-captions.sty b/doc/gost/gost-7-32-captions.sty new file mode 100644 index 0000000..79a4620 --- /dev/null +++ b/doc/gost/gost-7-32-captions.sty @@ -0,0 +1,30 @@ +\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{caption} +\RequirePackage{subcaption} +\RequirePackage{capt-of} + +% +% Table caption aligned to the left with dash as a separator +% +\captionsetup[table]{labelsep=endash, skip=0.5em, justification=centering, singlelinecheck=off} + +% +% Dash as separator in figure caption and centering +% +\captionsetup[figure]{labelsep=endash, justification=centering} + +% +% Listing caption +% +\captionsetup[listing]{labelsep=endash, skip=0.5em, singlelinecheck=off, position=above} + +\addto\captionsrussian{\renewcommand{\figurename}{Рис.}} +\addto\captionsrussian{\captionsetup[listing]{name=Рис.}} +\makeatletter +\AtBeginDocument{% + \let\c@figure\c@listing + \let\thefigure\thelisting + \let\ftype@listing\ftype@figure +} +\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 @@ +\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017] + +% +% Values for capital russian letters counter +% +\makeatletter +\newcommand\AlphRus[1]{% + \expandafter \@AlphRus \csname c@#1\endcsname +} + +\newcommand\@AlphRus[1]{% + \ifcase #1% + \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or + Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or + Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я% + \else \@ctrerr +\fi +} +\makeatother + +% +% Values for lowercase russian letters counter +% +\makeatletter +\newcommand\alphRus[1]{% + \expandafter \@alphRus \csname c@#1\endcsname +} + +\newcommand\@alphRus[1]{% + \ifcase #1% + \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or + л\or м\or н\or п\or р\or с\or т\or у\or ф\or + х\or ц\or ш\or щ\or э\or ю\or я% + \else \@ctrerr +\fi +} +\makeatother + +% Increment figure counter when using lstlisting +% \let\oldlstlisting\lstlisting +% \renewcommand{\lstlisting}[1][]{% +% \refstepcounter{figure} +% \oldlstlisting[#1] +% } 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 @@ +\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{titlesec} +\RequirePackage{titling} +\RequirePackage{setspace} + +\RequirePackage{gost-7-32-counters} + +% +% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection +% +\titleformat{\section}[block]{\centering\large\setstretch{1}\bfseries}{\thesection}{0.5em}{} +\titlespacing*{\section}{0cm}{0cm}{0.5cm} +\newcommand{\sectionbreak}{\clearpage} + +\titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{} +\titlespacing{\subsection}{0cm}{0.5cm}{0.5cm} + +\titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent] +\titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm} + +\makeatletter +\let\oldsection\section +\newcommand{\@sectionnostar}[1]{\phantomsection\oldsection*{#1}\addcontentsline{toc}{section}{#1}} +\newcommand{\@sectionstar}[1]{\oldsection{#1}} +\renewcommand{\section}{\sectionbreak\@ifstar{\@sectionnostar}{\@sectionstar}} +\makeatother + +% +% Make special headings, that have their own formatting rules: +% - centered +% - all-caps +% - bold +% +% Only three of them must appear in TOC: introduction, conclusion and references +% +\newcommand{\introduction}{ + \addcontentsline{toc}{section}{ВВЕДЕНИЕ} + \begin{center} + \bfseries\large + ВВЕДЕНИЕ + \end{center} +} + +\newcommand{\conclusion}{ + \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ} + \begin{center} + \bfseries\large + ЗАКЛЮЧЕНИЕ + \end{center} +} + +\newcommand{\references}{ + \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ} + \begin{center} + \bfseries\large + СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ + \end{center} +} + +\newcommand{\essay}{ + \begin{center} + \bfseries\large + РЕФЕРАТ + \end{center} +} + +\newcommand{\definitions}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ + \end{center} +} + +\newcommand{\abbreviations}{ + \begin{center} + \bfseries\large + ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +\newcommand{\defsabbrs}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +% +% Appendices headings. Appendices have autoincrementing number, +% that is represented with russian letter. +% This heading must appear in TOC +% +\newcounter{appendixcnt} +\setcounter{appendixcnt}{1} + +\renewcommand{\appendix}[1]{ + \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1} + \begin{center} + \bfseries\large + ПРИЛОЖЕНИЕ \AlphRus{appendixcnt} + + #1 + \end{center} + \stepcounter{appendixcnt} +} diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty new file mode 100644 index 0000000..6f41980 --- /dev/null +++ b/doc/gost/gost-7-32-lists.sty @@ -0,0 +1,17 @@ +\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{enumitem} +\RequirePackage{gost-7-32-counters} + +\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1} + +\setlist{nosep} +\setlist[itemize, 1]{label=\textendash} +\setlist[itemize, 2]{label=\bullet} +\setlist[itemize, 3]{label=\bullet} + +\setlist[enumerate, 2]{label=\alphRus*)} + +\setlist[1]{wide=\parindent} +\setlist[2]{wide=2\parindent, leftmargin=\parindent} +\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 @@ +\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{booktabs} +\RequirePackage{xltabular} +\renewcommand\tabularxcolumn[1]{m{#1}} % for vertical centering text + +% +% Center-aligned column with automatic width +% +\newcolumntype{C}{>{\centering\arraybackslash}X} + +% +% Right-aligned column with automatic width +% +\newcolumntype{R}{>{\raggedleft\arraybackslash}X} + +% +% Table with designations +% +\newenvironment{designations}{ + \noindent + \tabularx{\textwidth}{@{} + >{\raggedright \arraybackslash \hsize=0.25\hsize}X + >{\centering \arraybackslash \hsize=0.05\hsize}X + >{\arraybackslash \hsize=0.70\hsize}X + } +}{ + \endtabularx +} + +\newcommand{\designation}[2]{#1 &---& #2. \\} diff --git a/doc/gost/gost-7-32-toc.sty b/doc/gost/gost-7-32-toc.sty new file mode 100644 index 0000000..328079d --- /dev/null +++ b/doc/gost/gost-7-32-toc.sty @@ -0,0 +1,34 @@ +\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{tocloft} +\RequirePackage[ + bookmarks=true, + colorlinks=true, + unicode=true, + urlcolor=black, + linkcolor=black, + anchorcolor=black, + citecolor=black, + menucolor=black, + filecolor=black, + hidelinks +]{hyperref} + +% +% Set custom font styles +% +\renewcommand{\cftsecfont}{\normalfont} +\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} +\renewcommand{\cftsecpagefont}{\normalsize} +\renewcommand{\cftaftertoctitle}{\hfill\hfill} +\renewcommand{\cfttoctitlefont}{\hfill\normalfont\large\bfseries} +\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{} +\titlespacing{\tableofcontents}{0cm}{0cm}{1cm} + +% +% Set indents and line spacing +% +\setlength{\cftbeforesecskip}{0cm} +\setlength{\cftbeforesubsecskip}{0cm} +\setlength{\cftbeforesubsubsecskip}{0cm} +\setlength{\cftbeforeparaskip}{0cm} diff --git a/doc/gost/gost-7-32.cls b/doc/gost/gost-7-32.cls new file mode 100644 index 0000000..efbe9d8 --- /dev/null +++ b/doc/gost/gost-7-32.cls @@ -0,0 +1,62 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017] + +% +% Supported font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +% +% Set A4 paper format +% +\LoadClass[a4paper]{extarticle} + +% +% Use 1.5 line spacing +% +\RequirePackage{setspace} +\singlespacing % or \setstretch{1} + +% +% First paragraph indentation +% +\RequirePackage{indentfirst} +\setlength{\parindent}{12.5mm} + +% +% Page margin +% +\RequirePackage[ + left=2.5cm, + right=2cm, + top=2cm, + bottom=2cm, + footskip=1cm, +]{geometry} + +% +% Use TMR-like font +% +\RequirePackage{fontspec} +\RequirePackage{xunicode} +\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +\setmainfont{Times New Roman} + +% +% Use russian language +% +\RequirePackage[main=russian, english]{babel} +\babelhyphenation[russian]{} + +% +% gost-7-32 packages +% +\RequirePackage{gost-7-32-headings} +\RequirePackage{gost-7-32-toc} +\RequirePackage{gost-7-32-lists} +\RequirePackage{gost-7-32-bibliography} +\RequirePackage{gost-7-32-captions} +\RequirePackage{gost-7-32-tables} diff --git a/doc/ox-init.el b/doc/ox-init.el new file mode 100644 index 0000000..47ef892 --- /dev/null +++ b/doc/ox-init.el @@ -0,0 +1,132 @@ +;;; ox-init.el --- Initialization script for async org exprort session +;;; Commentary: +;;; Code: +;; (org-babel-do-load-languages +;; 'org-babel-load-languages +;; '((latex . t))) + +(require 'ox-extra) +(ox-extras-activate '(ignore-headlines)) + +(setq org-latex-src-block-backend 'minted) + +(require 'oc-bibtex) +(setq org-latex-bib-compiler "biber") + +(setq org-latex-remove-logfiles nil) + +(setq org-export-default-language "ru") + +(setq org-latex-default-packages-alist nil) + +(setq org-latex-tables-booktabs t) + +(setq org-latex-caption-above '(table)) + +(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f" + "%bib %b" + "%latex -shell-escape -interaction nonstopmode -output-directory %o %f")) +(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}" + ("\\section{%s}" . "\\section*{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}") + ("\\paragraph{%s}" . "\\paragraph*{%s}") + ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) + +;; TODO(cmmm): add \addlinespace between rows which don't have 'rule +;; TODO(cmmm): wrap head columns in something like: +;; \multicolumn{1}{c}{\bold head1} +(defun cmmm-org-latex-table-row (table-row contents info) + "Transcode a TABLE-ROW element from Org to LaTeX. +CONTENTS is the contents of the row. INFO is a plist used as +a communication channel." + (let* ((attr (org-export-read-attribute :attr_latex + (org-element-parent table-row))) + (booktabsp (if (plist-member attr :booktabs) (plist-get attr :booktabs) + (plist-get info :latex-tables-booktabs))) + (longtablep + (member (or (plist-get attr :environment) + (plist-get info :latex-default-table-environment)) + ;; adding xltabular is the only change + '("longtable" "longtabu" "xltabular")))) + (if (eq (org-element-property :type table-row) 'rule) + (cond + ((not booktabsp) "\\hline") + ((not (org-export-get-previous-element table-row info)) "\\toprule") + ((not (org-export-get-next-element table-row info)) "\\bottomrule") + ((and longtablep + (org-export-table-row-ends-header-p + (org-export-get-previous-element table-row info) info)) + "") + (t "\\midrule")) + ;; Memorize table header in case it is multiline. We need this + ;; information to define contents before "\\endhead" in longtable environments. + (when (org-export-table-row-in-header-p table-row info) + (let ((table-head-cache (plist-get info :org-latex-table-head-cache))) + (unless (hash-table-p table-head-cache) + (setq table-head-cache (make-hash-table :test #'eq)) + (plist-put info :org-latex-table-head-cache table-head-cache)) + (if-let* ((head-contents (gethash (org-element-parent table-row) table-head-cache))) + (puthash (org-element-parent table-row) (concat head-contents "\\\\\n" contents) + table-head-cache) + (puthash (org-element-parent table-row) contents table-head-cache)))) + ;; Return LaTeX string as the transcoder. + (concat + ;; When BOOKTABS are activated enforce top-rule even when no + ;; hline was specifically marked. + (and booktabsp (not (org-export-get-previous-element table-row info)) + "\\toprule\n") + contents "\\\\\n" + (cond + ;; Special case for long tables. Define header and footers. + ((and longtablep (org-export-table-row-ends-header-p table-row info)) + (let ((columns (cdr (org-export-table-dimensions + (org-element-lineage table-row 'table) info)))) + (format "%s +\\endfirsthead +\\multicolumn{%d}{l}{%s} \\\\ +%s +%s \\\\\n +%s +\\endhead +%s\\multicolumn{%d}{r}{%s} \\\\ +\\endfoot +\\endlastfoot" + (if booktabsp "\\midrule" "\\hline") + columns + (org-latex--translate "Continued from previous page" info) + (cond + ((not (org-export-table-row-starts-header-p table-row info)) + "") + (booktabsp "\\toprule\n") + (t "\\hline\n")) + (gethash (org-element-parent table-row) (plist-get info :org-latex-table-head-cache)) + (if booktabsp "\\midrule" "\\hline") + (if booktabsp "\\midrule" "\\hline") + columns + (org-latex--translate "Continued on next page" info)))) + ;; When BOOKTABS are activated enforce bottom rule even when + ;; no hline was specifically marked. + ((and booktabsp (not (org-export-get-next-element table-row info))) + "\\bottomrule")))))) +(advice-add 'org-latex-table-row :override 'cmmm-org-latex-table-row) + +(defun cmmm-org-export-translate (s encoding info) + "Translate string S according to language specification. + +ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1' +and `:utf-8'. INFO is a plist used as a communication channel. + +Translation depends on `:language' property. Return the +translated string. If no translation is found, try to fall back +to `:default' encoding. If it fails, return S." + (let* ((lang (plist-get info :language)) + (translations (cdr (assoc lang + (cdr (assoc s org-export-dictionary)))))) + (or (plist-get translations encoding) + (plist-get translations :default) + (plist-get translations :utf-8) + s))) +(advice-add 'org-export-translate :override 'cmmm-org-export-translate) + +;;; ox-init.el ends here diff --git a/doc/report.org b/doc/report.org new file mode 100644 index 0000000..6788e20 --- /dev/null +++ b/doc/report.org @@ -0,0 +1,418 @@ +#+title: Простой генетический алгоритм +#+subtitle: Вариант 14 +#+author: Михалец М. +#+date: 2025 +#+latex_header: \reportof{О ВЫПОЛНЕНИИ ПРАКТИЧЕСКОЙ РАБОТЫ №1} +#+latex_header: \subject{по дисциплине «Генетические алгоритмы»} +#+latex_header: \university{Федеральное государственное автономное образовательное учреждение высшего образования \enquote{Санкт-Петербургский политехнический университет Петра Великого}} +#+latex_header: \institute{Институт компьютерных наук и кибербезопасности} +#+latex_header: \school{Высшая школа технологии искусственного интеллекта} +#+latex_header: \direction{02.03.01 Математика и компьютерные науки} +#+latex_header: \reviewertitle{}\reviewer{Большаков А.А.} +#+latex_header: \city{Санкт-Петербург} + +#+setupfile: setup.org +#+latex: \sloppy + +* ВВЕДЕНИЕ +:PROPERTIES: +:UNNUMBERED: t +:END: +Цель данной работы --- изучение основных принципов функционирования +генетических алгоритмов и приобретение практических навыков их +реализации. Генетические алгоритмы представляют собой один из +эффективных методов решения задач оптимизации, основанный на +механизмах естественного отбора и эволюции. + +В процессе выполнения работы необходимо было ознакомиться с +теоретическими основами метода, изучить различные способы кодирования +хромосом, а также рассмотреть реализацию основных операторов +генетического алгоритма --- репродукции, кроссинговера и мутации. +Итогом работы является выполнение индивидуального задания на языке +высокого уровня Си с детальными комментариями и анализом полученных +результатов. + +* Постановка задачи +#+latex: \noindent +В данной работе были поставлены следующие задачи: +- Изучить теоретический материал; +- Ознакомиться с вариантами кодирования хромосомы; +- Рассмотреть способы выполнения операторов репродукции, кроссинговера + и мутации; +- Выполнить индивидуальное задание на любом языке высокого уровня с + необходимыми комментариями и выводами + +#+latex: \bigbreak\noindent +*Индивидуальное задание вариант 14:* + +#+latex: \bigbreak +*Дано:* Функция одной переменной \(f(x) = \frac{\cos(x - 0.5)}{|x|}\); +промежуток нахождения решения \(x \in [-10, 10]\) +(см. Рис. [[fitness-function]]). + +#+latex: \bigbreak +*Требуется:* +1. Разработать простой генетический алгоритм для нахождения минимума + данной функции в заданном промежутке; +2. Исследовать зависимость времени поиска, числа поколений (генераций) + и точности нахождения решения от числа особей в популяции и + вероятности кроссинговера и мутации; +3. Вывести на экран график функции с указанием найденного экстремума + для каждого поколения; +4. Сравнить найденное решение с действительным. + +#+latex: \bigbreak +*Ограничения:* +1. \(\min f(x) = \frac{\cos(x - 0.5)}{|x|} \approx -0.41101\) +2. Точность решения составляет 3 знака после запятой. + +#+name: fitness-function +#+caption: График целевой функции +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/fitness-function} +#+end_figure + +* Теоретические сведения +Генетические алгоритмы (ГА) используют принципы и терминологию, +заимствованные у биологической науки --- генетики. В ГА каждая особь +представляет потенциальное решение некоторой проблемы. В классическом +ГА особь кодируется строкой двоичных символов – хромосомой, каждый бит +которой называется геном. Множество особей – потенциальных решений +составляет популяцию. Поиск (суб)оптимального решения проблемы +выполняется в процессе эволюции популяции --- последовательного +преобразования одного конечного множества решений в другое с помощью +генетических операторов репродукции, кроссинговера и мутации. + +Предварительно простой ГА случайным образом генерирует начальную +популяцию стрингов (хромосом). Затем алгоритм генерирует следующее +поколение (популяцию), с помощью трех основных генетических +операторов: +1. Оператор репродукции (ОР); +2. Оператор скрещивания (кроссинговера, ОК); +3. Оператор мутации (ОМ). + +ГА работает до тех пор, пока не будет выполнено заданное количество +поколений (итераций) процесса эволюции или на некоторой генерации +будет получено заданное качество или вследствие преждевременной +сходимости при попадании в некоторый локальный оптимум. На +Рис. [[simple-genetic-algorithm]] представлен простой генетический алгоритм. + +#+name: simple-genetic-algorithm +#+caption: Простой генетический алгоритм +#+attr_latex: :options [H] :height .55\textheight +[[./res/simple-genetic-algorithm.png]] + +** Основная терминология в генетических алгоритмах +/Ген/ --- элементарный код в хромосоме \(s_i\), называемый также знаком +или детектором (в классическом ГА \(s_i = 0, 1\)). + +/Хромосома/ --- упорядоченная последовательность генов в виде +закодированной структуры данных \(S = (s_1, s_2, \ldots, s_n)\), +определяющая решение (в простейшем случае двоичная последовательность +--- строка, где \(s_i = 0, 1\)). + +/Локус/ --- местоположение (позиция, номер бита) данного гена в +хромосоме. + +/Аллель/ --- значение, которое принимает данный ген (например, 0 или 1). + +/Особь/ --- одно потенциальное решение задачи (представляемое +хромосомой). + +/Популяция/ --- множество особей (хромосом), представляющих +потенциальные решения. + +/Поколение/ --- текущая популяция ГА на данной итерации алгоритма. + +/Генотип/ --- набор хромосом данной особи. В популяции могут +использоваться как отдельные хромосомы, так и целые генотипы. + +/Генофонд/ --- множество всех возможных генотипов. + +/Фенотип/ --- набор значений, соответствующий данному генотипу. Это +декодированное множество параметров задачи (например, десятичное +значение \(x\), соответствующее двоичному коду). + +/Размер популяции \(N\)/ --- число особей в популяции. + +/Число поколений/ --- количество итераций, в течение которых +производится поиск. + +/Селекция/ --- совокупность правил, определяющих выживание особей на +основе значений целевой функции. + +/Эволюция популяции/ --- чередование поколений, в которых хромосомы +изменяют свои признаки, чтобы каждая новая популяция лучше +приспосабливалась к среде. + +/Фитнесс-функция/ --- функция полезности, определяющая меру +приспособленности особи. В задачах оптимизации она совпадает с +целевой функцией или описывает близость к оптимальному решению. + +** Генетические операторы +*** Оператор репродукции +/Репродукция/ --- процесс копирования хромосом в промежуточную популяцию +для дальнейшего «размножения» в соответствии со значениями +фитнесс-функции. В данной работе рассматривается метод колеса +рулетки. Каждой хромосоме соответствует сектор, пропорциональный +значению фитнесс-функции. Хромосомы с большим значением имеют больше +шансов попасть в следующее поколение. + +#+caption: Колесо рулетки +#+attr_latex: :width .35\textwidth +[[./res/pie.png]] + +*** Оператор скрещивания (кроссинговера) +Одноточечный кроссинговер выполняется следующим образом: +1. Из промежуточной популяции выбираются две хромосомы (родители). +2. Определяется случайная точка скрещивания \(k \in [1, n - 1]\), где + \(n\) -- длина хромосомы. + #+attr_latex: :width .35\textwidth + [[./res/crossover-1.png]] +3. Две новые хромосомы (потомки) формируются путём обмена подстрок + после точки \(k\). + #+attr_latex: :width .2\textwidth + [[./res/crossover-2.png]] + +*** Оператор мутации +Мутация применяется с малой вероятностью $P_m \approx 0.001$: +1. В хромосоме \(A = a_1a_2 \ldots a_n\) выбирается случайная позиция \(k\). +2. Ген \(a_k\) инвертируется: \(a_k' = \lnot a_k\). + +* Особенности реализации +В рамках работы создана программа =simple-genetic-algorithm.c= для +экспериментов с простым генетическим алгоритмом (ГА) на одной +переменной. Она позволяет легко управлять параметрами эксперимента, +брать статистику о времени выполнения, рисовать графики генерации и +экспортировать таблицы. + +- *Кодирование особей:* каждая хромосома --- целочисленная беззнаковая + переменная с ограничением на количество используемых битов. + Декодирование --- линейное в \([-10, 10]\). Для точности + \(10^{-3}\) для данного декодирования необходимо использовать хотя + бы 15 бит, которые дают шаг дискретизации \approx 0.0006. Длина + хромосомы была округлена до 16. За это отвечают: + - ~#define CHROMOSOME_SIZE 16~ + - ~uint8_t bits_for_precision (int digits_after_decimal);~ + - ~double decode (chromosome gene);~ +- *Фитнесс и минимум/максимум:* целевая функция передаётся параметром. + Для режима /минимизации/ используется внутреннее преобразование при + селекции (инвертирование знака/сдвиг), что позволяет единообразно + применять рулетку при отрицательных значениях. За это отвечают: + - ~#define MINMAX -1~ + - ~bool measure_fitness (size_t population_size);~ +- *Селекция (рулетка):* вероятности нормируются после сдвига на + минимальное значение в поколении (устойчиво к отрицательным + фитнессам). Функция: ~void fitness_proportionate_selection (size_t + population_size)~. +- *Кроссинговер:* одноточечный, попарно по перемешанной популяции. При + нечётном размере последняя особь скрещивается со случайной другой + особью (возможно повторное участие в кроссинговере одной из особей). + Пары скрещиваются с вероятностью \(P_c\), иначе родители добавляются + в новую популяцию без изменений. Функция: ~void crossover (size_t + population_size, double probability)~ +- *Мутация:* с вероятностью \(P_m\) /на хромосому/ инвертируется ровно + один случайный бит. Функция: ~void mutation (size_t population_size, + double probability)~. +- *Критерий остановки:* поддержаны критерии по дисперсии значений + фитнесс функции в популяции и по среднему значению (настраиваемые + пороги), но для экспериментов в данной лабораторной работе + используются критерий по лучшему значению и по достижению популяцией + максимального возраста в 200 поколений. Проверка выполняется внутри + функции: ~measure_fitness~. +- *Визуализация:* снимок поколения включает график целевой функции, + точки всей текущей популяции, лучшую особь (выделена зелёным + цветом), а также историю лучших по предыдущим поколениям (выделены + жёлтым цветом). Функция: ~void plot (const char *output, size_t + population_size, size_t generation);~. +- *Измерение времени:* Выполняются только необходимые операции, пока не + достигнут критерии остановки. Функция: ~struct measurement + run_experiment__measure (size_t population_size, double + probability_crossover, double probability_mutation)~ + +* Результаты работы +На Рис. [[generation-first]]-[[generation-last]] представлены результаты работы генетического алгоритма со следующими параметрами: +- \(N = 25\) --- размер популяции. +- \(P_c = 0.5\) --- вероятность кроссинговера. +- \(P_m = 0.1\) --- вероятность мутации. +- \(-0.411\) --- минимальное значение фитнесс функции по популяции для + остановки алгоритма. Настоящий минимум функции равен примерно + \(-0.41101\). + +С каждым поколением точность найденного минимума становится выше. На +втором поколении популяция еще распределена по всей области поиска +решения. На поколении 8 особи «конденсируются» вблизи двух лучших +минимумов, а с поколения 11 вблизи глобального минимума. На поколении +13 достигается заданная точность нахождения минимума функции. + +#+name: generation-first +#+caption: График целевой функции и популяции поколения №0 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/p25-c0.50-m0.10-g000} +#+end_figure + +#+caption: График целевой функции и популяции поколения №1 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/p25-c0.50-m0.10-g001} +#+end_figure + +#+caption: График целевой функции и популяции поколения №2 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/p25-c0.50-m0.10-g002} +#+end_figure + +#+caption: График целевой функции и популяции поколения №3 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/p25-c0.50-m0.10-g003} +#+end_figure + +#+caption: График целевой функции и популяции поколения №5 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/p25-c0.50-m0.10-g005} +#+end_figure + +#+caption: График целевой функции и популяции поколения №8 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/p25-c0.50-m0.10-g008} +#+end_figure + +#+caption: График целевой функции и популяции поколения №11 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/p25-c0.50-m0.10-g011} +#+end_figure + +#+caption: График целевой функции и популяции поколения №12 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/p25-c0.50-m0.10-g012} +#+end_figure + +#+name: generation-last +#+caption: График целевой функции и популяции поколения №13 +#+attr_latex: :options [H] +#+begin_figure +\centering +\input{res/p25-c0.50-m0.10-g013} +#+end_figure + +* Исследование реализации +** Проведение измерений +В рамках лабораторной работы необходимо было исследовать зависимость +времени выполнения задачи и количества поколений от популяции и +вероятностей кроссинговера и мутации хромосомы. + +Для исследования были выбраны следующие значения параметров: +- \(N = 10, 25, 50, 100\) --- размер популяции. +- \(P_c = 0.3, 0.4, 0.5, 0.6, 0.7, 0.8\) --- вероятность + кроссинговера. +- \(P_m = 0.001, 0.01, 0.05, 0.1, 0.2\) --- вероятность мутации. + +Результаты измерений представлены в таблицах [[results-10]]-[[results-100]]. +В ячейках указано усредненное время в микросекундах нахождения +минимума функции. В скобках указано усредненное количество поколений, +за которое было найдено решение. Каждый эксперимент запускался 100 +раз. Если ячейка перечеркнута, то это означает, что решение ни разу +не было найдено за 200 поколений. Лучшее значение по времени +выполнения для каждого размера популяции выделено жирным шрифтом. + +#+include: "./res/results-010.org" + +#+include: "./res/results-025.org" + +#+include: "./res/results-050.org" + +#+include: "./res/results-100.org" + +** Анализ результатов +#+latex: \noindent +*Ключевые наблюдения:* +1. Из \(P_m\) себя лучше показало наибольшее значение \(0.2\) при всех + размерах популяции \(N\). +2. Эффект \(P_c\) положительно растёт с размером популяции \(N\). +3. При небольших популяциях (\(N = 10\)) вероятность ОК \(P_c\) не + влияла на скорость схождения; наилучшее время при \(P_c = 0.3\) + (175 μс, 162 пок.) --- лучшее среди всех экспериментов. При \(P_c + \in (0.4, 0.8)\) и \(P_m = 0.001\) решение не находилось за 200 + поколений. +4. Для \(N = 25\) значительный минимум времени при \(P_c = 0.7\), (310 + μс, 107 пок.). +5. Для \(N=50\) лучшее время при \(P_c = 0.5\) (302 μс, 50 пок.). +6. Для \(N=100\) оптимальны высокие \(P_c\); лучший результат при + \(P_c = 0.8\), (368 μс, 27 пок.). +7. Увеличение \(P_c\) и \(P_m\) ускоряет достижение решения и снижает + число поколений. +8. С ростом размерности популяции \(N\) вероятность нахождения + оптимального решения так же растёт. +9. Для больших \(N\) эффект высоких значений \(P_c\) и \(P_m\) + становился более выраженным --- снижение времени было значительным. +10. Рост \(N\) не гарантирует ускорения: число поколений может + уменьшаться, но суммарное время часто растёт из-за большей + стоимости одной итерации. + +#+latex: \bigbreak\noindent +*Практические выводы:* +1. Поскольку затраты времени низкие, для стоит выбирать большие + размеры популяции \(N\), в которых показывают себя лучше большие + \(P_c\) и \(P_m\). +2. С ростом \(N\) скорее всего оптимальные \(P_c\) и \(P_m\) + снижаются, не стоит считать, что их большие значения себя всегда + показывают лучше. + +* Ответ на контрольный вопрос +#+latex: \noindent +*Вопрос:* Исследуйте зависимость работы ПГА от значения вероятности ОК +(\(P_c\)). + +#+latex: \bigbreak\noindent +*Ответ:* Для популяции крайне малых размеров (\(N = 10\)) значение +вероятности ОК (\(P_c\)) имеет минимальный эффект, но с ростом размера +популяции большие значения \(P_c\) себя показывают лучше. + +* ЗАКЛЮЧЕНИЕ +:PROPERTIES: +:UNNUMBERED: t +:END: +В ходе первой лабораторной работы: +1. Был изучен теоретический материал, основная терминология ГА, + генетические операторы, использующиеся в простых ГА; +2. Реализована программа на языке Си для нахождения минимума заданной + функции; +3. Проведено исследование зависимости времени выполнения программы и + количества поколений от мощности популяции и вероятностей + кроссинговера и мутации. + +* СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ +:PROPERTIES: +:UNNUMBERED: t +:END: +#+latex: \nocite{METODA} +#+print_bibliography: :heading none + +* ПРИЛОЖЕНИЕ А +:PROPERTIES: +:UNNUMBERED: t +:END: +#+include: "../src/simple-genetic-algorithm.c" src c + +# Local Variables: +# org-confirm-babel-evaluate: nil +# org-export-async-init-file: "ox-init.el" +# org-export-in-background: t +# End: diff --git a/doc/setup.org b/doc/setup.org new file mode 100644 index 0000000..4bd1382 --- /dev/null +++ b/doc/setup.org @@ -0,0 +1,30 @@ +#+options: ':nil *:t -:t ::t <:t H:3 \n:nil ^:{} arch:headline +#+options: author:t broken-links:nil c:nil creator:nil +#+options: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t +#+options: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t +#+options: timestamp:nil title:t toc:t todo:t |:t +# #+creator: Emacs 29.1 (Org mode 9.6.9) + +#+select_tags: export +#+exclude_tags: noexport + +#+bibliography: biblio.bib +#+cite_export: biblatex + +#+latex_compiler: xelatex +#+latex_class: spbstu-report +# #+latex_class_options: [draft] + +#+latex_header: \usepackage{enumitem} +#+latex_header: \usepackage{float} +#+latex_header: \usepackage{soul} + +#+latex_header: \usepackage[newfloat]{minted} +#+latex_header: \usemintedstyle{bw} +#+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=@@,ignorelexererrors} + +#+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}} + +#+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +#+latex_header: \setmainfont{Times New Roman} +#+latex_header: \setmonofont{Aporetic Serif Mono}[Contextuals=AlternateOff] diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls new file mode 100644 index 0000000..3937b79 --- /dev/null +++ b/doc/spbstu-report.cls @@ -0,0 +1,79 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов] + +% +% Support font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +\LoadClass[a4paper]{gost-7-32} + +\RequirePackage{csquotes} +\RequirePackage{amsmath} +\RequirePackage{amssymb} +\RequirePackage{adjustbox} +\RequirePackage{graphicx} +\RequirePackage{wrapfig} +\RequirePackage{rotating} + +\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}} +\newcommand{\@university}{}\newcommand{\university}[1]{\renewcommand{\@university}{#1}} +\newcommand{\@institute}{}\newcommand{\institute}[1]{\renewcommand{\@institute}{#1}} +\newcommand{\@school}{}\newcommand{\school}[1]{\renewcommand{\@school}{#1}} +\newcommand{\@direction}{}\newcommand{\direction}[1]{\renewcommand{\@direction}{#1}} +\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}} +\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}} +\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}} +\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$} +\newcommand{\@city}{}\newcommand{\city}[1]{\renewcommand{\@city}{#1}} +\renewcommand{\maketitle}{ + \begin{titlepage} + \begin{center} + \vspace{2cm} + \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ} + + \normalsize{\@university} + + \vspace{0.5cm} + \normalsize{\@institute} + + \normalsize{\@school} + + \normalsize{Направление \@direction} + + \vspace{2cm} + \LARGE{ОТЧЁТ} + + \normalsize{\@reportof} + + \large{\@subject} + + \large{\textit{\@title}} + + \normalsize{\textit{\@subtitle}} + \end{center} + + \vspace{3cm} + \small{ + \begin{tabular}{lrrl} + \!\!\!Студент, & \hspace{2cm} & & \\ + \!\!\!группы 5130201/20101 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\ + \!\!\!Преподаватель, & \hspace{2cm} & \\ + \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\ + &&\hspace{5cm} + \end{tabular} + \begin{flushright} + \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г. + \end{flushright} + } + + \vspace*{\fill} + \begin{center} + \small{\@city, \@date} + \end{center} + \end{titlepage} + \setcounter{page}{2} +} diff --git a/src/simple-genetic-algorithm.c b/src/simple-genetic-algorithm.c new file mode 100644 index 0000000..728fc78 --- /dev/null +++ b/src/simple-genetic-algorithm.c @@ -0,0 +1,480 @@ +// simple-genetic-algorithm.c --- simple genetic algorithm +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define POPULATION_CAPACITY 100 +#define CHROMOSOME_SIZE 16 +#define GENERATION_MAX 200 +#define FITNESS_TRESHOLD_AVERAGE -0.411 +#define FITNESS_TRESHOLD_VARIANCE -1 +#define FITNESS_TRESHOLD_BEST FITNESS_TRESHOLD_AVERAGE +#define DIGITS_AFTER_DECIMAL 3 +#define MINMAX -1 +#define X_MIN ((double) -10) +#define X_MAX ((double) +10) +#define Y_MIN ((double) -0.5) +#define Y_MAX ((double) +2.0) +#define PLOT_SAMPLE_COUNT 400 +// #define SEED time (NULL) +#define SEED 1760052039 +#define MEASUREMENT_RUNS 100 + +size_t population_sizes [] = { 10, 25, 50, 100 }; +double probabilities_crossover [] = { 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 }; +double probabilities_mutation [] = { 0.001, 0.01, 0.05, 0.1, 0.2 }; + +#define ASSERT assert +#define CTZL __builtin_ctzl +#define EPSILON 1e-12 + +#define ARRAY_LENGTH(T) (sizeof (T)/sizeof (*(T))) +#define FOR_EACH_ELEMENT(ELEMENT, ARRAY) \ + for (typeof (*(ARRAY)) *(ELEMENT) = (ARRAY); \ + (ELEMENT) < (ARRAY) + ARRAY_LENGTH (ARRAY); ++(ELEMENT)) \ + +#if CHROMOSOME_SIZE < 2 +#error "CHROMOSOME_SIZE smaller than 2" +#elif CHROMOSOME_SIZE <= 8 + typedef uint8_t chromosome; +#elif CHROMOSOME_SIZE <= 16 + typedef uint16_t chromosome; +#elif CHROMOSOME_SIZE <= 32 + typedef uint32_t chromosome; +#else +#error "CHROMOSOME_SIZE larger than 32" +#endif + +#define CHROMOSOME_MAX ((chromosome) -1 >> (8*sizeof (chromosome) - CHROMOSOME_SIZE)) + +struct sample { + double x, y; +}; +struct measurement { + double time; + size_t generations; +}; + +chromosome population [POPULATION_CAPACITY]; +chromosome population_breeding_pool [POPULATION_CAPACITY]; +double population_fitness [POPULATION_CAPACITY]; +double population_fitness_normalized [POPULATION_CAPACITY]; +double population_fitness_normalized_min; +double population_cdf [POPULATION_CAPACITY]; +size_t population_best_i; +double population_best_fitness; +chromosome generation_bests [GENERATION_MAX]; +double generation_bests_fitness [GENERATION_MAX]; +struct sample plot_samples [PLOT_SAMPLE_COUNT]; +struct measurement measurements [ARRAY_LENGTH (probabilities_crossover)] + [ARRAY_LENGTH (probabilities_mutation )]; + +double +decode (chromosome chromosome) +{ + return X_MIN + chromosome*(X_MAX - X_MIN)/CHROMOSOME_MAX; +} + +double +fitness_function (double x) +{ + return cos (x - 0.5)/fabs (x); +} + +uint8_t +bits_for_precision (int digits_after_decimal) +{ + ASSERT (digits_after_decimal < 18); + + uint64_t interval_count_min = ceil ((X_MAX - X_MIN)*pow (10, digits_after_decimal)); + uint64_t interval_count = 1; + while (interval_count < interval_count_min) + interval_count <<= 1; + return CTZL (interval_count); +} + +void +create_initial_population (size_t population_size) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + for (size_t i = 0; i < population_size; ++i) { + population[i] = rand () % (1 << CHROMOSOME_SIZE); + } +} + +bool +measure_fitness (size_t population_size) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + population_fitness_normalized_min = DBL_MAX; + // double fitness_average = 0; + // double fitness_variance = 0; + population_best_i = 0; + population_best_fitness = DBL_MAX; + for (size_t i = 0; i < population_size; ++i) { + double fitness = fitness_function (decode (population[i])); + double fitness_normalized = MINMAX*fitness; + population_fitness [i] = fitness; + population_fitness_normalized [i] = fitness_normalized; + if (fitness_normalized < population_fitness_normalized_min) + population_fitness_normalized_min = fitness_normalized; + // fitness_average += fitness; + // fitness_variance += fitness*fitness; + if (MINMAX*(fitness - population_best_fitness) > 0) { + population_best_i = i; + population_best_fitness = fitness; + } + } + population_fitness_normalized_min -= 1e-12; + // fitness_average /= population_size; + // fitness_variance = fitness_variance/population_size - + // fitness_average*fitness_average; + // printf ("%lg\n", fitness_average); + // if (fitness_average - FITNESS_TRESHOLD_AVERAGE < EPSILON) return true; + // if (fitness_variance - FITNESS_TRESHOLD_VARIANCE < EPSILON) return true; + // printf ("%lg\n", population_best_fitness); + if (MINMAX*(population_best_fitness - FITNESS_TRESHOLD_BEST) > 0) return true; + return false; +} + +void +fitness_proportionate_selection (size_t population_size) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + double population_fitness_sum = 0; + for (size_t i = 0; i < population_size; ++i) { + population_fitness_sum += + population_fitness_normalized[i] -= population_fitness_normalized_min; + } + + double last = 0; + for (size_t i = 0; i < population_size; ++i) { + last = population_cdf[i] = + last + population_fitness_normalized[i]/population_fitness_sum; + } + + for (size_t i = 0; i < population_size; ++i) { + double a = rand () /(double) RAND_MAX; + size_t j = 0; + // TODO(cmmm): use binary search + while (j < population_size) { + if (population_cdf[j] > a) break; + j += 1; + } + + population_breeding_pool[i] = population[j]; + } +} + +void +crossover (size_t population_size, double probability) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + for (size_t i = 0; i < population_size; i += 2) { + size_t i_a = i; + size_t i_b = (i + 1) % population_size; + + chromosome a = population_breeding_pool[i_a]; + chromosome b = population_breeding_pool[i_b]; + + if (rand () /(double) RAND_MAX > probability) { + population[i_a] = a; + population[i_b] = b; + } else { + size_t k = rand () % (CHROMOSOME_SIZE - 1) + 1; + chromosome mask_left = (1 << k) - 1; + chromosome mask_right = -1 << k; + population[i_a] = a & mask_left | b & mask_right; + population[i_b] = b & mask_left | a & mask_right; + } + } +} + +void +mutation (size_t population_size, double probability) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + for (size_t i = 0; i < population_size; ++i) { + if (rand () /(double) RAND_MAX > probability) + continue; + + size_t k = rand () % CHROMOSOME_SIZE; + population[i] ^= 1 << k; + } +} + +void +plot (const char *output, size_t population_size, size_t generation) +{ + // FILE *gp = popen ("gnuplot", "w"); + FILE *gp = fopen ("test.gp", "w"); + // fprintf (gp, "set term png\n"); + fprintf (gp, "set term cairolatex pdf input blacktext notransparent" + " nocrop size 15cm,10cm noheader\n"); + fprintf (gp, "set output '%s'\n", output); + + fprintf (gp, "set size ratio 0.66\n"); + fprintf (gp, "set lmargin at screen 0.1\n"); + fprintf (gp, "set rmargin at screen 0.9\n"); + fprintf (gp, "set bmargin at screen 0.1\n"); + fprintf (gp, "set tmargin at screen 0.9\n"); + + fprintf (gp, "set title 'Поколение №%lu, \\quad Лучшая особь: %lf'\n", + generation, population_best_fitness); + fprintf (gp, "set xlabel '\\(x\\)'\n"); + fprintf (gp, "set ylabel '\\(f(x)\\)'\n"); + fprintf (gp, "set xrange [%lf:%lf]\n", X_MIN, X_MAX); + fprintf (gp, "set yrange [%lf:%lf]\n", Y_MIN, Y_MAX); + + fprintf (gp, "plot "); + fprintf (gp, "'-' with lines title '%s',", "\\small{Целевая функция}"); + if (generation > 0) + fprintf (gp, "'-' with points pt 7 ps 1 lc 'yellow' title '\\small{Лучшие особи}',"); + fprintf (gp, "'-' with points pt 7 ps 1 lc 'green' title '\\small{Лучшая особь поколения}',"); + fprintf (gp, "'-' with points pt 7 ps 0.5 lc 'red' title '\\small{Популяция}'\n"); + for (size_t i = 0; i < PLOT_SAMPLE_COUNT; ++i) { + fprintf (gp, "%lf %lf\n", plot_samples[i].x, plot_samples[i].y); + } fprintf (gp, "e\n"); + if (generation > 0) { + for (size_t i = 0; i < generation; ++i) { + double x = decode (generation_bests[i]); + fprintf (gp, "%lf %lf\n", x, generation_bests_fitness[i]); + } fprintf (gp, "e\n"); + } + fprintf (gp, "%lf %lf\ne\n", + decode (population[population_best_i]), + population_best_fitness); + for (size_t i = 0; i < population_size; ++i) { + double x = decode (population[i]); + fprintf (gp, "%lf %lf\n", x, population_fitness[i]); + } fprintf (gp, "e\n"); + fclose (gp); +} + +void +run_experiment__plot (size_t population_size, + double probability_crossover, + double probability_mutation) +{ + void + plot_generation (size_t generation) + { + static char plot_output[256]; + + snprintf (plot_output, sizeof (plot_output), "res/p%llu-c%4.2lf-m%4.2lf-g%03u.tex", + population_size, probability_crossover, + probability_mutation, generation); + + plot (plot_output, population_size, generation); + } + + create_initial_population (population_size); + measure_fitness (population_size); + size_t generation; + for (generation = 0; generation < GENERATION_MAX; ++generation) { + if (measure_fitness (population_size)) break; + + generation_bests [generation] = population[population_best_i]; + generation_bests_fitness [generation] = population_best_fitness; + printf ("fitness: %lf\n", population_best_fitness); + plot_generation (generation); + + fitness_proportionate_selection (population_size); + crossover (population_size, probability_crossover); + mutation (population_size, probability_mutation); + } + if (generation == GENERATION_MAX) + measure_fitness (population_size); + printf ("fitness: %lf\n", population_best_fitness); + printf ("chromosome: %0*b\n", CHROMOSOME_SIZE, population[population_best_i]); + plot_generation (generation); +} + +struct measurement +run_experiment__measure (size_t population_size, + double probability_crossover, + double probability_mutation) +{ + double total_time = 0; + size_t total_generations = 0; + for (int run = 0; run < MEASUREMENT_RUNS; ++run) { + clock_t begin = clock (); + create_initial_population (population_size); + size_t generation; + for (generation = 0; generation < GENERATION_MAX; ++generation) { + if (measure_fitness (population_size)) break; + fitness_proportionate_selection (population_size); + crossover (population_size, probability_crossover); + mutation (population_size, probability_mutation); + } + double time = (clock () - begin) /(double) CLOCKS_PER_SEC; + total_time += time; + total_generations += generation; + } + + return (struct measurement) { + .time = total_time/MEASUREMENT_RUNS, + .generations = (total_generations + MEASUREMENT_RUNS/2)/MEASUREMENT_RUNS, + }; +} + +void +sample_fitness_function () +{ + double x = X_MIN; + double dx = (X_MAX - X_MIN)/PLOT_SAMPLE_COUNT; + for (size_t i = 0; i < PLOT_SAMPLE_COUNT; ++i) { + plot_samples[i].x = x; + plot_samples[i].y = fitness_function (x); + x += dx; + } +} + +typedef int (*print_function)(void *user, const char *template, ...); +typedef int (*cell_function)(int x, int y, print_function, void *); + +int +print__measure (void *user, const char *template, ...) +{ + va_list ap; + va_start (ap, template); + int len = vsnprintf (NULL, 0, template, ap); + va_end (ap); + return len; +} + +int +print__stream (void *stream, const char *template, ...) +{ + va_list ap; + va_start (ap, template); + int len = vfprintf (stream, template, ap); + va_end (ap); + return len; +} + +void +print_org_table (const char *filename, const char *name, const char *caption, + int rows, int cols, cell_function cell) +{ + int cell_widths[rows][cols]; + int column_widths[cols]; + memset (column_widths, 0, sizeof (column_widths)); + for (int y = 0; y < rows; ++y) { + for (int x = 0; x < cols; ++x) { + cell_widths[y][x] = cell (x, y, print__measure, NULL); + if (cell_widths[y][x] > column_widths[x]) + column_widths[x] = cell_widths[y][x];; + } + } + + FILE *stream = fopen (filename, "w"); + fprintf (stream, "#+name: %s\n", name); + fprintf (stream, "#+caption: %s\n", caption); + for (int y = 0; y < rows; ++y) { + fprintf (stream, "|"); + for (int x = 0; x < cols; ++x) { + fprintf (stream, " "); + if (x == 0) { + for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i) + fprintf (stream, " "); + } + cell (x, y, print__stream, stream); + if (x > 0) { + for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i) + fprintf (stream, " "); + } + fprintf (stream, " |"); + } fprintf (stream, "\n"); + if (y == 0) { + fprintf (stream, "|"); + for (int x = 0; x < cols; ++x) { + for (int i = 0; i < column_widths[x] + 2; ++i) + fprintf (stream, "-"); + fprintf (stream, "|"); + } fprintf (stream, "\n"); + } + } + + fclose (stream); +} + +int +main (int argc, char *argv[]) +{ + ASSERT (CHROMOSOME_SIZE >= bits_for_precision (DIGITS_AFTER_DECIMAL)); + + printf ("SEED: %u\n", SEED); + srand (SEED); + sample_fitness_function (); + + run_experiment__plot (25, .5, .1); + return 0; + + struct measurement *best_measurement = &measurements[0][0]; + FOR_EACH_ELEMENT (population_size, population_sizes) { + struct measurement *measurement = &measurements[0][0]; + FOR_EACH_ELEMENT (probability_crossover, probabilities_crossover) { + FOR_EACH_ELEMENT (probability_mutation, probabilities_mutation) { + *measurement = run_experiment__measure (*population_size, + *probability_crossover, + *probability_mutation); + if (measurement->time < best_measurement->time) + best_measurement = measurement; + measurement += 1; + } + } + + char *table_filename, *table_name, *table_caption; + asprintf (&table_filename, "res/results-%03lu.org", *population_size); + asprintf (&table_name, "results-%lu", *population_size); + asprintf (&table_caption, "Результаты для \\(N = %lu\\)", + *population_size); + int table_cell (int x, int y, print_function print, void *user) + { + int m = x - 1; + int c = y - 1; + if (x == 0 && y == 0) return print (user, "\\(P_c \\;\\backslash\\; P_m\\)"); + if ( y == 0) return print (user, "%.3lg", probabilities_mutation [m]); + if (x == 0 ) return print (user, "%.1lg", probabilities_crossover[c]); + + int len = 0; + bool max_generation_reached = + measurements[c][m].generations == GENERATION_MAX; + bool is_best = &measurements[c][m] == best_measurement; + if (max_generation_reached) len += print (user, "\\st{"); + if (is_best) print (user, "*"); + len += print (user, "%.2lf (%lu)", + measurements[c][m].time*1000000, + measurements[c][m].generations); + if (is_best) print (user, "*"); + if (max_generation_reached) len += print (user, "}"); + + return len; + } + print_org_table (table_filename, table_name, table_caption, + 1 + ARRAY_LENGTH (probabilities_crossover), + 1 + ARRAY_LENGTH (probabilities_mutation), table_cell); + } + + return EXIT_SUCCESS; +} + +// simple-genetic-algorithm.c ends here -- cgit v1.3.1