From ad89b477c86cd4f9ac632260a87549a6b7f132c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Wed, 11 Mar 2020 03:38:31 +0100 Subject: [PATCH] [yul-phaser] GeneticAlgorithms: Add methods for selecting a crossover operator --- tools/yulPhaser/GeneticAlgorithms.cpp | 39 +++++++++++++++++++++++++++ tools/yulPhaser/GeneticAlgorithms.h | 20 ++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/tools/yulPhaser/GeneticAlgorithms.cpp b/tools/yulPhaser/GeneticAlgorithms.cpp index 701bdf28c..7dcc44ed4 100644 --- a/tools/yulPhaser/GeneticAlgorithms.cpp +++ b/tools/yulPhaser/GeneticAlgorithms.cpp @@ -21,8 +21,47 @@ #include using namespace std; +using namespace solidity; using namespace solidity::phaser; +function phaser::buildCrossoverOperator( + CrossoverChoice _choice, + optional _uniformCrossoverSwapChance +) +{ + switch (_choice) + { + case CrossoverChoice::SinglePoint: + return randomPointCrossover(); + case CrossoverChoice::TwoPoint: + return randomTwoPointCrossover(); + case CrossoverChoice::Uniform: + assert(_uniformCrossoverSwapChance.has_value()); + return uniformCrossover(_uniformCrossoverSwapChance.value()); + default: + assertThrow(false, solidity::util::Exception, "Invalid CrossoverChoice value."); + }; +} + +function phaser::buildSymmetricCrossoverOperator( + CrossoverChoice _choice, + optional _uniformCrossoverSwapChance +) +{ + switch (_choice) + { + case CrossoverChoice::SinglePoint: + return symmetricRandomPointCrossover(); + case CrossoverChoice::TwoPoint: + return symmetricRandomTwoPointCrossover(); + case CrossoverChoice::Uniform: + assert(_uniformCrossoverSwapChance.has_value()); + return symmetricUniformCrossover(_uniformCrossoverSwapChance.value()); + default: + assertThrow(false, solidity::util::Exception, "Invalid CrossoverChoice value."); + }; +} + Population RandomAlgorithm::runNextRound(Population _population) { RangeSelection elite(0.0, m_options.elitePoolSize); diff --git a/tools/yulPhaser/GeneticAlgorithms.h b/tools/yulPhaser/GeneticAlgorithms.h index 0d1f0375f..22ab62c04 100644 --- a/tools/yulPhaser/GeneticAlgorithms.h +++ b/tools/yulPhaser/GeneticAlgorithms.h @@ -20,11 +20,31 @@ #pragma once +#include #include +#include + namespace solidity::phaser { +enum class CrossoverChoice +{ + SinglePoint, + TwoPoint, + Uniform, +}; + +std::function buildCrossoverOperator( + CrossoverChoice _choice, + std::optional _uniformCrossoverSwapChance +); + +std::function buildSymmetricCrossoverOperator( + CrossoverChoice _choice, + std::optional _uniformCrossoverSwapChance +); + /** * Abstract base class for genetic algorithms. * The main feature is the @a runNextRound() method that executes one round of the algorithm,