{"id":142,"date":"2023-02-26T23:10:07","date_gmt":"2023-02-26T22:10:07","guid":{"rendered":"https:\/\/portfolio.porombka.pl\/?p=142"},"modified":"2023-03-22T12:24:46","modified_gmt":"2023-03-22T11:24:46","slug":"4-genetic-algorithms-example-code","status":"publish","type":"post","link":"https:\/\/portfolio.porombka.pl\/index.php\/2023\/02\/26\/4-genetic-algorithms-example-code\/","title":{"rendered":"[4] Genetic Algorithms: example code"},"content":{"rendered":"\n<p class=\"has-x-large-font-size\">TL;DR<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>In this post I present an implementation of the Classic Genetic Algorithm version, as an interactive <strong>widget<\/strong>, using binary representation of chromosome (we use 0\/1 bits as a genes in chromosome, to encode variables). As you may know from previous post, this king of representation make operators easier to implement.<\/p>\n<\/blockquote>\n\n\n\n<p>In this post I would like to share with you an implementation of the Classic Genetic Algorithm version in JavaScript. The implementation is available on <a href=\"https:\/\/github.com\/passions-blog\/Genetic-Algorithms-Classic-Example-001\" data-type=\"URL\" data-id=\"https:\/\/github.com\/passions-blog\/Genetic-Algorithms-Classic-Example-001\" target=\"_blank\" rel=\"noreferrer noopener\">this blog Github<\/a>. <\/p>\n\n\n\n<p>Below I embedded my implementation of the Classic Genetic Algorithm using binary chromosome representation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Classic Genetic Algorithm widget<\/h2>\n\n\n\n<p>Just click Execute button and see the results. I created three sections, first with all parameters prefilled, second to see visualization of the function in 3D and results with all chromosomes from the last population containing final solution. Feel free to manipulate parameters to see how it affects results.<\/p>\n\n\n\n<iframe id=\"ifrm\" style=\"border: none; margin: 0; padding: 0; width: 100%; box-sizing: border-box\" data-src=\"https:\/\/passions-blog.github.io\/Genetic-Algorithms-Classic-Example-001\/\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" class=\"lazyload\" data-load-mode=\"1\"><\/iframe>\n\n<script type=\"text\/javascript\">\n        window.addEventListener('message', receiveMessage, false);\n        function receiveMessage(evt) {\n            \/\/ Do we trust the sender of this message?\n            if (evt.origin !== \"https:\/\/passions-blog.github.io\") {\n                return;\n            }\n            if (evt.data.type === \"frame-resized\") {\n                document.getElementById(\"ifrm\").style.height = evt.data.value + \"px\";\n            }\n        }\n<\/script>\n\n\n\n<p>Above widget available also repository Github page <a rel=\"noreferrer noopener\" href=\"https:\/\/passions-blog.github.io\/Genetic-Algorithms-Classic-Example-001\/\" data-type=\"URL\" data-id=\"https:\/\/passions-blog.github.io\/Genetic-Algorithms-Classic-Example-001\/\" target=\"_blank\">here<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The code<\/h2>\n\n\n\n<p>The widget above has a little bit more than just a RAW classic algorithm. I added there function visualization and some basic controls parametrizing the algorithm. I will focus on algorithm code only. I implemented solution in pure JavaScript ES5, to make it work everywhere just like that. Implementation was quite easy, so I could resign of ES6.<\/p>\n\n\n\n<p>The code I prepared consists of two main JavaScript files: <\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/github.com\/passions-blog\/Genetic-Algorithms-Classic-Example-001\/blob\/main\/ga-classic.js\" data-type=\"URL\" data-id=\"https:\/\/github.com\/passions-blog\/Genetic-Algorithms-Classic-Example-001\/blob\/main\/ga-classic.js\" target=\"_blank\" rel=\"noreferrer noopener\">ga-classic.js<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/github.com\/passions-blog\/Genetic-Algorithms-Classic-Example-001\/blob\/main\/ga.helpers.js\" data-type=\"URL\" data-id=\"https:\/\/github.com\/passions-blog\/Genetic-Algorithms-Classic-Example-001\/blob\/main\/ga.helpers.js\" target=\"_blank\" rel=\"noreferrer noopener\">ga.helpres.js<\/a><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Chromosome structure<\/h3>\n\n\n\n<p>I used following object structure for single chromosome (expressed here in TypeScript):<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-ts\" data-lang=\"TypeScript\"><code>{\n    genes: number[]; \/\/ array of bits (0\/1 values)\n    eval: number; \/\/ calculated value of function for given x,y =&gt; f(x,y)\n    x: number; \/\/ decoded position X (from genes binary array)\n    y: number; \/\/ decoded position Y (from genes binary array)\n}<\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Helper functions<\/h3>\n\n\n\n<p>I implemented following helper functions for encoding\/decoding binary representation of chromosome. First one is to decode binary array into decimal number.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga.helpers.js\" data-lang=\"JavaScript\"><code>\/**\n * Converts binary array to decimal number.\n * @param binaryArray Array of 0\/1 values to convert.\n * @returns {number} Result is a decimal number.\n *\/\nfunction binaryArrayToNumber(binaryArray) {\n    var result = 0;\n    var exponent = binaryArray.length - 1;\n    for (var i = 0; i &lt; binaryArray.length; i++) {\n        if (binaryArray[i]) {\n            result += Math.pow(2, exponent);\n        }\n        exponent--;\n    }\n    return result;\n}<\/code><\/pre><\/div>\n\n\n\n<p>To decode chromosome into two x,y values we have to calculate following equations, which I explained earlier in <a rel=\"noreferrer noopener\" href=\"https:\/\/portfolio.porombka.pl\/index.php\/2023\/02\/08\/genetic-algorithms-3-binary-chromosomes\/\" data-type=\"post\" data-id=\"76\" target=\"_blank\">[3] Genetic Algorithms: Binary chromosomes<\/a>.<\/p>\n\n\n\n<p>\\[ x = x_1 + \\frac{decimal(\\textrm{genes representing x})\\cdot (x_n &#8211; x_1)}{2^N &#8211; 1}\\]<\/p>\n\n\n\n<p>\\[ y = y_1 + \\frac{decimal(\\textrm{genes representing y})\\cdot (y_n &#8211; y_1)}{2^N &#8211; 1}\\]<\/p>\n\n\n\n<p>where<\/p>\n\n\n\n<p>\\( x, y \\) &#8211; represent position of chromosome &#8211; solution in search space,<br>\\( x_1 \\dots x_n \\) &#8211; is the available range on X axis,<br>\\( y_n \\dots y_n \\) &#8211; is the available range on Y axis,<br>\\( N \\) &#8211; is the number of bits representing single variable x or y in <code>genes: number[]<\/code> array,<br>\\( decimal(&#8230;) \\) &#8211; is the function <code>binaryArrayToNumber(binaryArray)<\/code>.<\/p>\n\n\n\n<p>In code it looks like this:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga.helpers.js\" data-lang=\"JavaScript\"><code>\/**\n * Decodes array of numbers 0 or 1 into array of variables.\n * @param binaryArray Array of 0,1 values that represents a chromosome (array of genes).\n * The length of the array must be divisible by numberOfVariables.\n * @param numberOfVariables The number of variables encoded in binary array.\n * @param ranges An array of two element arrays containing ranges of values,\n * first element in each array is starting value, second element is ending value.\n * @returns {number[]} Returns array of floating point numbers encoded in {@param binaryArray}.\n *\/\nfunction decodeBinaryChromosome(binaryArray, numberOfVariables, ranges) {\n    if (binaryArray.length % numberOfVariables &gt; 0) {\n        throw new Error(&#39;Invalid number of variables or binary array length. &#39; +\n            &#39;The length of the array must be divisible by number of variables.&#39;);\n    }\n    var result = [];\n    var variableSize = binaryArray.length \/ numberOfVariables;\n    for (var i = 0; i &lt; numberOfVariables; i++) {\n        var binArray = binaryArray.slice(i * variableSize, i * variableSize + variableSize);\n        var decimalValue = binaryArrayToNumber(binArray);\n        var value = ranges[i][0] + decimalValue * (ranges[i][1] - ranges[i][0]) \/ (Math.pow(2, variableSize) - 1);\n        result.push(value);\n    }\n    return result;\n}<\/code><\/pre><\/div>\n\n\n\n<p>Additionally I created opposite function to encode x,y chromosome variables back into binary array. We can transform previous equations into:<\/p>\n\n\n\n<p>\\[ decimal(\\textrm{genes representing x}) = \\frac{(x-x_1) \\cdot (2^N-1)}{x_n-x_1} \\]<\/p>\n\n\n\n<p>\\[ decimal(\\textrm{genes representing y}) = \\frac{(y-y_1) \\cdot (2^N-1)}{y_n-y_1} \\]<\/p>\n\n\n\n<p>In code I&#8217;ve made small optimization and I create whole string array of bits first then, I convert string of 0\/1 into numeric array. <\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga.helpers.js\" data-lang=\"JavaScript\" data-line=\"13\"><code>\/**\n * Encodes given variables into binary array of given ranges, with fixed number of bits for each of variables.\n * @param values Floating point values to be encoded.\n * @param variableSize Size of the single variable in bits.\n * @param ranges An array of two-element arrays containing ranges of values,\n * first element in each array is starting value, second element is ending value.\n * @returns {number[]} An array of 0,1 values representing a chromosome.\n *\/\nfunction encodeBinaryChromosome(values, variableSize, ranges) {\n    var finalBinaryString = &#39;&#39;;\n    for (var i = 0; i &lt; values.length; i++) {\n        var range = ranges[i];\n        var decValue = Math.round((Math.pow(2, variableSize) - 1) * (values[i] - range[0]) \/ (range[1] - range[0]));\n        var binaryString = decValue.toString(2);\n        var missingNumberOfZeroes = variableSize - binaryString.length;\n        finalBinaryString += Array(missingNumberOfZeroes + 1).join(&#39;0&#39;) + binaryString;\n    }\n    return Array.from(finalBinaryString.split(&#39;&#39;), Number);\n}<\/code><\/pre><\/div>\n\n\n\n<p>The decimal value calculation is highlighted. You can notice that the result is rounded to integer. This is caused by possible JavaScript precision problems, because in JS, sometimes after calculation you can get a small error on 10-th position after the comma. That would cause above equations to fail. I assume that possible x and y values are not any floating point numbers, but values with specific precision denoted by \\( N \\) (number of bits representing single variable). Bigger \\( N \\) gives as better precision (more discrete values), so we get our ranges divided into more sub ranges.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Algorithm structure function<\/h3>\n\n\n\n<p>The main part of algorithm is a function <code>run(options)<\/code> below:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga-classic.js\" data-lang=\"JavaScript\"><code>function run(options) {\n    if (options) {\n        EVAL_FN = options.evalFunction;\n        VARIABLE_SIZE = options.variableSize;\n        CHROMOSOME_SIZE = VARIABLE_SIZE * 2;\n        MUTATION_PROBABILITY = options.pm;\n        CROSSOVER_PROBABILITY = options.pc;\n        POPULATION_SIZE = options.popSize;\n        SELECTION_COUNT = options.selCount;\n        MAX_GENERATIONS = options.maxGenerations;\n        MAXIMIZATION = options.maximize;\n        space.x1 = options.x1;\n        space.xn = options.xn;\n        space.y1 = options.y1;\n        space.yn = options.yn;\n    }\n\n    \/\/ Classic genetic algorithm - binary chromosome representation\n\n    \/\/ 1. Create an initial population\n    \/\/    during generation we also evaluate each chromosome value\n    population = createPopulation();\n\n    \/\/ 2. Start calculations\n    var generation = 0;\n    while (generation &lt; MAX_GENERATIONS) {\n        crossover(); \/\/ generates new chromosomes to fill in population\n        mutation(); \/\/ mutate random genes in chosen chromosomes\n        evaluation(); \/\/ make sure everything is calculated correctly after all operators\n        selection(); \/\/ leave only the best solutions and limit population back to fixed size\n        generation++;\n    }\n\n    \/\/ 3. Sort population and get the best individual\n    selection();\n\n    return population;\n}<\/code><\/pre><\/div>\n\n\n\n<p>We have 3 sections here:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Initial population generation<br><em>The initial chromosomes set is randomly generated, this is the population which we start with.<\/em><\/li>\n\n\n\n<li>Main calculations loop<br><em>Here we create generations of chromosomes. One by one, the part of old population dies, new chromosomes are created by crossover, mutation introduces unpredictable changes, finally we make sure that all chromosomes have calculated objective function value.<\/em><\/li>\n\n\n\n<li>Final sorting (selection)<br><em>At the end we finally make one more final population selection, to sort population and leave only the best chromosomes with the highest evaluation function values.<\/em><\/li>\n<\/ol>\n\n\n\n<p>Function requires a set of parameters that are explained below:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-lang=\"JavaScript\"><code>options.evalFunction \/\/ string representation of evaluation function e.g. sin(x)*y\noptions.variableSize \/\/ number of bits (genes) used to encode one variable e.g. x position\noptions.pm \/\/ mutation probability 0.0 ... 1.0\noptions.pc  \/\/ crossover probability 0.0 ... 1.0\nptions.popSize \/\/ population initial size\noptions.selCount \/\/ selection count - number of the best chromosomes left after selection\noptions.maxGenerations \/\/ maximum number of iterations of algorithm\noptions.maximize \/\/ true if we search for maximum, false if minimum\noptions.x1 \/\/ starting point of search space on X axis\noptions.xn \/\/ ending point of search space on X axis\noptions.y1  \/\/ starting point of search space on Y axis\noptions.yn  \/\/ ending point of search space on Y axis<\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Initial population<\/h3>\n\n\n\n<p>In first part of algorithm we prepare initial population from random chromosomes:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga-classic.js\" data-lang=\"JavaScript\"><code>\/**\n * Creates a new population of chromosomes.\n * @returns {[]} An array of new random chromosomes.\n *\/\nfunction createPopulation() {\n    var population = [];\n    for (var i = 0; i &lt; POPULATION_SIZE; i++) {\n        population.push(generateChromosome());\n    }\n    return population;\n}<\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Breeding \/ Crossover<\/h3>\n\n\n\n<p>Nest step is to start first of 4 common algorithm phases &#8211; crossover. This operator extends a population by new chromosomes created from two parents selected randomly from actual population.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga-classic.js\" data-lang=\"JavaScript\"><code>\/**\n * Generates new chromosomes by crossover (extends population).\n *\/\nfunction crossover() {\n    var parents = [];\n    for (var i = 0; i &lt; population.length; i++) {\n        if (parents.indexOf(i) &gt;= 0) {\n            continue; \/\/ skip already selected parent\n        }\n        if (Math.random() &lt; CROSSOVER_PROBABILITY) {\n            parents.push(i);\n        }\n    }\n\n    \/\/ if odd number of parents choose one more\n    var index = -1;\n    while (parents.length % 2 === 1) {\n        index++;\n        index = index === population.length ? 0 : index;\n\n        \/\/ select another parent\n        if (parents.indexOf(index) &gt;= 0) {\n            continue; \/\/ skip already selected parent\n        }\n        if (Math.random() &lt; CROSSOVER_PROBABILITY) {\n            parents.push(index);\n            break;\n        }\n\n    }\n\n    \/\/ crossover parents and extend population by new children\n    for (var i = 0; i &lt; parents.length; i+=2) {\n        \/\/ crossover parents\n        var crossingPoint = getRandomInt(1, CHROMOSOME_SIZE - 2);\/\/ from 1 to make crossover up to one less than last one\n        var chromosomeA = cloneChromosome(population[parents[i]]);\n        var chromosomeB = cloneChromosome(population[parents[i+1]]);\n\n        var a1 = chromosomeA.genes.slice(0, crossingPoint);\n        var a2 = chromosomeA.genes.slice(crossingPoint);\n        var b1 = chromosomeB.genes.slice(0, crossingPoint);\n        var b2 = chromosomeB.genes.slice(crossingPoint);\n\n        chromosomeA.genes = a1.concat(b2);\n        chromosomeB.genes = b1.concat(a2);\n\n        \/\/ clear old information about position and eval in chromosomes\n        chromosomeA.x = undefined;\n        chromosomeA.y = undefined;\n        chromosomeA.eval = undefined;\n        chromosomeB.x = undefined;\n        chromosomeB.y = undefined;\n        chromosomeB.eval = undefined;\n\n        population.push(chromosomeA);\n        population.push(chromosomeB);\n    }\n}<\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Uniform Mutation<\/h3>\n\n\n\n<p>The simplest mutation version I know, which randomly introduces some mutated genes into new chromosomes generated during breeding. We choose or not chromosome, and then we select which gene to mutate.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga-classic.js\" data-lang=\"JavaScript\"><code>\/**\n * Randomly introduce mutated genes into new chromosomes.\n * Mutation is done only for new child chromosomes, that are beyond \n * original population size. \n *\/\nfunction mutation() {\n    \/\/ mutate only children\n    for (var i = POPULATION_SIZE - 1; i &lt; population.length; i++) {\n        var shouldMutate = Math.random() &lt; MUTATION_PROBABILITY;\n        if (shouldMutate) {\n            \/\/ choose gene to mutate\n            var geneIndex = getRandomInt(0, CHROMOSOME_SIZE - 1);\n            population[i].genes[geneIndex] = getRandomInt(0, 1); \/\/ random value 0 or 1 - mutation\n        }\n    }\n}<\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Evaluation function (objective)<\/h3>\n\n\n\n<p>Evaluation is penultimate step in GA, which ensures that every chromosome in population has calculated fitness. We simply iterate over population to execute \\(f(x,y)\\) function for each chromosome, like below.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga-classic.js\" data-lang=\"JavaScript\"><code>\/**\n * Calculate each chromosome fitness.\n *\/\nfunction evaluation() {\n    for (var i = 0; i &lt; population.length; i++) {\n        fxy(population[i]);\n    }\n}<\/code><\/pre><\/div>\n\n\n\n<p>I used great freeware JavaScript library <a rel=\"noreferrer noopener\" href=\"https:\/\/mathjs.org\/\" data-type=\"URL\" data-id=\"https:\/\/mathjs.org\/\" target=\"_blank\">math.js<\/a> to evaluate function expression from string representation. The evaluation function \\(f(x,y)\\) is defined as below.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga-classic.js\" data-lang=\"JavaScript\"><code>\/**\n * Evaluates value of the objective function, sets the chromosome position x,y and eval.\n * @param chromosome The chromosome representing solution.\n *\/\nfunction fxy(chromosome) {\n\n    var variables = decodeBinaryChromosome(chromosome.genes, 2, ranges);\n\n    \/\/ calculate real x,y coordinates\n    var x = variables[0];\n    var y = variables[1];\n    chromosome.x = x;\n    chromosome.y = y;\n\n    \/\/ here we can implement penalty function when the chromosome is outside the ranges or violates constraints\n    if (x &lt; space.x1 || x &gt; space.xn || y &lt; space.y1 || y &gt; space.yn) {\n        \/\/ make this chromosome very bad one according to target optimization\n        chromosome.eval = MAXIMIZATION ? Number.MIN_VALUE : Number.MAX_VALUE;\n        return chromosome;\n    }\n\n    chromosome.eval = math.evaluate(EVAL_FN, {\n        x: x, y: y\n    });\n    return chromosome;\n\n}<\/code><\/pre><\/div>\n\n\n\n<p>Very important part of this function is a &#8220;penalty&#8221; applied to the result. If the solution position is located outside the available search space, we make the chromosome a &#8220;very bad looking one&#8221;, I mean with very low evaluation value, we set it to <code>Number.MIN_VALUE<\/code> &#8211; minimal available JavaScript number. This finally will eliminate such chromosome from population, so no invalid individuals in population. We call this behavior a <strong>penalty function<\/strong>.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga-classic.js\" data-lang=\"JavaScript\"><code>\/\/ here we can implement penalty function when the chromosome is outside the\n\/\/ ranges or violates constraints\nif (x &lt; space.x1 || x &gt; space.xn || y &lt; space.y1 || y &gt; space.yn) {\n    \/\/ make this chromosome very bad one according to target optimization\n    chromosome.eval = MAXIMIZATION ? Number.MIN_VALUE : Number.MAX_VALUE;\n    return chromosome;\n}<\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Selection operator<\/h3>\n\n\n\n<p>Below you can see the implementation of selection operator. Selection is executed also at the end to finally sort and trim the population after the main loop will end.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-js\" data-file=\"ga-classic.js\" data-lang=\"JavaScript\"><code>\/**\n * Selects a number of the best individuals from population and removes the rest,\n * the population is decreased by the worst chromosomes.\n * @param trim Trim the population to SELECTION_COUNT.\n *\/\nfunction selection(trim) {\n    \/\/ sort population\n    population.sort(function (chromosomeA, chromosomeB) {\n        \/\/ search for maximum, so we sort bigger values (evaluations) at the beginning as the\n        \/\/ best chromosomes\n        return MAXIMIZATION\n            \/\/ result &lt; 0 will sort A before B (B &lt; A =&gt; result &lt; 0)\n            \/\/ result &gt; 0 will sort B before A (A &lt; B =&gt; result &gt; 0)\n            \/\/ result = 0 will leave the order\n            ? chromosomeB.eval - chromosomeA.eval\n\n            \/\/ result &lt; 0 will sort B before A (A &lt; B =&gt; result &lt; 0)\n            \/\/ result &gt; 0 will sort A before B (B &lt; A =&gt; result &gt; 0)\n            \/\/ result = 0 will leave the order\n            : chromosomeA.eval - chromosomeB.eval;\n    });\n\n    \/\/ select only the best chromosomes, remove the rest from population\n    population = population.slice(0, SELECTION_COUNT);\n}<\/code><\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<p>And&#8230; that&#8217;s it. It looks like the code grown more than I was expecting. I hope it is clear for everyone. If you have questions, ask me in comments.<\/p>\n\n\n\n<p>Thank you for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this post I present an implementation of the Classic Genetic Algorithm version, as an interactive widget, using binary representation of chromosome (we use 0\/1 bits as a genes in chromosome, to encode variables). As you may know from previous post, this king of representation make operators easier to implement.<\/p>\n","protected":false},"author":1,"featured_media":55,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6,14],"tags":[22,47,24,16,11,15,46,18,23,48],"class_list":["post-142","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-genetic-algorithms","tag-algorithm","tag-code","tag-computation","tag-evaluation","tag-evolution","tag-genetic","tag-javascript","tag-numerical","tag-objective","tag-widget","grid-sizer"],"_links":{"self":[{"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/posts\/142","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/comments?post=142"}],"version-history":[{"count":55,"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/posts\/142\/revisions"}],"predecessor-version":[{"id":237,"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/posts\/142\/revisions\/237"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/media\/55"}],"wp:attachment":[{"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/media?parent=142"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/categories?post=142"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/portfolio.porombka.pl\/index.php\/wp-json\/wp\/v2\/tags?post=142"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}