Beispiel #1
0
 /// <summary>
 ///     Creates a new <see cref="Population{TProgram,TOutput}" /> with the given arguments.
 /// </summary>
 /// <param name="maxSize">The maximum size of the population.</param>
 /// <param name="primitives">The primitive set used to generate new programs.</param>
 /// <param name="programGenerator">The generator of new programs.</param>
 /// <param name="programComparer">The function used to compare programs and select the best program.</param>
 /// <param name="selectionOperator">The operator to perform selection.</param>
 /// <param name="crossoverOperator">The operator to crossover programs. </param>
 /// <param name="mutationOperator">The operator to mutate programs.</param>
 /// <param name="maxGenerationDepth">The maximum depth of elements generated during GP.</param>
 /// <param name="maxElementLength">The maximum length of elements generated during GP.</param>
 /// <param name="crossoverPercent">The percentage of a population used for the crossover operator during GP.</param>
 /// <param name="mutationPercent">The percentage of a population used for the mutation operator during GP.</param>
 /// <param name="elitismPercent">The percentage of a population used for elite selection during GP.</param>
 public Population(
     uint maxSize,
     PrimitiveSet <TProgram> primitives,
     IProgramGenerator <TProgram, TOutput> programGenerator,
     IComparer <TProgram> programComparer,
     ISelectionOperator <TProgram> selectionOperator,
     ICrossoverOperator <TProgram> crossoverOperator,
     IMutationOperator <TProgram> mutationOperator,
     uint maxGenerationDepth = 4,
     uint maxElementLength   = 20,
     double crossoverPercent = 0.65d,
     double mutationPercent  = 0.2d,
     double elitismPercent   = 0.1d)
 {
     this._maxSize            = maxSize;
     this._primitives         = primitives;
     this._programGenerator   = programGenerator;
     this._maxGenerationDepth = maxGenerationDepth;
     this._maxElementLength   = maxElementLength;
     this._programComparer    = programComparer;
     this._selectionOperator  = selectionOperator;
     this._mutationOperator   = mutationOperator;
     this._crossoverOperator  = crossoverOperator;
     this.ElitismPercent      = elitismPercent;
     this.MutationPercent     = mutationPercent;
     this.CrossoverPercent    = crossoverPercent;
 }
        public ObjectOperatorsPackage()
        {
 

            Operators = new IMutationOperator[]
            {
                new DEH_MethodDelegatedForEventHandlingChange(), 
                new DMC_DelegatedMethodChange(), 
                //new EOC_EqualityOperatorChange(), 
                new EMM_ModiferMethodChange(), 
                new EAM_AccessorMethodChange(), 
                new EHC_ExceptionHandlingChange(), 
                new EHR_ExceptionHandlerRemoval(), 
                new EXS_ExceptionSwallowing(), 
                new ISD_BaseKeywordDeletion(), 
                new JID_FieldInitializationDeletion(), 
                new JTD_ThisKeywordDeletion(), 
               // new RFI_ReferencingFaultInsertion(), 
                new PRV_ReferenceAssignmentChange(), 
                new MCI_MemberCallFromAnotherInheritedClass(), 
              //  new NullInsertion(), 
                //new RSO_RemoveStatementOperator(),
            };

        }
Beispiel #3
0
        private void InitializeGeneticAlgorithm()
        {
            fitnessFunction           = new FitnessFunction(cities);
            selectionOperator         = new TournamentSelection(Convert.ToInt32(inputTournamentSize.Value));
            elitistSelection          = new ElitistSelection();
            crossoverOperator         = GetSelectedCrossoverOperator();
            mutationOperator          = GetSelectedMutationOperator();
            initialPopulationProvider = new InitialPopulationProvider();

            settings = new Settings
            {
                Cities         = cities,
                NumberOfElites = Convert.ToInt32(inputElites.Value),
                PopulationSize = Convert.ToInt32(inputMaxPopulation.Value),
                CrossoverRate  = Convert.ToDouble(inputCrossoverRate.Value),
                MutationRate   = Convert.ToDouble(inputMutationRate.Value)
            };

            selectionOperator = new TournamentSelection(Convert.ToInt32(inputTournamentSize.Value));

            geneticAlgorithm = new GeneticAlgorithm(settings, initialPopulationProvider, fitnessFunction, selectionOperator, elitistSelection, crossoverOperator, mutationOperator);

            generationsPlotData  = new List <double>();
            averageScorePlotData = new List <double>();
            bestScorePlotData    = new List <double>();
            UpdatePlotData();
            Plot();
            DrawSolution(geneticAlgorithm.CurrentBestSolution, panelBestSolution, bestSolutionGraphics);

            buttonNextGeneration.Enabled = true;
            buttonRun.Enabled            = true;
            buttonReset.Enabled          = true;
        }
Beispiel #4
0
        private Tuple <int, long> RunBenchmark(ICrossoverOperator crossover, IMutationOperator mutation)
        {
            crossoverOperator = crossover;
            mutationOperator  = mutation;

            var bestFitnessScores = new List <int>();
            var computationTimes  = new List <long>();

            for (int k = 0; k < 20; k++)
            {
                Initialize();
                var stopwatch = new Stopwatch();
                for (int i = 0; i < inputGenerationsNumber.Value; i++)
                {
                    stopwatch.Start();
                    geneticAlgorithm.ComputeNextGeneration();
                    stopwatch.Stop();
                }

                bestFitnessScores.Add(geneticAlgorithm.CurrentBestSolution.FitnessScore);
                computationTimes.Add(stopwatch.ElapsedMilliseconds);
            }

            var avgBestScore       = bestFitnessScores.Average();
            var avgComputationTime = computationTimes.Average();

            return(new Tuple <int, long>((int)avgBestScore, (long)avgComputationTime));
        }
Beispiel #5
0
        private void InitializeGeneticAlgorithm()
        {
            fitnessFunction           = new FitnessFunction(inventory);
            selectionOperator         = new RouletteWheelSelection();
            elitistSelection          = new ElitistSelection();
            crossoverOperator         = new ContinuousUniformCrossover();
            mutationOperator          = new WeightsMutation();
            initialPopulationProvider = new InitialPopulationProvider();

            settings = new Settings
            {
                Inventory         = inventory,
                NumberOfCriterias = 3,
                NumberOfElites    = Convert.ToInt32(inputElites.Value),
                PopulationSize    = Convert.ToInt32(inputMaxPopulation.Value),
                CrossoverRate     = Convert.ToDouble(inputCrossoverRate.Value),
                MutationRate      = Convert.ToDouble(inputMutationRate.Value)
            };

            selectionOperator = new TournamentSelection(Convert.ToInt32(inputTournamentSize.Value));

            geneticAlgorithm = new GeneticAlgorithm(settings, initialPopulationProvider, fitnessFunction, selectionOperator, elitistSelection, crossoverOperator, mutationOperator);

            generationsPlotData  = new List <double>();
            averageScorePlotData = new List <double>();
            bestScorePlotData    = new List <double>();
            UpdatePlotData();
            Plot();

            buttonNextGeneration.Enabled = true;
            buttonRun.Enabled            = true;
            buttonReset.Enabled          = true;
        }
 public EvolutionService(IProblemService problemService, IPopulationFactory populationFactory,
                         ICrossoverOperator crossoverOperator,
                         IMutationOperator mutationOperator)
 {
     _problemService    = problemService;
     _populationFactory = populationFactory;
     _crossoverOperator = crossoverOperator;
     _mutationOperator  = mutationOperator;
 }
 public MutationConditionalTests()
 {
     testDv = Helpers.CreateDecisionVectorWithMixedElements();
     insideMutationDoNothing = new MutationAddRandomIntegerFromSet(
         new[] { mutation },
         0, 1);
     insideMutation = new MutationAddRandomIntegerFromSet(
         new[] { mutation },
         1, 1);
 }
        public async Task <MutationResult> ExecuteMutation(Mutant mutant, CciModuleSource moduleSource)
        {
            var type   = new TypeIdentifier((INamedTypeDefinition)mutant.MutationTarget.ProcessingContext.Type.Object);
            var method = new MethodIdentifier((IMethodDefinition)mutant.MutationTarget.ProcessingContext.Method.Object);
            var filter = new MutationFilter(type.InList(), method.InList());

            _log.Debug("ExecuteMutation of: " + type + " - " + method);
            IMutationOperator mutationOperator = mutant.MutationTarget.OperatorId == null ? new IdentityOperator() :
                                                 _mutOperators.Single(m => mutant.MutationTarget.OperatorId == m.Info.Id);
            var cci = moduleSource;

            try
            {
                _log.Info("Execute mutation of " + mutant.MutationTarget + " contained in " + mutant.MutationTarget.MethodRaw + " modules. ");
                var mutatedModules = new List <IModuleInfo>();
                var module         = moduleSource.Modules.Single();

                var visitorBack = new VisualCodeVisitorBack(mutant.MutationTarget.InList(),
                                                            _sharedTargets.GetValues(mutationOperator, returnEmptySet: true),
                                                            module.Module, mutationOperator.Info.Id);
                var traverser2 = new VisualCodeTraverser(_filter, visitorBack, moduleSource);
                traverser2.Traverse(module.Module);
                visitorBack.PostProcess();
                var operatorCodeRewriter = mutationOperator.CreateRewriter();

                var rewriter = new VisualCodeRewriter(cci.Host, visitorBack.TargetAstObjects,
                                                      visitorBack.SharedAstObjects, _filter, operatorCodeRewriter, traverser2);

                operatorCodeRewriter.MutationTarget =
                    new UserMutationTarget(mutant.MutationTarget.Variant.Signature, mutant.MutationTarget.Variant.AstObjects);


                operatorCodeRewriter.NameTable     = cci.Host.NameTable;
                operatorCodeRewriter.Host          = cci.Host;
                operatorCodeRewriter.Module        = module.Module;
                operatorCodeRewriter.OperatorUtils = _operatorUtils;
                operatorCodeRewriter.Initialize();

                var rewrittenModule = rewriter.Rewrite(module.Module);

                rewriter.CheckForUnfoundObjects();

                mutant.MutationTarget.Variant.AstObjects = null; //TODO: avoiding leaking memory. refactor
                mutatedModules.Add(new ModuleInfo(rewrittenModule, ""));

                var result = new MutationResult(mutant, cci, null,
                                                mutant.MutationTarget.MethodMutated);
                mutant.MutationTarget.MethodMutated = null; //TODO: avoiding leaking memory. refactor
                return(result);
            }
            catch (Exception e)
            {
                throw new MutationException("CreateMutants failed on operator: {0}.".Formatted(mutationOperator.Info.Name), e);
            }
        }
Beispiel #9
0
        public async Task <MutationResult> ExecuteMutation(Mutant mutant, List <CciModuleSource> moduleSource)
        {
            //Ta druga funkcja
            _log.Debug("ExecuteMutation in object: " + ToString() + GetHashCode());
            IMutationOperator mutationOperator = mutant.MutationTarget.OperatorId == null ? new IdentityOperator() :
                                                 _mutOperators.Single(m => mutant.MutationTarget.OperatorId == m.Info.Id);

            try
            {
                _log.Info("Execute mutation of " + mutant.MutationTarget + " contained in " + mutant.MutationTarget.MethodRaw + " modules. ");
                var mutatedModules = new List <IModuleInfo>();

                foreach (var cci in moduleSource)
                {
                    var module      = cci.Module;
                    var visitorBack = new VisualCodeVisitorBack(mutant.MutationTarget.InList(),
                                                                _sharedTargets.GetValues(mutationOperator, returnEmptySet: true),
                                                                module.Module, mutationOperator.Info.Id);
                    var traverser2 = new VisualCodeTraverser(_filter, visitorBack, cci);
                    traverser2.Traverse(module.Module);
                    visitorBack.PostProcess();
                    var operatorCodeRewriter = mutationOperator.CreateRewriter();

                    var rewriter = new VisualCodeRewriter(cci.Host, visitorBack.TargetAstObjects,
                                                          visitorBack.SharedAstObjects, _filter, operatorCodeRewriter, traverser2);

                    operatorCodeRewriter.MutationTarget =
                        new UserMutationTarget(mutant.MutationTarget.Variant.Signature, mutant.MutationTarget.Variant.AstObjects);


                    operatorCodeRewriter.NameTable     = cci.Host.NameTable;
                    operatorCodeRewriter.Host          = cci.Host;
                    operatorCodeRewriter.Module        = module.Module;
                    operatorCodeRewriter.OperatorUtils = _operatorUtils;
                    operatorCodeRewriter.Initialize();

                    var rewrittenModule = rewriter.Rewrite(module.Module);
                    rewriter.CheckForUnfoundObjects();
                }



                mutant.MutationTarget.Variant.AstObjects = null; //TODO: avoiding leaking memory. refactor
                // mutatedModules.Add(new ModuleInfo(rewrittenModule, ""));
                List <IMethodDefinition> methodMutated = new List <IMethodDefinition>();
                methodMutated.Add(mutant.MutationTarget.MethodMutated);
                var result = new MutationResult(mutant, null, moduleSource, mutant.MutationTarget.MethodMutated);
                mutant.MutationTarget.MethodMutated = null; //TODO: avoiding leaking memory. refactor
                return(result);
            }
            catch (Exception e)
            {
                throw new MutationException("CreateMutants failed on operator: {0}.".Formatted(mutationOperator.Info.Name), e);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Constructs a mutation operator that restricts application of a mutation to elements of a <see cref="DecisionVector"/> where all conditions are met.
        /// </summary>
        /// <param name="mutation">The <see cref="IMutationOperator"/> to restrict.</param>
        /// <param name="conditions">The restrictions to apply on the current value of each <see cref="DecisionVector"/> element.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when conditions are null or empty.</exception>
        public MutationConditional(IMutationOperator mutation, params Func <object, bool>[] conditions)
        {
            this.mutation = mutation;

            if (conditions.Length == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(conditions), "The conditions cannot be null or empty.");
            }

            this.conditions = conditions;
        }
Beispiel #11
0
        public IChromosome <T> ApplyMutationOperator(IMutationOperator mutationOperator)
        {
            var newGenes = new T[Length];

            for (var i = 0; i < Length; i++)
            {
                newGenes[i] = mutationOperator.MutateGene(i, this);
            }

            return(new Chromosome <T>(newGenes));
        }
Beispiel #12
0
 public GenerationalGeneticAlgorithm(
     IProblem <T> problem,
     int populationSize,
     ISelectionOperator <T> selectionOperator,
     ICrossoverOperator <T> crossoverOperator,
     IMutationOperator <T> mutationOperator,
     ITerminationCondition terminationCondition,
     double elitismRate)
     : base(problem, populationSize, selectionOperator,
            crossoverOperator, mutationOperator, terminationCondition)
 {
     _elitismRate = elitismRate;
 }
Beispiel #13
0
 public StandardOperatorsPackage()
 {
     Operators = new IMutationOperator[]
     {
         new AOR_ArithmeticOperatorReplacement(),
         // new ABS_AbsoluteValueInsertion(),
         new SOR_ShiftOperatorReplacement(),
         // new UOI_UnaryOperatorInsertion(),
         new LCR_LogicalConnectorReplacement(),
         new LOR_LogicalOperatorReplacement(),
         new ROR_RelationalOperatorReplacement(),
     };
 }
Beispiel #14
0
 public Population(
     ISelectionOperator selectionOperator,
     ICrossoverOperator crossoverOperator,
     IMutationOperator mutationOperator,
     int maxPopulationSize)
 {
     this.selectionOperator = selectionOperator ?? throw new ArgumentNullException(nameof(selectionOperator));
     this.crossoverOperator = crossoverOperator ?? throw new ArgumentNullException(nameof(crossoverOperator));
     this.mutationOperator  = mutationOperator ?? throw new ArgumentNullException(nameof(mutationOperator));
     this.size        = maxPopulationSize;
     this.individuals = new List <IIndividual>();
     this.isSorted    = false;
 }
 static ChromosomeOperator()
 {
     //crossover = new CrossoverOperatorAEX();
     //crossover = new CrossoverOperatorPMX();
     crossover = new CrossoverOperatorOX();
     //mutationOperator = new MutationOperatorRandomTwoPoints();
     mutationOperator = new MutationOperatorRSM();
     //mutationOperator = new MutationOperatorRandomAndThenRSM();
     //mutationOperator = new MutationOperatorPSM();
     //mutationOperator = new MutationOperatorHalfRSMHalfPSM();
     //mutationOperator = new MutationOperatorInsertionsWithReverse();
     // mutationOperator = new MutationOperatorHalfRSMHalfInsertions();
 }
 public SteadyStateGeneticAlgorithm(
     IProblem <T> problem,
     int populationSize,
     ISelectionOperator <T> selectionOperator,
     ICrossoverOperator <T> crossoverOperator,
     IMutationOperator <T> mutationOperator,
     ITerminationCondition terminationCondition,
     double generationGap,
     IReplacementOperator <T> replacementOperator) :
     base(problem, populationSize, selectionOperator,
          crossoverOperator, mutationOperator, terminationCondition)
 {
     _generationGap       = generationGap;
     _replacementOperator = replacementOperator;
 }
Beispiel #17
0
 public GeneticAlgorithm(int numberOfIndividuals, int chromosomeSize,
                         ICrossOperator crossOperator,
                         IMutationOperator mutationOperator,
                         ISelectionOperator selectionOperator,
                         Func <double, double> fitnessFunction)
 {
     _numberOfIndividuals = numberOfIndividuals;
     _chromosomeSize      = chromosomeSize;
     _crossOperator       = crossOperator;
     _mutationOperator    = mutationOperator;
     _selectionOperator   = selectionOperator;
     _fitnessFunction     = fitnessFunction;
     CrossoverProbability = 0.90;
     MutationProbability  = 0.05;
 }
        public StandardOperatorsPackage()
        {
            Operators = new IMutationOperator[]
            {
  
                new AOR_ArithmeticOperatorReplacement(), 
               // new ABS_AbsoluteValueInsertion(),
                new SOR_ShiftOperatorReplacement(), 
               // new UOI_UnaryOperatorInsertion(), 
                new LCR_LogicalConnectorReplacement(), 
                new LOR_LogicalOperatorReplacement(), 
                new ROR_RelationalOperatorReplacement(), 

            };
        }
Beispiel #19
0
 public EvolutionaryAlgorithmBuilderContinuousMO(
     Population population,
     DecisionSpace decisionSpace,
     HyperParameterManager hyperParameters,
     IParentSelectionOperator parentSelector,
     IRecombinationOperator recombinationOperator,
     IMutationOperator mutationOperator,
     IReinsertionOperator reinsertionOperator)
 {
     this.decisionSpace = decisionSpace;
     HyperParameters.AddFromExistingHyperParameterSet(hyperParameters);
     this.population            = population;
     this.parentSelector        = parentSelector;
     this.recombinationOperator = recombinationOperator;
     this.mutationOperator      = mutationOperator;
     this.reinsertionOperator   = reinsertionOperator;
 }
Beispiel #20
0
        public GeneticAlgorithm(Settings settings,
                                IInitialPopulationProvider initialPopulationProvider,
                                IFitnessFunction fitnessFunction,
                                ISelectionOperator selectionOperator,
                                IElitistSelection elitistSelection,
                                ICrossoverOperator crossoverOperator,
                                IMutationOperator mutationOperator)
        {
            this.settings          = settings;
            this.fitnessFunction   = fitnessFunction;
            this.selectionOperator = selectionOperator;
            this.elitistSelection  = elitistSelection;
            this.crossoverOperator = crossoverOperator;
            this.mutationOperator  = mutationOperator;

            currentPopulation = initialPopulationProvider.GetInitialPopulation(settings.PopulationSize, settings.NumberOfCriterias);
            ComputeCurrentGenerationData();
        }
 public GeneticAlgorithmBuilder(
     IProblem <T> problem,
     ICrossoverOperator <T> crossoverOperator,
     IMutationOperator <T> mutationOperator)
 {
     _problem             = problem;
     _crossoverOperator   = crossoverOperator;
     _mutationOperator    = mutationOperator;
     _selectionOperator   = new TournamentSelectionOperator <T>(3, problem);
     _replacementOperator = new WorstFitnessReplacementOperator <T>(problem);
     _populationSize      = 1000;
     _maxGenerations      = 1000;
     _maxEvaluations      = 100000;
     _fitnessValue        = 10e-6;
     _elitismRate         = 1.0 / _populationSize;
     _generationGap       = 0.4;
     _variant             = GeneticAlgorithmVariant.SteadyState;
 }
 /// <summary>
 /// Creates an Evolutionary Algorithm.
 /// </summary>
 /// <param name="initialPopulation">The initial population (can be empty).</param>
 /// <param name="fitnessCalculator">A <see cref="FitnessCalculatorSingleObjective"/>. <see cref="Optimiser"/></param>
 /// <param name="initialIndividualGenerator">Creates new decision vectors to build the first population. <seealso cref="Base.Conversion.IModel"/></param>
 /// <param name="parentSelector">The <see cref="IParentSelectionOperator"/> to use.</param>
 /// <param name="recombinationOperator">The <see cref="IRecombinationOperator"/> to use.</param>
 /// <param name="mutationOperator">The <see cref="IMutationOperator"/> to use.</param>
 /// <param name="reinsertionOperator">The <see cref="IReinsertionOperator"/> to use.</param>
 /// <param name="hyperParameters">The <see cref="HyperParameterManager"/> object with relevant settings.</param>
 public EvolutionaryAlgorithm(
     Population initialPopulation,
     IFitnessCalculator fitnessCalculator,
     Func <DecisionVector> initialIndividualGenerator,
     IParentSelectionOperator parentSelector,
     IRecombinationOperator recombinationOperator,
     IMutationOperator mutationOperator,
     IReinsertionOperator reinsertionOperator,
     HyperParameterManager hyperParameters)
     : base(initialPopulation, fitnessCalculator)
 {
     this.initialIndividualGenerator = initialIndividualGenerator;
     this.parentSelector             = parentSelector;
     numberOfParents            = hyperParameters.GetHyperParameterValue <int>(EvolutionaryAlgorithmHyperParameters.Number_Of_Parents);
     this.recombinationOperator = recombinationOperator;
     this.mutationOperator      = mutationOperator;
     this.reinsertionOperator   = reinsertionOperator;
 }
 public ObjectOperatorsPackage()
 {
     Operators = new IMutationOperator[]
     {
         new DEH_MethodDelegatedForEventHandlingChange(),
         new DMC_DelegatedMethodChange(),
         //new EOC_EqualityOperatorChange(),
         new EMM_ModiferMethodChange(),
         new EAM_AccessorMethodChange(),
         new EHC_ExceptionHandlingChange(),
         new EHR_ExceptionHandlerRemoval(),
         new EXS_ExceptionSwallowing(),
         new ISD_BaseKeywordDeletion(),
         new JID_FieldInitializationDeletion(),
         new JTD_ThisKeywordDeletion(),
         // new RFI_ReferencingFaultInsertion(),
         new PRV_ReferenceAssignmentChange(),
         new MCI_MemberCallFromAnotherInheritedClass(),
         //  new NullInsertion(),
     };
 }
Beispiel #24
0
        protected AbstractGeneticAlgorithm(
            IProblem <T> problem,
            int populationSize,
            ISelectionOperator <T> selectionOperator,
            ICrossoverOperator <T> crossoverOperator,
            IMutationOperator <T> mutationOperator,
            ITerminationCondition terminationCondition)
        {
            _problem              = problem;
            _populationSize       = populationSize;
            _selectionOperator    = selectionOperator;
            _crossoverOperator    = crossoverOperator;
            _mutationOperator     = mutationOperator;
            _terminationCondition = terminationCondition;

            CurrentGeneration = 1;
            EvolutionTime     = TimeSpan.Zero;

            _population = CreateInitialPopulation();
            _population = EvaluatePopulation(_population);
        }
Beispiel #25
0
        public Population(PopulationSettings settings, ICrossoverOperator crossoverOperator, ISelectionOperator selectionOperator, IMutationOperator mutationOperator, Func <Individual> createIndividualDelegate)
        {
            _ = settings ?? throw new ArgumentNullException(nameof(settings));

            _mutationRate     = settings.MutationRate;
            _matingPoolSize   = settings.MatingPoolSize;
            _populationSize   = settings.PopulationSize;
            _offspringSize    = settings.OffspringSize;
            _generationsCount = settings.GenerationsCount;

            _crossoverOperator = crossoverOperator;
            _selectionOperator = selectionOperator;
            _mutationOperator  = mutationOperator;

            MatingPool  = new List <Individual>();
            Individuals = new List <Individual>();

            for (int i = 0; i < _populationSize; i++)
            {
                var individual = createIndividualDelegate.Invoke();
                Individuals.Add(individual);
            }
        }
 public static void ChangeOperator(IMutationOperator mOperator)
 {
     mutationOperator = mOperator;
 }
 public static IEnumerable <TChromosome> Mutate <TChromosome, TGene>(this IEnumerable <TChromosome> chromosomes,
                                                                     IMutationOperator <TChromosome, TGene> mutationOperator, double probability)
     where TChromosome : IChromosome <TChromosome, TGene> where TGene : IGene <TGene>
 {
     return(chromosomes.Select(c => mutationOperator.Apply(c, probability)));
 }
Beispiel #28
0
 public OperatorNode(PackageNode parent, IMutationOperator mutationOperator)
     : base(mutationOperator.Info.Id + " - " + mutationOperator.Info.Name)
 {
     Operator = mutationOperator;
     Parent   = parent;
 }
Beispiel #29
0
        public async Task <MutationResult> ExecuteMutation(Mutant mutant, CciModuleSource moduleSource, CciModuleSource moduleSource2)
        {
            /*var type = new TypeIdentifier((INamedTypeDefinition) mutant.MutationTarget.ProcessingContext.Type.Object);
             * var type2 = new TypeIdentifier((INamedTypeDefinition)mutant.MutationTarget2.ProcessingContext.Type.Object);//
             * var method = new MethodIdentifier((IMethodDefinition) mutant.MutationTarget.ProcessingContext.Method.Object);
             * var method2 = new MethodIdentifier((IMethodDefinition)mutant._mutationTarget2.ProcessingContext.Method.Object); //
             * var filter = new MutationFilter(type.InList(), method.InList());
             * var filter2 = new MutationFilter(type2.InList(), method2.InList());//
             */
            //_log.Debug("ExecuteMutation of: " + type+" - " +method );
            //_log.Debug("ExecuteMutation of: " + type + " - " + method + " + " + method2);
            IMutationOperator mutationOperator = mutant.MutationTarget.OperatorId == null ? new IdentityOperator() :
                                                 _mutOperators.Single(m => mutant.MutationTarget.OperatorId == m.Info.Id);
            IMutationOperator mutationOperator2 = mutant._mutationTargets[0].OperatorId == null ? new IdentityOperator() :
                                                  _mutOperators.Single(m => mutant._mutationTargets[0].OperatorId == m.Info.Id);
            var cci = moduleSource;

            try
            {
                //_log.Info("Execute mutation of " + mutant.MutationTarget + " contained in " + mutant.MutationTarget.MethodRaw + " modules. ");
                _log.Info("Execute mutation of " + mutant.MutationTarget + " contained in " + mutant.MutationTarget.MethodRaw + " modules and " + mutant._mutationTargets[0] + " contained in " + mutant._mutationTargets[0].MethodRaw + " modules.");
                var mutatedModules = new List <IModuleInfo>();
                var module         = moduleSource.Modules.Single();

                List <MutationTarget> mutationTargets = new List <MutationTarget>();
                mutationTargets.Add(mutant.MutationTarget);
                mutationTargets.Add(mutant._mutationTargets[0]);
                List <MutationTarget> sharedtargets = new  List <MutationTarget>();
                foreach (var element in _sharedTargets.GetValues(mutationOperator, returnEmptySet: true))
                {
                    sharedtargets.Add(element);
                }
                foreach (var element in _sharedTargets.GetValues(mutationOperator2, returnEmptySet: true))
                {
                    sharedtargets.Add(element);
                }
                var visitorBack = new VisualCodeVisitorBack(mutationTargets,
                                                            sharedtargets,
                                                            module.Module, mutationOperator.Info.Id + mutationOperator2.Info.Id);


                var traverser2 = new VisualCodeTraverser(_filter, visitorBack, moduleSource);

                traverser2.Traverse(module.Module);

                visitorBack.PostProcess();

                var operatorCodeRewriter = mutationOperator.CreateRewriter();

                var rewriter = new VisualCodeRewriter(cci.Host, visitorBack.TargetAstObjects,
                                                      visitorBack.SharedAstObjects, _filter, operatorCodeRewriter, traverser2);

                operatorCodeRewriter.MutationTarget =
                    new UserMutationTarget(mutant.MutationTarget.Variant.Signature, mutant.MutationTarget.Variant.AstObjects);

                operatorCodeRewriter.NameTable     = cci.Host.NameTable;
                operatorCodeRewriter.Host          = cci.Host;
                operatorCodeRewriter.Module        = module.Module;
                operatorCodeRewriter.OperatorUtils = _operatorUtils;
                operatorCodeRewriter.Initialize();

                /*var operatorCodeRewriter2 = mutationOperator2.CreateRewriter();//
                 * var rewriter2 = new VisualCodeRewriter(cci.Host, visitorBack.TargetAstObjects,
                 *  visitorBack.SharedAstObjects, _filter, operatorCodeRewriter2, traverser2);//
                 *
                 * operatorCodeRewriter2.MutationTarget =
                 *  new UserMutationTarget(mutant._mutationTarget2.Variant.Signature, mutant.MutationTarget2.Variant.AstObjects);//
                 *
                 * operatorCodeRewriter2.NameTable = cci.Host.NameTable;
                 * operatorCodeRewriter2.Host = cci.Host;
                 * operatorCodeRewriter2.Module = module.Module;
                 * operatorCodeRewriter2.OperatorUtils = _operatorUtils;
                 * operatorCodeRewriter2.Initialize();
                 */
                var rewrittenModule = rewriter.Rewrite(module.Module);
                //var rewrittenModule2 = rewriter2.Rewrite(module.Module);//
                rewriter.CheckForUnfoundObjects();
                //rewriter2.CheckForUnfoundObjects();//

                //2nd mutation

                /*IMutationOperator mutationOperator2 = mutant._mutationTarget2.OperatorId == null ? new IdentityOperator() :
                 *  _mutOperators.Single(m => mutant._mutationTarget2.OperatorId == m.Info.Id); //
                 * var cci2 = moduleSource2;
                 * var module2 = moduleSource2.Modules.Single();//
                 * var visitorBack2 = new VisualCodeVisitorBack(mutant.MutationTarget2.InList(),
                 * _sharedTargets.GetValues(mutationOperator2, returnEmptySet: true),
                 *  module2.Module, mutationOperator2.Info.Id); //
                 *
                 * var traverser22 = new VisualCodeTraverser(_filter, visitorBack2, moduleSource2);//
                 * traverser22.Traverse(module2.Module);//
                 * visitorBack2.PostProcess();//
                 * var operatorCodeRewriter2 = mutationOperator2.CreateRewriter();//
                 * var rewriter2 = new VisualCodeRewriter(cci2.Host, visitorBack2.TargetAstObjects,
                 *  visitorBack2.SharedAstObjects, _filter, operatorCodeRewriter2, traverser22);//
                 *
                 * operatorCodeRewriter2.MutationTarget =
                 *  new UserMutationTarget(mutant._mutationTarget2.Variant.Signature, mutant.MutationTarget2.Variant.AstObjects);//
                 *
                 * operatorCodeRewriter2.NameTable = cci2.Host.NameTable;
                 * operatorCodeRewriter2.Host = cci2.Host;
                 * operatorCodeRewriter2.Module = module2.Module;
                 * operatorCodeRewriter2.OperatorUtils = _operatorUtils;
                 * operatorCodeRewriter2.Initialize();
                 *
                 * var rewrittenModule2 = rewriter2.Rewrite(module2.Module);//
                 * rewriter2.CheckForUnfoundObjects();//
                 */
                mutant.MutationTarget.Variant.AstObjects      = null; //TODO: avoiding leaking memory. refactor
                mutant._mutationTargets[0].Variant.AstObjects = null; //TODO: avoiding leaking memory. refactor
                mutatedModules.Add(new ModuleInfo(rewrittenModule, ""));
                //mutatedModules.Add(new ModuleInfo(rewrittenModule2, ""));//

                //List<ICciModuleSource> cci = new List<ICciModuleSource>();
                //cci.Add(cci1);
                //cci.Add(cci2);
                List <IMethodDefinition> methodsMutated = new List <IMethodDefinition>();
                methodsMutated.Add(mutant._mutationTargets[0].MethodMutated);

                var result = new MutationResult(mutant, cci, null, mutant.MutationTarget.MethodMutated, methodsMutated);
                mutant.MutationTarget.MethodMutated      = null; //TODO: avoiding leaking memory. refactor
                mutant._mutationTargets[0].MethodMutated = null; //TODO: avoiding leaking memory. refactor
                return(result);
            }
            catch (Exception e)
            {
                throw new MutationException("CreateMutants failed on operator: {0}.".Formatted(mutationOperator.Info.Name), e);
            }
        }
Beispiel #30
0
        public static OptimiserBuilder GetBuilder(DecisionSpace problemSpace,
                                                  AvailableOperators.ParentSelector parentSelection,
                                                  AvailableOperators.RecombinationOperator recombination,
                                                  AvailableOperators.MutationOperators mutation,
                                                  AvailableOperators.ReinsertionOperators reinsertion,
                                                  int?populationSize = null)
        {
            var hyps = EvolutionaryAlgorithmHyperParameters.GetDefaultHyperParameters();

            if (populationSize != null)
            {
                hyps.UpdateHyperParameterValue(
                    EvolutionaryAlgorithmHyperParameters.Population_Size, populationSize);
            }
            var population = new Population(
                hyps.GetHyperParameterValue <int>(EvolutionaryAlgorithmHyperParameters.Population_Size));

            IParentSelectionOperator parentSelector;

            switch (parentSelection)
            {
            case AvailableOperators.ParentSelector.Tournament:
                parentSelector = new ParentSelectionTournament(
                    20,
                    false);
                break;

            case AvailableOperators.ParentSelector.Greedy:
                parentSelector = new ParentSelectionGreedy();
                break;

            case AvailableOperators.ParentSelector.Random:
                parentSelector = new ParentSelectionRandom();
                break;

            case AvailableOperators.ParentSelector.Roulette:
                parentSelector = new ParentSelectionRoulette(
                    false);
                break;

            default:
                throw new NotImplementedException();
            }

            IRecombinationOperator recombinationOperator;

            hyps.UpdateHyperParameterValue(EvolutionaryAlgorithmHyperParameters.Number_Of_Parents, 2);
            switch (recombination)
            {
            case AvailableOperators.RecombinationOperator.MultiPoint:
                recombinationOperator = new CrossoverMultiPoint(
                    2);
                break;

            case AvailableOperators.RecombinationOperator.ArithmeticTwoParentWeighted:
                recombinationOperator = new CrossoverArithmeticWeighted(
                    false,
                    0.5);
                break;

            case AvailableOperators.RecombinationOperator.Sbx:
                recombinationOperator = new CrossoverSimulatedBinary(
                    2);
                break;

            case AvailableOperators.RecombinationOperator.SbxSa2:
                recombinationOperator = new CrossoverSimulatedBinarySelfAdaptive2(
                    population, 2);
                break;

            case AvailableOperators.RecombinationOperator.ArithmeticMultiParent:
                recombinationOperator = new CrossoverArithmeticMultiParent();
                hyps.UpdateHyperParameterValue(
                    EvolutionaryAlgorithmHyperParameters.Number_Of_Parents,
                    4);
                break;

            case AvailableOperators.RecombinationOperator.Uniform:
                recombinationOperator = new CrossoverUniform(
                    0.5);
                break;

            case AvailableOperators.RecombinationOperator.Pcx:
                recombinationOperator = new RecombinationParentCentric(
                    0.1,
                    0.1);
                hyps.UpdateHyperParameterValue(
                    EvolutionaryAlgorithmHyperParameters.Number_Of_Parents,
                    6);
                break;

            default:
                throw new NotImplementedException();
            }

            IMutationOperator mutationOperator;

            switch (mutation)
            {
            case AvailableOperators.MutationOperators.AddRandomNumber:
                mutationOperator = new MutationAddRandomNumber(
                    0.1,
                    0.1,
                    1);
                break;

            case AvailableOperators.MutationOperators.RandomSwap:
                mutationOperator = new MutationRandomSwap(
                    0.1);
                break;

            case AvailableOperators.MutationOperators.ReplaceWithRandomNumber:
                mutationOperator = new MutationReplaceWithRandomNumber(
                    0.1,
                    1);
                break;

            case AvailableOperators.MutationOperators.None:
                mutationOperator = new MutationReplaceWithRandomNumber(
                    0, 1);
                break;

            default:
                throw new NotImplementedException();
            }

            IReinsertionOperator reinsertionOperator;

            switch (reinsertion)
            {
            case AvailableOperators.ReinsertionOperators.ReplaceWorst:
                reinsertionOperator = new ReinsertionReplaceWorst();
                break;

            case AvailableOperators.ReinsertionOperators.ReplaceRandom:
                reinsertionOperator = new ReinsertionReplaceRandom();
                break;

            default:
                throw new NotImplementedException();
            }

            return(new EvolutionaryAlgorithmBuilderContinuousSO(population, problemSpace, hyps,
                                                                parentSelector, recombinationOperator, mutationOperator, reinsertionOperator));
        }
Beispiel #31
0
 public OperatorNode(PackageNode parent, IMutationOperator mutationOperator)
     : base(mutationOperator.Info.Id+" - "+ mutationOperator.Info.Name)
 {
     Operator = mutationOperator;
     Parent = parent;
 }