From 55441438454aea974a1fac1314bcc77d974d9c9d Mon Sep 17 00:00:00 2001 From: Mick de Peinder Date: Sat, 4 May 2019 13:03:18 +0200 Subject: [PATCH] Full commit. --- .gitignore | 334 ++++++++++++++++++ GeneticAlgorithmRaw/GeneticAlgorithmRaw.cpp | 25 ++ .../GeneticAlgorithmRaw.vcxproj | 167 +++++++++ .../GeneticAlgorithmRaw.vcxproj.filters | 42 +++ GeneticAlgorithmRaw/algorithm_raw.cpp | 101 ++++++ GeneticAlgorithmRaw/algorithm_raw.h | 26 ++ GeneticAlgorithmRaw/individual_raw.cpp | 65 ++++ GeneticAlgorithmRaw/individual_raw.h | 25 ++ GeneticAlgorithmRaw/population_raw.cpp | 83 +++++ GeneticAlgorithmRaw/population_raw.h | 26 ++ 10 files changed, 894 insertions(+) create mode 100644 .gitignore create mode 100644 GeneticAlgorithmRaw/GeneticAlgorithmRaw.cpp create mode 100644 GeneticAlgorithmRaw/GeneticAlgorithmRaw.vcxproj create mode 100644 GeneticAlgorithmRaw/GeneticAlgorithmRaw.vcxproj.filters create mode 100644 GeneticAlgorithmRaw/algorithm_raw.cpp create mode 100644 GeneticAlgorithmRaw/algorithm_raw.h create mode 100644 GeneticAlgorithmRaw/individual_raw.cpp create mode 100644 GeneticAlgorithmRaw/individual_raw.h create mode 100644 GeneticAlgorithmRaw/population_raw.cpp create mode 100644 GeneticAlgorithmRaw/population_raw.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f00a0eb --- /dev/null +++ b/.gitignore @@ -0,0 +1,334 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ \ No newline at end of file diff --git a/GeneticAlgorithmRaw/GeneticAlgorithmRaw.cpp b/GeneticAlgorithmRaw/GeneticAlgorithmRaw.cpp new file mode 100644 index 0000000..ffe5fcf --- /dev/null +++ b/GeneticAlgorithmRaw/GeneticAlgorithmRaw.cpp @@ -0,0 +1,25 @@ +// GeneticAlgorithmRaw.cpp : This file contains the 'main' function. Program execution begins and ends there. +// + +#include +#include "algorithm_raw.h" + +int main() +{ + _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); + std::cout << "[GeneticAlgorithmRaw]" << std::endl; + algorithm_raw algorithm{"Sample string goal", 500, 1}; + algorithm.run(); + return EXIT_SUCCESS; +} + +// Run program: Ctrl + F5 or Debug > Start Without Debugging menu +// Debug program: F5 or Debug > Start Debugging menu + +// Tips for Getting Started: +// 1. Use the Solution Explorer window to add/manage files +// 2. Use the Team Explorer window to connect to source control +// 3. Use the Output window to see build output and other messages +// 4. Use the Error List window to view errors +// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project +// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file diff --git a/GeneticAlgorithmRaw/GeneticAlgorithmRaw.vcxproj b/GeneticAlgorithmRaw/GeneticAlgorithmRaw.vcxproj new file mode 100644 index 0000000..b0c7df0 --- /dev/null +++ b/GeneticAlgorithmRaw/GeneticAlgorithmRaw.vcxproj @@ -0,0 +1,167 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + {0DB3ACB5-3B22-46BB-9D15-4367A3DE42E1} + Win32Proj + GeneticAlgorithmRaw + 10.0 + + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + Level3 + Disabled + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + Level3 + MaxSpeed + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/GeneticAlgorithmRaw/GeneticAlgorithmRaw.vcxproj.filters b/GeneticAlgorithmRaw/GeneticAlgorithmRaw.vcxproj.filters new file mode 100644 index 0000000..65ddb7d --- /dev/null +++ b/GeneticAlgorithmRaw/GeneticAlgorithmRaw.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/GeneticAlgorithmRaw/algorithm_raw.cpp b/GeneticAlgorithmRaw/algorithm_raw.cpp new file mode 100644 index 0000000..02d29cf --- /dev/null +++ b/GeneticAlgorithmRaw/algorithm_raw.cpp @@ -0,0 +1,101 @@ +#include "algorithm_raw.h" +#include +#include +algorithm_raw::algorithm_raw(std::string goal, int population_size, int mutation_chance) +{ + _goal = goal; + _population_size = population_size; + _mutation_chance = mutation_chance; + _generation_count = 0; + + _population = new population_raw(goal); + _population->initialize(_population_size); + random_number_generator.seed(std::random_device()()); +} + +//Destructor to free memory +algorithm_raw::~algorithm_raw() +{ + delete _population; + _mating_pool.clear(); +} + +//Main loop for the algorithm +void algorithm_raw::run() +{ + _population->calculate_fitness(); + std::cout << "Generation: " << _generation_count << ", fittest: " << _population->get_fittest_individual()->get_gene() << "(" << _population->get_fittest_individual()->get_fitness() << ")" << std::endl; + while (_generation_count < 3000) { + _generation_count++; + selection(); + create_new_generation(); + _population->calculate_fitness(); + + std::cout << "Generation: " << _generation_count << ", fittest: " << _population->get_fittest_individual()->get_gene() << "(" << _population->get_fittest_individual()->get_fitness() << ")" << std::endl; + double total_fitness = _population->get_total_fitness(); + int average_fitness = ((total_fitness / _population_size) / (double)_goal.length()) * 100; + std::cout << "Average fitness: " << average_fitness << "%" << std::endl; + } +} + +//Roulette wheel selection +void algorithm_raw::selection() +{ + _mating_pool.clear(); + _population->calculate_fitness(); + + for (int i = 0; i < _population_size; i++) { + individual_raw* individual = _population->get_individual(i); + for (auto j = 0; j < individual->get_fitness(); j++) { + _mating_pool.push_back(individual); + } + } +} + +//Crossover 2 individuals. +//1: Pick a random crossover point +//2: Swap the individual's genes at that crossover point +//3: Return the child generated by this crossover. +individual_raw* algorithm_raw::crossover(individual_raw & parent_a, individual_raw & parent_b) +{ + std::uniform_int_distribution random_distribution(1, _goal.size() - 1); //Make sure the first and last can't be crossover points + individual_raw * child = new individual_raw(_goal); + int crossover_point = random_distribution(random_number_generator); + for (int i = 0; i < _goal.length(); i++) { + if (i > crossover_point) { + child->manipulate_gene(i, parent_a.get_gene()[i]); + } + else { + child->manipulate_gene(i, parent_b.get_gene()[i]); + } + } + + return child; +} + +//Creates a new generation. +//1: Get 2 random individuals from the mating pool +//2: Generate a child by doing crossover +//3: Mutate the child (1% chance by default). +//4: Add the child to the new population. +//5: Set the new population +void algorithm_raw::create_new_generation() +{ + std::vector new_population; + new_population.reserve(_population_size); + std::uniform_int_distribution random_distribution(0, _mating_pool.size() - 1); + + for (int i = 0; i < _population_size; i++) { + int random_number1 = random_distribution(random_number_generator); + int random_number2 = random_distribution(random_number_generator); + individual_raw* parent_a = _mating_pool[random_number1]; + individual_raw* parent_b = _mating_pool[random_number2]; + individual_raw* child = crossover(*parent_a, *parent_b); + child->mutate(_mutation_chance); + new_population.push_back(child); + } + + _population->set_new_population(new_population); +} + + diff --git a/GeneticAlgorithmRaw/algorithm_raw.h b/GeneticAlgorithmRaw/algorithm_raw.h new file mode 100644 index 0000000..fbad8ac --- /dev/null +++ b/GeneticAlgorithmRaw/algorithm_raw.h @@ -0,0 +1,26 @@ +#pragma once +#include +#include "population_raw.h" +class algorithm_raw +{ +public: + algorithm_raw(std::string goal, int population_size, int mutation_chance); + ~algorithm_raw(); + + void run(); + +private: + std::string _goal; + int _generation_count; + int _mutation_chance; + int _population_size; + + population_raw* _population; + std::mt19937 random_number_generator; + std::vector _mating_pool; + + void selection(); + individual_raw* crossover(individual_raw& parent_a, individual_raw& parent_b); + void create_new_generation(); +}; + diff --git a/GeneticAlgorithmRaw/individual_raw.cpp b/GeneticAlgorithmRaw/individual_raw.cpp new file mode 100644 index 0000000..64b8209 --- /dev/null +++ b/GeneticAlgorithmRaw/individual_raw.cpp @@ -0,0 +1,65 @@ +#include "individual_raw.h" + +individual_raw::individual_raw(std::string goal) +{ + _fitness = 0; + _goal = goal; + random_number_generator.seed(std::random_device()()); + _possible_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "; + generate_random_gene(); +} + +individual_raw::~individual_raw() +{ +} + +int individual_raw::get_fitness() +{ + return _fitness; +} + +void individual_raw::calculate_fitness() +{ + _fitness = 0; + for (int i = 0; i < _goal.length(); i++) { + if (_gene[i] == _goal[i]) { + _fitness++; + } + } +} + +std::string individual_raw::get_gene() +{ + return _gene; +} + +void individual_raw::manipulate_gene(int index, char manipulation) +{ + _gene[index] = manipulation; +} + +//Mutates the gene. +//1: Generate random number 0-100 +//2: Check if mutation chance is met +//3: Manipulate a random character in the gene +void individual_raw::mutate(int mutation_chance) +{ + std::uniform_int_distribution random_precentage(0, 100); + std::uniform_int_distribution random_character_index(0, _possible_characters.size() - 1); + for (int i = 0; i < _goal.length(); i++) { + if (random_precentage(random_number_generator) <= mutation_chance) { + auto random_character = _possible_characters[random_character_index(random_number_generator)]; + manipulate_gene(i, random_character); + } + } +} + +//Generates a random gene by picking a random number from the available characters +void individual_raw::generate_random_gene() +{ + std::uniform_int_distribution random_distribution(0, _possible_characters.size() - 1); + for (int i = 0; i < _goal.length(); i++) { + auto random_character = _possible_characters[random_distribution(random_number_generator)]; + _gene += random_character; + } +} diff --git a/GeneticAlgorithmRaw/individual_raw.h b/GeneticAlgorithmRaw/individual_raw.h new file mode 100644 index 0000000..fbf7825 --- /dev/null +++ b/GeneticAlgorithmRaw/individual_raw.h @@ -0,0 +1,25 @@ +#pragma once +#include +#include +class individual_raw +{ +public: + individual_raw(std::string goal); + ~individual_raw(); + + int get_fitness(); + void calculate_fitness(); + std::string get_gene(); + void manipulate_gene(int index, char manipulation); + void mutate(int mutation_chance); + +private: + int _fitness; + std::string _goal; + std::string _gene; + std::string _possible_characters; + std::mt19937 random_number_generator; + void generate_random_gene(); + +}; + diff --git a/GeneticAlgorithmRaw/population_raw.cpp b/GeneticAlgorithmRaw/population_raw.cpp new file mode 100644 index 0000000..f13ea18 --- /dev/null +++ b/GeneticAlgorithmRaw/population_raw.cpp @@ -0,0 +1,83 @@ +#include "population_raw.h" +#include + +population_raw::population_raw(std::string goal) +{ + _goal = goal; +} + +population_raw::~population_raw() +{ + //Delete all individuals from memory. + for (individual_raw* individual : _individuals) { + delete individual; + } +} + +void population_raw::initialize(int size) +{ + _individuals.reserve(size); + for (int i = 0; i < size; i++) { + _individuals.push_back(new individual_raw(_goal)); + } +} + +void population_raw::calculate_fitness() +{ + for (auto individual : _individuals) { + individual->calculate_fitness(); + } +} + +void population_raw::manipulate(int index, individual_raw* manipulation) +{ + delete _individuals[index]; + _individuals[index] = manipulation; +} + +double population_raw::get_total_fitness() +{ + double total = 0.0; + for (individual_raw* individual : _individuals) { + total += individual->get_fitness(); + } + return total; +} + +individual_raw* population_raw::get_individual(int index) +{ + // TODO: insert return statement here + return _individuals[index]; +} + +void population_raw::set_new_population(std::vector new_population) +{ + for (individual_raw* individual : _individuals) { + delete individual; + } + _individuals.clear(); + _individuals = new_population; +} + +individual_raw* population_raw::get_fittest_individual() +{ + // TODO: insert return statement here + int fittest_individual_index = 0; + int highest_fitness = 0; + for (int i = 0; i < _individuals.size(); i++) { + int individual_fitness = _individuals[i]->get_fitness(); + + if (individual_fitness > highest_fitness) { + highest_fitness = individual_fitness; + fittest_individual_index = i; + } + } + + return _individuals[fittest_individual_index]; +} + +void population_raw::print_population() { + for (auto indiv : _individuals) { + std::cout << indiv << "(" << indiv->get_gene() << ")" << std::endl; + } +} diff --git a/GeneticAlgorithmRaw/population_raw.h b/GeneticAlgorithmRaw/population_raw.h new file mode 100644 index 0000000..bb97d4d --- /dev/null +++ b/GeneticAlgorithmRaw/population_raw.h @@ -0,0 +1,26 @@ +#pragma once +#include +#include "individual_raw.h" +class population_raw +{ +public: + population_raw(std::string goal); + ~population_raw(); + + void initialize(int size); + void calculate_fitness(); + void manipulate(int index, individual_raw* manipulation); + double get_total_fitness(); + + individual_raw* get_individual(int index); + void set_new_population(std::vector new_population); + individual_raw* get_fittest_individual(); + + void print_population(); + +private: + std::string _goal; + std::vector _individuals; + +}; +