Exemple #1
0
 public Engine(IInitializer initializer, ICrossover crossoverer, IMutator mutator, bool isDebug)
 {
     PopulationInitializer = initializer;
     PopulationMutator     = mutator;
     PopulationCrossoverer = crossoverer;
     IsDebug = isDebug;
 }
Exemple #2
0
    public IMutator GetUsedMutator()
    {
        switch (mutator)
        {
        case MutatorLoad.BitFlip:
            rtnMutator = new MutatorBitFlip();
            break;

        case MutatorLoad.Invert:
            rtnMutator = new MutatorInvert();
            break;

        case MutatorLoad.Reset:
            rtnMutator = new MutatorReset();
            break;

        case MutatorLoad.Scramble:
            rtnMutator = new MutatorScramble();
            break;

        case MutatorLoad.Swap:
            rtnMutator = new MutatorSwap();
            break;

        default:
            rtnMutator = new MutatorReset();
            break;
        }
        return(rtnMutator);
    }
Exemple #3
0
        public Simulation(
            ISimulationParameters simulationParams,
            IMutator mutator,
            IItemSelector itemSelector,
            IPopulationLogger logger,
            IEvaluator evaluator,
            ICrossoverSelector selector,
            ICrossBreeder breeder,
            IPopulationGenerator populationGenerator)
        {
            ObjectValidator.IfNullThrowException(simulationParams, nameof(simulationParams));
            ObjectValidator.IfNullThrowException(mutator, nameof(mutator));
            ObjectValidator.IfNullThrowException(itemSelector, nameof(itemSelector));
            ObjectValidator.IfNullThrowException(logger, nameof(logger));
            ObjectValidator.IfNullThrowException(evaluator, nameof(evaluator));
            ObjectValidator.IfNullThrowException(selector, nameof(selector));
            ObjectValidator.IfNullThrowException(breeder, nameof(breeder));
            ObjectValidator.IfNullThrowException(populationGenerator, nameof(populationGenerator));

            _mutator              = mutator;
            _itemSelector         = itemSelector;
            _logger               = logger;
            _evaluator            = evaluator;
            _selector             = selector;
            _breeder              = breeder;
            _populationGenerator  = populationGenerator;
            _simulationParameters = simulationParams;
        }
Exemple #4
0
        public void TestMutate()
        {
            var input         = BinaryConvertor.IntsToBinaryString(4, -123, 7, 7, 9, 0, -2);
            var inputLength   = input.Length;
            var mutationImpls = new IMutator[]
            {
                new SimpleMutator(),
                new RepeatableMutator(1, 1),
                new RepeatableMutator(15, 0.7),
                new AdaptiveMutator(1, 1),
                new AdaptiveMutator(17, 1, 1, 0.5, 7),
                new HackMutator(1, 1),
                new HackMutator(10, 0.45)
            };

            foreach (var mutator in mutationImpls)
            {
                var algorithm = new Lab1_C.Algorithm(new AlgorithmOptions(
                                                         lowerBound: -100, // so random value won't ever match `-123`
                                                         mutator: mutator
                                                         ));
                var result = algorithm.Mutate(input);

                Assert.AreNotEqual(input, result);
                Assert.AreEqual(inputLength, result.Length);
            }
        }
Exemple #5
0
        public GeneticData GeneticAlgorithm(
            ISelector selector,
            IMutator mutator,
            ICrosser crosser,
            IEndCondition endCondition,
            GeneticData startPopulation
            )
        {
            const int selectedCount = 4;

            GeneticData best = null;
            var         currentCombinations = new List <GeneticData> {
                startPopulation
            };

            while (!endCondition.IsEnd(currentCombinations, envData))
            {
                var selected = selector.SelectBests(currentCombinations, selectedCount, envData);
                var crossed  = crosser.Cross(selected, envData);
                currentCombinations = mutator.Mutate(crossed, envData);
                best = selector.SelectBests(currentCombinations.Concat(new[] { best }).ToList(), 1, envData).First();
            }

            return(best);
        }
Exemple #6
0
 public HillClimbing(ISolver <TProblem, TSolution> baseSolver, IMutator <TProblem, TSolution> mutator,
                     bool stopOnRepeatedMutation = false)
 {
     this.baseSolver             = baseSolver;
     this.mutator                = mutator;
     this.stopOnRepeatedMutation = stopOnRepeatedMutation;
 }
Exemple #7
0
 public Solver(SurvivalSelection survivalSelection, Breeder breeder, IMutator mutator, int maxStepsWithoutChanges)
 {
     _breeder = breeder;
     _mutator = mutator;
     _maxStepsWithoutChanges = maxStepsWithoutChanges;
     _survivalSelection      = survivalSelection;
 }
        public GeneticSettings(int populationSize,
                               int geneCount,
                               int selectionSize,
                               double mutationProbabiltyAgents,
                               double mutationProbabilityGenes,
                               IRandomNumberGenerator randomNumberGenerator,
                               IFitnessCalculator fitnessCalculator,
                               IMutator mutator,
                               ISelector selector,
                               ICrossover crossover,
                               IAgentViewer agentViewer,
                               int topKAgentsCount)
        {
            if (populationSize < selectionSize)
            {
                throw new Exception("The population size has to be greater than the selection size");
            }

            PopulationSize = populationSize;
            GeneCount      = geneCount;
            SelectionSize  = selectionSize;

            MutationProbabiltyAgents = mutationProbabiltyAgents;
            MutationProbabilityGenes = mutationProbabilityGenes;

            RandomNumberGenerator = randomNumberGenerator;
            FitnessCalculator     = fitnessCalculator;
            Mutator   = mutator;
            Selector  = selector;
            Crossover = crossover;

            AgentViewer = agentViewer;

            TopKAgentsCount = topKAgentsCount;
        }
        public TaskState( NBTag tag )
        {
            if( FormatVersion != tag["FormatVersion"].GetInt() ) throw new FormatException( "Incompatible format." );
            Shapes = tag["Shapes"].GetInt();
            Vertices = tag["Vertices"].GetInt();
            ImprovementCounter = tag["ImprovementCounter"].GetInt();
            MutationCounter = tag["MutationCounter"].GetInt();
            TaskStart = DateTime.UtcNow.Subtract( TimeSpan.FromTicks( tag["ElapsedTime"].GetLong() ) );

            ProjectOptions = new ProjectOptions( tag["ProjectOptions"] );

            BestMatch = new DNA( tag["BestMatch"] );
            CurrentMatch = BestMatch;

            Initializer = (IInitializer)ModuleManager.ReadModule( tag["Initializer"] );
            Mutator = (IMutator)ModuleManager.ReadModule( tag["Mutator"] );
            Evaluator = (IEvaluator)ModuleManager.ReadModule( tag["Evaluator"] );

            byte[] imageBytes = tag["ImageData"].GetBytes();
            using( MemoryStream ms = new MemoryStream( imageBytes ) ) {
                OriginalImage = new Bitmap( ms );
            }

            var statsTag = (NBTList)tag["MutationStats"];
            foreach( NBTag stat in statsTag ) {
                MutationType mutationType = (MutationType)Enum.Parse( typeof( MutationType ), stat["Type"].GetString() );
                MutationCounts[mutationType] = stat["Count"].GetInt();
                MutationImprovements[mutationType] = stat["Sum"].GetDouble();
            }
        }
    public void Launch()
    {
        if (generations != null)
        {
            generations.Reset();
        }
        if (setup == null)
        {
            setup = GetComponent <SetupScript>();
        }
        ui           = GetComponent <UIManager>();
        cars         = setup.Setup();
        carStates    = new Dictionary <GameObject, CarState>();
        carExecutors = new Dictionary <GameObject, GeneExecutor>();
        generations  = GetComponent <GenerationDB>();
        fitness      = (IFitnessFunction)System.Activator.CreateInstance(setup.FitnessFunctions.Where(type => type.Name.Equals(selectedFitnessFunction)).First());
        terminator   = (ITerminator)System.Activator.CreateInstance(setup.Terminators.Where(type => type.Name.Equals(selectedTerminator)).First());
        mutator      = (IMutator)System.Activator.CreateInstance(setup.Mutators.Where(type => type.Name.Equals(selectedMutator)).First());
        foreach (string genetype in selectedGenes)
        {
            mutator.AssignGene(((IGene)System.Activator.CreateInstance(setup.GeneTypes.Where(type => type.Name.Equals(genetype)).First())).ID);
        }
        selector   = (ISelector)System.Activator.CreateInstance(setup.Selectors.Where(type => type.Name.Equals(selectedSelector)).First());
        recombiner = (IRecombiner)System.Activator.CreateInstance(setup.Recombiners.Where(type => type.Name.Equals(selectedRecombiner)).First());
        init       = (IInitializer)System.Activator.CreateInstance(setup.Initializers.Where(type => type.Name.Equals(selectedInitializer)).First());
        foreach (string genetype in selectedGenes)
        {
            init.AssignGene(((IGene)System.Activator.CreateInstance(setup.GeneTypes.Where(type => type.Name.Equals(genetype)).First())).ID);
        }

        SetupCars();
        simulation = StartCoroutine(FullSimulation());
    }
Exemple #11
0
        public TaskState(NBTag tag)
        {
            if (FormatVersion != tag["FormatVersion"].GetInt())
            {
                throw new FormatException("Incompatible format.");
            }
            Shapes             = tag["Shapes"].GetInt();
            Vertices           = tag["Vertices"].GetInt();
            ImprovementCounter = tag["ImprovementCounter"].GetInt();
            MutationCounter    = tag["MutationCounter"].GetInt();
            TaskStart          = DateTime.UtcNow.Subtract(TimeSpan.FromTicks(tag["ElapsedTime"].GetLong()));

            ProjectOptions = new ProjectOptions(tag["ProjectOptions"]);

            BestMatch    = new DNA(tag["BestMatch"]);
            CurrentMatch = BestMatch;

            Initializer = (IInitializer)ModuleManager.ReadModule(tag["Initializer"]);
            Mutator     = (IMutator)ModuleManager.ReadModule(tag["Mutator"]);
            Evaluator   = (IEvaluator)ModuleManager.ReadModule(tag["Evaluator"]);

            byte[] imageBytes = tag["ImageData"].GetBytes();
            using (MemoryStream ms = new MemoryStream(imageBytes)) {
                OriginalImage = new Bitmap(ms);
            }

            var statsTag = (NBTList)tag["MutationStats"];

            foreach (NBTag stat in statsTag)
            {
                MutationType mutationType = (MutationType)Enum.Parse(typeof(MutationType), stat["Type"].GetString());
                MutationCounts[mutationType]       = stat["Count"].GetInt();
                MutationImprovements[mutationType] = stat["Sum"].GetDouble();
            }
        }
Exemple #12
0
 public RepeatableMutator(int times, double chance)
 {
     _times   = times;
     _chance  = chance;
     _random  = new Random();
     _mutator = new SimpleMutator();
 }
Exemple #13
0
 public static IDataStoreDescription <TKey, TValue> Mutator <TKey, TValue>(
     this IDataStoreDescription <TKey, TValue> target,
     IMutator mutator)
 {
     return(new Builder <TKey, TValue>(
                target.Root.ArgumentItem("untypedMutators", mutator)));
 }
Exemple #14
0
        public void AddMutatorToNewChain(IMutator mutator, object parameters, Type wantedOutput)
        {
            MutatorChain mutatorChain = new MutatorChain();

            mutatorChain.AddMutatorToChain(mutator, parameters, wantedOutput);
            this.chain.MutatorChains.Add(mutatorChain);
        }
Exemple #15
0
 public GeneticAlgorithm(INeuralNetworkConverter converter, IMutator mutator, IMixer mixer, ISelector selector)
 {
     this.converter = converter;
     this.mutator   = mutator;
     this.mixer     = mixer;
     this.selector  = selector;
 }
        public void Pick(IMutator mutator, ISourcer sourcer, IPnLConsumer pnLConsumer, MatchResult matchResult)
        {
            //5. Pool Result arrives and is consumed
            Mutation matchMutationLeg1 = mutator.GetMatchMutation(matchResult.Result, matchResult.PoolId);

            sourcer.Source(matchMutationLeg1);
            pnLConsumer.Consume(matchMutationLeg1);
        }
Exemple #17
0
 internal static object CreateObservableProxy <TObject>(this IMutator <TObject> mutator) where TObject : class
 {
     return(ProxyEngine
            .CreateClassProxyWithTarget(typeof(TObject),
                                        new Type[] {
         typeof(ICarbonProxy),
     }, mutator.Options.Target, mutator.Options, mutator.Options.Interceptors));
 }
 private IOperationResult Mutate(IMutator[] mutators, MutationParameters parameters)
 {
     var compositeResult = new CompositeOperationResult();
       foreach (var mutator in mutators) {
     var result = mutator.Mutate(parameters);
     compositeResult.AddResult(result);
       }
       return compositeResult;
 }
Exemple #19
0
 public AllUpProcessor(IMutator mutator, IPnLConsumer pnLConsumer, ISourcer sourcer, IReducer reducer, IScenarioGenerator scenarioGenerator, IEventReceiver eventReceiver)
 {
     this.mutator           = mutator;
     this.pnLConsumer       = pnLConsumer;
     this.sourcer           = sourcer;
     this.reducer           = reducer;
     this.scenarioGenerator = scenarioGenerator;
     this.eventReceiver     = eventReceiver;
 }
Exemple #20
0
 /*
  * For each `Mutate` call that is less or equal to `threshold` increments amount of mutations
  * (`times`) by `deltaTimes` and decrements mutation chance by `deltaChance`.
  * For calls after `threshold` amount of mutations is reduced by the same value per call,
  * mutation chance is increased.
  */
 public AdaptiveMutator(int times, double chance,
                        double deltaTimes = 0.01, double deltaChance = 0.005, int threshold = 2000)
 {
     _times       = times;
     _chance      = chance;
     _deltaTimes  = deltaTimes;
     _deltaChance = deltaChance;
     _threshold   = threshold;
     _random      = new Random();
     _mutator     = new SimpleMutator();
 }
Exemple #21
0
        public GeneticAlgorithmBuilder <T> SetMutator(IMutator <T> mutator)
        {
            if (mutator == null)
            {
                throw new System.ArgumentNullException(nameof(mutator));
            }

            Mutator = mutator;

            return(this);
        }
Exemple #22
0
 /// <summary>
 /// Invokes the mutation method on all agents in the population.
 /// </summary>
 /// <param name="mutator">The mutation method that defines how the population should be mutated.</param>
 /// <param name="mutationProbability">The probability for an agent to be mutated.</param>
 /// <param name="mutationProbilityGene">The probability for a gene to be mutated.</param>
 /// <param name="random">The random generator that produces random numbers used in the method to determine
 /// if an agent or a gene should be mutated.</param>
 public void MakeMutations(IMutator mutator, double mutationProbability, double mutationProbilityGene, IRandomNumberGenerator random)
 {
     // Mutate all agents in population
     for (int i = 0; i < Agents.Count; i++)
     {
         // Check if agent should be mutated
         double randomDouble = random.GetDouble(0, 1);
         if (randomDouble < mutationProbability)
         {
             Agents[i].Mutate(mutator, mutationProbilityGene, random);
         }
     }
 }
 public GeneticAlgorithm <T> Create(IMutator <T> mutator,
                                    ICrossOver <T> crossOver,
                                    IPopulationCreator <T> populationCreator,
                                    Func <T[], int> fitnessFunction) =>
 new GeneticAlgorithm <T>(mutator,
                          crossOver,
                          populationCreator,
                          PopulationSize,
                          MutationProbability,
                          maxGenerations,
                          eliteSize,
                          solutionPrecision,
                          fitnessFunction);
        private IEnumerable <Mutant> ApplyMutator(SyntaxNode syntaxNode, IMutator mutator)
        {
            var mutations = mutator.Mutate(syntaxNode);

            foreach (var mutation in mutations)
            {
                yield return(new Mutant
                {
                    Id = MutantCount++,
                    Mutation = mutation,
                    ResultStatus = MutantStatus.NotRun
                });
            }
        }
Exemple #25
0
 public EvolutionaryAlgorithm(
     IPopulation population,
     IEvaluator evaluator,
     ICrossover crossover,
     ISelector selector,
     IMutator mutator
     )
 {
     _population = population;
     _evaluator  = evaluator;
     _crossover  = crossover;
     _selector   = selector;
     _mutator    = mutator;
 }
Exemple #26
0
 // Changes operators via roulette-operators function
 private void ChangeOperators()
 {
     if (mDiversity < CRITICAL_DIVERSITY || mDiversity == mPreDiversity)
     {
         mSelOperator = mSelOperators[1];
     }
     else
     {
         mSelOperator = mSelOperators[0];
     }
     mCurrentOperators[0] = OperatorsRoulette(mCrossRoulette);
     mCurrentOperators[1] = OperatorsRoulette(mMutRoulette);
     mCrossOperator       = mCrossOperators[mCurrentOperators[0]];
     mMutOperator         = mMutOperators[mCurrentOperators[1]];
 }
Exemple #27
0
        /// <summary>
        /// Mutates one single SyntaxNode using a mutator
        /// </summary>
        private IEnumerable <Mutant> ApplyMutator(SyntaxNode syntaxNode, IMutator mutator)
        {
            var mutations = mutator.Mutate(syntaxNode);

            foreach (var mutation in mutations)
            {
                _logger.LogDebug("Mutant {0} created {1} -> {2} using {3}", _mutantCount, mutation.OriginalNode, mutation.ReplacementNode, mutator.GetType());
                yield return(new Mutant()
                {
                    Id = _mutantCount++,
                    Mutation = mutation,
                    ResultStatus = MutantStatus.NotRun
                });
            }
        }
        static void Main(string[] args)
        {
            NeuralNetworkConfigurationSettings networkConfig = new NeuralNetworkConfigurationSettings
            {
                NumInputNeurons    = 1,
                NumOutputNeurons   = 1,
                NumHiddenLayers    = 2,
                NumHiddenNeurons   = 3,
                SummationFunction  = new SimpleSummation(),
                ActivationFunction = new TanhActivationFunction()
            };
            GenerationConfigurationSettings generationSettings = new GenerationConfigurationSettings
            {
                UseMultithreading    = true,
                GenerationPopulation = 500
            };
            EvolutionConfigurationSettings evolutionSettings = new EvolutionConfigurationSettings
            {
                NormalMutationRate  = 0.05,
                HighMutationRate    = 0.5,
                GenerationsPerEpoch = 10,
                NumEpochs           = 1000,
                NumTopEvalsToReport = 10
            };
            MutationConfigurationSettings mutationSettings = new MutationConfigurationSettings
            {
                MutateAxonActivationFunction       = true,
                MutateNumberOfHiddenLayers         = true,
                MutateNumberOfHiddenNeuronsInLayer = true,
                MutateSomaBiasFunction             = true,
                MutateSomaSummationFunction        = true,
                MutateSynapseWeights = true
            };
            var random = new RandomWeightInitializer(new Random());
            INeuralNetworkFactory factory          = NeuralNetworkFactory.GetInstance(SomaFactory.GetInstance(networkConfig.SummationFunction), AxonFactory.GetInstance(networkConfig.ActivationFunction), SynapseFactory.GetInstance(new RandomWeightInitializer(new Random()), AxonFactory.GetInstance(networkConfig.ActivationFunction)), SynapseFactory.GetInstance(new ConstantWeightInitializer(1.0), AxonFactory.GetInstance(new IdentityActivationFunction())), random);
            IBreeder            breeder            = BreederFactory.GetInstance(factory, random).Create();
            IMutator            mutator            = MutatorFactory.GetInstance(factory, random).Create(mutationSettings);
            IEvalWorkingSet     history            = EvalWorkingSetFactory.GetInstance().Create(50);
            IEvaluatableFactory evaluatableFactory = new GameEvaluationFactory();

            IStorageProxy proxy  = new NodeJSProxy(1, "http://localhost:3000", "123456789");
            IEpochAction  action = new BestPerformerUpdater(proxy);

            var GAFactory             = GeneticAlgorithmFactory.GetInstance(evaluatableFactory);
            IGeneticAlgorithm evolver = GAFactory.Create(networkConfig, generationSettings, evolutionSettings, factory, breeder, mutator, history, evaluatableFactory, action);

            evolver.RunSimulation();
        }
Exemple #29
0
        public IFluentProcessMutatorBuilder AddMutator(IMutator mutator)
        {
            if (AutomaticallySetRowFilter != null)
            {
                mutator.RowFilter = AutomaticallySetRowFilter;
            }

            if (AutomaticallySetRowTagFilter != null)
            {
                mutator.RowTagFilter = AutomaticallySetRowTagFilter;
            }

            mutator.InputProcess  = ProcessBuilder.Result;
            ProcessBuilder.Result = mutator;
            return(this);
        }
        public GeneticAlgorithm(IRandom rand, Population candidates, Func<IOrganism, double> fitnessFunction, ISelector selector, IMutator mutator, ICrossover crossLinker, double elitismProportion, int maximumGenerations)
        {
            this.rand = rand;
            this.candidates = candidates;
            this.fitnessFunction = fitnessFunction;
            this.selector = selector;
            this.mutator = mutator;
            this.crossLinker = crossLinker;
            this.elitismProportion = elitismProportion;
            this._generationCount = 0;
            this.generationInformation = new Dictionary<int, double>();
            this.initialCount = candidates.Count;
            this.maximumGenerations = maximumGenerations;

            this.candidates.CalculateFitnesses(this.fitnessFunction);
        }
        public GeneticAlgorithm(IRandom rand, Population candidates, Func <IOrganism, double> fitnessFunction, ISelector selector, IMutator mutator, ICrossover crossLinker, double elitismProportion, int maximumGenerations)
        {
            this.rand                  = rand;
            this.candidates            = candidates;
            this.fitnessFunction       = fitnessFunction;
            this.selector              = selector;
            this.mutator               = mutator;
            this.crossLinker           = crossLinker;
            this.elitismProportion     = elitismProportion;
            this._generationCount      = 0;
            this.generationInformation = new Dictionary <int, double>();
            this.initialCount          = candidates.Count;
            this.maximumGenerations    = maximumGenerations;

            this.candidates.CalculateFitnesses(this.fitnessFunction);
        }
Exemple #32
0
        private static ProcessKind GetProcessKind(IProcess process)
        {
            if (process.GetType().GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IExecutableWithResult <>)))
            {
                return(ProcessKind.jobWithResult);
            }

            return(process switch
            {
                IRowReader _ => ProcessKind.reader,
                IRowWriter _ => ProcessKind.writer,
                IMutator _ => ProcessKind.mutator,
                IScope _ => ProcessKind.scope,
                IEvaluable _ => ProcessKind.producer,
                IExecutable _ => ProcessKind.job,
                _ => ProcessKind.unknown,
            });
Exemple #33
0
 public NsgaSolver(
     Sorter sorter,
     IPopulationInitializer populationInitialiser,
     IEvaluator evaluator,
     TournamentSelector selector,
     ICrossOver crossOver,
     IMutator mutator,
     Configuration configuration)
 {
     _sorter = sorter;
     _populationInitialiser = populationInitialiser;
     _evaluator             = evaluator;
     _selector  = selector;
     _crossOver = crossOver;
     _mutator   = mutator;
     _config    = configuration;
 }
 public IGeneticAlgorithm Create(NeuralNetworkConfigurationSettings networkConfig, GenerationConfigurationSettings generationConfig, EvolutionConfigurationSettings evolutionConfig, INeuralNetworkFactory networkFactory, IBreeder breeder, IMutator mutator, IEvalWorkingSet workingSet, IEvaluatableFactory evaluatableFactory, IEpochAction epochAction)
 {
     return GeneticAlgorithm.GetInstance(networkConfig, generationConfig, evolutionConfig, _networkFactory, breeder, mutator, workingSet, _evaluatableFactory, epochAction);
 }
 public void Add(float p, IMutator mutator)
 {
     mutators.Add(new KeyValuePair<float, IMutator>(p, mutator));
 }